JS test can’t find html element with assertContains

I have this test in a js file (that I can’t change).

browser.waitForElementPresent("body", 10000, "Page loaded")
.url(browser.launch_url)
.waitForElementVisible("body")
.assert.attributeContains("nav > label", "class", "logo").end();

It’s checking this code I have in html:

<body>
    <nav>
        <label class ="logo"></label>
    </nav>
</body>

I can tell from other tests that it can find the body element, but I’m getting this error message:

✖ Testing if attribute ‘class’ of element nav > label contains ‘logo’ in 5000ms – expected “contains ‘logo'” but got: “element could not be located” (5127ms)

Does anyone see the issue here? I don’t understand why it can’t find the label element.

I tried seeing if I could reformat it but html doesn’t accept the other versions I’ve tried. I’ve tried looking up as much as I can about that attributeContains method but I’ve found shockingly little relevant info.

Error: Cannot find module ‘nx/presets/npm.json’

Working on a legacy application and this error popped up out of nowhere after not updating any packages or changing any of the build setup

Run lerna bootstrap
  lerna bootstrap
  shell: /bin/bash -e {0}
  env:
    FORTAWESOME_AUTH_TOKEN: ***
    HST_AUTH_TOKEN: ***
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'nx/presets/npm.json'
Require stack:
- /Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/nx/src/config/workspaces.js
- /Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/nx/src/devkit-exports.js
- /Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/@nrwl/devkit/index.js
- /Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/dist/cli.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.resolve (node:internal/modules/cjs/helpers:108:19)
    at Workspaces.readNxJson (/Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/nx/src/config/workspaces.js:145:52)
    at readNxJson (/Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/nx/src/config/configuration.js:7:72)
    at Object.<anonymous> (/Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/nx/src/daemon/client/client.js:290:72)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:999:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/nx/src/config/workspaces.js',
    '/Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/nx/src/devkit-exports.js',
    '/Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/node_modules/@nrwl/devkit/index.js',
    '/Users/runner/hostedtoolcache/node/17.9.1/x64/lib/node_modules/lerna/dist/cli.js'
  ]
}

Node.js v17.9.1
Error: Process completed with exit code 1.

I’ve tried updating nx in a million different ways which most solutions suggest, but that does nothing. Here is my nx.json

{
  "extends": "nx/presets/npm.json",
  "tasksRunnerOptions": {
    "default": {
      "runner": "nx/tasks-runners/default",
      "options": {
        "cacheableOperations": [
          "dev",
          "build",
          "lint",
          "clean",
          "test",
          "compile",
          "setup",
          "format",
          "commitlint",
          "document",
          "storybook",
          "build-storybook"
        ]
      }
    }
  },
  "targetDependencies": {
    "build": [
      {
        "target": "build",
        "projects": "dependencies"
      }
    ]
  },
  "affected": {
    "defaultBase": "main"
  }
}

I updated nx, but no idea what else to attempt at this point since 0 configuration files were changed, so I don’t even have anything to revert.

https://nx.dev/core-features/automate-updating-dependencies#updating-nx`

Moving files while updating imports automatically and preserving git history

VSCode’s Rename... function from the file-browser context menu is a super useful refactoring tool because it prompts to udpate imports in other files. Git’s mv command is useful to ensure that file moves/renames preserve the history of changes within the file.

I haven’t been able to find a way to take advantage of both simultaneously to ensure that a file move preserves history and imports are updated automatically. This becomes a pretty big deal when attempting a large re-organization of files in a Typescript or JS project.

Does anyone know of a way to achieve both objectives simultaneously?

Tailwindcss and Flowbite – flowbite.min.js file not found (404) in Next.js

I want to use only flowbite package with tailwind in my nextjs application. I configure everything correctly. But adding flowbite.min.js script throws me error –

GET http://localhost:3000/node_modules/flowbite/dist/flowbite.min.js net::ERR_ABORTED 404 (Not Found)

I add the script in my _app.js file as nextjs documentation suggested. Here is my _app.js file

import Script from 'next/script'
import '~/styles/globals.css'

export default function App({Component, pageProps}) {
  return (
    <>
      <Script src='../node_modules/flowbite/dist/flowbite.min.js' />
      <Component {...pageProps} />
    </>
  )
}

In flowbite documentation at number 4 they suggest to add this script end of the body tag

<script src="../path/to/flowbite/dist/flowbite.min.js"></script>

Since I’m using nextjs, I add this script in my _app.js file. I try with cdn and it works. Probably I’m adding path wrongly. What should be the path for flowbite.min.js script?

In nextjs I don’t want to use flowbite-react.

firestore firebase not adding the information I send to it

So I am creating a react app to manage routines, and I set up the database with firestore. Now, everything works fine when I try to retrieve data from the database, but when I want to send it data, it never saves it unless the console is open, and even then it functions sometimes.

this is the code I use to add an item:
const addNewItem = async(titleValue,descriptionValue, repetitionValue) =>{

  try {
   await addDoc(routineCollectionRef,{
   title:titleValue,
   description:descriptionValue,
   repetition:repetitionValue
  })
  .then(console.log('thing done'))
 } catch (error) {
  console.error(error)
}

}

I guess it’s worth specifying that I start the server and add the data in two different files, but by importing the reference key from the first to the second everything should work fine I guess.

JavaScript: when does addEventListener get executed?

I have the following code:

const $details = document.querySelector('.my-details')

const onDetailsToggle = () => {
  console.log('details toggled!')
}

const foo = () => {
  $details.open = true
  $details.addEventListener('toggle', onDetailsToggle, { once: true })
}
foo()

I’m baffled – why is onDetailsToggle being executed even though the toggle happens before I attach the listener?

I’m trying to display info from items in my database based on the suggested clicked on itemname but it’s not showing the information

Im using three files to manage or not i guess this, these are as follows (I’m sorry i had to get rid of a lot proper grammar since i kept getting errors posting)

userNavbar.php
searchItems.php
handlerSearchInput.js

The code that matters

from the userNavbar.php

<div class="tab-content">
    <div id="items" class="tab-pane active">
        
    <label for="itemSearch">Item Search:
    </br> the suggestions shown are clickable working on making that more clear</label>
        <input type="text" class="form-control" id="itemSearch" placeholder="Type to search...">
    <div id="suggestions">
    </div>
    <div class="form-group">
      <?php
      // Connect to your database and fetch data
      $pdo = new PDO('Filled in properly but sensitive information');
      $stmt = $pdo->query('SELECT id, itemName FROM items');
      ?>
    </select>
  </div>

and further down

<!---- EXTRA INFORMATION AFTER CLICK AUTO SUGGESTED SEARCH BAR ----->
<div id="itemInfo" style="display: none;">
  <h2>Item Information</h2>
  <p><strong>Name:</strong> <span id="itemName"></span></p>
  <p><strong>Price:</strong> <span id="itemPrice"></span></p>
  <p><strong>Description:</strong> <span id="itemDescription"></span></p>
</div>    

The whole searchItems.php file

<?php
// Connect to database
$pdo = new PDO('Is properly filled in');

// Get search query from POST data
$itemSearch = $_POST['itemSearch'];

// Query database for matching items
$stmt = $pdo->prepare('SELECT id, itemName, price, description FROM items WHERE itemName LIKE :itemSearch');
$stmt->execute(['itemSearch' => '%' . $itemSearch . '%']);
$matchingItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Return matching items as JSON
header('Content-Type: application/json');
echo json_encode($matchingItems);

?>    

And last but not least my handlerSearchInput.js

$(document).ready(function () {
  // Handler for search input
  $('#itemSearch').on('input', function () {
    // Get search query
    var itemSearch = $(this).val()

    // Send AJAX request to get matching items
    $.ajax({
      url: '../includes/searchItems.php',
      type: 'POST',
      data: { itemSearch: itemSearch },
      dataType: 'json',
      success: function (items) {
        console.log('Success:', items);

        // Get suggestions container
        var suggestionsContainer = $('#suggestions')

        // Clear the suggestions container
        suggestionsContainer.empty()

        // If there are matching items
        if (items.length > 0) {
          // Loop through the matching items
          $.each(items, function (index, item) {
            // Create a suggestion element
            var suggestion = $('<div>')
              .addClass('suggestion')
              .text(item.itemName)
              .data('item', item); // Store the item data on the suggestion element

            // Add a click event listener to set the value of the search input to the clicked suggestion
            suggestion.on('click', function () {
              var itemData = $(this).data('item'); // Retrieve the item data from the clicked suggestion
      
              $('#itemSearch').val(itemData.itemName)
      
              // Clear the suggestions container
              suggestionsContainer.empty()
      
              // Show the item information div
              $('#itemInfo').show()
      
              // Populate the item information
              $('#itemName').text(itemData.itemName)
              $('#itemPrice').text(itemData.price)
              $('#itemTime').text(itemData.time)
            })

            // Append the suggestion element to the suggestions container
            suggestionsContainer.append(suggestion)
          })
        }
      },

      error: function (xhr, status, error) {
        console.error('Error:', error) // log the error message
      },
    })
  })
})

Ive been trying to solve this for a while now but i cant seem to find it, additionally
in the browser console if i decide to add console.log(itemData); the line to show me the itemData, its exactly what i want it to be. HOWEVER when i want to show it on the webpage it doesnt populate it.

Theres also searchItems.php but that shouldn’t matter in this case.

Thanks in advance for reading this.

Debugging, had someone else try and help and alot of googling. I expected to have solved it by now but Ive been stuck for way too long.

user is not allowed to do action in Nodejs

I am working with Nodejs,I am using Expressjs,Right now i am tring to run project,Connection established successfully but whenever i try to use url (localhost:3001/api/plans) then i am getting following error in console

MongoServerError: user is not allowed to do action [find] on [git_flow.plans]

And i am getting following error in my browser

success false
ok  0
code    8000
codeName    "AtlasError"

Here is my “user-router.js” file

import express from 'express';
import * as UserCtrl from '../controllers/user-ctrl.js';
Const router = express.Router()
router.get('/github/auth/redirect', UserCtrl.redirectGithub)
router.post('/users', UserCtrl.createUser)
router.put('/user/:id', UserCtrl.updateUser)
export default router
Here is my controller file (user-ctrl.js) file code
export const redirectGithub = async (req, res) => {
  let code = req.query.code;
  console.log(req.query.code);
  if(!code) {
    return res.send({
      success: false,
      message: 'Error: no code'
    })
  }
  User.findOne({ githubAuthing: true }, (err, user) => {
    if (err) {
        return res.status(400).json({ success: false, error: err })
    }
    user.githubAuthing = false;
    user.code = code;

    console.log(user.redirect_uri);
    
    user
    .save()
    .then(() => {
        res.redirect(user.redirect_uri);
    })

  }).clone().catch(err => console.log(err))
}
H

ere is my model file,Where i am wrong ?

import mongoose from 'mongoose';
const Schema = mongoose.Schema
const User = new Schema(
    {
        settings: { type: String, required: false },
        plan: { type: mongoose.ObjectId, required: false },
        introCompleted: { type: Number, required: false },
        session_id: { type: mongoose.ObjectId, required: true },
        githubToken: { type: String, required: false },
        githubUser: { type: Object, required: false },
        repo: { type: Object, required: false },
        shop: { type: String, required: false },
        githubAuthing: { type: Boolean, required: false },
        code: { type: String, required: false },
        redirect_uri: { type: String, required: false },
    },
    { timestamps: true },
)

export default mongoose.model('users', User)


Update useContext through user input

I’d like to make a version of useContext where some of the components receives an input that updates the state throughout the entire application. For example, I need the room name in my JoinRoom component to reach my LiveChat component without resorting to prop drilling. I already made a context folder to hold all of the context used in my web app. Here is my code so far:

import { createContext, useState } from "react";

export const RoomContext = createContext("");

export const RoomContextProvider = ({ children }) => {
   const [room, setRoom] = useState("");
   return (
      <RoomContext.Provider value={{ room, onChange: setRoom }}>
         {children}
      </RoomContext.Provider>
   );
};

This is the component I’d like to receive the update from:

import { RoomContext } from "../context/RoomContext";

const JoinRoom = () => {
   const {onChange} = useContext(RoomContext)
   const [room, setRoom] = useState("");
   const navigate = useNavigate();
   const handleSubmit = async (e) => {
      e.preventDefault(); // prevents page reload
      if (room !== "") {
         // socket.emit("join_room", room);
         navigate("/live_chat");
      }
   };
 return(<input
                        placeholder="Enter any room name"
                        className="w-full py-2"
                        type="text"
                        onSubmit={handleSubmit}
                        onChange={(event) => {
                           setRoom(event.target.value);
                           onChange(event.target.value)
                        }}
                     />)

If you need more information just let me know.

After building and previewing my website vuex isn’t properly working

When I run my project on a local development server it works just fine. Once I build it I’m getting the following error

TypeError: can't access property "$store", this is undefined setup http://localhost:4173/assets/index-36acef3f.js:1 Ln http://localhost:4173/assets/index-36acef3f.js:1 y http://localhost:4173/assets/index-36acef3f.js:1

My project is running with Vue, vuex and vite.

I tried updating my dependencies as well as checking whether the store was properly set up.

How to get data from response? Express js

I am very new to node js. I am just testing some stuff about client-server communication.

I have these codes:

server:

app.post('/zsa', (req, res) => {
    res.send("zsamo");
});
client:

fetch("http://localhost:3000/zsa", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
})
  .then((data) => {
    console.log(data);
  });

With this code i get a response object:

enter image description here

I want to log to the console what was in the response data: “zsamo”

write a code for faq page for a website in html, css and js

I am creating a website related to car and I am not sure how to do coding for the help page in it, so I want it to know that how can I do coding for the same using HTML, CSS and JAVASCRIPT.

I tried to create FAQs page of my website to do it something uniquely but I am not able t create it in a perfect form so I want your help

Getting complete stack trace as variable

I am trying to acquire the stack trace at a given position in my code as a variable.

For the moment I have been trying to use console.trace() and new Error().stack but they are not optimal.
The first prints the stack to the console while I want to save it in a variable, while the latter does not correctly handles async function calls such as setTimeout.

For example, using the following code:

var getStackTrace = function() {
  var obj = {};
  Error.captureStackTrace(obj, getStackTrace);
  return obj.stack;
};

function f(){
    console.log(getStackTrace());
}

function f1(){
    setTimeout(f);
}

f1();

I only get:

VM3498:2 Error
    at f (<anonymous>:2:17)

Is there a way to get the full stack trace or the get the output of console.trace() in a variable?

Returned object is showing as undefined

I’m using MapBox to plot multiple coordinates onto a map, and for some reason the longitude and latitude that I’m trying to return in my return object are coming up as undefined. Am I missing some kind of config to bring the data into the object? I’ve done this before and it worked fine.

    targetLocations() {
      const data = []
      const timer = setInterval(() => {
        for (let i = 0; i < store.state.location.locations.length; i++) {
          this.coordinates = [store.state.location.locations[i]]
          data.push(this.coordinates)
        }
        this.map.getSource('data-source').setData({
          "type": "FeatureCollection",
          "features": data.map(this.targetElements)
        });
      }, 1000);
    },
    targetElements(index) { // index returns the totals I expect
      console.log(index)
      const { longitude, latitude, dateTimeStored } = index;
      return {
        "type": "Feature",
        "properties": {
          'description':"Lng/Lat: " + longitude + " / " + latitude + "<br />" + "Captured At: " + dateTimeStored,
          'capturedAt': dateTimeStored,
        },
        "geometry": {
          "type": "Point",
          "coordinates": [longitude, latitude]
        }
      };
    },

Example of data object "index" in console

Creating an offline html page that can play audio on different bluetooth speakers

I’m trying to create an html page that I can use offline where I can play audio that goes to different speakers (connected by bluetooth) that are connected to my machine.

I’ve looked into this already and found some javascript code but the code only seems to recognize that I have one output device. It’s possible my Chrome browser is limiting it in some way.

` // First Create a new audio element
var audio = new Audio(“videos/” + “BattleMusic.mp3”);

// Get the list of available audio output devices
function setSound() {
    navigator.mediaDevices.enumerateDevices()
        .then(function (devices) {
            // Filter the devices to get only the audio output ones
            var audioOutputDevices = devices.filter(function (device) {
                return device.kind === "audiooutput";
            });
            // Log the devices to the console
            console.log(audioOutputDevices);
            console.log("audioDevice count " + audioOutputDevices.length)
            // If there is at least one audio output device, use the first one as the output device
            if (audioOutputDevices.length > 0) {
                // Set the sink ID of the audio element to the device ID of the first audio output device
                audio.setSinkId(audioOutputDevices[0].deviceId)
                    .then(function () {
                        // Play the audio
                        audio.play();
                    })
                    .catch(function (error) {
                        // Handle any errors
                        console.error(error);
                    });
            }
        })
}`

Alternatively, I would be happy with a Chrome extension like AudioXOut that allow you to set the audio output on different tabs. Unfortunately, I haven’t gotten such extensions to work except on Youtube. This is likely because Youtube was given permission to use my microphone. For some reason, allowing a page to use a microphone seems to enable AudioXout. I tried making my offline page ask to use the microphone but this did not work. Possibly because my page is offline.

So I have tried a few things but perhaps someone has the exact solution on hand.