How to run Stockfish in the browser using Javascript?

in a project I’m working on I need to evaluate random chess positions that I pull from elsewhere. I’d like to run Stockfish on the browser client-side (similar to how chess.com does it I think). How can I do that using JavaScript? All I need is some way to get the evaluation value of a position inside my code, which I can use later. There exists an npm stockfish module but I can’t find any documentation on how to use it. Can anyone help with this problem? Thanks!

jQuery animations ‘is not a function’

I’m trying to use .fadeIn() from jQuery to fade in a cloned element. But I get the error “is not a function” when trying to call any animation methods from jQuery.

I am using the min version of jQuery and I have tried with the normal version too. I am aware that the slim version doesn’t include animations.

My jQuery code:

$('#invoicelines').append($('#invoicelines').find('.invoicelineElements').first().clone());
$('#invoicelines').find('.invoicelineElements').last().hide().fadeIn('slow');

My HTML header:

<!--UTF-8 & BOOTSTRAP MOBILE-FIRST META TAG-->
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<!--BOOTSTRAP & CSS-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
    crossorigin="anonymous">
<link rel="shortcut icon" href="#">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="{%static '/css/main.css'%}">

<!--J-QUERY-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>

<!--VUEJS-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Writable div reverses text

I have been trying to add text highlighting to python code in a writable div using spans since spans do not work inside textarea, but for some reason the div reverses any text, here’s a simplified version of the code:

<div id="code-editor" spellcheck="false" contenteditable="true"></div>

<script>

    const writableDiv = document.getElementById("code-editor");

    const pythonKeyWords = [ /* has all python keywords */ ]

    const keywordRegex = new RegExp('\b(' + pythonKeywords.join('|') + ')\b', 'g');

    writableDiv.addEventListener('input', () => {
        let text = writableDiv.innerText;
        text = text.replace(keywordRegex, '<span style="color: #f200ff;">$&</span>');
        writableDiv.innerHTML = text;
    });

</script>

Here, if I enter def from the keyword, it comes out as fed in the the div, and vice versa.

I would like to know what’s wrong with what I am doing, because I have tried to use highlights.js and to customize it a bit but it got the same issue as this one.

Electron – Contents in window is larger than previous page

I’m having a slight issue with the contents in the window. Basically in my index.html the contents are the right size and everything(images, texts, etc.). However when I click on the link “Click here” which bring me to the register.html the contents size increased. I tested without css and it’s still giving me this kind of issue. I also have useContentSize:true, enabled in my main.js.

Here’s the gif of both pages so you can spot the difference easily.
enter image description here

Exact same resolution, css disabled, both pages are set with useContentSize:true and both are using this exact same settings in main.js

useContentSize:true,
width: 700,
height: 700,
minWidth: 700,
minHeight: 700,
frame: false,

So how would I be able to resolve this issue?

How can I ensure that x number of mines are placed on a minesweeper board, if the mines are generated at random? [duplicate]

So I am making minesweeper in html/css/javascript. I have 3 different difficulty states that the player can choose that determine how large the board is going to be, and how many mines it will have.
for the purposes of this question I’ll go with the intermediate settings, 16×16 board with 40 mines on it.

board is initiated to board = [];
to populate it I use

function createBoard(row,col,mines){
    let count=0;
    for(let r=0;r<row;r++){
        board[r]=[];
        for(let c=0;c<col;c++){
            if(count <= mines){
                board[r][c]=new CELL(row,col,false);
            }
            else{
                let mine = Math.round(Math.random());
                board[r][c]=new CELL(row,col,Boolean(mine)); //0 is no mine, 1 means mine
                if(mine){
                    count++;
                }
            }
        }
    }
}

so that should create the right sized board, and populate it with CELL objects, some of which are mines. The problem is that my count variable only ensures that my randomizer doesnt generate MORE THAN 40 mines. The randomizer could (theoretically) choose 0 for every single object.

so how can I make sure my board gets created with the appropriate number of mines while still being truly random?

Local WebRTC Unity to JS Client for Monodirectional Video

The direction is Unity –> JavaScript, where Unity is capturing video.
Using WebRTC the Unity and JavaScript clients are able to communicate to each other, but it seems that the JavaScript client cannot display any video being sent by the Unity client.

I do not know why the JavaScript client cannot display any video output despite having clear communication (i.e receiving).

I’ve tried changing/adding a codec to now avail, but I’m not sure if I need to since the docs (Unity WebRTC 2.4.0) don’t really specify that a codec is need. I am using NativeWebSocket (a C# library) to communicate to my local server. SDPs are able to be sent from both clients, but (again) there seems to be no video displaying on my JavaScript client.

Unity Client

using System.Collections;
using UnityEngine;
using Unity.WebRTC;
using System;
using NativeWebSocket;

public class LocalMediaSender : MonoBehaviour
{
    public Camera capture_camera;
    private RTCPeerConnection local_connection;
    private RTCDataChannel data_channel;
    private WebSocket ws;
    public string ip = "192.168.X.X"; // TODO: add your IP here
    // Start is called before the first frame update
    async void Start()
    {
        ws = new WebSocket($"ws://{ip}:8080");
        ws.OnOpen += () =>
        {
            Debug.Log("Connection open!");
            InitializeWebRTC();
        };

        ws.OnError += (e) =>
        {
            Debug.Log("Error! " + e);
        };

        ws.OnClose += (e) =>
        {
            Debug.Log("Connection closed!");
        };

        ws.OnMessage += (bytes) =>
        {
            Debug.Log("OnMessage!");
            Debug.Log(bytes);

            // Getting the message as a string
            var message = System.Text.Encoding.UTF8.GetString(bytes);
            Debug.Log("OnMessage! " + message);

            // Deserialize the message to SDPMessage
            SDPMessage sdpMessage = JsonUtility.FromJson<SDPMessage>(message);

            // Check if the message is an answer
            if (sdpMessage.type == "answer")
            {
                // Create a RTCSessionDescription for the answer
                RTCSessionDescription answer = new RTCSessionDescription
                {
                    type = RTCSdpType.Answer,
                    sdp = sdpMessage.sdp
                };

                // Start the coroutine to set the remote description for the local connection
                StartCoroutine(HandleSetRemoteDescription(answer));
            }
        };


        await ws.Connect();
    }

    private void InitializeWebRTC()
    {
        // [Step 1] Create Peer Connection
        local_connection = new RTCPeerConnection(/*ref config*/);

        /* ADD EVENT HANDLERS */
        {
            // [Step 2] onopen Connection Notification
            RTCDataChannelInit init = new RTCDataChannelInit { ordered = true }; // to ensure that data packets are delivered in order makes it reliable
            data_channel = local_connection.CreateDataChannel("myChannel", init);
            data_channel.OnOpen += () =>
            {
                Debug.Log("Data Channel Opened -- Unity");
            };

            // [Step 3] onicecandidate To Print SDP
            local_connection.OnIceCandidate = (e) =>
            {
                string iceCandidateString = JsonUtility.ToJson(e);
                // Inside the OnIceCandidate event handler in Unity
                ws.SendText(iceCandidateString);
                //Debug.Log("[ICE Candidate] " + iceCandidateString);
            };
        }

        // [Step 4] addTrack Video Media To Send
        if (capture_camera == null){ Debug.LogError("[ERROR] There is no camera!"); }
        MediaStream video_stream_track = capture_camera.CaptureStream(1280, 720);
        foreach (var track in video_stream_track.GetTracks()) { 
            local_connection.AddTrack(track, video_stream_track);
        }

        // [Step 5] createOffer 
        // use button to start offer
    }


    public void StartOffer() {
        StartCoroutine(HandleCreateOffer());
    }

    public void StopOffer() {
        StopCoroutine(HandleCreateOffer());
    }

    IEnumerator HandleCreateOffer()
    {
        RTCOfferAnswerOptions offerOptions = default;

        var op = local_connection.CreateOffer(ref offerOptions);
        yield return op;

        if (op.IsError)
        {
            Debug.LogError($"Error creating offer: {op.Error}");
            yield break;
        }

        RTCSessionDescription offer = op.Desc;
        offer.sdp = offer.sdp.Replace("m=video 9 UDP/TLS/RTP/SAVPF 96 97 98 99 100 101 102", "m=video 9 UDP/TLS/RTP/SAVPF 96");

        // [Step 6] setLocalDescription Once Offer Is Successful
        var setLocalDescOp = local_connection.SetLocalDescription(ref offer);
        yield return setLocalDescOp;

        if (setLocalDescOp.IsError)
        {
            Debug.LogError($"Error setting local description: {setLocalDescOp.Error}");
        }
        else
        {
            // Send local_description after it has been set
            if (ws.State == WebSocketState.Open)
            {
                //string sdp_string = JsonUtility.ToJson(local_connection.LocalDescription);
                string sdp_string = JsonUtility.ToJson(new SDPMessage { sdp = local_connection.LocalDescription.sdp, type = local_connection.LocalDescription.type.ToString() });
                ws.SendText(sdp_string);
                Debug.Log("[SDP] " + sdp_string);
            }
            else
            {
                Debug.LogError("WebSocket connection is not open.");
            }
        }
    }

    IEnumerator HandleSetRemoteDescription(RTCSessionDescription answer)
    {
        var op = local_connection.SetRemoteDescription(ref answer);
        yield return op;

        if (op.IsError)
        {
            Debug.LogError($"Error setting remote description: {op.Error}");
        }
        else
        {
            Debug.Log("Remote description set successfully.");
        }
    }


    [Serializable]
    public class SDPMessage
    {
        public string sdp;
        public string type;
    }

    // Update is called once per frame
    void Update()
    {
        // required to recieve messages from signaling server
        #if !UNITY_WEBGL || UNITY_EDITOR
                ws.DispatchMessageQueue();
        #endif
    }
}

JavaScript Client

<html>
  <head>
    <title>Local WebRTC Receiver</title>
  </head>

  <body>
    <!-- Create a video element to display the remote video stream -->
    <video 
        style="box-sizing: border-box; border: 5px solid black;" 
        id="remote-video" 
        autoplay 
        playsinline 
        width="1280" 
        height="720">
        <!-- video body -->
    </video>

    <script>
        let ip = "192.168.X.X" // TODO: add your IP here
        
        const local_connection = new RTCPeerConnection();
        let offer = null;
        

        // Connect to the WebSocket signaling server
        const signalingServer = new WebSocket(`ws://${ip}:8080`);

        signalingServer.onopen = (e) =>{ /* when connected */ }
        
        signalingServer.onmessage = (event) => {
            event.data.text().then((msg)=>{
                console.log("De-Blobed Message:", msg);
                const message = JSON.parse(msg);
                console.log("JSON Message:", message);

                // Answer offer
                if(message.type == "Offer"){
                    offer = message;
                    offer.type = "offer"; // <-- THIS IS DUMB BUT NEEDED

                    local_connection.setRemoteDescription(new RTCSessionDescription(offer))
                        .then((e)=>{
                            console.log("offer set!");
                            return local_connection.createAnswer();
                        })
                        .then((answer)=>{
                            console.log("setting local description!");
                            return local_connection.setLocalDescription(answer);
                        })
                        .then((e)=>{
                            console.log("Sending Local Description")
                            const sdp = local_connection.localDescription;
                            signalingServer.send(JSON.stringify(sdp));
                        })
                        .catch((err)=>{console.error(err);})
                }
                
                // Handle incoming messages (ICE candidates, offers, etc.)
            })

        };

      local_connection.onicecandidate = (e) =>{
        console.log("[SDP] ", local_connection.localDescription);
      };


      local_connection.ontrack = (e) =>{
        console.log("Received remote track:", e.track);
        console.log("Received remote streams:", e.streams);
        console.log("Kind:", e.track.kind);

        if(e.track.kind == "video"){            
            // Display the remote video stream in the video element
            const remoteVideo = document.getElementById('remote-video');
            remoteVideo.srcObject = e.streams[0];

            console.log(remoteVideo.srcObject);
            console.log("Codec: ",e.track.getSettings().codec);
            console.log("Settings: ",e.track.getSettings());
        }
        
      };

      local_connection.ondatachannel = (e) =>{
        var receiveChannel = ev.channel;

        receiveChannel.onmessage = (e) =>{
            console.log("[Message from Unity]n",e.data);
        };
        
        receiveChannel.onopen = (e) =>{
            console.log("Connected! -- JS");
        };

        receiveChannel.onclose = (e) =>{ /* when connection closes*/ };
      }
 
    </script>
  </body>
</html>

Node JS Server

const WebSocket = require("ws");
const host_ip = "192.168.X.X" // TODO: add your IP here
const server = new WebSocket.Server({ host: host_ip, port: 8080 });

const clients = new Set();

server.on("connection", (socket) => {
  clients.add(socket);
  console.log("[Server] Client connected");

  socket.on("message", (message) => {
    console.log("-=-=-=-=-=-[New Message Received]-=-=-=-=-=-");
    console.log(message.toString())
    console.log("-=-=-=-=-=-[END Message Received]-=-=-=-=-=-");

    // console.log("Received:", message);

    // Broadcast the message to all other clients
    for (const client of clients) {
      if (client !== socket) {
        client.send(message);
      }
    }
  });

  socket.on("close", () => {
    clients.delete(socket);
    console.log("[Server] Client disconnected");
  });
});

console.log(`[Server] WebSocket signaling server running on ws://${host_ip}:8080`);

To run the server make sure to have Node.JS installed and then run npm i and npm start. Also ensure you add the host’s (computer where server will be running on) IP address.

How to sequence GraphQL queries to output data dependent from each other?

I have two microservices ms1 and ms2 that output different types of data each time an API gateway built with Apollo GraphQL sends requests through resolvers.

To be specific, the first resolver getCart(userId: ID!): Cart! calls ms1 and it responds it with the following response body:

{
  "items": [
    {
      "itemId": "8a016af8-5336-4799-b806-73976996aa6f",
      "quantity": 1
    },
    {
      "itemId": "9a016af8-5336-4799-b806-73976996aa6f",
      "quantity": 2
    }
  ]
}

That is, the Cart type, just an object containing an array of items with id and quantity.

The second resolver getItem(itemId: ID!): Item! calls ms2 and it responds it with the following response body:

{
  "itemId": "7a016af8-5336-4b99-b806-73976996aadf",
  "name": "Jack Daniel's Blue Label",
  "price": 29.99
}

Is there any way to “combine” or sequence these two queries directly from a frontend (e.g. Apollo Sandbox or GraphiQL) in such a way that I get the following response?

{
  "items": [
    {
      "itemId": "8a016af8-5336-4799-b806-73976996aa6f",
      "name": "Jack Daniel's - Honey",
      "price": 19.99,
      "quantity": 1
    },
    {
      "itemId": "7a016af8-5336-4799-b806-73976996aa6f",
      "name": "Jack Daniel's - Red Label",
      "price": 29.99,
      "quantity": 2
    }
  ]
}

In pseudo-graphql I was thinking about something like this:

query GetCartInfo($userId: ID!) { 
  getCart(userId: $userId) {
    items {
      itemId => getItem(itemId: $itemId) {
        name
        price
      }
      quantity
    }
  }
}

If that’s not possible, what would be the best way to achieve this? Create a new resolver in the API gateway? Modify the array from another service in the frontend?

Thanks for the help and information about the topic, I would really appreciate it 😀

Have a nice day!

Send notification request on client Vue app

I’m new to JavaScript and web apps and I’m building a Vue app that uses Firebase for hosting, database, authentication, and messaging. My app stores certain items, and I want to send a push notification to users subscribed to each item when it gets updated.

I’m trying to follow this Firebase Cloud Messaging (FCM) documentation to achieve this: https://firebase.google.com/docs/cloud-messaging/send-message?hl=es-419#send_messages_to_device_groups

However, I’m having trouble invoking the send() method because the getMessaging() function I’m importing from ‘firebase/messaging’ (and the Messaging type it returns) doesn’t have any methods. It only has the app property.

I’m concerned that this approach might not be intended for client apps, and that it might be impossible to achieve what I want with a simple Vue app.

Any insights or suggestions would be greatly appreciated.

I’ve attempted to resolve the issue by using the “// @ts-ignore” tag and invoking the “send()” method anyway. Additionally, I’ve tried installing @firebase/messaging-types with npm, searching for videos and examples, and re-reading the documentation repeatedly.

I had expected that vscode would stop underlining “send” in red and that my push notifications would work.

Type ‘void[]’ is not assignable to type ‘ReactNode’

This code block is OK:

        let attributes = <>
        {
            props.filter.attributes?.map((data) => {
                return
                <div className="form-check">
                    <input className="form-check-input" type="radio" id={data.id.toString()} name={props.filter.name} value={data.name} onChange={props.changeHandler} />
                    <label className="form-check-label">{data.name}</label>
                </div>
            })
        }
    </>

But this code has the error Type 'void[]' is not assignable to type 'ReactNode'. The only change is to wrap the map function in a div:

    let attributes = <>
        <div className="row row-cols-5">
            {
                props.filter.attributes?.map((data) => {
                    return
                    <div className="form-check">
                        <input className="form-check-input" type="radio" id={data.id.toString()} name={props.filter.name} value={data.name} onChange={props.changeHandler} />
                        <label className="form-check-label">{data.name}</label>
                    </div>
                })
            }
           </div>
        </>

What do I need to do to the second example to eliminate the error?

Importing SockJS into Lit project fails

I am building a web component using Lit that utilizes sockjs-client, but I’m encountering issues when attempting to import the library.

When using import SockJS from ‘sockjs-client’;, I receive the error message “Uncaught SyntaxError: The requested module ‘./../node_modules/sockjs-client/lib/entry.js’ does not provide an export named ‘default’.”

When trying import { SockJS } from ‘sockjs-client’;, I get the error “Uncaught SyntaxError: The requested module ‘./../node_modules/sockjs-client/lib/entry.js’ does not provide an export named ‘SockJS’.”

Importing using import * as SockJS from ‘sockjs-client’; results in the error “Uncaught ReferenceError: require is not defined.”

The only working solution so far is importing from a CDN, but I would prefer not to depend on a CDN. Can anyone provide advice?

Add different sounds to different buttons

I am working through a project using Javascript and jQuery. The projects requires me to add sounds to buttons. A different sound should play depending on the button I click. I know how to add a single audio file to buttons, but can someone help me with adding different audio to each button?

$(".btn").on("click" , function () {
    let buttonSound = $(this).attr("id");
    playSound(buttonSound);

});

My project gives a random color, which corresponds with a button. This code works to play the sound of that button, but it also plays that sound with my other buttons (instead of the sound they are suppose to play). The only way to change the sound is to refresh the screen, but this has the same issue, just with a different random button. Any help would be greatly appreciated.

Replace part of javascript string using regex and keep the variable part

The problem

Given following JS Object:

{"name":"a","rotation":2}

I am trying to convert all objects with either name: a, b, c or i their rotation to 0 if it is currently 2

The output for the case above should be:

{"name":"a","rotation":0}

I tried

Non-capture groups (?:) and other methods but no succes.

The solution below shows the problem where in the second parameter I cannot use [abci] to get the letter that was originally there. As I have to replace the whole thing.

let obj = '{"name":"b","rotation":2}';

obj.replace(
    /"name":"[abci]","rotation":2/g,
    '"name":"[abci]","rotation":0'
); // Expected: {"name":"b","rotation":0}

Node js passport authentication, can’t get user data after logging them in

I’m developing a node js react website and using passport I wanna manage users’ login and signup sessions. I can successfully register users and see their data in my MongoDB database and I also can successfully sign them in. But when I try to retrieve the data of a logged in user with req.user I can’t and it gives me ‘undefined’ and it seems the app doesn’t have any memory of the session. Here’s my node js code:

mongoose.connect("mongodb://localhost:27017/userDB", {
    useNewUrlParser: true, 
    useUnifiedTopology: true
});

const user = new mongoose.Schema({
    username: String,
    password: String
});
const User = new mongoose.model("User", user);

//middleware
app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
}));
app.use(express.urlencoded({
    extended: false
 }));
 app.use(express.json());

app.use(cors({
    origin: "http://localhost:3000",
    credentials: true,
}));

app.use(cookieParser("secret"));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser((user, cb) => {
    console.log("serializing user");
    cb(null, user.id);
});
passport.deserializeUser((id, cb) => {
    User.findById(id).then((err, user) => {
        if(err) throw err;
        console.log("id: " + id);
        console.log("userid: " + user);
        const userInformation = {
            username: user.email,
        };
        cb(err, user);
    }).catch((err) => {console.error(err)});
});

passport.use(
    new localStrategy(async (username, password, done) => {
        try{
            const user = await User.findOne({username: username});
            if(!user) {
                console.log("no user");
                return done(null, false);
            }
            bcrypt.compare(password, user.password, (err, result) => {
                if(err) throw err;
                if(result === true) {
                    return done(null, user);
                } else {
                    return done(null, false);
                }
            });
        } catch(err){
            console.log("err inside localStrategy: " + err);
            throw err;

        }

    })
);

app.post("/login", (req, res, next) => {
    console.log("inside login");
    passport.authenticate("local", (err, user, info) => {
        console.log("inside authenticate, user: " + user);
        if(err) {
            console.log("err: " + err);
            throw err;
        }
        if(!user) {
            console.log("No user");
            res.status(400);
            res.send("No user exists");
        }
        else {
            console.log("inside else");
            req.logIn(user, (err) => {
                if(err) throw err;
                res.status(200).json({message: "login successful"});
            });
        }
    })(req, res, next);
});

