I am facing error while building website the error is as follows when i run the command node index.js the data is not getting initialized

When I run the command node index.js in terminal the data is not getting initialized. It’s showing error

C:UsersSHANTANUDesktopMajor Projectnode_modulesmongooselibdocument.js:3201
    this.$__.validationError = new ValidationError(this);
                               ^

ValidationError: Listing validation failed: title: Path `title` is required.
    at Document.invalidate (C:UsersSHANTANUDesktopMajor Projectnode_modulesmongooselibdocument.js:3201:32)
    at C:UsersSHANTANUDesktopMajor Projectnode_modulesmongooselibdocument.js:2994:17
    at C:UsersSHANTANUDesktopMajor Projectnode_modulesmongooselibschemaType.js:1370:9
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
  errors: {
    title: ValidatorError: Path `title` is required.
        at validate (C:UsersSHANTANUDesktopMajor Projectnode_modulesmongooselibschemaType.js:1367:13)
        at SchemaType.doValidate (C:UsersSHANTANUDesktopMajor Projectnode_modulesmongooselibschemaType.js:1351:7)
        at C:UsersSHANTANUDesktopMajor Projectnode_modulesmongooselibdocument.js:2986:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: {
        validator: [Function (anonymous)],
        message: 'Path `title` is required.',
        type: 'required',
        path: 'title',
        fullPath: undefined,
        value: undefined
      },
      kind: 'required',
      path: 'title',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose#validatorError)]: true
    }
  },
  _message: 'Listing validation failed'
}

I am sharing the source code for reference. Please go to this link to download the file for data: https://github.com/apna-college/wanderlust/blob/main/init/data.js. Repository for the project: https://github.com/apna-college/wanderlust.

plz help me solve this error

How to check javascript bad word check as a whole?

There is a string list with bad words. I want it to give a warning when there are words in this list. True if it contains, false if it does not.

I wrote a function, but since I used the “includes” method, it perceives the words in the word as swearing. The word is “Albad”. It returns true because there is “bad” in the bad word list.

How can I detect profanity when written as a whole? For example, when you write “Al bad”, it will be perceived as swearing.

badWordCheck(value: string): boolean {
   var badWords = ["bad","bad1","bad2","bad3"];
   let isInclude = badWords.some(word => value.includes(word));
   return isInclude;
        
}
this.badWordCheck("Albad")

How to convert response as a function to JSON [duplicate]

The url I’m trying to fetch the data from:

"https://blob.niftyindices.com/jsonfiles/SectorialIndex/SectorialIndexDataNIFTY%20AUTO.js"

The response is a .js file. When I opened the file, this is the data I get:

modelDataAvailable({
    "groups": [{
        "label": "ASHOKLEY 2.8%",
        "weight": 2.8,
        "id": "1"
    }, {
        "label": "BHARATFORG 3.5%",
        "weight": 3.5,
        "id": "2"
    }, {
        "label": "BAJAJ-AUTO 9.61%",
        "weight": 9.61,
        "id": "3"
    }, {
        "label": "BALKRISIND 2.16%",
        "weight": 2.16,
        "id": "4"
    }, {
        "label": "BOSCHLTD 2.23%",
        "weight": 2.23,
        "id": "5"
    }, {
        "label": "EICHERMOT 5.82%",
        "weight": 5.82,
        "id": "6"
    }, {
        "label": "HEROMOTOCO 6.65%",
        "weight": 6.65,
        "id": "7"
    }, {
        "label": "M&M 16.38%",
        "weight": 16.38,
        "id": "8"
    }, {
        "label": "MARUTI 14.9%",
        "weight": 14.9,
        "id": "9"
    }, {
        "label": "MOTHERSON 2.98%",
        "weight": 2.98,
        "id": "10"
    }, {
        "label": "MRF 3.22%",
        "weight": 3.22,
        "id": "11"
    }, {
        "label": "SONACOMS 2.81%",
        "weight": 2.81,
        "id": "12"
    }, {
        "label": "TATAMOTORS 17.25%",
        "weight": 17.25,
        "id": "13"
    }, {
        "label": "TIINDIA 4.51%",
        "weight": 4.51,
        "id": "14"
    }, {
        "label": "TVSMOTOR 5.16%",
        "weight": 5.16,
        "id": "15"
    }, ]
}, {
    label: "NIFTY AUTO ",
    file: "SectorialIndexDataNIFTY AUTO.jsonp "
});

