How to access developer tools on android chrome on Honeywell EDA 70?

On Chrome on Android phone, we can use remote debugging (Source).

But this needs USB portal and Honeywell EDA 70 has no USB port. How to open developers tools here?

Basically it is scanning a QR code and our webpage reads it using onScan: function(scannedData) but the field are not being properly populated and we cannot simulate the QR code scan on a computer. So we need to debug this and we can’t access developer tools on Honeywell device.

How to show cart quantity in JavaScript on Cart Page with WooCommerce

I would like to show the cart quantity on the cart page i.e. Shopping Cart(2).

This should show next to the page heading. Below is the example of what I’m busy with example

I’ve added JavaScript code but it does not change regardless of how many products there is in the cart.

The JavaScript Code I inserted

<script>
        // Function to get the cart quantity using JavaScript
function getCartQuantity() {
    // Check if WooCommerce cart object exists
    if (typeof wc_cart_params === 'undefined') {
        return 0;
    }

    // Get the cart quantity
    console.log(wc_cart_params);
    var quantity = parseInt(wc_cart_params.cart_contents_count);
    return isNaN(quantity) ? 0 : quantity;
}

// Function to display the cart quantity on the page
function displayCartQuantity() {
    var quantity = getCartQuantity();
    document.getElementById('cart-quantity').textContent = quantity;
}

    </script>

The HTML code on front end

SHOPPING CART (<span id="cart-quantity"></span>)

The JavaScript I inserted in the element

<body onload="displayCartQuantity()">

How do I get the values of a nipple.js joystick

I’m having 2 joysticks and want to get their position and size properties with JS. The official documentation s hard for me to understand, because it is very very theoretical and has no practical examples.

I tried using the console to get the properties by checking the value of the joysticks, but I miserably failed getting any information out of that.

All I need is to get both joystick centers and stick positions.

Here is my js:

/touchdevice is set to true the moment a touch action happens 
if(touchdevice) {

    /mstick and astick are predefined

    mstick = document.querySelector("#mstick");
    astick = document.querySelector("#astick");

    window.mstick = nipplejs.create({
      color: "#000000",
      shape: "square",
      zone: mstick,
      threshold: 0.5,
      fadeTime: 300
    });

    window.astick = nipplejs.create({
      color: "#000000",
      shape: "circle",
      zone: astick,
      threshold: 0.5,
      fadeTime: 300
    });
    
  }

React-router-dom: Whenever I click on a link in my navbar(Header.js file), the url changes but not the page

I have used react-router-dom version @5.2.0 in my react application. Whenever I click on the link in navbar(Header.js file), the url in the address bar changes but the page that the link is targeting does not changes. But when I click the refresh button on the browser, the page changes

Here are my code files:

App.js

import React from 'react'
import './App.css';
import Header from './Header';
import Home from './Home';
import Checkout from './Checkout';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {

  return (

    <Router>
      <div className="app">
        <Header />
        <Switch>

          <Route path="/checkout" exact>
            <Checkout />
          </Route>
          <Route path="/" exact>
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>


  );
}

export default App;

Header.js

import React from 'react'
import './Header.css'
import SearchIcon from '@mui/icons-material/Search';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import { Link } from "react-router-dom";
import { useStateValue } from "./StateProvider";
function Header() {
  const [{ basket }, dispatch] = useStateValue();

  return (
    <div className='header'>
      <Link to="/">
        <img className='header_logo' src="http://pngimg.com/uploads/amazon/amazon_PNG11.png" alt="" />
      </Link>

      <div className="header_search"><input type="text" className='header_searchInput' /><SearchIcon className='header_searchIcon' /></div>
      <div className="header_nav">
        <div className="header_option">
          <span className='header_optionLineOne'>Hello Guest</span>
          <span className='header_optionLineTwo'>Sign In</span>
        </div>
        <div className="header_option">
          <span className='header_optionLineOne'>Returns</span>
          <span className='header_optionLineTwo'>Orders</span>
        </div>
        <div className="header_option">
          <span className='header_optionLineOne'>Your</span>
          <span className='header_optionLineTwo'>Prime</span>
        </div>
        <Link to="/checkout">
          <div className="header_optionBasket">
            <ShoppingCartIcon />
            <span className="header_optionLineTwo header_basketCount">{basket?.length}</span>
          </div>
        </Link>
      </div>
    </div>
  )
}

