Exceptions while creating dirs with getDirectoryHandle in specific cases

I’m trying to create a web app that can modify a directory in order to install mods for a game for the user. It uses FileSystemDirectoryHandle. However, for some reason, using .getDirectoryHandle("dirname", { create: true }) throws an exception of

DOMException: An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk.

if I drag the directory into it. If I pick the directory using window.showDirectoryPicker(), it doesn’t happen.

It also only happens for directories in .local and subfolders. As for anything about that directory in particular, it has drwx------ from ls -la. Using the utility lsd fails in anything inside of the .local directory, but /usr/bin/ls works fine, and Nautilus works fine in there too. If it matters, I’m on Ubuntu and using Chromium.

Here’s a demo page (needs to be hosted on localhost):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Testing DragN'Drop</title>
    <style>
      body {
        background: #0a2d2e;
        color: #fff;
        font-family: system-ui, sans-serif;
      }
    </style>
  </head>
  <body>
    <p>Drag anywhere!</p>
    <button>Browse.</button>
    <script>
      addEventListener("dragover", (e) => e.preventDefault(), false);
      addEventListener("drop", (e) => {
        e.preventDefault();
        e.dataTransfer.items[0].getAsFileSystemHandle().then(handleHandle);
      });
      document.querySelector("button").onclick = async () => {
        const handle = await window.showDirectoryPicker();
        handleHandle(handle);
      };
      const handleHandle = (handle) => {
        console.log(handle);
        handle
          .getDirectoryHandle("never", { create: true })
          .then(console.log)
          .catch(console.error);
      };
    </script>
  </body>
</html>

(I understand that this question could fit more on other Stack Exchange sites, but I’m asking here first because I don’t know of any yet are that good of a fit.)

How to disable submit button after click

Im currently working on an extension where I currently have a submit button and input. When a user is clicking on the submit button, the user should not be able to click on the submit button anymore and should be disabled and if the user has already entered a user ID then it should also not be able to click on submit again.

How can I be able to disable the submit button when a user has clicked it?

popup.js

function get_discord_id(callback) {
    chrome.storage.sync.get(["discord_id"], (result) => {
        callback(result.discord_id);
    });
}

function set_discord_id(discord_id) {
    chrome.storage.sync.set({ discord_id: discord_id }, () => {});
}

window.addEventListener("DOMContentLoaded", () => {
    // check if discord ID is already stored
    get_discord_id((discord_id) => {
        if (discord_id != null) {
            let input = document.getElementById("discord-id-input");
            input.value = "";
            input.placeholder = discord_id;
        }
    });

    document.getElementById("discord-id-button").addEventListener("click", () => {
        let input = document.getElementById("discord-id-input");
        let value = input.value;
        input.value = "";
        input.placeholder = value;

        chrome.runtime.sendMessage({ discord_id: value }, function(response) {
        });

        set_discord_id(value);
    });
});

HTML

<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="../css/style.css">
    <script src="../js/popup.js"></script>
</head>

<body>
    <div class="text-center">
        <div class="form-control mt10">
            <input type="text" id="discord-id-input" name="discord-id-input" placeholder="Discord ID">
            <button id="discord-id-button" type="submit" class="submit" onclick="this.disabled=true;"></button>
            <a class="help-text">ENTER DISCORD USER ID AND SUBMIT</a>
        </div>
    </div>
</body>

CSS

#discord-id-button {
    box-shadow: 0 0 10px 0 #251431;
    border-radius: 8px;
    transition: 0.3s;
}

#discord-id-button:hover {
    box-shadow: 0 0 10px 6px #251431;
}

#discord-id-input {
    box-shadow: 0 2px 1px 0 #251431;
    border-radius: 8px;
}

body {
    background-image: url('../images/bg2.jpg');
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 250px;
    padding: 5px 15px 30px 15px;
    width: 500px;
}

.text-center {
    text-align: center;
}

*:focus {
    outline: none;
}