Now my question is that this data is coming in the form of a function and not an object. So, how should I actually get the data in the object form so I can display on screen.

How can I exit Firebase in this node example?

I am running a script and after some issues and some help on here !! I got the script to work only to find out it won’t exit after the final loop.

I am using Firebase Admin and I believe the connection keeps open so the script won’t close. I tried using process.exit(0), but – it exits before the whole task is complete. In my case I have a For loop that is using an array id_Arr for length. The loop should access the strings in the array use them as a partial and do the task required. It all works fine before the final element. Instead of using the final element in the Array the program exits.

Why is that so?

const https = require('node:https');

// Firebase

var admin = require("firebase-admin");

var serviceAccount = require("...");

admin.initializeApp({
...
});

var db = admin.database();

// Firebase



const delay = ms => new Promise(res => setTimeout(res, ms));

arr = new Array();
id_Arr = new Array();
race_arr = new Array();



// Get and Push Lineups Function


const getLiveMatches = async () => {
    for(let m=0; m <= id_Arr.length - 1; m++){
  await delay(5000);
 https.get('https://lin-to-API/'+id_Arr[m]+'/API-Key', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

    res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
      const parsedDat = JSON.parse(rawData);
     race_arr.push(parsedDat);
     console.log(race_arr);
     console.log(id_Arr);

     var lines = db.ref("lineups");
const linesRef = lines.child(id_Arr[m]);

    // Writing Data

linesRef.set(race_arr[0]);

    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(e);
});

// Destroy Array
race_arr.splice(0, race_arr.length);

  }
process.exit(0);
}

// Get Daily Schedule


https.get('https://path/to/races', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

    res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
      const parsedData = JSON.parse(rawData);
      arr.push(parsedData.sport_events);
      // console.log(arr);
      var xm = arr[0].filter(function(item){
  return item.status == 'closed';
});

      for(i = 0; i  <= xm.length -1; i++){
        id_Arr.unshift(xm[i].id);
      }

console.log(id_Arr);
getLiveMatches();


    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(e);
});

I tried starting id_Arr with an filler value – that worked, but that is not the best idea.

I also removed the -1 from the for()
That worked well, can anyone explain this to me ? Why is this happening ?
Why is the loop exiting right before the last element ?

Javascript async/await blocking event listener

I have a simple grid-based game using an A* pathfinder algorithm. I think my pathfinder, which is triggered on mouseover, is blocking a separate right click event for grouping units for combat.

I have one event listener on mouseover that executes the pathfinder:

// (in view) (handler is findPath, below)
bindPathfinder(handler) {
  this.$grid.querySelectorAll('.cell').forEach(($cell) => {
    // show best path from active unit to cell on hover
    // (model will ignore if no active)
    const c_row = $cell.dataset.row;
    const c_col = $cell.dataset.col;
    $cell.addEventListener("mouseover", e => {
      // pass handler desired target cell
      // handler will call view.updatePath with path
      handler({'row': c_row, 'col': c_col});
    }); 
  });
}

// handler points to:
async findPath(target) {
  // find astar path from active unit to target
  // target is {row, col}

  if (this.activeUnitId == -1) {
    // if there's no active unit, do nothing
    return;
  }

  // otherwise, compute best path (async execution)
  const uid = this.activeUnitId;
  const start_cell = this.graph.getCell(this.units[uid].row, this.units[uid].col);
  const target_cell = this.graph.getCell(target.row, target.col);

  this.path = await astar(this.graph, start_cell, target_cell);

  this.onPathUpdate(this.path); // updates view
}

This works fine by itself. Then I have a second event handler for right clicks,

// in view
bindCombatGroup(handler) { 
  // handle combat grouping
        
  this.$grid.querySelectorAll('.unit').forEach(($unit) => {
    // on (right)click, attempt to group active unit
    // to the right clicked unit
    // model will ignore if no active unit, or if active unit not
    // adjacent to rightclicked unit
    const uid = $unit.dataset.id;
            
    $unit.addEventListener("contextmenu", e => {
      e.preventDefault();
      console.log('I don't get executed if astar is executing!');
      handler(uid);
    });
  });
}

If mouseover doesn’t trigger mouseover (for example if there’s no active unit), then the right click event will trigger its handler. But if astar is triggered at all, then the right click event doesn’t trigger.

Anyone know what’s going on here?

Is it possible to reexport typescript types modified at compile time?

In this question I’m trying to create an Angular library that registers some plugins in chart.js.

import gradient from 'chartjs-plugin-gradient';

Chart.register(...registerables);
Chart.register(gradient);

And when plugins are registered in Chart.js, it modifies the ChartConfiguration type so that the namespace for the type now supports the plugins.

However it seems this reconfiguration “Disappears” when the library compiles, and so clients of the library don’t know that the plugins have been registered.

Is there a way to reexport Typescript types that are modified at compile time?

For example if we have something very simple.

export class Test {
  public name: string = '';
}

And our code does something that programmatically modifies Test.

Can we reexport Test with the programmatic modification compiled into the package types?

If I understand correctly the Typescript compiler does not know that we have programmatically modified Test and so even though the Typescript runtime understands that it has been programmatically modified, the Typescript compiler does not …

Microsoft OAuth Access Token Request – 400 Bad Request

I have been trying to follow Microsoft’s authorization code flow, but unfortunately, I have run into an error when trying to request an access token with a client secret. I have ensured that all client IDs, redirect URLs, and scopes match from the retrieval of the authorisation code to the request for the access token, but I have been unable to fix the issues.

This is the initial URL created to retrieve the authorisation code is:

https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?
 client_id=237e....&
 redirect_uri=http://localhost:3000/xbox-oauth-callback&
 response_type=code&
 response_mode=query&
 code_challenge=aepyAU0M6wE8wRsEDUgp5G0VHpz5-qIAkG5dnuiHWpM&
 code_challenge_method=S256&state=38c597a6-1bdb-49b8-84ff-b5ec770b9930&
 scope=XboxLive.signin&
 prompt=consent

Following authentication, I am redirected to http://localhost:3000/xbox-oauth-callback?code=....047a539&state=38c597a6-1bdb-49b8-84ff-b5ec770b9930 to read the authorisation code from the URL. The error occurs after this when trying to request the access token:

const body = new URLSearchParams({
    client_id: 237e....,
    scope: "XboxLive.signin",
    code: "....047a539",
    redirect_uri: "http://localhost:3000/xbox-oauth-callback",
    grant_type: "authorization_code",
    code_verifier: "gVCClLeSnLF6zZAGm0LknUze38cHnTA1w27p0EF6vKGy6H3xDdyLHw",
    client_secret: 3ak...,
  });

  const response = await fetch(
    "https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body,
    }
  );

Error fetching OAuth tokens: [400] Bad Request

Html file reloads for unknown reason

I’m trying to make a small game in HTML, and it keeps reloading, and I don’t know why.

Page is found here: https://burritokitten.github.io/Trig-Practice/app2.html
I you think that the odd behavior might be caused by a lack of the preset cookies, they can be set here: https://burritokitten.github.io/Trig-Practice/options.html
All code is found here:
https://github.com/burritokitten/Trig-practice?tab=readme-ov-file

I’m likely making a stupid mistake somewhere, but would greatly appreciate the help.

