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>

Canvas drawing scaling when height changing

I have problem with canvas. I want canvas full height its working. But when i drawing a circle and i put some space in div then the circle is scaling very bad. scaled circle. I want circle stay where it was drew when i put some space in div. Here is my code. Please help me to find the solution. Thanks. If u test it first add some space in div and there you can draw.

https://jsfiddle.net/gu3w97zf/

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let coord = { x: 0, y: 0 };

document.addEventListener('mousedown', start);
document.addEventListener('mouseup', stop);
window.addEventListener('resize', resize);

function resize() {
  ctx.canvas.width = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
}

resize();

function start(event) {
  document.addEventListener('mousemove', draw);
  reposition(event);
}

function reposition(event) {
  coord.x = event.clientX - canvas.offsetLeft;
  coord.y = event.clientY - canvas.offsetTop;
}

function stop() {
  document.removeEventListener('mousemove', draw);
}

function draw(event) {
  ctx.beginPath();
  ctx.lineWidth = 5;
  ctx.lineCap = 'round';
  ctx.strokeStyle = '#ACD3ED';
  ctx.moveTo(coord.x, coord.y);
  reposition(event);
  ctx.lineTo(coord.x, coord.y);
  ctx.stroke();
}
.all {
      background: gray;
    position: relative;
    min-height: 100%;
    letter-spacing: 50px;
}

.text {
  position: inherit;
  min-height: 100%;
    z-index: 99;
    width: -webkit-fill-available;
}

#canvas {
  width: -webkit-fill-available;
    position: absolute;
    height: -webkit-fill-available;
    top: 0;
    z-index: 10;
}
<div class="all">
<canvas id="canvas">
  
</canvas>
<div contenteditable="true" class="text">

</div>
</div>

Weather app, how to write this function better? [closed]

Making the weather app and this is what ive built so far

const obj = {}