.form-control {
    align-items: center;
    display: flex;
    justify-content: center;
}

label {
    display: block;
}

select,
input {
    background: #582e79;
    border-radius: 8px;
    border: 1px #582e79;
    color: #999;
    margin-left: 60px;
    margin-top: 135px;
    padding: 5px 10px;
    text-align: center;
    width: 150px;
}

.mt10 {
    margin-top: 20px;
}

.submit {
    background-color: transparent;
    background-image: url("../images/arrow.png");
    background-position: center center;
    background-repeat: no-repeat;
    border: none;
    height: 15px;
    width: 50px;
    margin-left: 15px;
    margin-top: 135px;
    outline: none;
    padding-bottom: 25px;
}

.help-text {
    position: fixed;
    color: #FFFF;
    font-size: 9px;
    color: #999;
    margin-top: 190px;
}

How to set a particular state of a parent component from child component in React?

I’m new to React. I’m trying to do simple validation of a form elements. I’m stuck at validating input data and setting the ‘name_error’ state as the error msg inside <p> tag. Leaving my code below

// App.js

import React, { Component } from 'react';
import ValidateName from './component/validation';
import Modal from './modal';

class Home extends Component {
  state = {
    show: false,
    name: "",
    name_error: ""
  }

  handleChanges = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name] : value})
  }

  render() {
    console.log(this)
    return (
      <div>
        <div className='Main'>
          {/* < Main /> */}
          <button id='add' onClick={()=>{this.setState({show: true})}}>Add</button>
        </div>
        {this.state.show && 
          <Modal>
            <form>
              <div className='modalContainer'>
                <b className='title'>Register</b>
                <button id='xmark' onClick={()=>{this.setState({show: false})}} >&times;</button>
                <label for='name' >Name</label><br />
                <input type="text" id='name' placeholder='Enter your name here' name="name" onChange={this.handleChanges}/><br />
                < ValidateName content={this.state.name} />
                <button type='submit'>Sign Up</button>
                <button>Cancel</button>
              </div>
            </form>
          </Modal>}
      </div>
    );
  }
}
export default Home;

// Modal.js
import React, { Component } from 'react';

class Modal extends Component {
    render() { 
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
}
 
export default Modal;

//validation.js
class ValidateName extends Component {
    err1 ='Please enter any name';
    err2 = 'Use only letters in this field';
    render() { 
        const ren = this.props.content.length === 0 ? (<p>{this.err1}</p> ) : 
                (this.props.content.match(/[a-zA-Z]+$/) ? '' : <p>{this.err2}</p>)
        return ren;
    }
}

Please suggest an idea to set name_error as ‘Please enter any name‘ or ‘Use only letters in this field‘ when user enters wrong input

Stream transformer from async generator and options

Nodejs streams support generating a transform stream from an async generator function. As the docs state:

async generators are effectively a first-class language-level stream construct at this point1

const tf = stream.Duplex.from(async function* (source) {
  for await (const chunk of source)
    yield chunk;
});

However, it appears to not support any options argument, in contrast to many other stream-construction methods. E.g. objectMode is apparently hardcoded to true2, but similar issues arise for e.g. highWaterMark. The docs state:

Attempting to switch an existing stream into object mode is not safe3

(nothing about switching it off)

Therefore the missing options parameter is confusing to me.

Perhaps there are reasons, why such streams should always be in object-mode, but i don’t see them. Similar to e.g. readable streams, a transformer like this makes perfect sense to me (xor operation for demo purposes, imagine e.g. deflate):

const tf = stream.Duplex.from(async function* (source) {
  for await (const chunk of source) {
    for (let i = 0; i < chunk.length; i++) chunk[i] ^= 0x7C;
    yield chunk;
  }
});

I couldn’t find anything potentially difficult about adding an options parameter either. Therefore:

Is there a way to change options when creating streams this way?
(if not, why?)

setting cookie in php with jquery ajax call

I am trying to set a cookie in PHP using an AJAX call with jQuery.

This is my AJAX call, which is in a view component.

$.ajax({
      url: '/cookie',
      type: "POST",
      data: {'style': style},
      success: function(){ alert('cookie: success')},
      error: function(data){alert(data)}
})

This is my route:

Route::post('/cookies', ['uses' => $namespacePrefix . 'CookieController@cookieSet', 'as' => 'cookieSet']);

This is about as far as I got. I’ve tried to send it to the CookieController which is empty right now; I’m not sure what the next step needs to be. I’ve tried using the Controller to set the cookie but I don’t seem to understand the jQuery AJAX call, perhaps?

Getting a 500 error everytime

How could I inflate data ,I use Pako.js,php gzdeflate ,client server websocket connect

How could I inflate data ,I use Pako.js,php gzdeflate

server and client use websocket pass data

javascript