export default Header

Combine Latest – same observable returning different values

How to return different values from the same observable without multiple calls? I intend to subscribe just one time the firstObs$, but return the values and sumFromValues.

combineLatest([
            this.firstObs$,
            this.firstObs$.pipe(
                switchMap(someOperation => {
                    const sum = someOperation.first + someOperation.second
                    return sum
                })
            ),
          
            this.anotherObservable$,
        ])
          .subscribe(([values, sumFromValues, anotherValues]) => {
            }

auto Submit Form Only when Checkbox is Checked

auto Submmiting a form only when a checkbox is checked.

so i’ve been searching for something like this for awhile and didn’t found the proper answer, i’ve got a chechbox input that has 2 diffrent roles depending on whether it’s checked or unchecked. the answers that i’ve found were something like this:

<input onChange="this.form.submit()" ... />

or html:

<form method="post" id="form2">
        
  <input type="checkbox" value="on" id="switch" onchange="submit()">      
</form>

js:

function submit () {
$("#switch").change(function() {
        console.log($("#switch").val());
        $('#form2').delay(200).submit();
    });
}

as you can see this function will work whether the input gets checked or unchecked and i only want it to work when it gets checked (or only when it gets unchecked).
i can use a php trick to deactivate the onchange event temporarily but i don’t think that’s a good way to do it.
can anyone help here?
thanks

Access-Control-Allow-Origin Is set but fetch is blocked by CORS

I want to allow CORS access to static files in a folder, using curl -i I can see that the Access-Control-Allow-Origin * is set, yet when trying to use the fetch api the request is blocked.

// Allow any origin from Nginx to that folder ---
location /static/ {
  add_header Access-Control-Allow-Origin *;
} 

// Js ----
fetch('domain.com/static/file2', {method: 'GET'})
.then() ...

Why is the header not working when using fetch, is that not enough to allow CORS ?

webpack5 how to know a file is newly generated (other than cached) in a plugin?

webpack5 how to know a file is newly generated (other than cached) in a plugin?

  apply(compiler) {
    // Webpack 5
      compiler.hooks.emit.tapAsync('my-webpack-plugin', (compilation, callback) => {
        const newGenerated = compilation.assets.filter(??) // files newly generated, (with different hash, different content)
        const cached = compilation.assets.filter(???) // the same file as previous run
      });

  }

Thanks!

Vector Stores storage in LangChain

I am working with LangChain for the first time. Due to data security, I want to be sure about the storage of langchain’s vector store storage. I am using HNSWLib vector store, which mentions it is an in-memory store. What does it mean? Does Langchain/vector stores store any data in its servers?

https://js.langchain.com/docs/modules/indexes/vector_stores/integrations/hnswlib
https://github.com/nmslib/hnswlib

Unable to run ‘npm run dev’ or ‘yarn run dev’

Description:

I am facing an issue where I am unable to run the npm run dev or yarn run dev command in my project. Whenever I try to execute these commands, they do not work as expected.

Troubleshooting Steps:
I have attempted a couple of troubleshooting steps based on suggestions from others in the community. First, I deleted the node_modules folder in my project directory to ensure a fresh installation of dependencies. Additionally, I cleaned the npm cache using the appropriate command. Despite these attempts, the problem persists and I am unable to run the development server successfully. I would greatly appreciate any insights or further troubleshooting suggestions from the Stack Overflow community.

Terminal Output

[ERROR] Unexpected "xff"

    ../../package.json:1:0:
      1 │ ��yarn init v1.22.19
        ╵ ^

failed to load config from C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactvite.config.js
error when starting dev server:
Error: Build failed with 1 error:
../../package.json:1:0: ERROR: Unexpected "xff"
    at failureErrorWithLog (C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:1624:15)
    at C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:1266:28
    at runOnEndCallbacks (C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:1046:63)
    at buildResponseToResult (C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:1264:7)
    at C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:1377:14
    at C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:678:9
    at handleIncomingPacket (C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:775:9)
    at Socket.readFromStdout (C:UsersGongoolDesktopReal-Estate-LandingPage-Using-Reactnode_modulesesbuildlibmain.js:644:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:324:12)




How to change a props.children state?

Down below is <SidebarOption /> and <SideBarConatiners /> these are both items that have a state called open to highlight them whenever they have been clicked and they are inside the <SidebarItemList />

       <SideBarItemList>
        <SidebarOption id="1" name="Startsida: Fjärrvärmenät" />
        <SidebarOption id="2" name="Startsida: Användare" />
        <SideBarContainers id="3" name="Allmänt" 
        options={[
            "Senaste uppdaterad", "Visa Pluginmoduler", "Öppna Arkivet", "Personliga inställningar", 
            "Regionala inställningar", "Om Driftportalen"
            ]}/>
        <SideBarContainers id="4" name="Planering" notPressAble={[0, 6, 11]}
        options={[
            "Aktiviteter:", "+ Ny Aktivitet", "Visa Alla Öppna", "Visa Försenat", "Visa Alla Stängda", "Visa Alla Kategoriserat",
            "Att göra:", "+ Ny Att göra", "Visa Alla Öppna", "Visa Alla Stängda", "Visa Alla Kategoriserat", 
            "Personal planering:", "+ Ny post", "Visa Alla enkel"
        ]} />
        </SideBarItemList>

Down below is the <SideBarItemList /> class, i want to change the open value of the items soo that if one item is higlighted and another item is pressed i want all the other items to set the state open to false so that only one item state open can be set to true the problem is that the items state open does not seem to be extensible what can i do about this?

import { Component } from "react";

class SideBarItemList extends Component{
    constructor(props){
        super(props);
        this.state ={
            sidebarItems: null
        };
    }

    static getDerivedStateFromProps(props, state){
        return{
            sidebarItems: props.children
        };
    }

    handleItems = () => {
        let openNumber = null;
        for(let x = 0; x < this.state.sidebarItems.length; x++)
        {
            if(this.state.sidebarItems[x].open = true)
            {
                openNumber = x;
            }
            this.state.sidebarItems[x].open = false;
        }

        this.state.sidebarItems[openNumber].open = true;
    }

    render(){
        return(
            <div onClick={this.handleItems}>
                {this.state.sidebarItems}
            </div>
        )
    }
}

export default SideBarItemList;

how to use loginRedirect with Vuejs and Msal

I’m currently working on integrating Azure authorization into my Vue.js Single Page Application (SPA) using the msal.js package.
My goal is to find an elegant way to save the accessToken to localStorage.
Since it’s an SPA, I acquire the token when the application loads for the first time. After the redirect, I have to refresh the page for the token acquisition function to run.

Many websites use a middle page that shows a countdown (e.g., “You will be redirected in 5, 4, 3, 2, 1…”) to provide a better user experience.
I want to implement something similar to enhance the UX feeling for the user. I’m trying to use the loginRedirect function with localStorage configured.

However, I’m facing a few issues:

First, for some reason, the cache items are saved in sessionStorage instead of localStorage as I have configured. I’m not sure why this is happening. Do you have any ideas?

Second, on the redirect page, when I call msalInstance.getAllAccounts(), it returns an empty list. I’m not sure what I’m doing wrong in the flow.

Here’s the relevant code:

In Mystore.ts:

const MSAL_CONFIG = {
  auth: {
    clientId: "clientid",
    authority: "authorities.signIn",
    knownAuthorities: [...knownAuthorities],
    redirectUri: "http:://localhost:3000/redirect-page",
  },
  cache: {
    cacheLocation: "localStorage",
    storeAuthStateInCookie: true,
  },
};

initMsalInstance() {
  this.msalInstance = new msal.PublicClientApplication(MSAL_CONFIG);
},

openLoginRedirect() {
  this.initMsalInstance();
  this.msalInstance.loginRedirect();
},

async fetchAccessToken() {
  // Get all accounts from the cache
  const accounts = this.msalInstance.getAllAccounts();
  // Perform some work if accounts are found, such as getting the token and saving it...
}

I’m not using promises as the documentation states that it’s not recommended in this case:

IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.

Then, the page redirects to the redirect page in order to fetch the token.

In the redirect page:

<template>
  <div>You will be redirected in 5 seconds...</div>
</template>

<script lang="ts" setup>
import { onBeforeMount } from "vue";
import { mystore } from "@/store";
import router from "@/router";

onBeforeMount(async () => {
  await mystore.fetchAccessToken();
  router.push({ name: "shop-home-page" });
});
</script>

<style scoped lang="scss">
</style>

The redirect page calls fetchAccessToken, but this.msalInstance.getAllAccounts() always returns 0. I’m not sure why this is happening.

Does my flow look okay? Is there something different I should be doing? I prefer not to use promises with loginRedirect or loginPopup in MSAL as it’s not recommended.

thank you!

How to Properly Define Execution Order in NestJS Interceptors with Dependency Injection?

I am working on a NestJS application, where I need to intercept a GET request. The interceptor accepts two parameters; the first one is an array and the second one is a service that is injected. I want to make sure that the DataConsistencySourceSetter interceptor (which sets sources for data consistency check) is executed first, and then the DataConsistencyChecker interceptor (which checks for data consistency) is executed.

However, defining it in the current way makes the interceptor global and the execution order is not guaranteed. How can I ensure a defined order of execution for these interceptors?

Here is the snippet of my code for the interceptors:

@Injectable()
export class DataConsistencyChecker implements NestInterceptor{
    constructor(private readonly monitoringService: MonitoringService) {};

    async intercept(context: ExecutionContext, next: CallHandler<any>): Promise<Observable<any>> {
        logger.debug("Entered DataConsistencyCheckInterceptor");
        const req = context.switchToHttp().getRequest();
        const sources: Sources[] = req.sources;
        const consistencyLevel = req.query._consistency;  // consistencyLevel is a query parameter

        if (consistencyLevel === LatencyLevel.HIGH) {
            const isConsistencyMet = await this.monitoringService.isAlertConditionMet(sources);
            
            if (!isConsistencyMet) {
                throw new ForbiddenException("Data consistency check failed for one or more sources");
            }
        }

        return next.handle();
    }
}

@Injectable()
class DataConsistencySourceSetter implements NestInterceptor {
    constructor(
        private readonly sources: Sources[]
    ) {}

    intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
        logger.debug("Entered DataConsistencySourceSetter");
        const req = context.switchToHttp().getRequest();
        req.sources = this.sources;
        return next.handle();
    }
}

export class DataConsistencyInterceptorFactory {
    static setSources(sources: Sources[]): NestInterceptor {
      return new DataConsistencySourceSetter(sources); 
    }
}

Here’s the relevant part of the controller:

@Controller('payment')
@UseInterceptors(HttpResponseTransferInterceptor)
@UseFilters(HttpExceptionFilter)
export class ApiController {
    constructor(
        private readonly apiService: ApiService,
        private readonly ingestService: IngestService
    ) {}

    @Get()
    @UseInterceptors(DataConsistencyInterceptorFactory.setSources([Sources.LOAN]), DataConsistencyChecker)
    async getState(@Query() requestDto: PaymentStateRequestDto, @Req() req: any) {
        const result = await this.apiService.fetchPaymentStates(requestDto);
        return result.map(r => plainToInstance(PaymentStateResponseDto, r));
    }
}

The interceptor is defined and applied on a route inside a controller, but how can I ensure the order of the interceptors?

Thanks in advance!

In my attempt to solve this problem, I tried to define the order of the interceptors by stacking the @UseInterceptors decorators as you can see in the controller:

@Get()
@UseInterceptors(DataConsistencyInterceptorFactory.setSources([Sources.LOAN]), DataConsistencyChecker)
async getState(@Query() requestDto: PaymentStateRequestDto, @Req() req: any) {
    const result = await this.apiService.fetchPaymentStates(requestDto);
    return result.map(r => plainToInstance(PaymentStateResponseDto, r));
}

I was expecting that NestJS would execute the interceptors in the order they are declared inside the @UseInterceptors decorator, meaning that the DataConsistencyInterceptorFactory.setSources([Sources.LOAN]) would run first, followed by the DataConsistencyChecker.

However, I found that the execution order is not consistent with my expectation. The DataConsistencyChecker runs before DataConsistencyInterceptorFactory.setSources([Sources.LOAN]), causing an inconsistency in the data consistency check because the sources aren’t set before the check happens. I am unsure about how to fix this.

Knowing which command was executed in vscode terminal in a vscode extension

I am trying to run certain methods in my vscode extension when a git checkout <branch_name> command is executed. One of the ways that works is through the vscode UI that allows me attach an event listener. But since the user can also update their branch using the terminal using git checkout ... how can I trigger some function based on what’s executed in the terminal? Is there a way to attach an event listener to the vscode terminal that allows me to know which commands are executed?

Trouble with d3.js: How can I assign values to predefined scales and accurately show -ve values on -ve, the +ve side and neutral values on both sides?

I tried to assign values to pre-defined Scale +ve, -ve or neutral like good, bad or neutral. Values are successfully assigned but show in just one way, can you guide me to to show it right way in d3.js
below is html and script.js file data. Assigning values to predefined scales in d3.js, how can I show -ve values on the +ve side and neutral values on both sides

