req.user.populate(…) IS NOT A FUNCTION

so this is my app.js
the thing i want to do is when go the cart in my website, show me all the products in the cart with the user model that i created which has a field of cart in that there is cart items, which has two fields one product id, and quantity.
so i want to populate the product id so i can see their inf on and ofcourse quantity in my cart.

const path = require('path');

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

const errorController = require('./controllers/error');

const User = require('./models/user');

const app = express();

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');


app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use((req,res,next)=>{
    User.findById('657167533934e81f519f9bbd')
    .then(user=>{
        req.user = user;
        next();
    })
    .catch(err=>{
        console.log(err)
    })
})

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.use(errorController.get404);

mongoose.connect('mongodb+srv://feri:[email protected]/shop?retryWrites=true&w=majority')
.then(result=>{
User.findOne().then(user =>{
    if(!user){
        const user = new User({
    name:'feri',
    email:'[email protected]',
    cart:{
        items:[]
    }
});
user.save();
    }
});
    app.listen(3000);
}).catch(err=>{
    console.log(err);
})

and this is my shop controller. which i have a problem with the populate function.

exports.getCart = (req, res, next) => {
  req.user
    .populate('cart.items.productId')
    .execPopulate()
    .then(user => {
      const products = user.cart.items;
      console.log(products);
        res.render('shop/cart', {
          path: '/cart',
          pageTitle: 'Your Cart',
          products: products
        })
    })
    .catch(err => console.log(err));
};

and this is my user model.

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  name:{
    type: String,
    required:true
  },
  email:{
    type:String,
    required: true
  },
  cart:{
    items:[{productId:{type:Schema.Types.ObjectId,ref:'Product',required:true},
    quantity:{type:Number,required:true}}]
  }
});
userSchema.methods.addToCart = function (product){
  const cartProductIndex = this.cart.items.findIndex(cp=>{
      return cp.productId.toString() === product._id.toString();
    });
    let newQuantity = 1;
    const updatedCartItems = [...this.cart.items];

    if(cartProductIndex>=0){
      newQuantity = this.cart.items[cartProductIndex].quantity + 1;
      updatedCartItems[cartProductIndex].quantity = newQuantity
    }
    else{
      updatedCartItems.push({productId:product._id,quantity:newQuantity})
    }
    const updatedCart = {items:updatedCartItems};
    this.cart = updatedCart;
    return this.save();
}

module.exports = mongoose.model('User',userSchema);

and this is my product model.

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const productSchema = new Schema({
  title: {
    type:String,
    required: true
  },
  price:{
    type: Number,
    required:true
  },
  description:{
    type: String,
    required: true
  },
  imageUrl:{
    type:String,
    required:true
  },
  userId:{
    type:Schema.Types.ObjectId,
    ref:'User',
    required:true,
  }
})

module.exports = mongoose.model('Product',productSchema);

i tried updating the mongoose.
changing the name an all that.
i dont know what is wrong anymore.your text

I’m trying to send the base64 dataUrl as payload to the backend, but my function is returning an empty string [duplicate]

I’m developing a certificate designing application, and I want to send a base64 datUrl of the certificate to the backend. I wrote a “getThumbnail()” function in order to return a compressed base64 dataUrl of the certificate for preview.

getThumbnail(): string {
let node: any = document.getElementById('certificate-preview-container');
let thumbnail: string = "";

htmlToImage.toPng(node).then(function (dataUrl) {
    let img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
    // console.log("DataUrl: ", dataUrl);
    console.log("DataUrl: ", typeof(dataUrl));
    //return dataUrl;
    img.onload = function() {
      // Create a canvas and draw the compressed image
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      // Set the canvas dimensions to the desired size (e.g., for compression)
      canvas.width = img.width * 0.2; // Adjust the width as needed
      canvas.height = img.height * 0.2; // Adjust the height as needed

      // Draw the image onto the canvas
      ctx!.drawImage(img, 0, 0, canvas.width, canvas.height);

      // Get the compressed data URL from the canvas
      const compressedDataURL = canvas.toDataURL('image/png', 0.5); // Adjust quality as needed

      // Display the compressed image
      const compressedImage = new Image();
      compressedImage.src = compressedDataURL;
      thumbnail = compressedDataURL;
      console.log("Thumbnail: ", typeof(thumbnail));
      //return thumbnail;
      document.body.appendChild(compressedImage);
      console.log("Compressed image: ", compressedDataURL);
      return thumbnail;
    }
  })
  .catch(function (error) {
    console.error('oops, something went wrong!', error);
    //return thumbnail;
  });

  return thumbnail;
}

