ERR_UNKNOWN_FILE_EXTENSION NodeJS

I am trying to import the @metamask/detect-provider” library but when I go to run npm start I get the error ERR_UNKNOWN_FILE_EXTENSION.
I tried searching online for a possible solution but was unsuccessful

Source code app.js

import detectEthereumProvider from '@metamask/detect-provider';

const provider = await detectEthereumProvider();
const express = require("express");
const app = express();


if (provider) {
    app.get("/", function (req, res) {
        res.sendFile(__dirname + "/index.html");
    });
} else {
    app.get("/", function (req, res) {
        res.sendFile(__dirname + "/error.html");
    });
}

module.exports = app;

package.json

{
  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "type": "module",
  "dependencies": {
    "@maticnetwork/maticjs": "^3.2.2",
    "@maticnetwork/maticjs-web3": "^1.0.1",
    "@metamask/detect-provider": "^1.2.0",
    "body-parser": "^1.18.3",
    "cookie-parser": "~1.4.4",
    "debug": "~2.6.9",
    "express": "~4.16.1",
    "http-errors": "~1.6.3",
    "jade": "~1.11.0",
    "morgan": "~1.9.1",
    "request": "^2.88.2",
    "truffle": "^5.4.33",
    "web3": "^1.7.0"
  }
}

JavaScript parseInt not working with “10”?

I wrote the function that tokenizes arithmetic string expression into an array of tokens, such as numbers and operators. Everything’s fine but I get a weird results when dealing wuth strings containing “10”. Here’s the code:

function tokenizeString(expressionString) {
    const tokenArray = [];

    let token = "";
    for (let i = 0; i < expressionString.length; i++) {
        if (parseInt(expressionString[i])) {
            token += expressionString[i];
        } else {
            tokenArray.push(parseInt(token));
            token = "";
            tokenArray.push(expressionString[i]);
        }
    }

    if (token !== "") {
        tokenArray.push(parseInt(token));
    }

    return tokenArray;
}

console.log(tokenizeString("14+2/8")); // [14, "+", 2, "/", 8]
console.log(tokenizeString("10+1")); // [1, '0', NaN, '-', 3] ??

For now I can’t come up with an idea, why this happens.

Display second prompt if the first prompt is not TRUE

I have a problem when i try to display new prompt, i use loop but it will display both my prompt. Here is my code and i really need help

<body>
<p id="age" style="font-weight: bold"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
var age = document.getElementById("age").value;
var age = prompt("Enter Your birth year:");// This is the first prompt 
const year = new Date().getFullYear();
if (age != null) { 
          document.getElementById("age").innerHTML =
            "Your " + age + " is so beautiful"; // If user enter birth year < current year will display this
        }
  do {
     age = prompt("Re-enter your birth year:"); // Ortherwise, this will display and they need to enter until birth year < current year
    } while (age > year && age != null);
        var tuoi = year - age;// This is just calculate user'age, for example if the user enter 2000 will display user'age is 22
        document.getElementById("age").innerHTML =
          "Tuổi " + tuoi + " này đẹp đó";
}
</script>
</body>

How to import css file of react-datepicker into SSR written in Nestjs and AdminJS?

I am using the react-datapicker inside of SSR project written in Nest.js and Admin.js. I need to add some React components so I need to import import ‘react-datepicker/dist/react-datepicker.css’ into the project so that should work properly with proper design. The error is says [Nest] 93478 – 02/12/2022, 12:47:22 PM ERROR [ExceptionsHandler] Unexpected character ‘@’ (Note that you need plugins to import files that are not JavaScript). I could not find any solution specific to my problem. Is there anyone can help me to solve this issue?

How to send a request to Nodejs backend server when the client closes the browser tab or window?

I am trying to build an application where whenever the client closes the browser window/tab I should send a notification to the backend to destroy the logged-in session and log the details of the running session. I have tried onbeforeunload but it is not working as intended, as it also executes on page reload. Also, it does not send the request by closing the browser tab.

why I cant see any output on my reactjs app?

I have started my first React lesson but I cant see any output on my localhost(3000), will you pls help me ?

this is my JS code :

import React from 'react';
import ReactDOM from 'react';

const element = React.createElement("div", { id: "title", className: "app-title" }, "this is a test text");

ReactDOM.render(element, document.getElementById("root"));

Randomize assigned colors in an array in p5.js

I have been trying to recreate one of Vera Molnar’s paintings, and to add a twist, I wanted to randomize the colors in the array as I drag my mouse over the canvas. However, I cannot for the life of me figure out how to do this. Below is one of many attempts at this. What could I be doing wrong?

As for the colors, the intial order of the colors is something I would like to keep, as it is directly mimicking the original painting, but as the mouse is moved into the canvas/frame, i want to trigger the random colors.

Thank you for your help!

https://editor.p5js.org/k-yr-k/sketches/vU7cTZ8Ra

// recreating Lent mouvement bleu, orange, rouge et noir, 1955, by Vera Molnar

const width = 700;
const height = 700;

let radius = 58;
let len = 8;
let color;
let colors;

function setup() {
  createCanvas(width, height);

  colors = [
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#d31a22",
    "#9bd6ff",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#e2592f",
    "#000000",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#000000",
    "#9bd6ff",
    "#e2592f",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#9bd6ff",
    "#d31a22",
    "#000000",
    "#000000",
    "#9bd6ff",
  ];
}

function draw() {
  background(255);

  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len; j++) {
      let x = i * 80;
      let y = j * 80;
      color = colors.shift();
      if (color === undefined) {
        color = "white";
      }
      fill(color);
      noStroke();
      ellipse(y + 65, x + 65, radius);
    }
  }

  noLoop();
}

function mouseDragged() {
  color = random(colors);
}

React-Hook Form: Cannot read properties of undefined (reading ‘field’)

My form is a nested one and if I’ll only submit one product, there are no errors, But If I’ll click Add More Product and click the button to add more colors this is the error that I’m getting:

Cannot read properties of undefined (reading 'field')

This is where it pointed out:

<input
  36 |   name={`test[${nestIndex}].nestedArray[${k}].color`}
  37 |   ref={register({ required: true })}
> 38 |   defaultValue={item.field}
     |                     ^
  39 |   style={{ marginRight: "25px" }}
  40 | />

and here:

return (
  19 |   <div>
> 20 |     {fields.map((item, k) => {
     |            ^
  21 |       return (
  22 |         <div key={item.id} style={{ marginLeft: 20 }}>
  23 |           <label>{k + 1}</label>

Adding more products, and adding more colors will make these errors appear

This is what the form looks like:

enter image description here

Codesandbox link: https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-vjwbp?file=/src/index.js

The error is in the fieldArray.js:

i

mport React from "react";
import { useFieldArray } from "react-hook-form";
import NestedArray from "./nestedFieldArray";
import { TextField } from "@mui/material";

let renderCount = 0;

export default function Fields({ control, register, setValue, getValues }) {
  const { fields, append, remove, prepends } = useFieldArray({
    control,
    name: "test"
  });

  renderCount++;

  return (
    <>
      <ul>
        {fields.map((item, index) => {
          return (
            <li key={item.id}>
              {/* <select
                ref={register()}
                name={`test[${index}].name`}
                defaultValue={item.name}
              >
                <option value="">Select</option>
                <option value="10">ItemA</option>
                <option value="20">ItemB</option>
              </select> */}
              {/* {index + 1}  to show the qty */}
              <TextField
                name={`test[${index}].nestedArray[${index}].product`}
                inputRef={register({ required: true })}
                defaultValue={item.name}
              />

              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
              <NestedArray nestIndex={index} {...{ control, register }} />
            </li>
          );
        })}
      </ul>

      <section>
        <button
          type="button"
          onClick={() => {
            append({ name: "append" });
          }}
        >
          Add product
        </button>
      </section>

      <span className="counter">Render Count: {renderCount}</span>
    </>
  );
}

How to hide Input fields if $GET_() is empty? [closed]

Good day experts!

I’m having trouble hiding the input fields if &_GET(N) method is empty without deleting its php code. Here’s the code below:

<html>
<body>
<?php echo $_GET["subject"]; ?><br><br>
<?php echo $_GET["instruction"]; ?><br><br>
<?php echo '<input type="text">' ; echo $_GET["new_1"]; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_2"] ; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_3"] ; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_4"] ; ?><br>
<?php error_reporting(0); echo '<input type="text">', $_GET["new_5"] ; ?><br>
</body>
</html> 

react-native-dropdown-picker How to show 2 information in 1 item

I am using React-Native-Dropdown-Picker to do a list of products, then I have trouble wanting to display information as at the bottom, which means I want to show both information in 1 Item as at the bottom of the picture

The images

I searched as well as reviewing the Props of React-Native-Dropdown-Picker, but I still haven’t found the answer

Hope everyone can help me

Thanks

Using a CancelToken with an axios instance

I’ve read several similar questions, but I’m still struggling to be able to cancel my requests given my code structure.

On clicking one of the following elements I’d like to be able to cancel all other requests except the new one, however it seems to cancel all requests, and then prevents axios making any new ones. I’m new to cancelling tokens, so don’t really know what I’m doing wrong here:

import {cancelTokenSource} from 'API';

let isActiveRequest;

document.body.addEventListener('click', async(e) => {
    const userElement = e.target.closest('.user-element');
    const appElement = e.target.closest('.app-element');


    if(isActiveRequest) {
        cancelTokenSource.cancel();
        isActiveRequest = false;
    }

    if(userElement) {
        isActiveRequest = true;
        try{
            const users = await Admin.getUsers();
            isActiveRequest = false;
            // display users
        } catch(err) { isActiveRequest = false; }
    }
    if(appElement) {
        isActiveRequest = true;
        try{
            const applications = await Admin.getApplications();
            isActiveRequest = false;
            // display applications
        } catch(err) { isActiveRequest = false; }
    }
});

API.js

export const cancelTokenSource = axios.CancelToken.source();

export default axios.create({
    baseURL: 'http://localhost:8080',
    cancelToken: cancelTokenSource.token
});

Admin.js

export default class Admin {
  
    getUsers({index, limit, orderField, orderDirection}) {
        return API.get('/admin/applicants', { params: { index, limit, orderField, orderDirection } });
    }
    getApplications({index, limit, orderField, orderDirection}) {
        return JRS.get('/admin/applications', { params: { index, limit, orderField, orderDirection} });

    ...
}

Thanks

Get value from input field and insert in URL Javascript

I have a form on wordpress, I need to get a value from a field and pass it into this script. This is what I’ve managed to do so far. The redirection works perfectly. I just need to put the value into the url as a parameter. I don’t know the basics or theories of javascript. I just google and manage to put them together. Could anyone please help me out?
Thanks!

<script>
  function getinputval()
    {
        var numpages1 = document.getElementById("numberofpages1").value;} 
document.addEventListener( 'wpcf7mailsent', function( event ) {
if (document.getElementById('selectservice').value=='Certified Translation') {location.replace('https://example.com?add-to-cart=856&quantity=+numpages1;')}
else if (document.getElementById('selectservice').value=='Business Translation') {location.replace('http://www.redirectedpage2.com')}
else { location.replace('http://www.redirectedpage3.com/') }
}, false );
</script>

Codepipeline using cdk with source as S3 and deploy as AppConfig

I have started my cdk, somedays ago and having this problem from 1-2 days. If someone could give insights it would be very helpful
Following is the code for the pipeline and receiving error:
throw new Error(‘Trying to resolve() a Construct at ‘ + pathName);

export class AppConfigCiCdStack extends Stack {
    private application: CfnApplication;
    private environments: CfnEnvironment;
    private deploymentStrategy: CfnDeploymentStrategy;
    private bucket: Bucket;
    private profile: CfnConfigurationProfile
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props);

        this.application = new CfnApplication(this, "ServerlessApplication", {
            description: "ConFiguration For Serverless Application",
            name: "ServerlessApplicationConfig"
        });

        this.environments = new CfnEnvironment(this, "Testing", {
            description: "Testing environment for app",
            name : "Test",
            applicationId : this.application.ref,
        });

        this.profile = new CfnConfigurationProfile(this, "LoggingConfiguration", {
            applicationId: this.application.ref,
            description : "Logging related configuration",
            name: "LoggingConfiguration",
            locationUri: `s3://${this.bucket}sampleApp.zip/`
        })
        
        this.bucket = new Bucket(this, 'source', {
            bucketName: 'source',
            versioned: true,
        })

        this.deploymentStrategy = new CfnDeploymentStrategy(this, "DeploymentStrategy", {
            deploymentDurationInMinutes : 0,
            finalBakeTimeInMinutes: 1,
            growthType: "LINEAR",
            growthFactor: 100,
            name: "Custom.Immediate.Bake5Minutes",
            replicateTo: "NONE",
        })

        this.pipeline(this.bucket, this.application, this.environments, this.deploymentStrategy, this.profile);
    }

    pipeline(bucket: Bucket, application: CfnApplication, environments: CfnEnvironment, strategy: CfnDeploymentStrategy, profile: CfnConfigurationProfile) {
        
        const pipelineArtifact = new Bucket(this, "serverlessappconfigpipelineartifact", {
            bucketName: "serverlessappconfigpipelineartifact",
            versioned: true,
            autoDeleteObjects: true, 
            removalPolicy: RemovalPolicy.DESTROY,
        })

        const sourceConfig = {"Application": application.ref, "Bucket": bucket, "S3ObjectKey": 'sampleApp.zip'};

        const outputArtifactProperty: CfnPipeline.OutputArtifactProperty = {
            name: 'sourceConfig',
        };

        const inputArtifactProperty: CfnPipeline.InputArtifactProperty = {
            name: 'sourceConfig',
        };

        const configSource : CfnPipeline.ActionDeclarationProperty = {
            actionTypeId: {
                category: "Source", 
                owner: "AWS",
                provider: "S3",
                version: "1",
            },
            configuration: {
                sourceConfig,
            },
            name: "ServerlessAppConfigSource",
            outputArtifacts: [outputArtifactProperty],
        }

        const sourceStage: CfnPipeline.StageDeclarationProperty = {
            name: "Source",
            actions: [configSource],
        }

        const deployConfig = {  "Application": application.ref, 
                                "Environment": environments.ref, 
                                "ConfigurationProfile": profile.ref, 
                                "DeploymentStrategy": strategy.ref,
                                "InputArtifactConfigurationPath": 'sampleApp.json'};

        const appConfigDeploy: CfnPipeline.ActionDeclarationProperty = {
            actionTypeId: {
                category: "Deploy",
                owner: "AWS",
                provider: "AppConfig",
                version: '1',
            },
            inputArtifacts: [inputArtifactProperty],
            configuration: deployConfig,
            name: "ServerlessAppConfigDeploy",
        }

        const deployStage : CfnPipeline.StageDeclarationProperty = {
            name: "Deploy",
            actions: [appConfigDeploy],
        }

        const artifactStoreProperty: CfnPipeline.ArtifactStoreProperty = {
            location: pipelineArtifact.bucketName,
            type: "S3",
        }

        const pipeline = new CfnPipeline(this, "ServerlessAppConfigPipeline", {
            stages: [sourceStage, deployStage],
            artifactStore: artifactStoreProperty,
            roleArn: '',
            name: 'ServerlessAppConfigPipeline'
        })
    }

}

error: throw new Error(‘Trying to resolve() a Construct at ‘ + pathName);

Adding an li in JS with appendChild to a ul that has an hr in it

Soo I did about 45 min of googling and couldn’t find anything..

Im working in JS and Im trying to add a li at the bottom of my ul list for an assignment. Part of the requirements is that I couldn’t make any changes to the HTML. Which looks like this:

            <hr>
            <ul id="list">
                <li>
                    <div>Milk</div>
                    <button>edit</button>
                    <button>X</button>
                </li>
                <li>
                    <div>Cheerios</div>
                    <button>edit</button>
                    <button>X</button>
                </li>
                <li>
                    <div>2 Goats</div>
                    <button>edit</button>
                    <button>X</button>
                </li>  
                <hr>              
            </ul>
        </div>

Because of the location of the bottom “hr” tag. All my newly appended children go under it.

This is what my JS looks like:

const form = document.addItem;
let listItem = document.createElement("li");
let editButton = document.createElement("button");
let xButton = document.createElement("button");

form.addEventListener("submit", (event) => {
  event.preventDefault();

  const item = form.title.value;
  console.log(item);
  form.title.value = "";

  listItem.textContent = item;
  editButton.textContent = "edit";
  xButton.textContent = "X";

  document.getElementById("list").appendChild(listItem);
  document.getElementById("list").appendChild(editButton);
  document.getElementById("list").appendChild(xButton);


});

Just want the newly appended children to either go above the hr tag or to the top of the list.

Firebase auth.currentUser error using typescript

When configuring typescript with firebase, I am getting the following error: Argument of type 'User | null' is not assignable to parameter of type 'User'. Type 'null' is not assignable to type 'User'.

The error is here: auth.currentUser It is unclear to me what type it would be.

updateProfile(auth.currentUser, {
                    displayName: name
                }

Full code:

import { getAuth, createUserWithEmailAndPassword, signOut, onAuthStateChanged, signInWithEmailAndPassword, updateProfile } from "firebase/auth";
import { useEffect, useState } from "react";
import FirebaseInitialization from "../Firebase/Firebase.init";



FirebaseInitialization()

interface IUseFirebaseProps {
}

const UseFirebase: React.FunctionComponent<IUseFirebaseProps> = (props) => {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()


      // REGISTER WITH EMAIL AND PASSWORD
      const RegisterUser = (email: string, password:string, name:string, history: any) => {
        setIsLoading(true)
        createUserWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                const newUser = { email, displayName: name };
                setUser(newUser);
                setError('')
                updateProfile(auth.currentUser, {
                    displayName: name
                }).then(() => {
                }).catch((error) => {
                });
                history.replace('/');
            })
            .catch((error) => {

                const errorMessage = error.message;
                setError(errorMessage)
            }).finally(() => setIsLoading(false));
    }
  return <h2>Firebase</h2>
};

export default UseFirebase;

How can I solve this? can anyone help me?