async function weather(city) {
    try {
        let response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=fe0199b3b09ac84b46e6413bc44a3a3f`, {mode: "cors"})
        let data = await response.json();

        obj["Weather"] = data.weather
        obj["Location"] = data.name
        obj["Temperatures"] = data.main
        obj["Wind"] = data.wind
        
    } catch (err){
        console.error(err)
    }

}

weather("London")

Based on these instructions: Weather app

Please tell me how to improve!!!!

Cannot find module ‘D:..servernode_modulessequelizetypesutils’

I am coding a React app in VS code and I had run it multiple times, everything was working great, and when I ran npm start another time, the server crashed and gave me this error. I hadn’t changed anything in my code, one minute it was working and then the other not. I’ve tried deleting node modules, package-lock.json, but nothing works. Does anyone have any idea? I didn’t know what snippets of code, if any, I should include, so please tell me.

Passing class method as callback to another class in javascript

I am trying to create a pop up menu (via a class) called from another class. After these inputs are filled in I want the input data to be processed by the object from which the pop up menu was initiated.

My thought process created the following code (simplified ofc):

class foo{
        constructor(){
            this.prroperty = 'yes';
        }

        eventMethod(){
            let eventForm = new bar();
            eventForm.fire(this.endMethod);
        }

        endMethod(values){
            // console.log(this);
            console.log(values + this.prroperty);
        }
    }

class bar{
    constructor(){
        this.property = 'no';
    }

    fire(callback){
        let value = 'message';
        callback(value);
    }
}

let object = new foo();
object.eventMethod();

this doesn’t work obviously because “this” now no longer referes to the foo created object.
I’m planning on using the controller from the foo class and the popup menu created by the bar class a lot. Therefore I’m using classes instead of creating single objects.

My question is if there is a way to deliver and process the values while still being able to do so within classes instead of objects because i want to use them multiple times.

How to make a simple calculation in HTML & JS with internal values

Good evening everyone,

I am trying to make an html email using a CRM that has a total price which i get from {total_price}
and a deposit 50% of the total price.
As there is no {deposit} in the CRM i am using , i though i would make a simple calculation

<!DOCTYPE html>

<html>
<p id="deposit"></p>
<script>

var x={total_price};
var y=0.5;
var  z=x*y;

document.getElementById("deposit").innerHTML = "Deposit : " + z + "€";
</script>

But my CRM doesn’t seem to be able to handle JS, is there any other way to have the same result?

FirebaseCloudFunctions only returns null

I am trying to get a response from a Firebase cloud function, but the only thing I get back is null. The console output shows that the fetch command works and outputs the correct data.

exports.create = functions.https.onCall((data, context) => {
fetch("https://mywebsite.com/x", {
    method: "POST",
    headers: {
        "Authorization": "Bearer MyKey",
        
    },
    body: JSON.stringify({"myData":data.myData})
}).then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
        
        
      });
      return data.json();
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

});

I tried using Promise, I tried returning is as json and just as return data nothing seems to work. The result is always null

The code I use to call it in my flutter app:

HttpsCallable callable =
        FirebaseFunctions.instance.httpsCallable('create');
    final response = await callable.call(<String, dynamic>{
      'myData': 'data',
      
    }).then((value) => print(value.data));

Having Issues with Flexbox

Trying to create dynamic react-mdl cards with specific height and widths. The problem is coming from a float being longer than the width of the card it is in. How can I fix the float or containers to allow cards equally spaced and dynamically sized on each row.

Here is the current code for the container and card
HTML

  <Card className="card">
    <CardTitle className="card-title">
      <img className="item-image" src={icon} alt={alt}/>
    </CardTitle>
    <CardText className="card-text">
      <div>Id: {id}</div>
      <div>Quantity to buy: {quan}</div>
      <div>Total Profit: {profit}</div>
    </CardText>
  </Card>

CSS

.itemlist {
    background-color: rgb(211, 208, 208);
    position: relative;
    border: 2px solid red;
    width: 50%;
    height: 100%;
    float: left;

    display: flex;
    flex-wrap: wrap;
    overflow-x: hidden;
    overflow-y: auto;
}

.card {
    display: flex;
    width: auto;
    height: auto;
    border: 2px solid black; 
    background: green;
    margin: 0 10px;
}

.card-title {
    height: 100px;
    color: #fff;
    background: red;
    justify-content: center;
    align-items: center;
}
.item-image {
    width:auto;
    height:auto;

}[enter image description here][1]

How to imperatively handle an error, with react-query?

Being that react-query is heavily based on the declarative approach, the error handling I see in all examples looks something like this:

function Todos() {
   const { isLoading, isError, data, error } = useQuery('todos', fetchTodoList)
 
   if (isLoading) {
     return <span>Loading...</span>
   }
 
   if (isError) {//If there is an error, render different JSX
     return <span>Error: {error.message}</span>
   } 
   
   return (
     <ul>
       {data.map(todo => (
         <li key={todo.id}>{todo.title}</li>
       ))}
     </ul>
   )
 }

But what if I want to just show an alert, in case of an error? Or perhaps, i’m using some error handling interface, that has an imperative trigger? Something like this:

if (isError) alert(`An error has occurred: ${error.message}`)

In this case, I get two alerts. Something causes the component to re-render, which of course leads to “duplicate” error handling.

Why is this important to me? Because my error handling logic might not be based on rendering some specific JSX within my component, but rather on some manual one-time trigger. The alert is just a basic example.

Any suggestions will be greatly appreciated!

Reactivity of primitives using reactive in Vue 3

According to the docs, primitives shouldn’t become reactive when using reactive wrapper, that’s why in this case we should go with ref. The same situation is when we want to reassign the entire object instead of mutating it.

My question is why in the following snippets counter2 and state2.counter start working correctly when we uncomment the commented lines?

<script setup>
import { ref, reactive } from 'vue';
  
let counter1 = ref(0);
let counter2 = reactive(0);
  
const increment = () => { 
  // counter1.value++;
  counter2++;
}
</script>

<template>
  <h3>counter1 {{ counter1 }}</h3>
  <h3>counter2 {{ counter2 }}</h3>
  <button @click="increment">increment</button>
</template>
<script setup>
import { ref, reactive } from 'vue';
  
let state1 = ref({ counter: 0 });
let state2 = reactive({ counter: 0 });
  
const increment = () => { 
  // state1.value = { counter: state1.value.counter + 1 };
  state2 = { counter: state2.counter + 1 };
}
</script>

<template>
  <h3>counter1 {{ state1.counter }}</h3>
  <h3>counter2 {{ state2.counter }}</h3>
  <button @click="increment">increment</button>
</template>