Then I wrote a “saveCertificate()” function which sends the required data as payload to the backend, which also includes the “thumbnail” field which is supposed to get the compressed base64 dataUrl.

saveCertificate(){

let data : CertificatePostBody = {
  certificate : {
    "id": Number(this.certificateId),
    "certificateTemplate": this.certificate.template,
    "height": this.certificate.height,
    "width": this.certificate.width,
    "backgroundImage": this.certificate.backgroundImage,
    "orientation": this.certificate.orientation,
    "certificateType": this.certificate.certificateType,
    "certificateName" : this.certificate.certificateName,
    "dateFormat" : this.certificate.date_format,
    "thumbnail" : this.getThumbnail()
    //"thumbnail": "test2"
  }
};
this.certificateService.updateCertificate(data).subscribe((res:any)=>{
  console.log('res=>', res);
  
})

The problem is that the “thumbnail” field shows blank when I check it in the network tab in inspect element, meaning the getThumbnail() function is returning a blank string. Now I am aware it could be because of the asynchronous nature of the htmlToImage.toPng function and it returns a promise. How can I modify the getThumbnail() function so that it returns the compressed dataUrl as string for me to send it to backend?

how to set custom image to background-image of body element using user property in web wallpaper of wallpaper engine?

body {background-image: url('wallpaper.jpg'); background-size: cover;}

window.wallpaperPropertyListener = {
            applyUserProperties: function(properties) {
                 if (properties.customimage) {
                    var customImageFile = 'file:///' + properties.customimage.value;
                    document.body.style.backgroundImage = `url('${customImageFile}')`;
                }        
            },
        };

this works if i set to img src instead of background-image.
when i import image to user property, nothing changes. but when i remove it, background image (default one) disappears.

small lib that track all ajax and fetch request

I need a library or if you could show me how to track all fetch and ajax operations(globally).

  • the info i need as follow
  • the call type get|post etc
  • the calls body json|other etc
  • the url
  • the header if possible
  • the response.

is there any way i can get those info globally, like chromevdev tools dose.

CRM JavaScript – SendAppNotification

We’re attempting to emulate the CRM Toast Notification JavaScript functionality described in the following Microsoft article…

https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/send-in-app-notifications?tabs=clientapi

Using the following first example from the article, the notification is successfully sent to the user:

var SendAppNotificationRequest = new Example.SendAppNotificationRequest(
    title = "Welcome",
    recipient = "/systemusers(8d585985-e1f4-ed11-8818-0022483d019b)",
    body = "Welcome to the world of app notifications!",
    priority = 200000000,
    iconType = 100000000,
    toastType = 200000000,
);

However, when we attempt the second following example, that includes an overrideContent element, we receive an error:

var SendAppNotificationRequest = new Example.SendAppNotificationRequest(title = "SLA critical",
    recipient = "/systemusers(8d585985-e1f4-ed11-8818-0022483d019b)",
    body = "Record assigned to you is critically past SLA.",
    iconType = 100000003,
    toastType = 200000000,
    overrideContent = {
        "@odata.type": "#Microsoft.Dynamics.CRM.expando",
        "title": "**SLA critical**",
        "body": "Case record [Complete overhaul required (sample)](?pagetype=entityrecord&etn=incident&id=0a9f62a8-90df-e311-9565-a45d36fc5fe8) assigned is critically past SLA and has been escalated to your manager."
    }
);

Here is the error we are receiving when attempting to execute that second example:

"message": "Error identified in Payload provided by the user for Entity :'', 
For more information on this error please follow this help link https://go.microsoft.com/fwlink/?linkid=2195293  
---->  InnerException : System.ArgumentException: Stream was not readable.

Has anyone seen this before or have any ideas why this second example is returning this error?

Convert form data into multi-dimensional array

I have a form that has fields like name email other[a] other[b] which is submitted by AJAX. At the moment, the script that prepares the data before using Axios for posting does this

const data = Array.from(new FormData(this.form).entries()).reduce((memo, pair) => ({
    ...memo,
    [pair[0]]: pair[1],
}), {});

which produces

  {
     "name":"X",
     "email":"Y",
     "other[a]":"A",
     "other[b]":"B",
  }

but it needs to be

  {
     "name":"X",
     "email":"Y",
     "other": {
       "a": "A",
       "b": "B"
     }
  }

What do I need to do so that the other fields become a nested array?

How can I add sounds and a scoreboard to my tic tac toe site?

I have an assignment that I have mostly done. It is coding a tic tac toe game using Javascript. But the two big things I cannot figure out how to do are to add a working scoreboard to the site that will increment wins and ties, and adding a sound that plays when someone wins and a different sound for when there is a tie game. I really need help. I’m so confused as to what to do. I’ve looked for solutions, but I can’t see how any of the ones I’ve found work with my specific case. I’m just getting really frustrated with the whole thing and I’m tired of staring at this stupid code.

My HTML code is here.

<!DOCTYPE html>
<html lang="en">
    <audio src="../sounds/win.mp3" id="win"></audio>
    <audio src="../sounds/fail.mp3" id="tie"></audio>
    
    <head>
        <title>Tic Tac Toe</title>
        <link href="css/style.css" rel="stylesheet" type="text/css">
        <script src="js/script.js"></script>
    </head>

    <body onload="startGame();">
        <h2 id="game-message">Tic Tac Toe</h2>
        <div id="game-board"></div>
        <table id="scoreboard">
            <tr>
                <th>Player 1</th>
                <th>Player 2</th>
                <th>Ties</th>
            </tr>
            <tr id="scores">
                <td class="score" id="p1score">
                    0
                </td>
                <td class="score" id="p2score">
                    0
                </td>
                <td class="score" id="tiescore">
                    0
                </td>
            </tr>
        </table>
        <div id=button><button id="playAgain" onclick="startGame();">Play Again?</button></div>
        
    </body>
</html>

And here’s my Javascript code:

var markers = ["X", "O"];
var players = [];
players[0] = prompt("Enter player one:");
players[1] = prompt("Enter player two:");
var totals = [];
var winCodes = [7,56,73,84,146,273,292,448];
var gameOver = false;
var whoseTurn = 0;
var p1Score = 0;
var p2Score = 0;
var win = new Audio('../sounds/success.mp3');
var tie = new Audio('../sounds/fail.mp3');

function startGame()
{
    var counter = 1;
    var innerDivs = "";
    for (i = 1; i <=3; i++)
    {
        innerDivs += '<div id="row-' + i + '">';
        
        for (j = 1; j <=3; j++)
        {
            innerDivs += '<div onclick="playGame(this,' + counter + ');"></div>';
            counter *=2;
        }

        innerDivs += '</div>';
    }

    document.getElementById("game-board").innerHTML = innerDivs;
    totals = [0, 0];
    gameOver = false;
    document.getElementById("game-message").innerText = "It's " + players[whoseTurn] + "'s Turn";
}

function playGame(clickedDiv, divValue)
{
    if (!gameOver)
    {
        //add x or o
        clickedDiv.innerText = markers[whoseTurn];

        //increment total for possible win
        totals[whoseTurn] += divValue;

        //call isWin() function
        if (isWin())
        {
            document.getElementById("game-message").innerText = players[whoseTurn] + " Wins!";
        }
        else if (gameOver)
            {
                document.getElementById("game-message").innerText = "Game Over, Man!";
            }
        else
        {
        //toggle player turn
        if (whoseTurn) whoseTurn = 0; else whoseTurn = 1;

        //prevent clicking same div again
        clickedDiv.onclick = "";

        //toggle message to display next player
        document.getElementById("game-message").innerText = "It's " + players[whoseTurn] +"'s turn";
        }
    }
}
//win code logic
function isWin()
{
    for (i = 0; i < winCodes.length; i++)
    {
        if ((totals[whoseTurn] & winCodes[i]) == winCodes[i]) { gameOver = true; return true; }        
    }

    if (totals[0] + totals[1] == 511) {gameOver = true;}

    return false;

}

var playSound = function()
{
    if (isWin() = true)
    {
        win.play();
    }
    if (gameOver = true)
    {
        tie.play();
    };
    playSound();
}

The last bit on the Javascript code was my attempt at making the audio work based off of an answer I saw to somebody else who seemed to have a similar issue, but it doesn’t work for me.

As far as the scoreboard goes, I don’t even know where to start.

ETA: I have tried moving the win.play() into the isWin function like this:

if ((totals[whoseTurn] & winCodes[i]) == winCodes[i]) { gameOver = true; win.play(); return true; }

It doesn’t work, either.

a small gap appeared between the two DIVs

When I debug on the iPhone 14 Pro, there is a small gap between the two DIVs, but it is normal on the other devices

enter image description here

.experience-thumb {
    width: 100%;
    height: 3px;
    background-color: rgba(255, 255, 255, 0.50);
    transform: skew(-25deg);
    border-top-left-radius: 1px;
    border-bottom-left-radius: 2px;
    border-top-right-radius: 2px;
    border-bottom-right-radius: 1px;
    overflow: hidden;
    position: relative;

    .experience-schedule {
       height: 3px;       transform: skew(3deg);
       border-top-left-radius: 1px;
       border-bottom-left-radius: 2px;
       border-top-right-radius: 2px;
       border-bottom-right-radius: 1px;
       transition: all 0.4s linear;
       background-size: contain;
    }
}

Downloading n number of html files which shows geospatial maps (hazard maps)

I have a nextjs application which let’s users upload an excel file with a list of addresses.

The application then shows a hazard map per each address. Further, the user can then download each hazard map as an html file.

The problem I’m running into at the moment is that when I have around 50+ addresses in the excel file, the download logic seems to fail, and by that I mean the screen just goes to Aw, Snap. Something went wrong.

I created a route handler (api route) to create and return the html template (the template of course contains a script tag for the necessary javascript to show the hazard maps via leaflet).

// the route handler:

export async function POST(request: NextRequest) {
  if (!request.body) return NextResponse.json({ status: 400 });

  const requestBody: LeafletData = await request.json();

  // consider minifying?
  const htmlTemplate = leafletTemplate(
    requestBody.address,
    requestBody.coords,
    requestBody.coastlines,
    requestBody.faultLines,
    requestBody.snowfall,
    requestBody.snowfallAreas,
    requestBody.volcanoes,
    requestBody.geoJson,
    requestBody.tileLayers
  );

  return NextResponse.json({
    status: 200,
    template: htmlTemplate,
  });
}


// fetching and downloading as a zip
for (const [index, fileItem] of selectedFile.fileContent.entries()) {
  const leafletData = leaflet[index];
  const coords = { lat: fileItem.lat, lng: fileItem.lng };
  const { type, features } = leafletData[fileItem.addr];

  // this endpoint returns the html template
  const response = await fetch("/leaflet/api", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
    address: fileItem.addr,
    coords,
    coastlines,
    faultLines,
    snowfall,
    snowfallAreas,
    volcanoes,
    geoJson: { type, features },
    tileLayers: leafletData[fileItem.addr],
    }),
  });

  const { template } = await response.json();

  zip.file(`${fileItem.id}_${fileItem.addr}.html`, template);
}

