Changing width directly vs changing width CSS Custom Property

I’m having an issue with expanding side panel width in JavaScript:

I need to resize it on mousemove event but visual performance of changing width (like el.style.width = value) is far more better than changing custom property (like style.setProperty('--side-panel-width, value)) – Actually, the second one is freezing 🙁

However, I want to change Custom Property, because 2 other panels positioning are depending on this Custom Property value:

.other-panel {
  left: calc(var(--side-panel-width) + var(--offset));
}

My mousemove event handler code (simplified):

    onMouseMove(e) {
      requestAnimationFrame(() =>
        const parent = this.$refs.resize.parentNode;
        const dx = this.size - e.x;
        this.size = e.x;

        const value = (parseInt(getComputedStyle(parent, '').width) + dx);

        parent.style.width = value + 'px'; // CHANGE WIDTH DIRECTLY
        // this.app.style.setProperty('--side-panel-width', value + 'px'); // OR CHANGE CUSTOM PROPERTY
         )
       }

Please, can you explain why is this performance issue happening and is there a way to solve it while not changing width directly?

Can you delete/overwrite an httpOnly cookie from JavaScript?

I know httpOnly cookies are designed to only be altered by the server, however is it possible to delete/overwrite an httpOnly cookie from JavaScript?

My use case is to support logout functionality from the client, even when the server is unavailable due to connectivity issues.

Currently if the server is inaccessible, the authentication cookies remain behind because the server is required to clear them.

An alternative I was thinking of was setting an “offline-logout=true” cookie from the client that the server can detect on the next request and act accordingly.

What to do when your JavaScript application doesn’t run in Android Studio?

I am making a primary application in Android Studio to know which one is the highest number when you type the number in Edit Text. But unfortunately, the application doesn’t run and crashes when I turn and run it on a Virtual phone. I don’t know why and how to fix the problem. Hope someone can help me thanks

Thank you for helping me!

Here is my code MainActivity.Java

package com.example.baitap1;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText num = (EditText) findViewById(R.id.editTextNumber);
        String text= num.getEditableText().toString();
        int mainnum = Integer.parseInt(text);

        EditText num2 = (EditText) findViewById(R.id.editTextNumber2);
        String text1= num2.getEditableText().toString();
        int mainnum2 = Integer.parseInt(text1);

            Button button = findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                TextView textView = findViewById(R.id.textview3);
                if(mainnum>mainnum2)
                    textView.setText(mainnum + "highest number");
                else if(mainnum2>mainnum)
                    textView.setText(mainnum2 + "highest number");
                else
                    textView.setText("tide");
            }

        });
    }}

Here is code from activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:rotationX="-6"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="138dp"
        android:layout_height="51dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="84dp"
        android:layout_marginEnd="8dp"
        android:padding="10dp"
        android:text="Type the number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.108"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextNumber"
        android:layout_width="198dp"
        android:layout_height="46dp"
        android:layout_marginTop="80dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.579"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="138dp"
        android:layout_height="51dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="200dp"
        android:layout_marginEnd="8dp"
        android:padding="10dp"
        android:text="Type the number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.108"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextNumber2"
        android:layout_width="208dp"
        android:layout_height="46dp"
        android:layout_marginTop="188dp"
        android:ems="10"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.577"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="368dp"
        android:text="Ket Qua"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.457"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textview3"
        android:layout_width="138dp"
        android:layout_height="51dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="432dp"
        android:layout_marginEnd="8dp"
        android:padding="10dp"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

React routes not rendering

I’m following along with this React Tutorial on YouTube but I can’t get my routes to render on own dev server.

This is what my home screen is rendering. My home screen should show a pink background underneath the navigation bar.

I suspect the error is happening in this section of my App.js code, since everything else outside of works fine:

<Routes>
  <Route exact path="/" component={HomeScreen}/>
</Routes>

I’m using react-router-dom v6.3.0

My App.js code:

import './App.css';
import { useState } from "react";
import { BrowserRouter as Router, Routes, Route} from "react-router-dom";

// Screens
import HomeScreen from './screens/HomeScreen';

// Components 
import Navbar from './components/Navbar';
import SideDrawer from './components/SideDrawer';
import Backdrop from './components/Backdrop';

function App() {
  const [sideToggle, setSideToggle] = useState(false);

  return (
    <Router>
      <Navbar click={() => setSideToggle(true)} />
      <SideDrawer show={sideToggle} click={() => setSideToggle(false)} />
      <Backdrop show={sideToggle} click={() => setSideToggle(false)} />
      <main>
        <div className="app">This is a test</div>
        <Routes>
          <Route exact path="/" component={HomeScreen}/>
        </Routes>
      </main>
    </Router>
  );
}

export default App;

My index.js code:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

ReactDOM.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
  document.getElementById("root")
);

reportWebVitals();

My HomeScreen code:

import "./HomeScreen.css";

