Socket.io – “Session ID unknown” problem when try to hanle websocket commuication

I am working on a project that involves a React client using Socket.io for real-time communication with a Node.js server. The server handles code blocks, and each code block has its own room to manage collaborative editing.

am encountering an issue where, upon emitting events to rooms, I receive a “session id unknown” error. This error seems to indicate a problem with identifying the session associated with a particular socket.

This is my server side:

const express = require("express");
const http = require("http");
const { Server } = require("socket.io");


const cors = require("cors");
const connectDB = require('./configs/db');
const codeBlockRouter = require('./routers/codeBlockRouter');
const users = require('./routers/userRouter')

const app = express();

app.use(cors());
app.use(express.json())

// routers
app.use('/codeblocks', codeBlockRouter)
app.use('/users', users)

connectDB();

const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: "https://online-coding-web-client.vercel.app",//client
    methods: ["GET", "POST"],
    credentials: true,
  },
});

let userCount = 0;

io.on("connection", (socket) => {

  const user = `${++userCount}`;

  console.log(`User connected: user${user}`);
  socket.emit("user_connected", { user });

  socket.on("join_room", (data) => {
    console.log(`User joined room: ${data}`);
    socket.join(data);

  });

  socket.on("send_message", (data) => {
    console.log(`Received message: ${data.messageText} from user ${data.user}`);
    socket.broadcast.emit("receive_message", { ...data, user });
  });


  socket.on("disconnect", () => {
    console.log(`User disconnected: user${user}`);
  });
});

server.listen(5000, () => {
  console.log("SERVER IS RUNNING");
});

This is my client side:

import io from 'socket.io-client'

const socket = io(serverURL, {
  withCredentials: true
})

  useEffect(() => {
    socket.emit("join_room", codeBlockId);
  }, [codeBlockId]);

  useEffect(() => {
    socket.on("user_connected", (data) => {
      setUser(data.user);
    });
  }, [socket]);


  useEffect(() => {
    socket.on("receive_message", (data) => {
      setText(data.messageText);

    });
  }, [socket]);

  useEffect(() => {
    return () => {
      socket.disconnect();
    };
  }, []);

  const sendMessage = (messageText) => {
    socket.emit("send_message", { messageText, user });
  };

I suspect that the issue may be related to how I am handling socket connections, disconnections, or room management. Could someone please review the provided code snippets and help me identify what might be causing the “session id unknown” error?

How to amend the start game function to become a difficulty selector?

I’m new to coding and have followed a tutorial in how to make a quiz game but I’ve decided that when I select the begin quiz button, I want it to ask what difficulty to begin with? The difficulties would be easy = 10 questions, medium = 15 questions and hard = 20 questions.

here is the code for the game:

const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
const progressText = document.getElementById("progress-text");
const scoreText = document.getElementById("score");

let currentQuestion = {}
let acceptingAnswers = true
let score = 0
let questionCounter = 0
let availableQuestions = []

let questions = [
     {
        question: "What year did Marty and Doc travel to in Back to the Future?",
        choice1: "1955",
        choice2: "1985",
        choice3: "1965",
        choice4: "1975",
        answer: 2,
    }
]

const SCORE_POINTS = 10
const MAX_QUESTIONS = 15

startGame = () => {
    questionCounter = 0
    score = 0
    availableQuestions = [...questions]
    getNewQuestion()
}

getNewQuestion = () => {
    if(availableQuestions.length === 0 || questionCounter > MAX_QUESTIONS) {
        localStorage.setItem('mostRecentScore', score)

        return window.location.assign('end.html')
    }

    questionCounter++
    progressText.innerText = `Question ${questionCounter} of ${MAX_QUESTIONS}`
    
    const questionsIndex = Math.floor(Math.random() * availableQuestions.length)
    currentQuestion = availableQuestions[questionsIndex]
    question.innerText = currentQuestion.question

    choices.forEach(choice => {
        const number = choice.dataset['number']
        choice.innerText = currentQuestion['choice' + number]
    })

    availableQuestions.splice(questionsIndex, 1)

    acceptingAnswers = true
}

choices.forEach(choice => {
    choice.addEventListener('click', e => {
        if(!acceptingAnswers) return

        acceptingAnswers = false
        const selectedChoice = e.target
        const selectedAnswer = selectedChoice.dataset['number']

        let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect'

        if(classToApply === 'correct') {
            incrementScore(SCORE_POINTS)
        }

        selectedChoice.parentElement.classList.add(classToApply)

        setTimeout(() => {
            selectedChoice.parentElement.classList.remove(classToApply)
            getNewQuestion()

        }, 1000)
    })
})

