Mongoose Query Printing Strange when Executing a Find Query

I have a project mongoose schema that contains the title and description of each project, and a ticket mongoose schema that also contains the title of the project the ticket is relevant to as well as the name of the user that the ticket is assigned to. Each individual project will be displayed on a post.ejs page, and I want to display the names of users who have been assigned tickets relating to that particular project.

Here is the get request so for the post.ejs page:

app.get("/posts/:postId", isLoggedIn, function(req, res) {
  const requestedPostId = req.params.postId;
  ProjectDetails.findOne({_id: requestedPostId}, function(err, post) {
    const tickets = TicketDetails.find({project: post.title});
    console.log(tickets);
    res.render("post", {title: post.title, content: post.content});
  });
});

I’m first querying the project database to find the project, then I’m querying the ticket database for all tickets related to the project, but when i console.log tickets I get an output like this:

output from console.log(tickets)

Issue with OpenAI API – Cannot find module ‘@openai/api’

I am having trouble using the OpenAI API with Node.js. Specifically, I am trying to use the openai.Completion object, but I keep getting a “Cannot find module ‘@openai/api'” error.

I have already tried installing the @openai/api package using npm install @openai/api, but I get a 404 error indicating that the package could not be found. I have also removed it and reinstalled but no luck.

I also tried upgrading to the latest version of Node.js, which is currently 19.1.0, but the issue is stuborn. I created a test script (test.js) with the following code:

const openai = require('openai');
openai.apiKey = 'sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
async function runTest() {
try {
const gpt3Response = await openai.Completion.create({
engine: 'davinci-codex',
prompt: `Create a simple conversational response for beginners, with an easy question at the end, based on the input: "Hello, how are you?"`,
max_tokens: 50,
n: 1,
stop: null,
temperature: 0.5,
});
console.log(gpt3Response.choices[0].text.trim());
} catch (error) {
console.error(error);
}
}
runTest();

When I run this script with node test.js, I get the following error:

Error: Cannot find module '@openai/api'
Require stack:
- C:UsersUserDocumentsCodingfolderstest.js

I have also tested the OpenAI API using VSC Thunder Client, and it seems to work. Here is the POST request I used:

POST https://api.openai.com/v1/engines/davinci/completions
{
"prompt": "do you like soccer",
"max_tokens": 50,
"n": 1,
"stop": null,
"temperature": 0.5,
"top_p": 1,
"echo": false
}

I received the following response:

{
"id": "cmpl-75BDDTIZ2Q1yodctHcEohCIsA1f46",
"object": "text_completion",
"created": 1681469095,
"model": "davinci",
"choices": [
{
"text": "?”nn“I’m not sure. I’ve never been to a game.”nn“I’m going to the game on Saturday. Would you like to go with me?",
"index": 0,
"logprobs": null,
"finish_reason": "length"
}
],
"usage": {
"prompt_tokens": 4,
"completion_tokens": 49,
"total_tokens": 53
}
}

Could you please help me understand what could be causing the “Cannot find module ‘@openai/api'” error?

To provide me with next steps to try figure out why this API is not working. Either solutions or further tests I can try.

Thank you!

Ionic 6 Dynamic Data & Sort Function

I’m having an issue using a function to sort an array:

I’m using a cartService which holds all the product data like this

 public product: Product[] = [
    {
      id:0,
  class: 'large',
  link: '/bars/0/',
  title:'bar zero',
  web1:'',
  },
  {
      id:1,
  class: 'large',
  link: '/hotel/1/',
  title:'hotel one',
  web1:'',
  },
  {
      id:2,
  class: 'large',
  link: '/bar/2/',
  title:'bar two',
  web1:'',
  }
  ];

and then to call the products

getProducts(): Product[] {
    return this.product;

  }

All works well using this in the page which calls the component providing a list of products using a filter by id pipe

<app-bars *ngFor="let product of getProducts() | filterbyid:{loctype: 'bars'}" [product]="product"></app-bars>

When you click on the view button

<ion-button [routerLink]="'/view-bars/' + product.id"></ion-button>