const HomeScreen = () => {
  return (
    <div className="homescreen">
      Home Screen
    </div>
  )
}

export default HomeScreen

Hope someone’s able to give some advice to a React newbie?
Please let me know if I need to provide more info.

Running a function inside Websocket triggers many times

I’ve been trying to take advantage of the Binance Websocket to trigger buys and sells based on the live price with my own logic. I know the WebSocket is sending back live data and there might be even 5-6 or more responses at the same time, but how do I make sure I get only 1 when I close the Websockets?

I am trying to make sure it will trigger only 1 buy or 1 sell when that happens.

I am using: (works great)

'node-binance-api'

The Websocket starts from here:

binance.websockets.bookTickers('BNBBUSD', (mainTicker) => {
  var priceNow = mainTicker.bestBid;
  liveStrategy(priceNow).then(isSold => {
      // console.log('THIS IS WHEN IS CHECKED ->>>>>>');
      if (isSold == true) {
          console.log('JUST SOLD -> Setting the count to 10');
          sleep(3000).then(() => { 
              console.log("Countdown finished: ", count);
              profitCalculations(mainCurrency);
              count = 10;
          });
      }
      if (isSold == false) {
          console.log('THIS WAS A BUY ->');
          count = 10;
      }
  }).catch((isSoldErr) => {
      console.warn('Error:', isSoldErr.message);
      dumpError(isSoldErr);
  });
});

The price is being sent back into the function, this function runs continuously until a buy or a sell happens. Before triggering a buy or a sell I close the WebSocket with:

    let endpoints = binance.websockets.subscriptions();
    for ( let endpoint in endpoints ) {
        console.log("..terminating websocket: "+endpoint);
        let ws = endpoints[endpoint];
        ws.terminate();
    }

This code stops the WebSocket, but it does take about 3 seconds so I trigger the buy/sell after this like:

if (priceNow > buyPrice) {
terminateAllWebsockets();
return new Promise((resolve) => {
    sleep(5000).then(sleep => {
        marketBuyFromNoLossStrategyAmount(buySymbol,buyAmount);
        resolve(false);
    })
})

}

When it returns it basically sends back to my liveStrategy(priceNow) to trigger the profit calculations. The profitCalculations(mainCurrency); might get triggered 3-4 times or even the buy or sell. Is it something that I can do for that not to happen? So the profit or the buy & sell will trigger only once? How do I make sure that happens with my setup?

Any thoughts are most welcome!

how to convert the html to pdf including the stylings?

Scenario – I want to create a pdf from the html including all the stylings,I am using react-editor-js and then the parsing that data to get html, I am not able to find a solution that creates a searchable pdf(I can do searching too in that pdf) till now I have found libraries that creates pdf content as image which is something I am looking for now.

chrome.local.storage get set – save checkbox checked state and functionality when popup is closed

This is the last step in building my extension and I am seriously stuck. I have researched chrome.local.storage, but can’t get it to work.

I have the following in mypopup.js

let a = document.getElementById("option01");

a.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true
    });

    a.setAttribute('aria-checked', a.getAttribute('aria-checked') === 'true' ? 'false' : 'true');

    if (a.getAttribute('aria-checked') === 'true') {

        try {
            await chrome.scripting.insertCSS({
                target: {
                    tabId: tab.id,
                },
                files: ["css/option01.css"],
            });
        } catch (err) {
            console.error(`failed to insert roles CSS: ${err}`);
        }

    } else if (a.getAttribute('aria-checked') === 'false') {

        try {
            await chrome.scripting.removeCSS({
                target: {
                    tabId: tab.id,
                },
                files: ["css/option01.css"],
            });
        } catch (err) {
            console.error(`failed to remove roles CSS: ${err}`);
        }
    }
});

I have tried all different variations of set and get for chrome storage, and although I understand the concept, making it work as I want has me pulling my hair out. I’d really appreciate some help.

This is as far as I got trying to save the checkbox state (checked/unchecked) and to test adding and removing a class.

Saving the checked state and the add/remove the style sheets from the code above this is what I want to achieve.

document.addEventListener('DOMContentLoaded', function () {
    chrome.storage.local.get('enabled', function (result) {
        if (result.enabled != null) {
            a.checked = result.enabled;
        }
    });

    chrome.storage.local.set({
        'enabled': a.getAttribute('aria-checked') === 'true'
    }, function () {


    });
});

http (not https) post request in vanilla js

I am trying (for a small personal project) to send an http (not https as I don’t have it set up) to my vps running nodejs. I can send the request perfectly fine with postman, but trying to use the xmlhttprequest prints the following error to the console:

Access to XMLHttpRequest at 'http://207.154.211.105/?postBidone={%22id%22:{%22nome%22:%22esempio1%22,%22localita%22:%22esempio2%22,%22extra%22:%22esempio3%22},%22action%22:%22add%22,%22content%22:%22plastic%22}' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Do you know a way to successfully send the request?
Thanks!