Trouble with d3.js: How can I assign values to predefined scales and accurately show -ve values on the +ve side and neutral values on both sides?

<html>
  <head>
    <title>Survey Data Visualization</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
  </head>
  <body>
    <div id="chart"></div>

    <script src="script2.js"></script>
  </body>
</html>

# Here is script.js code

const data = [
  { category: "Question 1", value: 75, value1: 65, value2: 55 },
  { category: "Question 2", value: 62, value1: 52, value2: 42 },
];

const AnswerScale = [
  { value: "bad" },
  { value1: "neutral" },
  { value2: "good" },
];

// Set up chart dimensions
const margin = { top: 50, right: 150, bottom: 50, left: 150 };
const width = 800 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;

// Create SVG element
const svg = d3
  .select("#chart")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);

// Set x-axis scale
const xScale = d3.scaleLinear().domain([-100, 100]).range([0, width]);

// Set y-axis scale
const yScale = d3
  .scaleBand()
  .domain(data.map((d) => d.category))
  .range([0, height])
  .padding(0.1);

// Set color scale for different values
const colorScale = d3
  .scaleOrdinal()
  .domain(Object.keys(data[0]))
  .range(["green", "red", "yellow"]);

// Create stacked bar chart
svg
  .selectAll(".bar")
  .data(data)
  .join("g")
  .attr("class", "bar")
  .attr("transform", (d) => `translate(0, ${yScale(d.category)})`)
  .selectAll("rect")
  .data((d) => Object.entries(d).slice(1))
  .join("rect")
  .attr("x", (d) => xScale(Math.min(0, d[1])))
  .attr("y", 0)
  .attr("width", (d) => Math.abs(xScale(d[1]) - xScale(0)))
  .each(function (d){
    console.log("ddddd", d)
    if (!"bad"){
      return (d) => xScale(d[1]) * -1;
    } else if (!"neutral") {
      return (d) => xScale(d[2]) + (xScale(d[0]) - xScale(d[2])) / 2;
    } else if (!"good") {
      return (d) => xScale(d[3]);
    }
  })
  .attr("height", yScale.bandwidth())
  .style("fill", (d) => colorScale(d[0]));

// Add x-axis
svg
  .append("g")
  .attr("class", "x-axis")
  .attr("transform", `translate(0, ${height})`)
  .call(d3.axisBottom(xScale).ticks(20));

// Add y-axis
svg.append("g").attr("class", "y-axis").call(d3.axisLeft(yScale));

// Add legend
const legend = svg
  .append("g")
  .attr("class", "legend")
  .attr("transform", `translate(${width +20}, 0)`);

const legendData = AnswerScale.map((d) => Object.values(d)[0]);

legend
  .selectAll("rect")
  .data(legendData)
  .join("rect")
  .attr("x", 0)
  .attr("y", (d, i) => i * 20)
  .attr("width", 15)
  .attr("height", 15)
  .style("fill", (d, i) => colorScale(`value${i}`));

legend
  .selectAll("text")
  .data(legendData)
  .join("text")
  .attr("x", 20)
  .attr("y", (d, i) => i * 20 + 12.5)
  .text((d) => d);