It sends you to the product page.

I’m trying to get the data to sort by title alphabetically. When I try this

getProducts(): Product[] {
    this.product.sort((a,b) => (a.title > b.title) ? 1 : ((b.title > a.title) ? -1 : 0))
    return this.product;

  }

all the products display alphabetically but when you press the view button it takes you to a completely different product. The rendered html is showing the link to the product correctly.

Obviously the sort function is causing the issue. Does anyone know anyway of solving this issue?

How to show multiple time reload dialog box with customize question using react js?

asking custom question

function handlePageReload(event:any) {
            const message = 'Are you sure you want to reload the page?';
            event.returnValue = message;
            return message;
          }
          useEffect(() => {
            window.addEventListener('beforeunload', handlePageReload);
          
            return () => {
              window.removeEventListener('beforeunload', handlePageReload);
            };
          }, []);

I need show reload dialog box every refresh on the browser. how?

Import module with require syntax even though module uses import/export syntax

I have a JavaScript class defined as:

// MyClass.js
module.exports = class MyClass {
  //...
}

This is imported elsewhere as:

// otherModule.js
const MyClass = require('./MyClass');

I’m trying to convert MyClass to TypeScript, so it’s now defined as:

// MyClass.ts
class MyClass {
  // ...
}
export default MyClass;

I need to continue to import this using the require syntax in JavaScript files, however do so I need to do either:

// otherModule.js
const MyClass = require('./MyClass').default;
// or
const { default: MyClass } = require('./MyClass');

Is there any way I can avoid having to explicitly specify that I’m importing default? Ideally I’d want to continue importing this with const MyClass = require('./MyClass');, if possible, even if this means I need to change how my TypeScript class is defined/exported.

Google Maps API: Schnellste Route (in km)

Guten Tag,

ich arbeite gerade an einem Projekt, um die schnellste Route (in km) von zwei Punkten zu bestimmen, heute ist mir aufgefallen, dass es einen Unterschied macht, ob man mit/ohne Autobahn, mit/ohne Mautstraßen …

Gib es in der API von Google eine Abfrage, wo er wirklich alle ignoriert und mir die schnellste Route zurückgibt? Egal, ob mit/ohne Autobahn, Verkehr, Baustellen … Ich brauche einfach die kürzeste Strecke.

Wäre cool, wenn ihr mir helfen könntet, da ich nichts finde.

Mit freundlichen Grüßen
Tom

Bis jetzt hab ich die Standart Ansicht, ohne Einstellungen, die gibt mir nur nicht alle Routen zurück die es gibt. Ich bräuchte die Route, sowenig km hat wie möglich.

Javascript redirection stalled and F5 reload

I have a behaviour on production site which cannot reproduce locally. Is it possible this behaviour in some browsers?
I have two pages A.php and B.php. I execute A.php, which redirects via Javascript to B.php, after making some php processing. Is it possible that if there is a lot of traffic, and B is no loaded, and still not showing on the URL bar, if I hit F5, I load A.php again, making some processing, but the redirection of the first step is still in process so:

  1. A.php is executed
  2. document.location href and load of B.php is started but stalled.
  3. F5 makes A.php executed again (this time without document.location.href as there is no stream data sent back to the browser yet)
  4. The 2) step is resumed when some stream data is sent from B.php

This would make that a F5 of impatient users would load A two times. Is it possible? I tried to reproduce it, putting a session variable to not write document.location.href a second time, but all I get is 1), 2) (I put a sleep() to reproduce), 3) F5 again loads A, without the redirect, and of course, it never redirects, it never reaches step 4).

How to make a workable comment system using blogger api v3

I using blogger and my website is https://scienhac.blogspot.com/
i want to add comment page so user can comment but how i use blogger api i try

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <div id="comments">
      <h2>Comments</h2>
      <ul id="comment-list"></ul>
      <form id="comment-form">
        <label for="name-input">Name:</label>
        <input type="text" id="name-input" required />
        <label for="email-input">Email:</label>
        <input type="email" id="email-input" required />
        <label for="comment-input">Comment:</label>
        <textarea id="comment-input" required></textarea>
        <button type="submit">Submit</button>
      </form>
    </div>
    <div id="comment-container"></div>
    <script>
      let x = document.querySelector("#comment-form");
      x.addEventListener("submit", (event) => {
        event.preventDefault();
      });
      const postID = "943659869113432918";
      const blogID = "9160331485130872315";
      const apiKey = "AIzaSyDZhYG2aZx-9XbFzJHi0H6Xjqn2Ntvbbqo";

      // Retrieve existing comments and display them on the page
      function getComments(postID) {
        const requestUrl = `https://www.googleapis.com/blogger/v3/blogs/${blogID}/posts/${postID}/comments?key=${apiKey}`;

        fetch(requestUrl)
          .then((response) => response.json())
          .then((data) => {
            const comments = data.items;
            comments.forEach((comment) => {
              const commentHtml = `
                <div class="comment">
                    <p class="comment-author">${comment.author.displayName} says:</p>
                    <p class="comment-text">${comment.content}</p>
                </div>
                `;
              document
                .getElementById("comment-container")
                .insertAdjacentHTML("beforeend", commentHtml);
            });
          })
          .catch((error) => console.error(error));
      }

      // Post a new comment
      function postComment(postID, name, email, comment) {
        const requestUrl = `https://www.googleapis.com/blogger/v3/blogs/${blogID}/posts/${postID}/comments?key=${apiKey}`;

        const commentData = {
          content: comment,
          author: {
            displayName: name,
          },
          blog: {
            id: blogID,
          },
          post: {
            id: postID,
          },
        };

        fetch(requestUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(commentData),
        })
          .then((response) => response.json())
          .then((data) => {
            // Add the new comment to the comment container
            const commentHtml = `
                <div class="comment">
                <p class="comment-author">${data.author.displayName} says:</p>
                <p class="comment-text">${data.content}</p>
                </div>
            `;
            document
              .getElementById("comment-container")
              .insertAdjacentHTML("beforeend", commentHtml);
          })
          .catch((error) => {
            console.error(error);
          });
      }

      // Attach event listener to the comment form
      document
        .getElementById("comment-form")
        .addEventListener("submit", (event) => {
          event.preventDefault();

          const name = document.getElementById("name-input").value;
          const email = document.getElementById("email-input").value;
          const comment = document.getElementById("comment-input").value;

          // Post the new comment
          postComment(postID, name, email, comment);

          // Clear the input fields
          document.getElementById("name-input").value = "";
          document.getElementById("email-input").value = "";
          document.getElementById("comment-input").value = "";
        });

      // Call getComments to retrieve existing comments
      getComments(postID);
    </script>
  </body>
</html>
const postID = '943659869113432918';
const blogID = '9160331485130872315';
const apiKey = 'AIzaSyDZhYG2aZx-9XbFzJHi0H6Xjqn2Ntvbbqo';
var commentData = {
    'content': 'This is a test comment.'
};

const requestUrl = `https://www.googleapis.com/blogger/v3/blogs/${blogID}/posts/${postID}/comments?key=${apiKey}`;

// Make the request to insert the comment
fetch(requestUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(commentData)
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
</script>

not works for blogid and postid i automate it i show you blogid and postid according to standard js but i use data:blogid etc //—> so how i made it sometime cors error or sometime any other error i receive

I want a comment page template i modigy it but it lowest scale send fetch and delete option must have

Appending more complex HTML elements using JS in a chrome extension

I’m working on my chrome extension to add some HTML elements to a currently existing page I don’t administrate.
I’m using JavaScript with no libraries due to system limitations.

I’ve currently successfully implemented 3 buttons using createElement() + appendChild().

I new want to add a multi level dropdown menu and my current method of adding elements gets very messy very quickly since I have to add all the HTML properties like this:

elementToAdd.id = "btnENG";
elementToADd.innerText = "Button English";

This is not viable for a multi element “ul” “li” dropdown menu since my code quickly becomes illegible (maybe due to my own syntax).

How would one create a complex HTML element or block and append it to an existing page using JS from a Chrome Extension?

Is insertAdjacentHTML good practice?

Is there a way I can add an HTML file to my extension’s manifest.json file and summon an HTML element from that file with JS to be appended on the website?

Thanks for any input.

React SetState not updating after axios call when component is unmounted

When the ‘Show Report’ button is clicked 1) showReport function is called 2) ReportLoadingPanel shows 3) axios api is triggered 3) when the api finishes, ReportLoadingPanel disappears.

This works when I stay on this page. However, when I switch to another tab and come back while the api is processing, setLoading(false) is never triggered. Loading is set to true from the stored session and this doesn’t set loading back to false so ReportLoadingPanel is showing forever even the api finishes.

How can I fix this?

const [loading, setLoading] = useState(false);

useEffect(() => {
  setLoading(!!window.sessionStorage.getItem("isButtonDisabled");
}, []);

useEffect(() => {
   console.log(loading);
}, [loading]);

const showReport = () => {
  setLoading(true);
  window.sessionStorage.setItem("isButtonDisabled", true);
  return axios({
    url: 'api/report/getdata',
    method: 'GET',
    responseType: 'blob'
  }).then(() => {
    window.sessionStorage.setItem("isButtonDisabled", false);
    setLoading(false);
  });
};    

return (
  <>
    {loading && <ReportLoadingPanel/>}
    <button onClick={showReport} disabled={loading}>Show Report</button>
  </>
);

Is import model to another not main model ok?

I have a restaurant application built in MVC architecture in JavaScript. Now I wonder whether import for example ingredientModel to recipeModel in order to take functionalities from ingredientModel is good idea?

Please help, write some alternatives if this idea is bad!

Console error in tweeter timeline added on website

I am getting console error in twitter timeline added on website. Twitter timeline is added in following way on website :

<div>
                <a href="@Model.TwitterTimeline" class="twitter-follow-button" data-dnt="true" data-show-count="false">@Model.TwitterFollowText</a>
                <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>

After digging more, I found that error occurs when poster object(don’t know about it’s source file in twitter) is undefined. Please check below snapshots for error and why it occurs. Please suggest If there is any solution.
console error in twitter timeline on website

I checked call stack and chrome inspector and get to know that it is failing at some code in twitter library only. But my point is, do I need to pass anything from my code for example as data attribute or if twitter has updated some thing in their code.

I am struggling with interacting with my code using OOP in javascript

I am busy creating a program in javascript where I have created a class called “Shoes” and given it the properties of “Name”, “Product Code”, “Quantity” and “Value per item”. I then created 5 instances of this. I want to push all 5 instances into an array and then create functions that will find any shoe in the array, find the shoe with the lowest value per item, the shoe with the highest value per item, a function where I can edit any instance of the “Shoes” class and a function that arranges them in ascending order. I am doing this in my spare time and I am struggling

let myArray =[]; 
class Shoes{
constructor(Name, ProductCode, Quantity, ValuePerItem){
    this.Name = Name,
    this.ProductCode = ProductCode,
    this.Quantity = Quantity,
    this.ValuePerItem = ValuePerItem
}
}

const shoe1 = new Shoes("Nike", 001, 500, 2000);
const shoe2 = new Shoes("Puma", 002, 1000, 1500);
const shoe3 = new Shoes("Adidas", 003, 250, 3000);
const shoe4 = new Shoes("Reebok", 004, 2500, 1000);
const shoe5 = new Shoes("Gucci", 005, 100, 5000);

myArray.push(Shoes.shoe1, Shoes.shoe2, Shoes.shoe3, Shoes.shoe4, Shoes.shoe5)
console.log(myArray)



function findShoes(shoe){
    let shoe = "Nike";
    for(let i = 0; i <= shoe.length; i++){
        if(shoe.length === "Nike"){
            console.log(shoe[i])
        }
}

}



console.log(shoe1, shoe2, shoe3, shoe4, shoe5);