incrementScore = num => {
    score += num
    scoreText.innerText = score
}

startGame();

I removed a number of questions to better show the js code.

Honestly, I don’t know where to begin and any help would be appreciated greatly.

Spotify Web API: 401 Unauthorized

I try to get access token for Spotify Web API:

const CLIENT_ID = "blablabla";
const CLIENT_SECRET = "blablabla";
const REDIRECT_URI = "http://localhost:3000";
const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize";
const RESPONSE_TYPE = "token";

const requestAccessToken = async () => {
    await fetch("https://accounts.spotify.com/api/token", {
      body: `grant_type=client_credentials&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}`,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      method: "POST",
    })
      .then((response) => response.json())
      .then((data) => {
        setAuthToken(data.access_token);
        navigate("/home");
      });
  };
<button onClick={requestAccessToken} className={styles.login}>
Login to Spotify
</button>

{/*Href:*/}
{/*https://accounts.spotify.com/authorize?client_id=blablabla&redirect_uri=http://localhost:3000&response_type=token*/}
<a
className={styles.login}
href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}`}

>Login to Spotify 2</a>

So, for the <button> one, I can get the access token and save it to the state, no problem. After that, if I try to send a request to /me api with that access token, it returns 401 Authorized.

The code:

const getUserData = async (token: string) => {
      await fetch("https://api.spotify.com/v1/me", {
        headers: {
          Authorization: "Bearer " + token,
        }
      })
        .then((response) => response.json())
        .then((data) => {
          console.log(data);
          setUser(User.fromJSON(data));
        }).catch((error) => {
          console.log(error);
        });
    };

But if I try the <a> tag and get the access token, The request works successfully and I can see the data.

What is the difference between <a> way and <button> way?

How to access arrow data in js?

I am fetching arrow tabular data from an api, the content-type of the response is application/vnd.apache.arrow.stream. In my react code, I am trying to read the response as such. I am not sure if this is the optimized way of reading arrow data.

function extractDataFromTable(table) {
    let extractedData = [];
  
    // Iterate over each row of the table
    for (const row of table) {
      const rowJson = row.toJSON();
      if (rowJson.origin_lat instanceof Float64Array) {
        rowJson.origin_lat = Array.from(rowJson.origin_lat)[0]; // Assuming only one element in the array
      }
      if (rowJson.origin_lon instanceof Float64Array) {
        rowJson.origin_lon = Array.from(rowJson.origin_lon)[0]; // Assuming only one element in the array
      }
  
      extractedData.push(rowJson);
    }
  
    return extractedData;
  }


const response = await axios.get(`${baseURL}/api/new_drives`, {
        params: {
          name: cname,
        },
        responseType: "arraybuffer",
      });
  
 // Convert the response data to an Apache Arrow table
 const buffer = new Uint8Array(response.data);
 const table = tableFromIPC(buffer);
  
 // Process the table to extract your data
 const extractedData = extractDataFromTable(table); 
 data.setApiData(extractedData);

is there a better and faster way of reading arrow data?

Changes to types in node_modules results in typescript errors while using the dev env of create-react-app

I have a script that modifies some files in the node_modules folder of my React TypeScript application. The problem I’m encountering is that the webpack dev server doesn’t recognize the changes I make to the types, resulting in errors like this:

webpack compiled with 3 warnings
ERROR in src/views/AllTasks.tsx:21:25
TS2339: Property 'someTest' does not exist on type 'typeof TaskService'.
    19 | 
    20 |
  > 21 | console.log(TaskService.someTest())
       |                         ^^^^^^^^
    22 |
    23 | export default function AllTasks() {
    24 |   const navigate = useNavigate();
Here I've addded the `someTest` method while webpack dev server was running. I've also changed the version in the package's package.json because I've read that this affects caching.

Upon further investigation, I discovered that the resulting JavaScript code includes the newly added method, as webpack compiles successfully. However, the type checking fails.

To test if I could reproduce this behavior with npm install, I created a new CRA app and installed tiny-types using npm install tiny-types command. I imported a type from tiny-types, then manually commented it out in the tiny-types’ implementation in node_modules folder. I started the webpack dev server and, as expected, encountered an error. But, after running npm install tiny-types again, anticipating that my modification would be reversed and the CRA would no longer report the missing type, the error persisted. No matter what I did, the error continued to appear. The only possibility is to restart the webpack dev server.

Any ideas how to work around this issue?

Modal component slow to close based on state updates

I have the following component that should show a modal when the APIs are fetching data from the back end, and close it once all API calls are successful. However, I noticed a substantial lag between when isAllSuccess turns true and the modal gets dismissed. I know state updates are not immediate, is there a good way to make the modal more realtime? Thanks

const CustomPageLayoutComponent = (): JSX.Element => {
  const { searchParams } = useQueryParamsHook();
  const dispatch = useDispatchHook();

  const { customParameter } = useParamsHook<{customParameter: string}>();
  const { data: firstApiDataResponse, ...firstApiLifecycle } = useFirstApiQuery(customParameter);  //RTK query
  const { data: secondApiDataResponse, ...secondApiLifecycle } = useSecondApiQuery(); //RTK query
  const { data: thirdApiData, ...thirdApiLifecycle } = useThirdApiQuery(customParameter); //RTK query

  const customDataSelector = useAppSelectorHook((state: RootState) => state.customModule.customData);
  const customSelectorResult = useAppSelectorHook((state: RootState) => selectCustomSelector(state, customParameter));
  const customListState = useAppSelectorHook((state: RootState) => selectCustomListState(state, customParameter));
  const customList = useAppSelectorHook(selectCustomList);
  const customProcessedData = thirdApiData?.customProcessedData || [];
  const customMappedData = thirdApiData?.customMappedData || {};

  // State for API status messages
  const [apiStatus, setApiStatus] = useState({});
  const [showApiModal, setShowApiModal] = useState(false);
  const handleCloseModal = () => {
    setApiStatus({});
    setShowApiModal(false);
  };

  const isAnyLoadingOrFetching = firstApiLifecycle.isLoading || secondApiLifecycle.isLoading || thirdApiLifecycle.isLoading || firstApiLifecycle.isFetching || secondApiLifecycle.isFetching || thirdApiLifecycle.isFetching;
  const isAnyError = firstApiLifecycle.isError || secondApiLifecycle.isError || thirdApiLifecycle.isError;
  const isAllSuccess = firstApiLifecycle.isSuccess && secondApiLifecycle.isSuccess && thirdApiLifecycle.isSuccess;
  
  useEffect(() => {
    let newApiStatus = {};
    newApiStatus["FirstApi"] = getApiStatusMessage(firstApiLifecycle);
    newApiStatus["SecondApi"] = getApiStatusMessage(secondApiLifecycle); 
    newApiStatus["ThirdApi"] = getApiStatusMessage(thirdApiLifecycle);
    setApiStatus(newApiStatus);
    if (isAllSuccess || (!isAnyLoadingOrFetching && !isAnyError)) {
      setShowApiModal(false);
    } else {
      setShowApiModal(true);
    }
  }, [isAnyLoadingOrFetching, isAnyError, isAllSuccess]);

  useEffect(() => {
    if (customLogicForUpdatingData) {
      dispatch(updateCustomDataAction({ customParam: searchParams.customParam, customParameter }));
    }
  }, [searchParams.customParam, customParameter, dispatch]);

  const [navOpen, setNavOpen] = useState<boolean>(false);

  return (
    <CustomLayout 
      contentType={"default"}
      content={
        <>
          <ApiStatusModalComponent isVisible={showApiModal} hasError={isAnyError} message={apiStatus} onClose={handleCloseModal}/>
          <CustomLayoutContainer size={"large"} direction={"vertical"}>
            <CustomBreadcrumbComponent
              items={[
                { text: "Custom Dashboard", href: "/customPath" },
                { text: `${customParameter}`, href: "" },
              ]}
            />
            <CustomHeaderComponent customParameter={customParameter} customSelectorResult={customSelectorResult} customListState={customListState} processedData={customProcessedData}/>
            <CustomTableComponent customParameter={customParameter} customList={customListState.customList} customCompareList={customDataSelector} customList={customList} customMappedData={customMappedData}/>
          </CustomLayoutContainer>
        </>
      }
      navigation={<CustomNavigation />}
      navigationOpen={navOpen}
      onNavigationChange={(event) => {
        setNavOpen(event.detail.open);
      }}
      toolsHide={true}/>
    )
};

Why jQuery add quotation marks? [closed]

jQuery absolutely unclear add some quotation marks.

There is ajax request to the server, which returns Html code… When I doing append this code, jQuery absolutely unclear add some quotation marks.
Ajax request:

$.ajax({
    url         : 'ajax/data-notice',
    method      : 'POST',
    dataType    : 'html',
    success     : function(data){
        if(data!=null){
            alert(data);
        $(mod).find('.modal-body').append(data);
        }
    },
    error : function(jqXHR, exception){
    console.log('Error occured!!');
    }
  });

I want to do append the button:

<span class="btn btn-default btn-xs" onclick=openChat(3,'Test 3')">open</span>

When I look data in the window “alert(data)” everything is correct, but when I doing append in the modal window (Bootstrap), I get a String like this:

<span class="btn btn-default btn-xs" onclick="openChat(3,'Test" 3')"="">open</span>

How to understand this and how to fix it?

Trouble Implementing Authentication in Node.js Using Passport.js – Error: ‘Strategy requires a verify callback

I’m working on implementing authentication in my Node.js application using Passport.js, and I’m encountering an issue with a “Strategy requires a verify callback” error. I’ve followed various tutorials and documentation but seem to be missing something crucial.

Here’s a snippet of my code:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    // Authentication logic here
  }
));
Error: The strategy requires a verify callback

I’ve double-checked my implementation against multiple examples, but I’m still unable to resolve this issue. Could someone please provide guidance on what might be causing this error or suggest a proper implementation of the verify callback for the LocalStrategy in Passport.js?

OOP “Classes” and DOM manipulation with JavaScript, undefined element

This is my first personal project using JavaScript to make a website dynamic. I don’t feel utterly lost, but after a few days I will take a knee at being “stuck”. I have a grid container containing 6 items which I would like to attach a “click” eventListener to. Essentially I am using Classes and Constructors to organize my code, and my problem likely lies in inadequate familiarity with how to compose the code properly.

// these are the `grid items`
function mapContainers() {
    let values = ["1", "2", "3", "4", "5", "6"];
    let gridItems = values.map((element) => {
        return document.querySelector(`.item${element}`);
    });
    return gridItems;
}

// this is my GridButton Class
class GridButton {
    constructor(button, direction) {
        this.button = button;
        this.direction = direction;
    }

    // Getter
    get whenClicked() {
        return this.button.addEventListener("click", popUp(`${this.direction}`));
    }
    // Method
    popUp(direction) {
        gridContainer.style.zIndex = "-1";
        gridContainer.style.opacity = "0.2";
        dogBone.style.display = "block";
        dogBone.animate(
            {
                transform: "scale(0, 0)",
                transformOrigin: `${this.direction}`
            },
            {
                transform: "scale(1, 1)"
            },
            {
                duration: 400,
                iterations: 1
            }
        );
    }
}

// this is my init()
function init() {
    // Call functions here
    const gridItems = mapContainers();
    const dogWalking = new GridButton(gridItems[0], "top left");
    const dayCare = new GridButton(gridItems[1], "top right");
    const boarding = new GridButton(gridItems[2], "left");
    const bath = new GridButton(gridItems[3], "right");
    const parties = new GridButton(gridItems[4], "bottom left");
    const petWasteRemoval = new GridButton(gridItems[2], "left");
    dogWalking.whenClicked();
    dayCare.whenClicked();
    boarding.whenClicked();
    bath.whenClicked();
    parties.whenClicked();
    petWasteRemoval.whenClicked();
}

// variously defined variables:
const gridContainer = document.querySelector("services_grid_container");
const serviceElaboration = document.querySelector("service_elaboration");
const serviceElaborationText = document.querySelector("service_elaboration_text");
const dogBone = document.querySelector("dog-bone");
const dogBoneText = document.querySelector("dog-bonetext");

// running the init()
document.addEventListener('DOMContentLoaded', init);

for some reason, the console logs an error:

script.js:19 Uncaught ReferenceError: popUp is not defined
    at get whenClicked [as whenClicked] (script.js:19:28)
    at HTMLDocument.init (script.js:51:16)
get whenClicked @ script.js:19
init @ script.js:51

I’m not sure why it is saying popUp is not defined. I do not mean to be airing out my dirty laundry, I’m just trying to understand! I’ll keep trying to understand this in the meantime, but thank you for anyone who considers helping.

I tried consulting Chat GPT, and that didn’t solve the problem. Chat GPT suggested adding the eventListener to the constructor, but I couldn’t figure that out beyond its code which yielded the same error. I’ve contemplated integrating popUp into the constructor, but that seems like a dead-end. Finally I am utilizing stack overflow.

Why python is considered as object oriented?

meaning of object oriented programming

I need an answer for this question.Object-oriented programming is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects.

For example, an object could represent a person with properties like a name, age, and address and behaviors such as walking, talking, breathing, and running. Or it could represent an email with properties like a recipient list, subject, and body and behaviors like adding attachments and sending.

Put another way, object-oriented programming is an approach for modeling concrete, real-world things, like cars, as well as relations between things, like companies and employees or students and teachers. OOP models real-world entities as software objects that have some data associated with them and can perform certain operation

make tow type form in one componet

i want to make a form in inline and vertical type and write this

import React from "react";

export default function Form({ children, onSubmit, layout }) {
  const handleSubmit = (e) => {
    e.preventDefault();
    if (onSubmit) {
      onSubmit(e);
    }
  };

  const formClass = layout === 'horizontal' ? 'form-inline' : '';

  return (
    <form className={`m-2 ${formClass}`} onSubmit={handleSubmit}>
      {layout === 'horizontal' ? (
        <div className="form-group">
          <div className="col">{children}</div>
        </div>
      ) : (
        <div className="form-group">{children}</div>
      )}
    </form>
  );
}

but year, month and day not be inline type i dont undrestand that
i use bootstrap to make a responsive register page

import React, { useState } from "react";
import './Register.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios';
import AlertColors from '../../Alert/AlertColors'
import FormData from '../../../data/FormData/FormData.json'
import FormGroup from '../../Form/FormGroup'
import Form from "../../Form/Form";
import { Link } from 'react-router-dom';

export default function Register  (){
    const [formData, setFormData] = useState(FormData);
    const [errorOccurred, setErrorOccurred] = useState(false);
    const [curred, setcurred] = useState(false);
  
    const handleChange = (e) => {
      const { name, value } = e.target;
      setFormData({
        ...formData,
        [name]: value,
      });
    };
    
    const handleSubmit = async (e) => {
      e.preventDefault();
      try {
        await axios.post('/api/registry/', formData, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        setcurred(true)
      } catch (error) {
        setErrorOccurred(true)
        
      }
    };

    return (
      <FormGroup>
        {curred && <AlertColors color="green" text="An error alert for showing message." />}
        {errorOccurred && <AlertColors color="red" text="A success alert for showing message." />}
        <Form layout="vertical">
          <input type="text" name="first_name" value={formData.first_name} onChange={handleChange} className="form-control hover" placeholder="First Name" />
          <input type="text" name="last_name" value={formData.last_name} onChange={handleChange} className="form-control" placeholder="Last Name" />
        </Form>
        <Form layout="horizontal">
              <input type="text" name="year" value={formData.year} onChange={handleChange} className="form-control" placeholder="year" />
              <input type="text" name="month" value={formData.month} onChange={handleChange} className="form-control" placeholder="mouth" /> 
              <input type="text" name="day" value={formData.day} onChange={handleChange} className="form-control" placeholder="day" />
        </Form>
        <Form layout="vertical">
          <input type="text" name="phone_number" value={formData.phone_number} onChange={handleChange} className="form-control" placeholder="Phone Number" />
          <input type="email" name="email" value={formData.email} onChange={handleChange} className="form-control" placeholder="Email" />
          <input type="text" name="username" value={formData.username} onChange={handleChange} className="form-control" placeholder="Username" />
          <input type="password" name="password" value={formData.password} onChange={handleChange} className="form-control" placeholder="Password" />
          <input type="password" name="rePassword" value={formData.rePassword} onChange={handleChange} className="form-control" placeholder="rePassword" />
          <button onClick={handleSubmit} type="submit" className="btn btn-primary">Register</button>
          <Link to="/" className="btn btn-warning m-3">Login</Link>
        </Form>
      </FormGroup>
      )
  };

I expected that my year, month and day must be in the inline type not in the vertical type
and i don’t now how can i fix that
🙁

Javascript fetch WordPress Rest Api [duplicate]

I have a wordpress rest api that I want to GET. I can use postman and type in my credentials and it spits out a desired response no problem.

This is fetched from a different domain/origin that the WordPress site.

With my current code, I get a status of 200 but does not give me a response. Instead I get an error of:

“Uncaught (in promise) error with status 0”

Where is my issue and how can it be fixed? It’s taken me a while just to spit out a status: 200, and I am pulling my hair out at this point.

async function getTravelCredit() {
    
    let tcnumber = document.getElementById('travel_credit_number');
    let USERNAME = 'username';
    let PWD = 'password';
    
    const response = await fetch("https://example.com/wp-json/jet-cct/travel_credit", {
        mode: 'no-cors',
        credentials: 'include',
        headers: {
            'Authorization' : 'Basic ' + btoa(USERNAME + ":" + PWD),
        }
    });
    if (!response.ok){
        throw `error with status ${response.status}`;
    }
    return reponse.json();
  
  }

how to upload image in mysql using nodejs

I am trying to send data in mysql but return error.
TypeError: Cannot read properties of undefined (reading ‘query’)
my code is

const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const getConnection = require('./database');
// Set storage engine
const storage = multer.diskStorage({
destination: './uploads/',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
},
});
const upload = multer({
storage: storage,
}).single('photo');
router.post('/upload', async (req, res) => {
try {
const connection = await getConnection();
await upload(req, res, async (err) => {
if (err) {
console.error('Error uploading file:', err);
return res.status(500).send('Internal Server Error');
}
if (!req.file) {
console.error('No file uploaded.');
return res.status(400).send('No file uploaded.');
}
const imagePath = req.file.path;
const imageBuffer = fs.readFileSync(imagePath);
const query = 'INSERT INTO image (photo) VALUES (?)';
await connection.query(query, [imageBuffer]);
connection.release();
res.send('File uploaded and saved to MySQL!');
});
} catch (error) {
console.error('Error:', error.message);
res.status(500).send('Internal Server Error');
}
});
module.exports=router

**check my code and please solve **
**check my code and please solve **

mergedGeometry LineSegment combination problem Three.js

I want to create my edge lines of merged geometry. But with that code ı can create edges lines independentyl with 2 main geometry

// Combine two geometriesconst geometry1 = new THREE.BoxGeometry(0.01, 9.1, 0.01);
const geometry2 = new THREE.BoxGeometry(1, 1, 1);
const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries([geometry1, geometry2]);
// Create a mesh with a material that suppresses edge linesconst mergedMaterial = new THREE.MeshBasicMaterial({
color: 0x542452,
wireframe: true, // Enable wireframe rendering
opacity: 0, // Set opacity to 0 to suppress edge lines
transparent: true // Make the material transparent
});

const mergedMesh = new THREE.Mesh(mergedGeometry, mergedMaterial);
scene.add(mergedMesh);
// Create edges for the entire merged geometryconst edgesGeometry = new THREE.EdgesGeometry(mergedMesh.geometry);
const mergedLines = new THREE.LineSegments(
edgesGeometry,
new THREE.LineBasicMaterial({ color: 0xff0000 })
);`

scene.add(mergedLines);`
I want to

TensorFlow.js MLP Regression Model output not returning as expected

I’ve created a MLP Regression Model with TensorFlow.js that takes as input a tensor like this:

tf.tensor2d([[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 8]])

The Model was constructed this way:

function createModel(inputShape) {
  const model = tf.sequential();
  model.add(tf.layers.dense({
    inputShape: inputShape,
    activation: 'sigmoid',
    units: 50,
  }));
  model.add(tf.layers.dense({
    activation: 'sigmoid',
    units: 50,
  }));
  model.add(tf.layers.dense({
    units: 1,
  }));
  model.compile({optimizer: tf.train.sgd(0.01), loss: 'meanSquaredError'});
  return model;
}

But the answer I’m getting is not as expected. No matter the input, I always get something like: 0.3157223165035248 instead of 0s and 1s.

My dataset has values like this example below, where the last column is the label, and should be the output of the training model. (I added the same input layer on first line here just as a demonstration)

1,0,1,1,1,0,1,1,1,1,1,0,8,1
1,1,1,1,0,0,1,1,0,0,1,0,6,0
1,1,0,1,0,0,0,1,0,1,0,1,5,0
1,1,0,1,1,0,1,1,1,1,0,1,8,1
1,1,0,1,0,0,1,1,0,1,1,1,6,0
1,0,0,0,0,0,0,1,0,0,1,0,2,0
1,1,1,1,1,0,1,1,1,1,0,0,9,1
0,1,0,0,0,0,0,1,0,0,1,0,2,0
1,1,1,1,0,0,0,0,1,0,0,0,5,0
1,1,0,0,1,0,0,1,1,1,0,0,6,0
1,1,1,1,0,1,1,1,1,0,0,1,8,1

I was using the TensorFlow Albalone Node example and adapting it to what I needed, so my code is pretty similar to it.

I’ve tried changing the activation and optimizers methods, changing the learning rate and loss values, reducing or increasing the dataset, epochs and batches, etc. but none helped. The results are always the same or pretty close to that.