zip.generateAsync({ type: "blob" }).then((content) => {
  const url = URL.createObjectURL(content);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${selectedFile.filename}_result.zip`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
});

Would minifying help? How much can I save by removing whitespace? since it is geospatial data, some html files can be over well over 10MB.

I could limit how many files a user can download (perhaps only download selected), but I think they’ll want to be able to download them all at once.

Any ideas/tips/advice?

Java Scripting Password [closed]

I am trying to make a password code to my bank account java scripting. And deposit and withdraw code. But I have zero clue how, this is what I have now

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner myObj = new Scanner(System.in);
        String userName;
        String passWord;
        System.out.println("Enter Username:");
        userName = myObj.nextLine();
        ArrayList<String> people = new ArrayList<String>();
        people.add("Person1");
        people.add("Person2");
        people.add("Person3");
        people.add("Person4");
        for (int i = 0; i < 4; i++) {
            if (userName.equals(people.get(i))) {
                System.out.println("Account found. Password Required.");
                passWord = myObj.nextLine();
                else if System.out.println("Invalid Username");
            }
            
        }
        ArrayList<Integer> money = new ArrayList<Integer>();
        money.add(5);
        money.add(1000);
        money.add(50001);
        money.add(1004);
    }
}

Transform currently opened Google sheet’s formulas entirely in the client

I would like to write a chrome extension (or some other simple pure client side JavaScript code) that grabs all the formulas of the “currently opened in the current browser tab” Google sheet then transforms them and copies the transformed formulas back into the client side representation of the Google sheet (as if the user had edited the formulas of the currently opened sheet to effect those changes).

I have existing JavaScript code that takes an entire spreadsheet’s formulas as input and returns the modified formulas that are to replace the original formulas. This code never hits the server; it’s a pure text array to text array function. So if I could do it all on the client would make everything easier (no authentication needed to access user’s data on server, etc.)

Never wrote a chrome extension never used a Google sheet but seems if there is an answer to my question would be possible to make it work without learning too much.

I have tried googling but seems there is no information on this pure client side avenue for transforming the currently opened Google sheet’s formulas. Of course this is trivial in Excel where everything is under local control. I have not tried anything on my own just trying to see if what I want to do is possible. If this is impossible open to other approaches but bear in mind the simplicity of everything happening in the browser is what I really want.

Adding Percentage in stacked bar charts of amCharts

I was trying to set the % symbol on the Y axis on the stacked bar chart using the R implementation of amCharts.
Below is my code with sample data

df <- data.frame( date = c('2016-12', '2017-12', '2018-12', '2019-12', '2020-12', '2021-12'),X4 = c(NA, NA, 1, NA, 3, NA), X5 = c(3, 2, 4, 1, 2, 3), X6 = c(1, 2, 1, 2, 3, 4), X7 = c(1, 2, 3, 4, 5, 6),X8 = c(2, NA, 3, 3, 2, 4), X9 = c(4, 3, 2, 1, NA, 2))

rAmCharts::amBarplot(x = "date", y = colnames(df)[-c(1)],data = df, stack_type = "100",legend = TRUE, show_values = T) %>% rAmCharts::setLegend(position = "bottom", useMarkerColorForLabels= TRUE)

I have tried with some Java script, but unfortunately it didn’t work.

Can anyone guide me on how to set the percentage either in the y axis or in the text label with the R implementation of amCharts?

Is it possible to use Github Pages to Deploy a Website that uses NPM Commands? [duplicate]

I am new to Node.js and GitHub pages and I have been trying to learn more about them both recently. I have a source code that uses Node.js, so it requires npm commands to run. My question: is it possible to use Github pages to deploy my website that requires npm commands to run? If yes, how? I am thinking I can write my own build script that GitHub can use and provide npm commands in it but I do not really know how to do that. Any advice?

My question is similar to the question below, but this question is too old (answered in 2013). I have also read newer blogs that mention it may be possible but they do not provide more details.

How to publish a website made by Node.js to Github Pages?

It is possible to make the values selected on the first input be displayed on the second input?

<StyledFieldsRow>

//First input
 
   <WhiteSelect
        tabIndex={7}
            requiredField
            placeholder="Select one"
            name="aso"
            defaultValue={{
              label: 'Normal',
              value: false,
            }}
            label="Type of service"
            options={[
              { label: 'ASO', value: true },
              { label: 'Normal', value: false },
            ]}
            menuPlacement="top"
      />
         

//Second input

       <WhiteInput
            style={{
              width: isMobile ? '100%' : '',
            }}
            name="note"
            label="Comments"
            tabIndex={9}
            placeholder="Enter notes"
         />
</StyledFieldsRow>

I’ve tried rewrite this in multiple ways, but none had worked and now I’m out of ideas. If anyone knows how to do this please answer.