app.get("/isLogin", function(req, res) {
    console.log("in isLogin");
    if(req.isAuthenticated()){
        console.log("it is logged in");
        res.status(200).json(req.user);
    }
    else {
        console.log("it is not logged in");
        res.status(200).json({message: "user not logged in"});

    }
});

app.listen(4000, () => {console.log("server started on port 4000")});

The login part works but /isLogin indicates that the user is not logged in and also when I try to get req.user it returns “undefined”. Would appreciate any help with this. Thanks

react-native-vector-icons IOS include some

I want to include only AntDesign and maybe FontAwesome icons in my project, the documentation says that if i use auto linking i need to add this to my react-native.config.js

module.exports = {
  dependencies: {
    'react-native-vector-icons': {
      platforms: {
        ios: null,
      },
    },
  },
};

so i did I want to have AntDesign available 100% is this goiong to be enough to do it like so?

module.exports = {
  dependencies: {
    'react-native-vector-icons': {
      platforms: {
        ios: ['AntDesign.ttf'],
      },
    },
  },
};

or is it not necessary? I asked chatGPT and it says that passing null means that thise fonts would be dowloaded at runtime from some remote server, is that not the case for android? Android seems to favour including them all without making a fuss about bundle size. Should i worry about bundling them, what would be more performant to have them downloaded every time or bundled?

Thanks