Getting Uncaught TypeError: Cannot read properties of undefined (reading ‘body’)

I am new to JS and trying learn node – supertest. I have came across this error. Kindly guide me.

import { describe } from "mocha";
import supertest from "supertest";
import { expect } from "chai";

const request = supertest('https://gorest.co.in/public/v2/');

const api_token = '45faa1e4b06b3cc1d5ecfbe639235376838cf638c85f88cb9bcc04e954bbf77f';

describe('GET /user' , () =>{
it('fetching user details', (done) =>{
    request.get(`users?access-token=${api_token}`).end((err,res) =>{
       console.log(err);
        console.log(res.body);  
   
       done();

    })
})
})

Console Error Image for the reference

Focus only elements on Tab keypress with “tabindex” property defined

I am developing a web application using Vue.js. I have a data entry form with 5 fields, business need is on tab it should focus first Input box and on subsequent tabs the next next element should be focused. That i have archived using tabindex property to the elements.

Now the issue is after the form elements are over and when we hit tab it goes to the other elements where tabindex is not defined such as links and Browsers’ URL bar.

What I want is if i have 6 elements (5 textbox + 1 submit button) and i have set tabindex from 1 to 6 than again after tab at element with tabindex 6 it should again focus on tabindex 1 and ignore other links and buttons on webpage.

Output of model in tensorflow js is a object, not a tensor

I am trying to the create word detection on live camera feed using tensorflowJS in the web. (NOT NodeJS).

I have found a model which was shared on tfhub. I was trying to load that model in the web and trying to get some output. I somewhat finished the code to give some output to check before drawing on the canvas. I have tried so many versions of tfjs version to get the code working because some part of the code wasn’t working when I was using a specific version, hence I did some reading documentation and copy pasting the code.

Finally, the code below is working but I dont understand the output and how do I use that output to draw anything on the screen? Am I missing any step?

Just for the reference I am also including the tfjs version that I am using in my code.

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-core"></script> 
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-cpu"></script> 
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-tflite/dist/tf-tflite.min.js"></script>

Now the code for the detection …

const videoElement = document.getElementById("webcam"); 
var model = undefined;

// Check if webcam access is supported.
function getUserMediaSupported() {
    var state = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
    console.log(state)
    return state
}

if (getUserMediaSupported()) {
    enableCam()
} else {
    console.warn("getUserMedia() is not supported by your browser");
}

// Enable the live webcam view and start classification.
function enableCam() { 
    // getUsermedia parameters to force video but not audio.
    const constraints = {
        video: true,
    };

    // Activate the webcam stream.
    navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        videoElement.srcObject = stream; 
    });
}


videoElement.addEventListener('loadeddata', (e) => {
    //Video should now be loaded but we can add a second check   
    if (videoElement.readyState >= 3) { 
        detect()
    } 
});

async function detect() {
    $('.loading').text("loading...")
    if (!model) {
        model = await tflite.loadTFLiteModel("./ocr.tflite")
    }

    const outputTensor = tf.tidy(() => {
        // Get pixels data from an image.
        let img = tf.browser.fromPixels(videoElement)
        img = tf.image.resizeBilinear(img,[320, 320]);
        // Normalize (might also do resize here if necessary).
       // const input = tf.sub(tf.div(tf.expandDims(img), 127.5), 1);
        // Run the inference. 
        let inputTensor = tf.expandDims(img)
        console.log("INPUT-->", inputTensor);
        let outputTensor = model.predict(inputTensor);
        console.log("OUTPUT-->", outputTensor)
        // De-normalize the result.
        return tf.mul(tf.add(outputTensor, 1), 127.5)
    });
    console.log(outputTensor);

    // const input_tensor = await tf.browser.fromPixels(videoElement);
    // // const input = tf.sub(tf.div(tf.expandDims(input_tensor), 127.5), 1);

    // // const tensor = await tf.browser.fromPixels(imageElement)

    // const input = tf.tidy(() => {
    //     return tf.reshape(input_tensor, [320, 320])
    //         .div(255).expandDims(0);
    // });
    
    // model.predict(input).then(predictions => {
    //     console.log('Predictions: ');
    //     console.log(predictions);
    // });


    // Run inference and get output tensors.
    // let outputTensor = model.predict(input);
    // console.log(outputTensor.dataSync());
//     let input = tf.image.resizeBilinear(tf.browser.fromPixels(input_tensor), [320, 320]);
//     input = tf.cast(tf.sub(tf.div(tf.expandDims(input), 127.5), 1), 'int32');

//     // Run the inference and get the output tensors.
//     let result = await model.predict(input);
//     console.log(result)
//    // renderDetectionResult(result);
//     $('.loading').text("loaded")
}

Microsoft Dynamic CRM

If user, change values of customer type or available services then system will create a new line of log as shown below
Changed , Previous Value: , Current Value: