Nodejs can’t find file

(1) I put script.js on desktop and test.js in a folder on desktop.
When I write “node script.js” in Mac terminal, it tells me this:
node:internal/modules/cjs/loader:942
throw err;
^
Error: Cannot find module
……
code: ‘MODULE_NOT_FOUND’,
requireStack: []

(2) When I copy paste the path of script.js (the file on desktop)”node /Users/Leah/Desktop/script.js”, it runs fine.

(3) However, if I copy paste the path of test.js (the file in a folder on desktop) “node /Users/Leah/Desktop/JavaScript projects/test.js”, it returns the same thing
as in (1).

I looked up on google but couldn’t find a solution. Could anyone please help me? (npm is installed as well)

results group by month based on the datetime c#

In my ASP.NET MVC application, there is a line chart in which I want to show record counts and the month on X-axis and Y-axis.

So I’m trying to call an ajax to the controller and the model has a record created date and the value.

I can’t figure out how to return it by grouping it like the month of April has 15 records. The month of May has 12 records… likewise.

In my model structured like this,

 public class CustomerFeedBack {
   [Key]
   public int Id {
     get;
     set;
   }
   public DateTime CreatedDate {
     get;
     set;
   } = DateTime.Now;
   public int TotalSatisfaction {
     get;
     set;
   }
 }

This is the javascript of the chart, here in the data I want to return the count of records and for labels months. Currently, it has dummy data.

var bouData = {
    // Generate the days labels on the X axis.
    labels: Array.from(new Array(30), function (_, i) {
      return i === 0 ? 1 : i;
    }),
    datasets: [{
          label: 'Satisfied',
          fill: 'start',
          data: [1500, 800, 320, 180, 240, 320, 230, 650, 590, 1200, 750, 940, 1420, 1200, 960, 1450, 1820, 2800, 2102, 1920, 3920, 3202, 3140, 2800, 3200, 3200, 3400, 2910, 3100, 4250],
          backgroundColor: 'rgba(0,123,255,0.1)',
          borderColor: 'rgba(0,123,255,1)',
          pointBackgroundColor: '#ffffff',
          pointHoverBackgroundColor: 'rgb(0,123,255)',
          borderWidth: 1.5,
          pointRadius: 0,
          pointHoverRadius: 3
        },

So in the controller, I want to return JsonResult and bind to labels as month and data as count.

This is my incomplete controller code.

var satisfied = (from a in db.tbl_Main where a.TotalSatisfaction >= 12 
                 select new {
                  // Here I want to check with the create date group it as Month and sum the value of a.TotalSatisfaction count.
                 }).ToList();

I’m not an experienced developer regarding this, Still learning and would appreciate if you can suggest if there is another way of doing this easily or how to complete this.

Thanks.

How can I render only once an Alert component in react native?

How can I render only once an Alert component in react native if my dashboardScreen is being render many times?

I’m using Context api, if I dispatch an action it causes another render, if I use a useState it causes another render/renders, any idea will be highly appreciate it.

**AppContext.js**
export const AppContext = createContext();

export const AppProvider = ({ children })=> { 

const [ state, dispatch ] = useReducer( appReducer, appInicialState);

 return (
        <AppProvider.Provider value={{
            ...state,
            .....
        }}>
            { children }
        </AppProvider.Provider>
    )

}

**Dashboard.js**


export const Dashboard = () => {
 const { state, dispatch } = useContext( AuthContext );
 const [showAlert, setShowAlert] = useState(true);

 const handleCancelPressed = () => {
      dispatch({ 
            type: 'cancelPressed',
            payload: {
                userInfo: false,
            }
        });
 }

 const handleAcceptPressed = () => {
      dispatch({ 
            type: 'acceptPressed',
            payload: {
                userInfo: true,
            }
        });
 }

 return (
  <View style={styles.container}>
    {showAlert && (
         Alert.alert(
    "Alert Title",
    "My Alert Msg",
    [
      {
        text: "Cancel",
        onPress: handleCancelPressed,
      },
 {
        text: "Ok",
        onPress: handleAcceptPressed ,
      },
    ],
    {
      cancelable: true,
    }
  );
    )}
  </View>

)}

How would you create a button to format text in a with JS?

I’m trying to make a basic text editor in HTML. I’ve got an editable div tag so far, and by using keyboard shortcuts, you can format it. However, I want it so that there are a couple of buttons which can bold, italicize, underline and change the color of the text. I’m using basic jQuery and JS for this.

Here’s (roughly) my code so far:

$('.text-editor').each(function(){
    this.contentEditable = true;
});
div.text-editor {
    width: 200px;
    height: 200px;
    border: 1px solid #ccc;
    padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-editor"></div>

coverage branch skipped at `func.apply(this, args)` when I test debounce in react testing library

I’m trying to test a debounce helper in my react project.
first off all, I created a debounce helper in my project that work nicely on my project. Here is my debounce code (debounce.js).

export default function debounce(func = () => { }, timeout = 500) {
    let timer = setTimeout(function () { }, 100);
    clearTimeout(timer);
    return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(
            () => {
                func.apply(this, args);
            },
            timeout
        );
    };
}

And I try to test my debounce.js file in my debounce.test.js file. The code like I write below.

import debounce from "../../scripts/utils/debounce"

test('normal debounce param test', () => {
    const paramtest = 'paramtest'
    debounce((params) => {
        expect(params).toBe(paramtest)
        expect(this).toBeDefined(Function)
    }, 100)(paramtest);

    debounce((params) => {
        expect(params).not.toBe(paramtest)
        expect(this).toBeDefined(Function)
    }, 100)();
})

test('multiple pump debounce & param test - 1500 test', () => {
    let debounceCount = 0;
    const deb = debounce(
        (params) => {
            debounceCount += params;
        },
        500)

    setTimeout(() => {
        deb(1)
    }, 499)

    setTimeout(() => {
        deb(1)
    }, 499)

    setTimeout(() => {
        expect(debounceCount).toBe(1)
    }, 1500)
})

test('multiple pump debounce & param test - 1000 test', () => {
    let debounceCount = 0;
    const deb = debounce(
        (params) => {
            debounceCount += params;
        },
        500)

    setTimeout(() => {
        deb(1)
    }, 499)

    setTimeout(() => {
        deb(1)
    }, 499)

    setTimeout(() => {
        expect(debounceCount).toBe(0)
    }, 1000)
})

test('debounce initializer', () => {
    const deb = debounce((params) => { })
    expect(deb).toBeDefined()
    expect(deb).toBeInstanceOf(Function)
})

test('debounce initializer function', () => {
    const func = jest.fn()
    const deb = debounce(func)
    expect(deb).toBeDefined()
    expect(deb).toBeInstanceOf(Function)
    expect(func).toHaveBeenCalledTimes(0)
    deb()
    setTimeout(() => {
        expect(func).toHaveBeenCalledTimes(1)
    }, 501)

    const secondDeb = debounce(null)
    secondDeb()
    setTimeout(() => {
        expect(secondDeb).toThrowError()
    }, 501)
})

Actually, that test result is passed successfully without any failed or error. Here is my result.
enter image description here

But when I look at my coverage test. It was blew my mind. the Stmts, branch, func, and the line results are not 100% covered, and the line that uncovered is func.apply(this, args);.
Here is my coverage result
enter image description here

Stmts: 83.33, branch: 50, func: 40, line: 83,33, uncovered line: 8

which uncovered line is func.apply(this, args), and actually I’ve test that argument in my first test (I thing).

How to cover that line? so I can get all the result to be 100? Thank you in advance.

insert data is not inserting

(adduser.php)
<?php
require('./database.php');
    $username = mysqli_real_escape_string($connection,$_POST['username']);
    $fullname = mysqli_real_escape_string($connection,$_POST['fullname']);
    $contact = mysqli_real_escape_string($connection,$_POST['contact']);
    $password = mysqli_real_escape_string($connection,md5($_POST['password']));
    $queryinsert = "INSERT INTO tbl_userinfo VALUES (null, ?, ?, ?, ?)";
    $queryconnection = mysqli_stmt_init($connection);
    if(!mysqli_stmt_prepare($queryconnection, $queryinsert)){
        echo "<script type='text/javascript'>alert('SQL ADDED ERROR');</script>";
    }
    else{
        mysqli_stmt_bind_param($queryconnection, "ssss", $username, $fullname, $contact, $password);
        mysqli_stmt_execute($queryconnection);
    }
?>

(queryuseradmin.js)
    $.post("../controller/adduser.php",{"username": username, "fullname": fullname, "contact": contact, "password": password},function data(){             
                    document.querySelector('.bg-successmodal').style.display='flex';
                     setTimeout(function(){ document.querySelector('.bg-successmodal').style.display='none';
                     },1500); 
                     $.post("../controller/useradminquery.php",{cache: false}, function data(data){
                        $('#tableid').html(data); 
                    });     
                     $('#userformid')[0].reset();                  
                    });  

can’t insert data but the modal form is still showing after inserting i have been working on this 2 days ago until now but still not working

My implementation of Breadth First Search with forEach doesn’t work

Here is my code inside a BinarySearchTree class. I don’t know if it is because of the behaviour of forEach, or because somewhere in my code is wrong.

class BinarySearchTree {
    constructor() {
        this.root = null;

    }
    .............
    BFS() {
        let data = [];
        let queue = [];
        if (!this.root) {
            return false
        } else if (this.root) {
            queue.push(this.root)

            while (queue.length) {
                queue.forEach(function (element) {
                    if (element.left) {
                        console.log('here 1')
                        queue.push(element.left)
                    }
                    if (element.right) {
                        console.log('here 2')

                        queue.push(element.right)
                    }
                    queue.shift()
                    data.push(element)
                })
            }
            return data
        }
    }

}
class Node {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

Rails 7 jquery: Uncaught ReferenceError: $ is not defined

I added jQuery to my Rails 7.0.2.4 project by the following:

First run command ./bin/importmap pin jquery, to add the following line in config/importmap.rb:

pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"

Then add lines to import jQuery in app/javascript/application.js:

import '@hotwired/turbo-rails'
import 'controllers'
import 'bootstrap'

import jquery from 'jquery'
window.jQuery = jquery
window.$ = jquery

My view with javascript:

<%= form_with(model: @micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class='field'>
    <%= f.text_area :content, placeholder: 'Compose new micropost...' %>
  </div>
  <%= f.submit 'Post', class: 'btn btn-primary' %>
  <span class='image'>
    <%= f.file_field :image %>
  </span>
<% end %>

<script type='text/javascript'>
  $('#micropost_image').bind('change', function() {
    if (this.files[0].size/1024/1024 > 5) {
      alert('Maximum file size is 5MB.  Please choose a smaller file.')
      $('#micropost_image').val('')
    }
  })
</script>

When the view is loaded, Chrome console shows:

Uncaught ReferenceError: $ is not defined at (index):103:3

And when I select a file bigger than 5MB, no error message is popped up, so I think the script isn’t run.

How to fix it?

get Forbidden resource even when the requested user is admin

Middleware is used to protect the resolver. The middleware checks the role of user and despite the right role of the requested user I cannot access listUser query. I get following response

"errors": [
    {
      "message": "Forbidden resource",
      "extensions": {
        "code": "FORBIDDEN",
        "response": {
          "statusCode": 403,
          "message": "Forbidden resource",
          "error": "Forbidden"
        }
      }
    }
  ],
  "data": null
}

Here is my code

model User {
  id            String           @id @default(uuid())
  firstName     String
  lastName      String
  email         String           @unique
  username      String           @unique
  password      String
  confirm       Boolean          @default(false)
  isValid       Boolean          @default(false) @map("is_valid")
  isSuperuser   Boolean          @default(false)
  userRoles     UserRole[]

  @@unique([id, email])
}

model Role {
  id        String      @id @default(uuid())
  name      String      @unique
  createdAt DateTime?   @db.Timestamp()
  updatedAt DateTime?   @updatedAt @db.Timestamp()
  userRoles UserRole[]
}

model UserRole {
  id        String    @id @default(uuid())
  userId    String
  user      User      @relation(fields: [userId], references: [id])
  roleId    String
  role      Role      @relation(fields: [roleId], references: [id])
  createdAt DateTime? @default(now())
  updatedAt DateTime? @updatedAt @db.Timestamp()
}

@Injectable()
export class UserMiddleware implements NestMiddleware {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly validationService: ValidationService,
  ) {}

  async use(req: any, res: any, next: () => void) {
    if (req.headers.authorization) {
      const { userId } = jwt.decode(
        String(req.headers.authorization).split(/ /g)[1],
      ) as JWT;
      const user = await this.prismaService.user.findFirst({
        where: { id: userId },
        include: { userRoles: true },
      });
      if (user && !user.confirm)
        throw new ForbiddenException('User not confirmed');

      if (user) {
        delete user.password;
        req.user = user;
        req.user.isAdmin = await this.validationService.isAdmin(userId);
      }
    }
    next();
  }
}

@Injectable()
export class ValidationService {
  constructor(private readonly prisma: PrismaService) {}

  async isAdmin(userId: string): Promise<boolean> {
    const u = await this.prisma.role.findUnique({
      where: { name: Role.Admin },
    });
    return await this.prisma.userRole
      .count({
        // could not find a way to access directly through role name instead of id
        where: { userId, roleId: u.id },
      })
      .then((count) => {
        return count ? true : false;
      });
  }
}

  @Query(() => UserPaginated)
  @Roles(Role.Admin)
  async listUsers(
    @Args('paginate', { nullable: true, defaultValue: { skip: 0, take: 50 } })
    paginate: PaginationArgs,
    @Args('order', {
      nullable: true,
      defaultValue: { orderBy: 'username', direction: 'desc' },
    })
    order: OrderListUsers,
    @Args('filter', { nullable: true })
    filter: FilterListUsers,
  ) {
    return await this.userService.list(paginate, order, filter);
  }

Why am I not able to access listUser with role as Admin ?

TypeError: Invalid value for schema path `author.type`, got value “undefined”

Estou desenvolvendo um sistema admin para um blog com base em um tutorial masquando tento rodar com $ node app.js da o seguinte erro:

meu erro no terminal:

TypeError: Invalid value for schema path author.type`, got value “undefined”

o express , mongoose e o bory-parser estao instalados no meu .json

alguem me ajuda pfventer code here

meu codigo é esse:

//Requirements
const mongoose = require('mongoose')
const express = require('express')
const bodyParser = require('body-parser')

//express server definition
const app = express()
app.use(bodyParser.json())

//Resources definitions
const User = mongoose.model('User', { name: String, email: String, surname: String })

var artcileSchema = new mongoose.Schema({
    title: String,
    body: String,
    author: {
        type: mongoose.Schema.Types.objectId,
        ref: 'User',
        required: true
    },
    created_at: { type: Date, default: Date.now}
});

const Article = mongoose.model('Article', artcileSchema);

//routes definitions
app.get('/', (req, res) => res.send('hello world!'))

// Route which returns users
app.get('/users', async (req, res) => {
    const users = await User.find({}).limit(10)
    res.send(users)
})

// Route which creates new user
app.post('/users', async (req, res) => {
    const user = await new User(req.body.user).save()
    res.send(user)
})

//Route whick retuns articles
app.get('/artcles', async (req, res) =>{
    const articles = await Article.find({}).limit(10)
    res.send(articles)
})

// Running the server
const run = async () => {
    await mongoose.connect('mongodb://localhost/admin', { userNewurlParser: true })
    await app.listen(8080, () => console.log('Exemple app listening on port 8080!'))
}

run()```

How can I change this functionality in this javascript code?

I have 2 js codes for this website. auction.js has a function that grts random cats pictures and displays them. I would like to change that and to be able to add fixed pictures from my laptop and fixed title+description..


auction.js:

        // For a real auction, set this to false
let demoAuction = true;
// For a real auction, populate these arrays
let primaryImages = [];
let titles = [];
let subtitles = [];
let details = [];
let secondaryImages = [];
let startingPrices = [55, 60, 20, 0, 4, 0, 99, 0, 12, 6, 3, 7];
let endTimes = []; // Make sure to fix these to UTC time so they don't change with the users timezone

// Random auction information
function generateRandomAuctions() {
  // Random cat images
  document.querySelectorAll(".card > img").forEach(img => {
    img.src = "https://cataas.com/cat/cute?random=" + Math.random();
    primaryImages.push(img.src);
    secondaryImages.push(img.src);
  });
  // Random cat names
  $.getJSON(
    "https://random-data-api.com/api/name/random_name",
    { size: startingPrices.length },
    function (data) {
      data.forEach((elem, idx) => {
        document.querySelector("#auction-" + idx + " > div > h5").innerHTML = elem.name;
        titles.push(elem.name);
      });
    }
  );
  // Random lorem ipsum cat descriptions
  $.getJSON(
    "https://random-data-api.com/api/lorem_ipsum/random_lorem_ipsum",
    { size: startingPrices.length },
    function (data) {
      data.forEach((elem, idx) => {
        document.querySelector("#auction-" + idx + " > div > p").innerHTML = elem.short_sentence;
        subtitles.push(elem.short_sentence);
        details.push(elem.very_long_sentence);
      });
    }
  );
}

// Initial state of auction, used for resetting database
let startPrices = [];
for (let i = 0; i < startingPrices.length; i++) {
  if (demoAuction) {
    let now = new Date();
    let endTime = new Date().setHours(8 + i, 0, 0, 0)
    if (endTime - now < 0) { endTime = new Date(endTime).setDate(now.getDate() + 1) }
    endTimes.push(endTime)
  }
  startPrices.push({
    bid0: {
      bidder: String(i),
      amount: startingPrices[i],
      time: Date().substring(0, 24)
    }
  })
}

// Convert time to string for HTML clocks
function timeBetween(start, end) {
  let _string = ""
  let secsRemaining = (end - start) / 1000;
  let d = parseInt(secsRemaining / 86400);
  let h = parseInt(secsRemaining % 86400 / 3600);
  let m = parseInt(secsRemaining % 3600 / 60);
  let s = parseInt(secsRemaining % 60);
  if (d) { _string = _string + d + "d " }
  if (h) { _string = _string + h + "h " }
  if (m) { _string = _string + m + "m " }
  if (s) { _string = _string + s + "s " }
  return _string.trim()
}

// Set time on HTML clocks
function setClocks() {
  let now = new Date();
  let nowTime = now.getTime();
  for (i = 0; i < startingPrices.length; i++) {
    let timer = document.getElementById("time-left-" + i)
    // remove finished auction after 5 minutes
    if (endTimes[i] - nowTime < -300) {
      document.getElementById("auction-" + i).parentElement.style.display = "none"
      if (demoAuction) {
        endTimes[i] = new Date(endTimes[i]).setDate(now.getDate() + 1) // add 1 day
        document.getElementById("auction-" + i).parentElement.remove()
        resetLive(i);
        resetStore(i);
        auctionGrid = document.getElementById("auction-grid");
        auctionCard = generateAuctionCard(i);
        auctionGrid.appendChild(auctionCard);
      }
      // disable bidding on finished auctions
    } else if (endTimes[i] - nowTime < 0) {
      timer.innerHTML = "Auction Complete";
      document.getElementById("bid-button-" + i).setAttribute('disabled', '')
    } else {
      timer.innerHTML = timeBetween(nowTime, endTimes[i]);
    }
  }
  setTimeout(setClocks, 1000);
}

// Place a bid on an item
function placeBid() {
  let nowTime = new Date().getTime();
  let modalBidButton = document.querySelector("#bid-modal > div > div > div.modal-footer > button.btn.btn-primary")
  modalBidButton.setAttribute('disabled', '') // disable the button while we check
  let i = modalBidButton.id.match("[0-9]+");
  let feedback = document.getElementById("bad-amount-feedback")
  // Cleanse input
  let amountElement = document.getElementById("amount-input")
  let amount = Number(amountElement.value)
  if (endTimes[i] - nowTime < 0) {
    feedback.innerText = "The auction is already over!"
    amountElement.classList.add("is-invalid")
    setTimeout(() => {
      bidModal.hide();
      amountElement.classList.remove("is-invalid");
      modalBidButton.removeAttribute('disabled', '');
    }, 1000);
  } else if (amount == 0) {
    // amount was empty
    feedback.innerText = "Please specify an amount!"
    amountElement.classList.add("is-invalid")
    modalBidButton.removeAttribute('disabled', '');
  } else if (!(/^-?d*.?d{0,2}$/.test(amount))) {
    // field is does not contain money
    feedback.innerText = "Please specify a valid amount!"
    amountElement.classList.add("is-invalid")
    modalBidButton.removeAttribute('disabled', '');
  } else {
    // Checking bid amount
    // Get item and user info
    let user = auth.currentUser;
    let itemId = i.toString().padStart(5, "0")
    // Documents to check and write to
    let liveRef = db.collection("auction-live").doc("items")
    let storeRef = db.collection("auction-store").doc(itemId)
    // Check live document
    liveRef.get().then(function (doc) {
      console.log("Database read from placeBid()")
      let thisItem = doc.data()[itemId];
      let bids = (Object.keys(thisItem).length - 1) / 2
      let currentBid = thisItem["bid" + bids]
      if (amount >= 1 + currentBid) {
        keyStem = itemId + ".bid" + (bids + 1)
        liveRef.update({
          [keyStem + "-uid"]: user.uid,
          [keyStem]: amount,
        })
        console.log("Database write from placeBid()")
        storeKey = "bid" + (bids + 1)
        storeRef.update({
          [storeKey]: {
            "bidder-username": user.displayName,
            "bidder-uid": user.uid,
            "amount": amount,
            time: Date().substring(0, 24)
          }
        })
        console.log("Database write from placeBid()")
        amountElement.classList.add("is-valid")
        amountElement.classList.remove("is-invalid")
        setTimeout(() => {
          bidModal.hide();
          amountElement.classList.remove("is-valid");
          modalBidButton.removeAttribute('disabled', '');
        }, 1000);
      } else {
        amountElement.classList.add("is-invalid")
        feedback.innerText = "You must bid at least £" + (currentBid + 1).toFixed(2) + "!"
        modalBidButton.removeAttribute('disabled', '');
      }
    });
  }
}

function argsort(array) {
  const arrayObject = array.map((value, idx) => { return { value, idx }; });
  arrayObject.sort((a, b) => (a.value - b.value))
  return arrayObject.map(data => data.idx);;
}

function generateAuctionCard(i) {
  // create auction card
  let col = document.createElement("div");
  col.classList.add("col");

  let card = document.createElement("div");
  card.classList.add("card");
  card.id = "auction-" + i
  col.appendChild(card);

  let image = document.createElement("img");
  image.classList.add("card-img-top");
  image.src = primaryImages[i];
  card.appendChild(image);

  let body = document.createElement("div");
  body.classList.add("card-body");
  card.appendChild(body);

  let title = document.createElement("h5");
  title.classList.add("title");
  title.innerText = titles[i];
  body.appendChild(title);

  let subtitle = document.createElement("p");
  subtitle.classList.add("card-subtitle");
  subtitle.innerText = subtitles[i];
  body.appendChild(subtitle);

  // Auction status
  let statusTable = document.createElement("table");
  statusTable.classList.add("table");
  card.appendChild(statusTable);

  let tableBody = document.createElement("tbody");
  statusTable.appendChild(tableBody);

  let bidRow = document.createElement("tr");
  tableBody.appendChild(bidRow);

  let bidTitle = document.createElement("th");
  bidTitle.innerHTML = "Current bid:"
  bidTitle.scope = "row";
  bidRow.appendChild(bidTitle);

  let bid = document.createElement("td");
  bid.innerHTML = "£-.-- [- bids]"
  bid.id = "current-bid-" + i
  bidRow.appendChild(bid);

  let timeRow = document.createElement("tr");
  tableBody.appendChild(timeRow);

  let timeTitle = document.createElement("th");
  timeTitle.innerHTML = "Time left:"
  timeTitle.scope = "row";
  timeRow.appendChild(timeTitle);

  let time = document.createElement("td");
  time.id = "time-left-" + i
  timeRow.appendChild(time);

  // Auction actions
  let buttonGroup = document.createElement("div");
  buttonGroup.classList.add("btn-group");
  card.appendChild(buttonGroup)

  let infoButton = document.createElement("button");
  infoButton.type = "button"
  infoButton.href = "#";
  infoButton.classList.add("btn", "btn-secondary")
  infoButton.innerText = "Info";
  infoButton.onclick = function () { openInfo(this.id); }
  infoButton.id = "info-button-" + i
  buttonGroup.appendChild(infoButton);

  let bidButton = document.createElement("button");
  bidButton.type = "button"
  bidButton.href = "#";
  bidButton.classList.add("btn", "btn-primary")
  bidButton.innerText = "Submit bid";
  bidButton.onclick = function () { openBid(this.id); }
  bidButton.id = "bid-button-" + i
  buttonGroup.appendChild(bidButton);

  return col
}

// Generatively populate the websire with auctions
function populateAuctionGrid() {
  auctionGrid = document.getElementById("auction-grid");
  let endingSoonest = argsort(endTimes);
  endingSoonest.forEach((i) => {
    auctionCard = generateAuctionCard(i);
    auctionGrid.appendChild(auctionCard);
  });
  if (demoAuction) { generateRandomAuctions() };
}

function numberWithCommas(x) {
  return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
}

function dataListener() {
  // Listen for updates in active auctions
  db.collection("auction-live").doc("items").onSnapshot(function (doc) {
    console.log("Database read from dataListener()")
    let data = doc.data()
    for (key in data) {
      let cb = document.getElementById("current-bid-" + Number(key))
      let bids = data[key]
      // Extract bid data
      let bidCount = (Object.keys(bids).length - 1) / 2
      let currPound = Number.parseFloat(bids["bid" + bidCount]).toFixed(2)
      // Check if the user is winning
      if (auth.currentUser) {
        let userWinning = bids["bid" + bidCount + "-user"] == auth.currentUser.uid
      }
      // Add bid data to HTML
      cb.innerHTML = "£" + numberWithCommas(currPound) + " [" + bidCount + " bid" + (bidCount != 1 ? "s" : "") + "]"
    }
  })
}

function resetLive(i) {
  let docRef = db.collection("auction-live").doc("items");
  let itemId = i.toString().padStart(5, "0")
  docRef.update({
    [itemId]: {
      bid0: startPrices[i]["bid0"]["amount"],
    }
  })
  console.log("Database write from resetLive()")
}

function resetAllLive() {
  console.log("Resetting live tracker")
  for (i = 0; i < startingPrices.length; i++) {
    resetLive(i);
  }
}

function resetStore(i) {
  let itemId = i.toString().padStart(5, "0")
  let docRef = db.collection("auction-store").doc(itemId);
  docRef.set(startPrices[i])
  console.log("Database write from resetStore()")
}

function resetAllStore() {
  console.log("Resetting auction storage")
  let batch = db.batch();
  for (i = 0; i < startingPrices.length; i++) {
    let itemId = i.toString().padStart(5, "0")
    let currentItem = db.collection("auction-store").doc(itemId);
    batch.set(currentItem, startPrices[i])
  }
  batch.commit()
  console.log(startingPrices.length + " database writes from resetAllStore()")
}

function resetAll() {
  resetAllLive();
  resetAllStore();
}

        ``` 

___
popup.js:

loginModal = new bootstrap.Modal(document.getElementById('login-modal'))
infoModal = new bootstrap.Modal(document.getElementById('info-modal'))
bidModal = new bootstrap.Modal(document.getElementById('bid-modal'))

function openInfo(id) {
  let i = id.match("[0-9]+");
  document.getElementById('info-modal-title').innerText = titles[i]
  document.getElementById('info-modal-desc').innerHTML = details[i]
  document.getElementById('info-modal-img').src = secondaryImages[i];
  document.querySelector("#info-modal > div > div > div.modal-footer > button.btn.btn-primary").id = "info-modal-submit-bid-btn-" + i
  infoModal.show()
}

function openBid(id) {
  let i = id.match('[0-9]+');
  document.getElementById("amount-input").value = ""
  document.getElementById("amount-input").classList.remove("is-invalid")
  document.getElementById('bid-modal-subtitle').innerText = titles[i]
  document.querySelector("#bid-modal > div > div > div.modal-footer > button.btn.btn-primary").id = "bid-modal-submit-bid-btn-" + i
  loggedIn = auth.currentUser && auth.currentUser.displayName
  if (loggedIn) {
    bidModal.show()
    document.getElementById("amount-input").focus()
  } else {
    openLogin()
  }
}

function openLogin() {
  loggedIn = auth.currentUser && auth.currentUser.displayName
  if (!loggedIn) { loginModal.show(); document.getElementById('username-input').focus() }
}

function newUserLogin() {
  loggedIn = auth.currentUser && auth.currentUser.displayName
  if (!loggedIn) {
    let username = document.getElementById('username-input').value
    let user = auth.currentUser;
    user.updateProfile({ displayName: username })
    db.collection("users").doc(user.uid).set({ name: username, admin: false })
    loginModal.hide()
    replaceSignupButton(username)
  }
}

function autoLogin() {
  auth.onAuthStateChanged(function (user) {
    if (user && user.displayName != null) {
      replaceSignupButton(user.displayName)
    } else {
      auth.signInAnonymously()
    }
  });
}

function replaceSignupButton(name) {
  document.getElementById('signup-button').style.display = "none"
  document.getElementById('username-display').innerText = "Hi " + name
}

I have 2 js codes for this website. auction.js has a function that grts random cats pictures and displays them. I would like to change that and to be able to add fixed pictures from my laptop and fixed title+description..

inverting object boolean property with ! vs =false , Is there any difference?

I am trying to make tic tac toe game in vanilla javascript. If I use ! to flip the value of object boolean property , it is changed to what it is defined in global memory object (as soon as it is out of its execution context), however If I flip by using = equal sign, it stays same. aren’t they both doing same thing(flipping value)?? Any explanation would be appreciated.
Here’s my code.

// we need an object for storing the state of our game.

const game = {
    xTurn: true,
    xState: [],
    oState: [],
    winningStates: [
        // Rows
        ['0', '1', '2'],
        ['3', '4', '5'],
        ['6', '7', '8'],

        // Columns
        ['0', '3', '6'],
        ['1', '4', '7'],
        ['2', '5', '8'],

        // Diagonal
        ['0', '4', '8'],
        ['2', '4', '6']
    ]
}


document.addEventListener('click',e=>{
    const target = e.target;
    console.log('initializing code')
    const isCell = target.classList.contains('grid-cell')
    const isDisabled = target.classList.contains('disabled');
    if(isCell && !isDisabled){
        const cellValue = target.dataset.value;
        if(game.xTurn){
            game.xState.push(cellValue)
        }else{
            game.oState.push(cellValue)
        }
        target.classList.add('disabled')
        target.classList.add(game.xTurn ? 'x' : 'o')
        // if(game.xTurn){
        //     target.classList.add('x')
        // }else{
        //     target.classList.add('o')
        // }
        console.log(game.xTurn)
        game.xTurn = !game.xTurn;
        // game.xTurn = false;
        console.log(game.xTurn)
    }

})

JavaScript – How do I print an input inside an array?

I already tried many ways to solve this, but it always returns undefined. What should I do to solve this issue?

function printThreeFavoriteColours() {
  const colours = [];
  const colorUserFav1 = prompt("type your first favorite color");
  const colorUserFav2 = prompt("now, type your second favorite color");
  const colorUserFav3 = prompt("finally, type your third favorite color");
  
  colours.push = (colorUserFav1, colorUserFav2, colorUserFav3);
  console.log(colours);
}

Simpler Method of Storing and Retreiving External Data via Javascript on Any Website

I have tried several solutions to store and retrieve data on a website. Local Storage has been great but the cross origin limitations and storage duration are a limitation.

I need to be able to read and write on a specific datasets using my browsers inspector console regardless of the website I am on.

One solution that does work but is very clunky is sheet.best where their API hooks into my google sheet to read and write data to my sheet from any website I am on.

Use case example.

I need to access a blog and I want to know if there was any posts since the last time I visited.

In my external dataset (stored locally), I have the URL for the blog and the last update that was made.

If the blog was recently updated, and there for the last update I have stored isn’t the most recent update on the blog, I want to extract the recent posts (anything since the update that was in my dataset) for reading later and update my dataset such that if I come back in a week the script would check against the more recent updates made on the blog.

I have been able to check for updates with a simple Object variable but with that I can’t store information and save it locally. I am able to convert the data to text then save it as a text file but it’s been a hassle getting that data back into the browser at another time.

Local storage works perfect for a individual websites, but I want to be able to use a single dataset on multiple websites. IE: URL1:Post5. URL2:Post2. URL3:Post4. If I access each website, and only URL1 was updated, that is the only one I want to look for recent posts on.

Things that come to mind but I have no idea how to implement are a local database I can access from any website via my browser.

Reading and Writing data that is stored locally across domains is new to me so I don’t even know what to search for. I use FireFox, so maybe there is an extension that I can use. Maybe a library? Any advise is appreciated.

TL:DR I need a method of storing and reading information via GreaseMonkey or inspector console from any website. That data should store locally or on the cloud (like with google sheets).

I have 0 experience with it, but is a extension based sqllite manager a route I should research? Or possibly any firefox extension that I just don’t know how to describe and therefor can’t search for?

My useState in React/NEXTjs is not appending the result from a socket.io event from the server, just overwriting it

Frameworks used: Next.js, Socket.io, React

I am making a simple messaging app. I am basically just emitting a message someone types, sending that message to the server, which is then “broadcasted” back through an event called “receive-chat-message”. The issue I’m having is when the response is handled on the front end with “receive-chat-message”, the [messages] state is not appending a new message to display, it’s just overwriting the state.

My goal is to send a message to the server; the server then sends the message back to the client. I then append the new message on the client, sent from the server, to the [messages] state on the client, and then render the state of [messages]. The problem is it’s only overwriting the [messages] state, and not appending new messages to it.

Code that sends message to the server

const [message, setMessage] = useState("");

  const handleChange = (e) => {
    setMessage(e.target.value);
  };

  const submitMessage = async () => {
    // socket.io
    const socket = io();
    socket.emit("send-chat-message", message, user);
    setMessage("");
  };

Front-End Code

const [messages, setMessages] = useState([]);

  useEffect(() => {
    const socket = io();
    socket.on("receive-chat-message", handleSetMessage);

    return () => socket.disconnect();
  }, []);

  const handleSetMessage = (data) => {
    /* data prop is the new message - it has a {message: "message", user: "name"} 
       sent from server.
       THIS IS THE PROBLEM IN THE CODE WHERE IT DOESN'T APPEND
       NEW MESSAGES TO THE [messages] STATE, IT JUST OVERWRITES
       THE CURRENT STATE WITH THE NEW MESSAGE. */

    setMessages([...messages, data]);
  };

Back-End Code

export default async function handler(req, res) {
    if (!res.socket.server.io) {
      const io = new Server(res.socket.server);
      res.socket.server.io = io;

      io.on("connection", async (socket) => {
        socket.on("send-chat-message", async (message, user) => {
          socket.broadcast.emit("recieve-chat-message", 
          {
            message,
            name: user && user.name,
          });
        });
      });
   }
 }