      websocket.onmessage = function (e) { 
        // var c = new Uint8Array(e.data.arrayBuffer())



    var blob = e.data;
    var reader = new FileReader();
    reader.readAsBinaryString(blob);
    reader.onload = function (evt) {
        console.log(evt.target.result)
      var data = pako.inflate(evt.target.result, { to: `string` })
      
      console.log(JSON.parse(data))
    };

php

        $data = gzdeflate('asdfsadf11');
        foreach($server->connections as $conn) {
            $server->push($conn, $data,WEBSOCKET_OPCODE_BINARY);
        }

not work

forloop div event listeners not adding/removing classes

if (div.id === 'firstDiv')
            {
                div.addEventListener('click', function() {
                        div.classList.remove('w-1/4')
                        div.classList.add('w-full')
                })
            }

I have this code block in a for loop, it checks the id of each div in the loop, and adds an event listener to it. However, while the event listener works if I console.log it, it doesn’t actually do anything with the classList

Click on the text and play the sound – any solution?

Dear Stackoverflow community,

I have these sentences on an HTML below. Each sentence has its voice clip in MP3. I want to find the simplest javaScript code for playing the voice clip. I mean if I click on a text of a sentence the voice clip starts to play. I don’t want buttons for clicking, but making the text clickable. Please, write me the simplest solution include an example HTML for this project. Thanks in advance from Hungary.

<html>
<head>

</head>
<body>

<h2>ENGLISH HOMONYMS</h2>

<p>The bandage was wound around the wound.</p>
<p>The farm was used to produce produce.</p>
<p>The dump was so full that it had to refuse more refuse.</p>
<p>We must polish the Polish furniture.</p>
<p>He could lead if he would get the lead out.</p>
<p>The soldier decided to desert his dessert in the desert.</p>

</body>
</html>

Set node-notifier left-top icon

In my Node.js application I implemented notifications, with the code like this:

const notifier = require('node-notifier');
const path = require('path');

notifier.notify(
  {
    // appID: "appID",
    title: "title",
    subtitle: "subtitle",  // doesn't work :(
    message: "message",
    icon: path.resolve(__dirname, 'info.png'), 
    sound: true,
    timeout: 10,
    wait: false
  },
  function (err, response, metadata) {
    // Response is response from notification
    // Metadata contains activationType, activationAt, deliveredAt
  }
);

If appID parameter is not specified, the result looks as follows:

enter image description here

…which includes preset default left-top icon and caption “SnoreToast”.


If I set my own appID parameter, the caption changes to desired text, however icon disappears:

enter image description here


Is it possible to set a custom left-top icon for this type of notification?

TypeError – Cannot read property ‘use’ of undefined when using i18next

I have a project with the following dependencies:

 "dependencies": {
    "@hapi/joi": "^17.1.1",
    "bcrypt": "^5.0.1",
    "config": "^3.3.7",
    "express": "^4.17.3",
    "express-async-errors": "^3.1.1",
    "express-rest-i18n": "^1.0.1",
    "http-status-codes": "^2.2.0",
    "i18next": "^21.6.14",
    "i18next-http-backend": "^1.4.0",
    "i18next-http-middleware": "^3.2.0",
    "joi": "^17.4.2",
    "lodash": "^4.17.21",
    "mongoose": "^6.2.4",
    "validator": "^13.7.0"
  },

my i18n configuration code is as following:

const i18next = require("i18next").default;
const Backend = require("i18next-http-backend").default;
const i18nextMiddleware = require("i18next-http-middleware");

i18next
  .use(Backend)
  .use(i18nextMiddleware.LanguageDetector)
  .init({
    backend: {
      loadPath: __dirname + `/locales/{{lng}}/{{ns}}.json`,
    },
    fallbackLng: "en",
    preload: ["en"],
  });

module.exports = { i18next };

My app code is as following:

const { i18next } = require("../locales/i18n");
const messages = require("../locales/en/translation.json");
const i18nextMiddleware = require("i18next-http-middleware");

require("express-async-errors");
const express = require("express");

const app = express();
app.use(express.json());
app.use(i18nextMiddleware.handle(i18next));

app.get("*", (req, res) => {
  const response = req.t("greeting");
  res.status(200);
  res.send(response);
});

const port = process.env.PORT || 3000;
module.exports = app.listen(port, () =>
  console.log(`Listening on port: ${port}`)
);

When I start the application by running npm start, I receive the error: TypeError: Cannot read property ‘use’ of undefined

This error exist because Backend in the configuration file is undefined.
I have used https://www.npmjs.com/package/i18next-http-middleware as a resource.

Anyone have an idea why I’m receiving this error and how to fix this?

Thanks in advanced!!!

How to make countdown start after clicking a button using local storage

if(localStorage.getItem("total_seconds")){
    var total_seconds = localStorage.getItem("total_seconds");
} 
else {
        var total_seconds = 6*10;
} 
var minutes = parseInt(total_seconds/60);
var seconds = parseInt(total_seconds%60);

function countDownTimer(){
    if(seconds < 10){
        seconds= "0"+ seconds ;
    }
    if(minutes < 10){
        minutes= "0"+ minutes ;
} 
document.getElementById("quiz-time-left").innerHTML = "Time Left :"+minutes+"minutes"+seconds+"seconds";
    if(total_seconds <= 0){
        setTimeout("document.quiz.submit()",1);
        
    } else {
        total_seconds = total_seconds -1 ;
        minutes = parseInt(total_seconds/60);
        seconds = parseInt(total_seconds%60);
        localStorage.setItem("total_seconds",total_seconds)
        setTimeout("countDownTimer()",1000);
} 
} 
setTimeout("countDownTimer()",1000);

Here is the countdown code I copied, I want this counter to start after button is clicked but I can’t seem to succed I couldn’t find a way to put the onclick working function would be good if I could receive some suggestions and tips

Dart Uint8list to javascript/node ArrayBuffer

I’m trying to pass the output from the microphone in a Flutter app to a Node server that proxies a Speech to Text service via a websocket. The microphone produces a Uint8list which I’m trying to convert to a javascript ArrayBuffer and send over the websocket. The node service works ok with other clients and on inspection is receiving data that looks like from the websocket:

<Buffer f9 ff fa ff f9 ff f7 ff f5 ff f7 ff f8 ff f5 ff f2 ff f0 ff f5 ff f7 ff f1 ff f2 ff f1 ff f2 ff f6 ff f5 ff f2 ff f4 ff f7 ff f7 ff f7 ff f9 ff fe ff ... 2922 more bytes>

However with the Flutter app it recieves data that looks like:

[
    7,  13, 114, 101,  99, 111, 114, 100, 105, 110, 103,  68,
   97, 116,  97,  13,   4,   7,   7, 115, 117,  99,  99, 101,
   ...
]

which can’t be consumed by the STT service. Can anyone help with this? The STT service expects audio data in the following format:


    - PCM format
    - One channel
    - 16 bits per sample, 8,000 or 16,000 samples per second (16,000 bytes or 32,000 bytes per second)
    - Two-block aligned (16 bit including padding for a sample)

It’s the last requirement that’s tripping me up I believe.

NuxtJS and event bus

I’m trying to create an event from an instance property in nuxt, however the event is not emitted or received.

plugins/internal/bus.js

import Vue from 'vue';

const eventBus = {}

eventBus.install = function (Vue) {
  Vue.prototype.$bus = new Vue()
}

Vue.use(eventBus)

plugins/internal/index.js

import Vue from 'vue';

export default function (_ctx, inject) {
  const notify  = function (msg) {

    console.log('emitting', msg);

    setInterval(() => {
      this.$bus.$emit('add', msg);
    }, 500);
  }
   .bind(new Vue());

  inject('notify', notify);
}

nuxt.config.js

  plugins: [
    '~/plugins/internal/bus.js',
    '~/plugins/internal/index.js',
    ...
  ]

And in my component,

  mounted() {
    this.$bus.$on('add', (val) => {
      console.log(val);
    })
    this.$bus.$on('close', this.onClose)
  },

Doing this.$notify({ foo: 'bar' }), calls the instance property correctly, however either the event is not emitted or is not received, frankly not sure how to debug this. What am I missing here?

I want to change my navbar from login to logout when the user is already login ESJ NodeJs

My problem here is when the user is already logged in, I want to change my navbar to logout. I am using Nodejs and Ejs templates for my web project. My code is below. please help me to figure this out. I am also using Level 1 Authentication. I am trying to do basic first before I do the hashing. Thank you very much!

APP.JS

//jshint esversion:6

const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const res = require("express/lib/response");

const app = express();


app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));



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