Currently, the code calls ‘checkAnswer’, and I believe that this is where it crashes.
The code is as follows:

const sinArray = [
  ['0°', '0', '0'],
  ['30°', 'π/6', '1/2'],
  ['45°', 'π/4', 'r2/2'],
  ['60°', 'π/3', 'r3/2'],
  ['90°', 'π/2', '1'],
  ['120°', '2π/3', 'r3/2'],
  ['135°', '3π/4', 'r2/2'],
  ['150°', '5π/6', '1/2'],
  ['180°', 'π', '0'],
  ['210°', '7π/6', '-1/2'],
  ['225°', '5π/4', '-r2/2'],
  ['240°', '4π/3', '-r3/2'],
  ['270°', '3π/2', '-1'],
  ['300°', '5π/3', '-r3/2'],
  ['315°', '7π/4', '-r2/2'],
  ['330°', '11π/6', '-1/2'],
  ['360°', '2π', 'NAN']
];
var startTime = new Date().getTime() / 1000;
var totalAnswered = 0;
var totalCorrect = 0;
var currentStreak = 0;
var currentAnswer;
var lastQuestion;
var currentScore = 0;
var bestScore = 0;
var timeOfLastCorrect = startTime;
var root = document.querySelector(':root');

function scanCookies() {
  cookie = getCookie("backgroundColor")
  if (!cookie == "") {
    console.log(cookie)
    document.body.style.backgroundColor = cookie;
    var all = document.getElementsByTagName("input")
    for (var i = 0, max = all.length; i < max; i++) {
      all[i].style.backgroundColor = cookie;
    }
  }
  cookie = getCookie("textColor")
  if (!cookie == "") {
    console.log(cookie)
    var all = document.getElementsByTagName("*");

    for (var i = 0, max = all.length; i < max; i++) {
      all[i].style.color = cookie;
    }
  }
  if (!getCookie("bestScore") == "") { bestScore = getCookie("bestScore"); }
}

function setCookie(cname, cvalue) {
  const d = new Date();
  d.setTime(d.getTime() + (10 * 24 * 60 * 60 * 1000));
  let expires = "expires=" + d.toUTCString();
  let cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  console.log("Cookie set to: " + cookie)
  document.cookie = cookie;
}

function getCookie(cookieName) {
  let name = cookieName + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let cookieArray = decodedCookie.split(';');
  console.log(cookieArray);
  for (let i = 0; i < cookieArray.length; i++) {
    let cookieElement = cookieArray[i];
    while (cookieElement.charAt(0) == ' ') {
      cookieElement = cookieElement.substring(1);
    }
    if (cookieElement.indexOf(name) == 0) {
      return cookieElement.substring(name.length);
    }
  }
  console.log("Failed to find cookie " + cookieName);
  return "";
}

function newQuestion() {
  //generate question
  let currentQuestion = getCookie('full_circle_toggle') == 'true' ? Math.floor(Math.random() * 17) : Math.floor(Math.random() * 9);
  let currentSinState = Math.floor(Math.random() * 2)
  //check if qestion is different from last (ignores rad/deg)
  if (currentQuestion + 17 * (currentSinState) == lastQuestion) {
    newQuestion();
    return;
  }
  //choose degree or radian
  let degVsRad = getCookie('degree_toggle') == 'true' ? (getCookie('radian_toggle') == 'true' ? Math.floor(Math.random() * 2) : 0) : 1;
  //actually select question
  let question = currentSinState == 0 ? "Sin (" + sinArray[currentQuestion][degVsRad] + ")" : "Cos (" + sinArray[currentQuestion][degVsRad] + ")";
  //choose matching answer
  currentAnswer = sinArray[(currentQuestion - 4 * currentSinState + 16) % 16][2];
  console.log(currentAnswer);
  //update last question
  lastQuestion = currentQuestion + 17 * (currentSinState);
  //SET QUESTION//
  document.getElementById('question').innerText = question;
}

function checkAnswer() {
  //collect answer
  var userAnswer = document.getElementById("answer").value.toLowerCase().trim();
  //check if answer is an option
  if (isAnswerOption(userAnswer)) {
    //increment total answers
    totalAnswered++;
    //check if answer is right
    if (userAnswer == currentAnswer) {
      //increase counts, update score
      timeOfLastCorrect = new Date().getTime() / 1000;
      currentStreak++;
      totalCorrect++;
      currentScore = totalCorrect * totalCorrect / (timeOfLastCorrect - startTime);
      if (currentScore > bestScore) {
        bestScore = currentScore;
        setCookie("bestScore", bestScore)
      }
      document.getElementById("result").innerText = "Correct! Well done!";
      //updateScore();
      //newQuestion();
    }
    else {
      currentStreak = 0;
      document.getElementById("result").innerText = "Incorrect. Please try again."
    }
  }
  else {
    document.getElementById("result").innerText = "Please enter a valid answer option.";
  }
}

function isAnswerOption(answer) {
  for (x = 0; x < 16; x++) {
    if (sinArray[x][2] == answer) { return true; }
  }
  return false;
}

How do I format the data prettier with nice format?

We receive data from our upstream source system with the format as provided below ( script section).. When I use the pre tag to display in our web page, the formatting does seem to be off due to the extra “t” or”r” .

Here is the source code,

<html>
<body>

<pre id="div">
</pre>
<script>
document.getElementById('div').innerHTML=
`Group Name:    Test GROUP BUSINESS - SAArnPRODUCT:ABCttPRIME  CTR: DenverrnOPTIONAL NAME: tttPLATINUM GROUP: YrNEWRK: ABC/KLFrnrSA STATE:    
AAtttET STATE:   COrSA  MANDATE:  N/AttET MANDATES: N/At\trnrnABCAA STATUS:ttGRANDFrnttttNETWORK:ttNON-NEWRK:rnCALENDAR YEAR  
 MAX:ttN/At  ttN/ArnLIFE MAX:tttt  $1000  (COMBINED)        trnttttttttntttNEWRK:ttNON-NEWRK:rnTESTIN
 ttt100%ttt80%rntttttttrnttttttttnrNEWRK:tt NON-NEWRK:rnMY MONEY:ttttttttrnCALENDAR YEARtttrn   
 IND:tttNonettGRPttt$1000rn   CROSS ACCUM?tttN/A`
</script>
</body>

</html>

My requirement is to
a) Need to “bold” the text before “:”
b) display it in a table format with border for each cell ( like below). A script formatting . Is it possible ?. ANy expertise thoughts ?

| **Group Name: ** Test Group |
| ——– ———————————-|
| Product: ABC |Prime CTR: Denver |
| ——– ———————————-|
| Optional Name: | **Platinum Group: ** Y|

I tried using table as below. But I am getting only the outer border. Also I don’t know how to bold the text before “:”.

<table id = 'div' border = 1>
       </table>

Why I am getting error when setting innerHTML of an element to some localstorage value through get Item in ReactJS?

Actually I am trying to set a

elements innerHTML to some value from local storage ,It shows the value for the first time but whenever I trying to reload the page it shows error like the screenshot below!

Error showing after reload

here is the code-

const getName = window.localStorage.getItem("name");

   if(getName.charAt(0) == "M"){
  document.getElementById("myidname").innerHTML = "some message";

   }else{
console.log("error")
   }

<p id='myidname'></p>

I tried to wrap statements into a method then using that method inside the

element but still showing same error.

Images are being deleted after I make any changes to the edit page

Whenever I go to my edit page and make any changes, I lose the images that I uploaded to the campground. The images are also being deleted in mongo. Any help would be greatly appreciated.
https://github.com/mike-codes91/Yelpcamp/tree/main

I was expecting the selected image on the edit page to be deleted when I hit the update button. What happens next is that all the images are deleted. Come to find out that whenever I update anything on the edit page, all my images are deleted.

Why is my For loop going outside of the number limit set?

I am trying to run this script in Node, that all works well till for some reason the For loop goes on for longer than it should.

The code here takes a Schedule of races and within that call to the Api it should filter for the races that are done. The resulting array XM is then used to determin the length of the For Loop and within that loop the objects contained in XM are pushed to Firebase RTDB. Everything seems to be fine till the last element in XM is accessed and pushed, at which point the loop goes one more time.

const delay = ms => new Promise(res => setTimeout(res, ms));

arr      = new Array();
id_Arr   = new Array();
race_arr = new Array();


https.get('https://link-to-races', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => {
    rawData += chunk;
  });
  res.on('end', () => {
    try {
      const parsedData = JSON.parse(rawData);
      arr.push(parsedData.sport_events);

      var xm = arr[0].filter(function(item) {
        return item.status == 'closed';
      });

      const getLiveRaces = async() => {

        for (i = 0; i <= xm.length - 1; i++) {

          await delay(5000);
          https.get('https://linktoapi/' + xm[i].id + '/rest-of-api/apikey', (res) => {
            console.log('statusCode:', res.statusCode);
            console.log('headers:', res.headers);

            res.setEncoding('utf8');
            let rawData = '';
            res.on('data', (chunk) => {
              rawData += chunk;
            });
            res.on('end', () => {
              try {
                const parsedDat = JSON.parse(rawData);
                race_arr.push(parsedDat);
                console.log(race_arr);
                console.log(id_Arr);

                var lines = db.ref("lineups");
                const linesRef = lines.child(xm[i].id);

                // Writing Data

                linesRef.set(race_arr[0]);

              } catch (e) {
                console.error(e.message);
              }
            });
          }).on('error', (e) => {
            console.error(e);
          });

          // Detroy Array
          race_arr.splice(0, race_arr.length);


          console.log(i);
          console.log(xm);

        }

      }

      getLiveRaces();


    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(e);
});

Whats wrong here ? Why the extra ?

How to open info window and close another infor window when marker clicked?

I use Places Service to load locations that are around the default location. The problem is that when I click the marker, it opens an infowindow but doesn’t close other open infowindows. How to open an infowindow and close other open infowindows?

Initial marker
enter image description here

nearbySearch: I want when I click the marker, other open infowindows will be closed

enter image description here

below are the codes that I have created

<script>
    function initMap() {
        const defaultLocation = { lat: {{ $property->latitude }}, lng: {{ $property->longitude }} };
        const map = new google.maps.Map(document.getElementById('property-full-address-map'), {
            center: defaultLocation,
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: false,
            streetViewControl: false,
            gestureHandling: "greedy",
            styles: [ { "elementType": "geometry", "stylers": [ { "color": "#f5f5f5" } ] }, { "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "elementType": "labels.text.fill", "stylers": [ { "color": "#616161" } ] }, { "elementType": "labels.text.stroke", "stylers": [ { "color": "#f5f5f5" } ] }, { "featureType": "administrative.land_parcel", "elementType": "labels.text.fill", "stylers": [ { "color": "#bdbdbd" } ] }, { "featureType": "poi", "elementType": "geometry", "stylers": [ { "color": "#eeeeee" } ] }, { "featureType": "poi", "elementType": "labels.text.fill", "stylers": [ { "color": "#757575" } ] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [ { "color": "#e5e5e5" } ] }, { "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [ { "color": "#9e9e9e" } ] }, { "featureType": "road", "elementType": "geometry", "stylers": [ { "color": "#ffffff" } ] }, { "featureType": "road.arterial", "elementType": "labels.text.fill", "stylers": [ { "color": "#757575" } ] }, { "featureType": "road.highway", "elementType": "geometry", "stylers": [ { "color": "#dadada" } ] }, { "featureType": "road.highway", "elementType": "labels.text.fill", "stylers": [ { "color": "#616161" } ] }, { "featureType": "road.local", "elementType": "labels.text.fill", "stylers": [ { "color": "#9e9e9e" } ] }, { "featureType": "transit.line", "elementType": "geometry", "stylers": [ { "color": "#e5e5e5" } ] }, { "featureType": "transit.station", "elementType": "geometry", "stylers": [ { "color": "#eeeeee" } ] }, { "featureType": "water", "elementType": "geometry", "stylers": [ { "color": "#91D5E4" } ] }, { "featureType": "water", "elementType": "labels.text.fill", "stylers": [ { "color": "#9e9e9e" } ] } ]
        });

        var marker = new google.maps.Marker({
            position: defaultLocation,
            map,
            title: "Property Location",
        });

        marker.setMap(map);

    }

    $(document).ready(function() {
        $('.nearby-search-btn').click(function() {
            const type = $(this).data('type');
            const defaultLocation = { lat: {{ $property->latitude }}, lng: {{ $property->longitude }} };
            const map = new google.maps.Map(document.getElementById('property-full-address-map'), {
                center: defaultLocation,
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControl: false,
                streetViewControl: false,
                gestureHandling: "greedy",
                styles: [ { "elementType": "geometry", "stylers": [ { "color": "#f5f5f5" } ] }, { "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "elementType": "labels.text.fill", "stylers": [ { "color": "#616161" } ] }, { "elementType": "labels.text.stroke", "stylers": [ { "color": "#f5f5f5" } ] }, { "featureType": "administrative.land_parcel", "elementType": "labels.text.fill", "stylers": [ { "color": "#bdbdbd" } ] }, { "featureType": "poi", "elementType": "geometry", "stylers": [ { "color": "#eeeeee" } ] }, { "featureType": "poi", "elementType": "labels.text.fill", "stylers": [ { "color": "#757575" } ] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [ { "color": "#e5e5e5" } ] }, { "featureType": "poi.park", "elementType": "labels.text.fill", "stylers": [ { "color": "#9e9e9e" } ] }, { "featureType": "road", "elementType": "geometry", "stylers": [ { "color": "#ffffff" } ] }, { "featureType": "road.arterial", "elementType": "labels.text.fill", "stylers": [ { "color": "#757575" } ] }, { "featureType": "road.highway", "elementType": "geometry", "stylers": [ { "color": "#dadada" } ] }, { "featureType": "road.highway", "elementType": "labels.text.fill", "stylers": [ { "color": "#616161" } ] }, { "featureType": "road.local", "elementType": "labels.text.fill", "stylers": [ { "color": "#9e9e9e" } ] }, { "featureType": "transit.line", "elementType": "geometry", "stylers": [ { "color": "#e5e5e5" } ] }, { "featureType": "transit.station", "elementType": "geometry", "stylers": [ { "color": "#eeeeee" } ] }, { "featureType": "water", "elementType": "geometry", "stylers": [ { "color": "#91D5E4" } ] }, { "featureType": "water", "elementType": "labels.text.fill", "stylers": [ { "color": "#9e9e9e" } ] } ]
            });

            var marker = new google.maps.Marker({
                position: defaultLocation,
                map,
                icon: {
                    url: "{{ asset('front/img/marker.png') }}",
                    scaledSize: new google.maps.Size(40, 40)
                },
                title: "Property Location",
            });

            var request = {
                location: defaultLocation,
                radius: '500',
                type: [type]
            };

            var service = new google.maps.places.PlacesService(map);
            service.nearbySearch(request, callback);

            function callback(results, status) {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
                        var place = results[i];
                        createMarker(results[i]);
                    }
                }
            }

            function createMarker(place) {
                var neighborhoodMarker = new google.maps.Marker({
                    map: map,
                    position: place.geometry.location,
                    icon: {
                        url: place.icon,
                        scaledSize: new google.maps.Size(25, 25)
                    },
                    label: ''
                });

                var ratingCount = place.rating;
                var rating = '';
                //add icon for rating count
                if (ratingCount >= 4.5) {
                    rating = '<i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i>';
                } else if (ratingCount >= 4) {
                    rating = '<i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i>';
                } else if (ratingCount >= 3.5) {
                    rating = '<i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning-half"></i>';
                } else if (ratingCount >= 3) {
                    rating = '<i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i>';
                } else if (ratingCount >= 2.5) {
                    rating = '<i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning-half"></i>';
                } else if (ratingCount >= 2) {
                    rating = '<i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning"></i>';
                } else if (ratingCount >= 1.5) {
                    rating = '<i class="fa-solid fa-star text-warning"></i><i class="fa-solid fa-star text-warning-half"></i>';
                } else if (ratingCount >= 1) {
                    rating = '<i class="fa-solid fa-star text-warning"></i>';
                } else {
                    rating = '<i class="fa-solid fa-star-half"></i>';
                }

                var contentString = `
                    <div class="card border-0 min-width-200px">
                    <div class="card-body px-0">
                        <span class="fw-bold text-brand-secondary-color fs-5">` + place.name + `</span>
                        <p class="text-brand-secondary-color mt-2">` + place.vicinity + `</p>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="small text-brand-secondary-color">` + rating + `</span>
                            <span class="small text-brand-secondary-color">` + place.user_ratings_total + ` Reviews</span>
                        </div>
                    </div>
                    </div>
                `;

                var neighborhoodInfoWindow = new google.maps.InfoWindow({
                    content: contentString
                });

                neighborhoodMarker.addListener('click', function() {
                    neighborhoodInfoWindow.open(map, neighborhoodMarker);
                });

                google.maps.event.addListener(map, 'click', function() {
                    neighborhoodInfoWindow.close();
                });
            }
        });
    });

</script>

Angular pipe calls httpclent twice

Server returns json data(not a array). I use pipe/map with http to retrieve the data.Somehow, pipe always execuse twice: first time empty json data; second time server code outputs the json data, but catcheerroc() generates “unknown error”. Below is the code snippet, please help.

export class DbstoreService {
  private apiURL: string;
  
  constructor(private http: HttpClient) { 
       this.apiURL = environment.proxyPath;
  }

  getInfo()  {
     return this.http.get(`${this.apiURL}api/getInfo/5`)
     .pipe(
        map(response => response),
       catchError(this.handleError)
    )
    }
    private handleError(error: Response) {
    console.error('handle Error: ' + error.toString());
    return throwError(() => error.toString() || 'Server error');
     }
}

export class AppComponent implements OnInit{
... 
  constructor(
    private dbstoreService: DbstoreService
    )
  {
  }

  async getInfo()
  {
     await this.dbstoreService.getAgencyInfo().subscribe((data) => {});
         //  this.info.name = a.name;
 //  });
  }
}

Server code

 public IHttpActionResult Get(int id)
      {
     ...
        return Json(new { name = "testertester" });
      }
  }

How to figure a way of avoiding these SyntaxError messages on VS

Long story short I’m using Microsoft Copilot to help me understand and program small projects so I can get the hang of and understand more of JS, React, React Native, Tailwind and Node.js. However I keep getting the same syntax error’s each and every time whether I type the entire code out from what Copilot sends me or literally copying and pasting the code straight from Copilot. I’m just not understanding and even when I ask what’s going on here, why’s this happening, etc.

I’m reaching out to an actual person who would know what’s going on instead of AI. I literally don’t think AI is all that intelligent because I have followed everything “solution” Copilot has suggested I do and nothing has been fixed, I can’t run my code to show my actual project in app form or web form.

SyntaxError here

Again, I’ve tried everything MC has told me or suggested that I do. Even tried the extentions it suggested that I install on visual studio code. I’m debating whether or not I get advice on other IDEs to use. I like VS and know it’s popular but there’s been a decent amount of projects that I’ve done on there that show the same error as shown in the picture provided and yet my code shows no problems at all. I’m just wondering if I probably should try other IDEs.