const userSchema = {
    firstname: String,
    lastname: String,
    email: String,
    password: String,
    conpassword: String,
    role: String
};
const User = new mongoose.model("User", userSchema);

app.get("/", function (req, res) {
    res.render("main");
});

app.get("/login", function (req, res) {
    res.render("login");
});


app.get("/register", function (req, res) {
    res.render("register");
});

app.get("/logout", async (req, res) => {
    res.redirect("/")

});


app.post("/login", function (req, res) {
    const username = req.body.username;
    const password = req.body.password;

    const role = "admin";

    User.findOne({ email: username }, function (err, foundUser) {
        if (err) {
            console.log(err);
        } else {
            if (foundUser) {
                if (foundUser.role === role) {
                    res.render("adminportal")
                }

                else if (foundUser.password === password) {
                    res.render("portal")
                }

            }
        }
    })
});


app.post("/register", function (req, res) {

    const newUser = new User({
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        email: req.body.username,
        password: req.body.password,
        conpassword: req.body.conpassword

    });
    newUser.save(function (err) {
        if (err) {
            console.log(err);
        } else {
            res.render("portal")
        }
    });

});



//---------------------------------------

app.listen(3000, function () {
    console.log("Server started on port 3000");
});

Here is my Navbar.ejs This is where I want to change my login to signout.

  <nav class="navbar navbar-expand-lg navbar-light">
    <div class="container">
      <a class="navbar-brand" href="/">Barangay Portal</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#home">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#News">About</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown"
              aria-expanded="false">
              Request
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="/reqbrgyid">Dropdown</a></li>
              <li><a class="dropdown-item" href="#">Drop Down</a></li>
         
           
                <hr class="dropdown-divider">
              </li>
              <li><a class="dropdown-item" href="#">Other</a></li>
            </ul>
          </li>

        </ul>
        <ul class="navbar-nav">
          <li class="nav-item navbar-distance">
              //this i want to change this to Sign out and remove the register button as well
            <a class="nav-link " href="/login">Sign in</a>
          </li>
          <li class="nav-item navbar-distance">
            <a class="nav-link nav-border-without" href="#contacts">Talk to Us</a>
          </li>
          <li class="nav-item navbar-distance">
            <a class="nav-link nav-border-with" href="/register">Register</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>