Error: TypeError: request is not iterable, Gemini API

im making clone of gemini AI using react and javascript, at first glance it seems works, but after i inspect my project at the browser i got these errors, can anyone explain to me? newbie here

@google_generative-ai.js?v=1f858b71:559 Uncaught (in promise) TypeError: request is not iterable
    at formatNewContent (@google_generative-ai.js?v=1f858b71:559:32)
    at ChatSession.sendMessage (@google_generative-ai.js?v=1f858b71:730:24)
    at async run (gemini.js:24:18)

this is my current code

import { GoogleGenerativeAI } from "@google/generative-ai";

const apiKey = "AIzaSyDBBrhCK33iSPdt8RXJF6ev_6pPBthW57w";
const genAI = new GoogleGenerativeAI(apiKey);

const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
});

const generationConfig = {
  temperature: 1,
  topP: 0.95,
  topK: 40,
  maxOutputTokens: 8192,
  responseMimeType: "text/plain",
};

async function run(prompt) {
  const chatSession = model.startChat({
    generationConfig,
    history: [],
  });

  const result = await chatSession.sendMessage(prompt);
  console.log(result.response.text());
}

run();

export default run;

Returning an Ajax response which consists of HTML and JavaScript to the front end to be rendered

been trying for days to figure this out…im trying to call a shortcode via php, process it via Ajax and return the response to a frontend but has been unable to do so.
It seems that the script just wont run despite the do_shortcode correctly outputs the correct response. the codes as below: (Enqueue of JS has been done in a separate php)

PHP

add_action('wp_ajax_get_amelia_shortcode', 'get_amelia_shortcode');
add_action('wp_ajax_nopriv_get_amelia_shortcode', 'get_amelia_shortcode');

function get_amelia_shortcode() 
{
    if (defined('DOING_AJAX') && DOING_AJAX) 
    {
          include_once WP_PLUGIN_DIR . '/ameliabooking/ameliabooking.php';
           $output = do_shortcode('[ameliaeventscalendarbooking location=2]');
            error_log('Shortcode Output: ' . $output);
            echo $output;
    }
    wp_die();
}

JAVA

jQuery(document).ready(function ($) {
    $('#call-amelia-button').on('click', function () {
        const $ameliaContent = $('#amelia-content');

        $ameliaContent.text('Loading...').addClass('loading');

        // Perform AJAX request
        $.ajax({
            type: 'POST',
            url: customAjax.ajaxurl, // Defined via wp_localize_script
            data: { action: 'get_amelia_shortcode' },
            success: function (response) {
    // Extract the script content and HTML content
    const $responseHTML = $('<div>').html(response); // Wrap response in a jQuery object

    // Insert the non-script parts of the response into the target
    const $ameliaContent = $('#amelia-content');
    $ameliaContent.html($responseHTML.find('*').not('script').clone()).removeClass('loading');

    // Execute scripts in the response
    $responseHTML.find('script').each(function () {
        const scriptContent = this.text || this.textContent || this.innerHTML;
        try {
            console.log("Response Content:", response);
            $.globalEval(scriptContent);
        } catch (error) {
            console.error("Error executing script:", error);
        }
    });
},
            error: function (xhr, status, error) {
                // Handle errors gracefully
                $ameliaContent.text('An error occurred. Please try again later.').removeClass('loading');
            }
        });
    });
});

any help would be highly appreciated.
many thanks!

The aim is to trigger the Amelia booking plugin using do_shortcode() and update the frontend in realtime, the above is a simple execution to make sure the code works before implementing more complex logics and criteria to trigger the plugin with different params.

transfering data from from to maps marker and back

I want my code working before I upgrade to latest ver of php and google maps API. So if ur comment is somin about old code or optimization I know some things have deprecated.

I have a form that somone fills out and it takes the form data and makes a marker using it. However im not sure how to pull the data from the form onto the marker window. The form data pulls fine with a phpmailer script, however I cant get the form data onto the map1 marker0 window.Can anyone help quide me to trasfer the form data onto the info window for the marker? I may have to redo code to place marker after the message is filled out

HERE IS A FIDDLE

https://jsfiddle.net/h9d2juyv/

    <!DOCTYPE html>
<head>
    <style>
    /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
    #map1 {
    width:95%;
    height:800px;
    border: 3px solid blue;
       margin: 0 auto;
 }
    #map2 {
    width:95%;
    height:800px;
    border: 3px solid green;
       margin: 0 auto;
 }
 





 
 
 #demo{  border: 2px solid yellow;
    display:table;}
 </style>  
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="SHORTCUT ICON" href="images/favicon.ico"/>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>

<title>Fine Line Auto Body Shop | Collision Repair | Columbus Ohio.</title>
<meta name="description" content="Fine Line Auto Body Shop specializes in collision repair servicing all of Columbus Ohio. Call us today 1(614) 258-5555 for free estimate." />
<meta name="keywords" content="Body Shop, Columbus, Ohio, Auto Body Repair, Collision Repair, Free estimate, Columbus Ohio Central Ohio Collision Repair, Auto Body, Truck Body, Van Body, Columbus, Ohio Body Shop" />
<script src="https://code.jquery.com/jquery-latest.min.js"></script>

<link rel="stylesheet" href="css/flipcard.css" type="text/css" />
<link rel="stylesheet" href="css/style22.css" type="text/css" />
<script src="js/estimate.js"></script>
    <script>
        
$(document).ready(function() {
$("#mobmenu_hidden").click(function(){
$("#navagation").toggle();

});
});
    $(document).ready(function() {
     $('#blah').removeClass('hidden');

    var $animationElements = $('.animation-element');
    var $window = $(window);

    // ps: Let's FIRST disable triggering on small devices!
     var isMobile = window.matchMedia("only screen and (max-width: 768px)");
    if (isMobile.matches) {
        $animationElements.removeClass('animation-element');
    }

    function checkIfInView() {

        var windowHeight = $window.height();
        var windowTopPosition = $window.scrollTop();
        var windowBottomPosition = (windowTopPosition + windowHeight);

        $.each($animationElements, function () {
            var $element = $(this);
            var elementHeight = $element.outerHeight();
            var elementTopPosition = $element.offset().top;
            var elementBottomPosition = (elementTopPosition + elementHeight);

//check to see if this current container is within viewport
            if ((elementBottomPosition >= windowTopPosition) &&
                (elementTopPosition <= windowBottomPosition)) {
                $element.addClass('in-view');
            } else {
                $element.removeClass('in-view');
            }
        });
    }

    $window.on('scroll resize', checkIfInView);
    $window.trigger('scroll');


    /* @end viewport trigger script  */

});
    </script>



<!--------------------------------- MAP CRAP----------------------------------->
    
    










</head>







<script type="text/javascript">


$(document).ready(function() {


    var $animationElements = $('.animation-element');
    var $window = $(window);

    // ps: Let's FIRST disable triggering on small devices!
    var isMobile = window.matchMedia("only screen and (max-width: 768px)");
    if (isMobile.matches) {
        $animationElements.removeClass('animation-element');
    }

    function checkIfInView() {
t = $window.height();
        var windowHeight = $window.height();
        var windowTopPosition = $window.scrollTop();
        var windowBottomPosition = (windowTopPosition + windowHeight);

        $.each($animationElements, function () {
            var $element = $(this);
            var elementHeight = $element.outerHeight();
            var elementTopPosition = $element.offset().top;
            var elementBottomPosition = (elementTopPosition + elementHeight);

//check to see if this current container is within viewport
            if ((elementBottomPosition >= windowTopPosition) &&
                (elementTopPosition <= windowBottomPosition)) {
                $element.addClass('in-view');
            } else {
                $element.removeClass('in-view');
            }
        });
    }

    $window.on('scroll resize', checkIfInView);
    $window.trigger('scroll');


    /* @end viewport trigger script  */

});




</script>












  













<div class="testwrap">
<div class="sec2">
<div class="content2">





      <div class="towright">
        <div class="callout animation-element fadeinright">

          <div class="bthead"><span class="mainHEader1">where is your vehicle?</span><br>
            <hr class="redline">
            <p><?php echo $content1; ?></p>
          </div>
          <div class="btloc">

<a href="#NoCredit">
            <button href="#NoCredit" type="input" id="try" name="submi" class="button_text" value="">
              <!--add this after value ""<?php echo $dis; ?>when u fix mobile location-->
              <span id="boxcorner"></span>
              <div class="right2_button"><?php echo $deviceType; ?></div>
            </button>
              </a>
          </div>


          <div class="bthr"><br>Or<br></div><br>


          <div class="btaddy">
            <a href="#NoCredit">
              <!--when clicked changes text to cacel tow witch will show main test div and clear form fields---->
              <button type="input" id="saveFor" name="submi" class="button_text" value="">
                <span id="boxcorner"></span>
                <div class="right2_button"><span id="offset">Enter</span> Address</div>
              </button>
            </a>
          </div>
          <br>
          <div class="dtdis">Computers cannot use GPS correctly due do privacy laws and can only locate the server your connected too. </div>







 <div class="callout animation-element fadeinleft">






        </div><!--fadeinright-->







        </div><!--fadeinright-->
      </div><!--towright-->














      <div class="towleft">
        <div class="callout animation-element fadeinleft">
            
          <div class="scene scene--card">
              
              
            <div class='card'>
                
                
                
                
                
              <div class="card__face card__face--front">




CLICK ENTER ADDY


              </div>



              <div class="card__face card__face--back">


                <div class="bktest">





                  <form id="AUTO" method="post" action="" novalidate>

          


         

                      <h3>CONTACT INFO</h3>
                      <input type="hidden" class="dddfff" name="token" value="3308f582b5dbc12f99a823c77be6cdc8" />
                      <input type="hidden" class="dddfff" name="miles" value="" />










<div id="addy_holder">
    
<div class="upd">
<div id="upddd4">Customer information:</div>  
</div>    
    
<div class="staydog">
<div id="contact_name">Name: </div> 
<input id="inputField" name="name" class="" size="15" maxlength="17" value="" type="text" placeholder="name">
</div><!--staydog-->


    
<div class="staydog">
<div id="contact_name">Email: *<span id="reqqq">Is Required</span></div> 
<input type="email" id="emailinput" name="email" class="" maxlength="40" value=""  placeholder="email" required/>
</div>
    
    
    
    
<div class="staydog">
<div id="contact_name">Phone: * <span id="req">Is Required</span></div> 
<input type="tel" id="cinfo" name="phone" class="" maxlength="15" value="" placeholder="Home/Cell Phone" title="Phone Number Format:1(614) 000-0000"/>
</div>  



</div><!--addyholder-->




<!--------------------- addy info ------------->

<div id="addy_holder">
    

        
<div class="upd">
<div id="upddd4">Location information:</div>  
</div>  
   
<div id="staydog9">
<div id="contact_name">Address: *</div> 
<input type="text" id="location" name="address" class="" size="" maxlength="40" value=""  placeholder="Address(PC users)">  
</div><!--hide when in mobile-->
    
        
        
        
        

<div class="staydog">
<div id="contact_phone">Address2: *</div> 
<input type="text" id="location2" name="address2" class=""  maxlength="40" value="" placeholder="Apt, Suite, etc (optional)"/>
</div>

</div><!-- addy holder -->


<div id="addy_holder">

    
<div id="staydog8">
<div id="contact_phone">City:</div> 
<input type="text" id="locality" name="city" class="" maxlength="50" value="" placeholder="City"/>
</div>

<div id="staydog7">
<div id="contact_name">State: </div> 
<input type="text" id="administrative_area_level_1" name="state" class="half-input" maxlength="17" value="Ohio"  placeholder="State/Province">
</div>  


<div class="staydog" style="display:none;">
<div id="contact_name">Country: </div> 
<input type="text" id="country" name="country" class="" maxlength="17" placeholder="Country"/>
</div>  



<div id="staydog6">
<div id="contact_name">Zip:</div> 
<input type="text" class="half-input" placeholder="Zip/Postal code" id="postal_code" name="zip" maxlength="5" /> 
</div>








</div><!-- addy holder -->










              








<div id="addy_holder22">
<div id="upddd4">Billing and Rental car:</div> 




<div class="staydog22">
<select name="sloc" id="sloc">
<option value="Any">Billing Choice</option>
<option value="Central">one</option>
<option value="North">two</option>
</select>
</div><!--staydog-->



<div class="staydog22">
  
<section class="plan cf">
<div id="ftx1"><span class=""></span>insurance</div>
<input type="radio" name="maincov" id="yes" value="Yes"><label class="free-label four col" for="yes">Yes</label>
<input type="radio" name="maincov" id="Full Coverage" value="No" ><label class="basic-label four col" for="Full Coverage">No</label>
</section>



</div><!--staydog-->



</div><!-- addy holder -->



              



                      <div id="contact_message">MESSAGE:<br>
                        <textarea id="element_3" name="message" class="element textarea medium" placeholder="START TYPING MESAGE HERE..."></textarea>
                      </div>





         


          




                 
                      <h4>THANK YOU!</h4>
                      <h5>Once you hit Submit a representative will be with you shortly.</h5>





                      <p id="demo">mob loc stats</p>
                      
                      <div class="CxName" id="CxName">name</div>
                      
                      <div id="map1"></div>





                      <div class="button_holder">

                        <input type="button" name="previous" class="previous action-button" value="Previous" />
                      </div>




                   






<input type="" class="field" id="latitude" name="lat" placeholder="does lat copy?"></input>
<input type="hidden" class="field" id="longitude" name="lng" placeholder="does long copy?"></input>






                  </form>






                </div><!--bktest-->

              </div>
            </div>
          </div>
        </div>
      </div><!--towleft-->



    </div>
  </div>

<script>
    //window.onload = initMap;
    let today = new Date();
    let yesterday = new Date();
    let tommorrow = new Date();
    //should be able to shorten and remove bottom 2 lines
    yesterday.setDate(today.getDate() - 1);
    tommorrow.setDate(today.getDate() + 1);

    console.log('Yesterday: ' + yesterday);
    console.log('Today: ' + today);
    console.log('Tommorrow: ' + tommorrow);

    "use strict";

    function flip() {
      $('.card').toggleClass('is-flipped');
      //document.getElementById('saveFor').disabled = true;
      //document.getElementById('try').disabled = true;
    }

    document.getElementById('saveFor').addEventListener('click', flip);
    document.getElementById('try').addEventListener('click', flip);
  document.getElementById('saveFor').addEventListener('click', initMap);
    function initMap() {
          window.alert('initMap ran');
      document.getElementById('try').addEventListener('click', cnn);
      const componentForm = [
        'location',
        'locality',
        'administrative_area_level_1',
        'country',
        'postal_code',
      ];

      const map1 = new google.maps.Map(document.getElementById("map1"), {
        zoom: 11,
        mapId: '744525hh',
        center: {
          lat: 38.998178,
          lng: -82.998795
        },
        mapTypeControl: false,
        fullscreenControl: true,
        zoomControl: true,
        streetViewControl: true

      }); //map1
//add more markers this way
    //  const usrloc = new google.maps.Marker({
    //    map: map1,
    //    draggable: false,
    //    setZoom: 11,
    //  });
      
      
      
      const marker0 = new google.maps.Marker({
        map: map1,
        draggable: false,
        setZoom: 11,
        icon: {
          url: "https://maps.google.com/mapfiles/ms/icons/blue-dot.png"
        }
      });
      const autocompleteInput = document.getElementById('location');
      const autocomplete = new google.maps.places.Autocomplete(autocompleteInput, {
        fields: ["address_components", "geometry", "name"],
        types: ["address"],
      });

      //console.log(autocompleteInput.value);

      autocomplete.addListener('place_changed', function() {
        marker0.setVisible(true);
       //add single markers this way usrloc.setVisible(true);
        const place = autocomplete.getPlace();
        //console.log(place.geometry.location);

        if (!place.geometry) {
          // User entered the name of a Place that was not suggested and
          // pressed the Enter key, or the Place Details request failed.
          window.alert('No details available for input: '' + place.name + ''');
          return;
        }
        renderAddress(place);
        fillInAddress(place);
      });


      function fillInAddress(place) { // optional parameter
        // optional parameter

        window.alert('fillInAddress fired');


        const addressNameFormat = {
          'street_number': 'short_name',
          'route': 'long_name',
          'locality': 'long_name',
          'administrative_area_level_1': 'short_name',
          'country': 'short_name',
          'postal_code': 'short_name',
        };
        const getAddressComp = function(type) {
          for (const component of place.address_components) {
            if (component.types[0] === type) {
              return component[addressNameFormat[type]];
            }
          }
          return '';
        };
        document.getElementById('location').value = getAddressComp('street_number') + ' ' +
          getAddressComp('route');

        //auto complete adress filling form from filling out form
        //document.getElementById("country").value = place.geometry.vicinity.short_name();
        document.getElementById("latitude").value = place.geometry.location.lat();
        document.getElementById("longitude").value = place.geometry.location.lng();
        for (const component of componentForm) {
          // Location field is handled separately above as it has different logic.
          if (component !== 'location') {
            document.getElementById(component).value = getAddressComp(component);


          }
        }

      }

      //when try byutton is pressd do this function
      function cnn(ddd) {
       
        //window.alert(' cnn was fired');
        
        
        //hide threse when in mobile have to figure out
        document.getElementById("staydog9").style.display = "none";
       document.getElementById("staydog8").style.display = "none";
  document.getElementById("staydog7").style.display = "none";
  document.getElementById("staydog6").style.display = "none";
        const x = document.getElementById("demo");

        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition);
        } else {
          x.innerHTML = "Geolocation is not supported by this browser.";
        }

        // mobile button to get cords
        function showPosition(ddd) {
          window.alert('showPosition mob');
          var lat = ddd.coords.latitude;
          var lon = ddd.coords.longitude;
          var latlon = new google.maps.LatLng(lat, lon);

         //inserts lat/lon into form fields
        document.getElementById("latitude").value = lat;
       document.getElementById("longitude").value = lon;
 console.log('|' + lat + '|', '|' + lon + '|'); // right click inspect and look at log empty by default.
          //not needed atm save for usefullness
          //x.innerHTML =
          //  "accu: " + ddd.coords.accuracy +
           // "<br>Latitude: " + lat +
          //  "<br>Longitude: " + lon +
          //  "<br>both: " + latlon +
          //  "<br>time stamp: " + ddd.timestamp;


          window.alert('does this even work');














  var lat = ddd.coords.latitude;
       var lon = ddd.coords.longitude;
      var latlon = new google.maps.LatLng(lat, lon);





          // makes the view fire one at a time instead of both at onces
          
//Mobile marker
          marker0.setPosition(latlon); // SET MARKER POSTION.
          map1.setCenter(latlon); // CENTER MAP.
          marker0.setTitle('Mobile Location'); // mobile pick up location
          map1.setZoom(14); //zoomz map to marker
          marker0.setVisible(true); // SEE MAKER?.
          marker0.setDraggable(false) //if true need listener to update cords
          // confirm address or a div(needs styled)???.
        }//showPosition(ddd)
          
      }//cnn(ddd)



//PC marker
      function renderAddress(place) {
        //window.alert('renderAddress fired');
        map1.setCenter(place.geometry.location); // CENTER MAP.
        map1.setZoom(13); //zoomz map to marker
        marker0.setPosition(place.geometry.location); // SET MARKER POSTION.
        marker0.setVisible(true); // SEE MAKER?.
        marker0.setTitle('PC Computer location');
        marker0.setDraggable(false)




        var place = autocomplete.getPlace();
        var lat = place.geometry.location.lat();
        var lng = place.geometry.location.lng();

        console.log('lat:' + lat, 'lng:' + lng);

      } //renderAddress






    // Get the input field
    var inputField = document.getElementById("inputField");

    // Add event listener to detect input changes
    inputField.addEventListener("input", function() {
      // Get the value from the input field
      var inputValue = inputField.value;
      
      // Display the value
      document.getElementById("CxName").innerText = inputValue;
    });






      //this is the div that both buttons use to display map info data
      var location1 = '<div class="bui_hold1"><p id="output"></p>Verify Your Info.<br><div class="CxInfo"><div class="CxName" id="CxName">name</div><div class="CxPhone">phone</div><div class="CxEmail">email</div><div class="CxAddy">addy</div></div><div class="CarInfo"><div class="CxYear">year</div><div class="CxMake">make</div><div class="CxModel">model</div><div class="CxBill">bill</div><div class="CxRent">rent</div><div class="CxMess">message</div></div><input id="saveForm" class="button_text" type="submit" name="submit" value="Submit "/></div>';

      var infoWindow1 = new google.maps.InfoWindow({
        'content': location1,
      });

      marker0.addListener('click', function() {
        infoWindow1.open(map1, marker0);
        //console.log('this happened');
       });

      //open infowindow1 window by defult
      infoWindow1.open(map1, marker0);

      //closes info window when clicking on map
      google.maps.event.addListener(map1, "click", function(event) {
        infoWindow1.close();
      });

      //try to get this first marker to marker1
      var markers = [
          
          

  
  
        {
          "title": 'place4',
          "lat": '29.928669',
          "lng": '-22.831665',
          "manager": 'tom.',
          "description": 'Brice Rd. is situated near Byculla station is famous as Mumbai (Bombay) Zoo.'
        },
        {
          "title": 'place5',
          "lat": '32.991079',
          "lng": '-82.026252',
          "manager": 'frank',
          "description": 'OSU is a large protected area in the northern part of Mumbai city.'
        },
        {
          "title": 'place1',
          "lat": '20.062229',
          "lng": '-22.994070',
          "manager": 'bill',
          "description": 'Morse rd is a large protected area in the northern part of Mumbai city.'
        }
      ];



      //Create and open InfoWindow.
      var infoWindow = new google.maps.InfoWindow();



      google.maps.event.addListener(map1, "click", function(event) {

        infoWindow.close();

      });

      for (var i = 0; i < markers.length; i++) {
        var data = markers[i];
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
        var marker = new google.maps.Marker({
          position: myLatlng,
          map: map1,
          title: data.title
        });

        //Attach click event to the marker for buinees.
        (function(markers, data) {
          google.maps.event.addListener(marker, "click", function(e) {
            //Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
            infoWindow.setContent("<div class='bui_hold1'><div class='info_sec'><div class='bui_name'>" + data.title + "</div><!--bui_name--><div class='geo_info'><div class='geo_dis'>" + data.dis + "</div><!--data.dis--><div class='geo_time'>" + data.time + "</div><!--data.time--></div><!--geo_info--></div><!--info_sec--><!--first section--><div class='bui_info'><div class='dir_addy'>" + data.address + "</div><!--dir_btn--><div class='con_info'><div class='label'>Phone</div><!--pho_num--><div class='pho_num'><a href='tel:16142585555'>" + data.phone + "</a></div><!--pho_num--><div class='label'>Fax</div><!--pho_num--><div class='fax_num'>" + data.fax + "</div><!--fax_num--></div><!--con_info--><div class='dir_info'><div class='label'>Get Directions</div><!--pho_num--></div><!--bui_info--><!--second section--><div class='bui_pic'><div class='man_pic'></div><!--man_pic--><div class='man_name'>" + data.manager + "</div><!--man_name--></div><!--bui_pic--><div class='hidcord'><div class='geo_lat'>" + data.lat + "</div><div class='geo_long'>" + data.lng + "</div></div><!--hidcord--></div><!--bui_hold-->"
            );
            infoWindow.open(map1, markers);
            map1.panTo(this.getPosition());
          });



        })



        (marker, data);
      }

    } // ini map
  </script>

</div><!--testwrap-->






    
    
    
    
    
    
    

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBHkuLjYNbP0A8UrsqKIUR3itSuyjcz9pc&libraries=places&channel=GMPSB_addressselection_v1_cAB&loading=async"></script>


    
    
    

    
    
    
    
    
    
    
    
    
    
</body>
</html>

Eloquent Javascript Question (Chapter 6) Classes/Constructors/Methods [duplicate]

My question is, given this code, how does the plus and minus methods work?

I see only one parameter (other) for the method ‘plus’.

Where is the other parameter coming from? I see it is coming from the first new Vec(1, 2) (e.g. this.x), however I don’t fully understand how this works.

Why doesn’t the ‘other’ parameter get a this.x and a this.y? Why is there only one ‘Vec’ that gets a this parameter?

If someone could explain in an easy to understand way I would appreciate it.

class Vec {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  plus(other) {
    return new Vec(this.x + other.x, this.y + other.y);
  }

  minus(other) {
    return new Vec(this.x - other.x, this.y - other.y);
  }
}
console.log(new Vec(1, 2).plus(new Vec(2, 3)));
// → Vec{x: 3, y: 5}

Bookmarks Tree to html

For one of my web extension, I need to get bookmarks from the user’s browser in html format, just like it looks like when you manually export your bookmarks and get bookmark.json.
The only thing I realized is that I can get the bookmarks tree through browser.bookmarks.getTree(), but it still doesn’t work stably to translate it into the same html format as the browser.

Is there anything I can do?

Localhost didn’t send any data in my Node/Express/Axios app

I’m working on a full-stack Node app using Express, with Axios to make a call to an external API. My API call is working, but it doesn’t seem to send any data back to my route handler and I’m getting a browser timeout and then the message:

“localhost didn’t send any data ERR_EMPTY_RESPONSE”

Here is my route handler, routes/met_route.js:

'use strict';
import express from "express";
import metData from "../models/metData.js";

const router = express.Router();
router.get('/', metData.searchArt, (req, res) => {
    res.send(res.data)
})

export default router;

And here is my code with the API call, models/metData.js:

'use strict';
import axios from "axios";

const metAPI = {
   searchArt: function() {
      axios.get("https://collectionapi.metmuseum.org/public/collection/v1/objects/11")
         .then(response => {
            console.log(response.data)
         })
         .catch(error => console.error('error:', error));
   }
};

export default metAPI;

My main server.js file is as follows:

import express from "express";
import cors from "cors";
import homeRoute from "../routes/home_route.js";
import metRoute from '../routes/met_route.js';

const PORT = process.env.PORT || 5050;
const app = express();

app.use(cors());
app.use(express.json());

//routing
app.use("/", homeRoute);
app.use("/met", metRoute);

// start the express server
app.listen(PORT, ()=> {
    console.log(`server listening on port ${PORT}`);
});

The route /met works fine as long as I don’t make a router.get request to my models/metData.js file, but once I make that request I am getting the error above. I am wondering if it could be an async issue. Any insight would be greatly appreciated.

JavaScript – export HTML to Word not including images

I’m trying to export an HTML element that includes images to a Word doc using the below function I’ve put together using various online sources. The Word document download is triggered, but the 1st download does not include the images. The 2nd time and every time after the download is triggered, it includes the images.

Has anyone come across this issue before? Is there anything wrong with my exportToDoc function?

export function exportToDoc(element, filename = "") {
  let html =
    "<html xmlns:o='urn:schemas-microsoft-com:office:office'" +
    " xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta><title>Export HTML To Doc</title></head><body>";
  let footer = "</body></html>";
  html = html + document.getElementById(element).innerHTML + footer;

  var statiC = {
    mhtml: {
      top:
      /* eslint-disable */
        "Mime-Version: 1.0nContent-Base: " +
        location.href +
        'nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"nn--NEXT.ITEM-BOUNDARYnContent-Type: text/html; charset="utf-8"nContent-Location: ' +
        location.href +
        "nn<!DOCTYPE html>n<html>n_html_</html>",
      head: '<head>n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">n<style>n_styles_n</style>n</head>n',
      body: "<body>_body_</body>",
    },
  };

  var css =
    "<style>" +
    "img {width:auto; height: 800px, margin-right: 100px}" +
    "</style>";

  //  Image Area %%%%
  var options = { maxWidth: 500 };
  var images = Array();
  var img = document.querySelectorAll("#" + element)[0].querySelectorAll("img");
  for (var i = 0; i < img.length; i++) {
    // Calculate dimensions of output image
    var w = Math.min(img[i].width, options.maxWidth);
    var h = img[i].height * (w / img[i].width);
    // Create canvas for converting image to data URL
    var canvas = document.createElement("CANVAS");
    canvas.width = w;
    canvas.height = h;
    // Draw image to canvas
    var context = canvas.getContext("2d");
    context.drawImage(img[i], 0, 0, w, h);
    // Get data URL encoding of image
    var uri = canvas.toDataURL("image/png");
    // document.querySelectorAll(img[i])[0].attr("src", img[i].src);
    img[i].src = img[i].src;
    img[i].width = w;
    img[i].height = h;
    // Save encoded image to array
    images[i] = {
      type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
      encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
      location: img[i].src,
      data: uri.substring(uri.indexOf(",") + 1),
    };
  }

  // Prepare bottom of mhtml file with image data
  var imgMetaData = "n";
  for (var i = 0; i < images.length; i++) {
    imgMetaData += "--NEXT.ITEM-BOUNDARYn";
    imgMetaData += "Content-Location: " + images[i].location + "n";
    imgMetaData += "Content-Type: " + images[i].type + "n";
    imgMetaData += "Content-Transfer-Encoding: " + images[i].encoding + "nn";
    imgMetaData += images[i].data + "nn";
  }
  imgMetaData += "--NEXT.ITEM-BOUNDARY--";
  // end Image Area %%

  const output = statiC.mhtml.top.replace("_html_", statiC.mhtml.head.replace("_styles_", css) + html) + imgMetaData;
  const url = "data:application/vnd.ms-word;charset=utf-8," + encodeURIComponent(output);

  //file name
  filename = filename ? filename + ".doc" : "document.doc";

  // Creates the  download link element dynamically
  let downloadLink = document.createElement("a");

  document.body.appendChild(downloadLink);

  //Link to the file
  downloadLink.href = url;

  //Setting up file name
  downloadLink.download = filename;

  //triggering the function
  downloadLink.click();
  
  //Remove the a tag after download starts.
  document.body.removeChild(downloadLink);
}

The element being exported just contain some basic div, p, and img tags

what is “console.system()” in chrome dev version?

In the debugger console in Chrome Developer “Version 133.0.6847.2 (Official Build) dev (64-bit)”, there is a “console.system(arg)” function which appears to be defined as:

{ pushToConsole(arg, "system") }

This function doesn’t exist in standard Chrome “Version 131.0.6778.86 (Official Build) (64-bit)”.

What does it do?

geolocation getCurrentPosition – is there ever a time when a location wouldn’t be available in cache?

I’m reading the docs on getCurrentPosition. For the maximumAge option it states:

If set to Infinity the device must return a cached position regardless
of its age.
(my bolding)

The word ‘must’ in that sentence is what I’m curious about. Is there ever a time when there is no cached position to retrieve? If so, what is the behaviour? Does it go fetch or return an error or null value?

Getting proper crop coordinates of a snip

I am building a chrome extension for OCR. Users can upload pdf and it gets converted into an image and I render it in a new tab. I create a overlay on top of the image container and let the user take a snippet and store the crop coordinates. The issue is that the crop is not happening with respect to the overlay I created over the image container but rather its happening with respect to the entire screen.

function createSelection() {
    if (selection && selection.parentNode) {
        selection.parentNode.removeChild(selection);
    }
    
    selection = document.createElement("div");
    selection.style.border = "2px solid #8e4dff";
    selection.style.position = "fixed";
    selection.style.zIndex = "900"; // above the overlay
    selection.style.display = "none";
    selection.style.pointerEvents = "none";
    document.body.appendChild(selection);   
}
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log(request.action)
    if (request.action === "showImageForSelection") {
        dataUrl = request.dataUrl;
        createOverlay();
        createSelection();
        
        overlay.addEventListener("mousedown", function (e) {
            isDragging = true;
            console.log("START DRAGG")
            // Mouse position relative to the image
            const containerRect = overlay.getBoundingClientRect();
            startX = e.clientX - containerRect.left;
            startY = e.clientY - containerRect.top;

            selection.style.left = `${startX + containerRect.left}px`;
            selection.style.top = `${startY + containerRect.top}px`;
            selection.style.width = "0px";
            selection.style.height = "0px";
            selection.style.display = "block";
        });
        overlay.addEventListener("mousemove", function (e) {
            if (!isDragging) return;
            const containerRect = overlay.getBoundingClientRect();
            const currentX = e.clientX - containerRect.left;
            const currentY = e.clientY - containerRect.top;

            const width = currentX - startX;
            const height = currentY - startY;

            selection.style.width = `${Math.abs(width)}px`;
            selection.style.height = `${Math.abs(height)}px`;

            if (width < 0) {
                selection.style.left = `${startX + width + containerRect.left}px`;
            } else {
                selection.style.left = `${startX + containerRect.left}px`;
            }

            if (height < 0) {
                selection.style.top = `${startY + height + containerRect.top}px`;
            } else {
                selection.style.top = `${startY + containerRect.top}px`;
            }
        });
        overlay.addEventListener("mouseup", function () {
            isDragging = false;
            console.log("STOP DRAGG", isDragging)
            const selectionRect = selection.getBoundingClientRect();
            const overlayRect = overlay.getBoundingClientRect();
            const imgContainer = getContentContainer();

            if (imgContainer) {
                const naturalWidth = imgContainer.naturalWidth;
                const naturalHeight = imgContainer.naturalHeight;

                // Adjust selection coordinates to the overlay's position
                const offsetX = selectionRect.left - overlayRect.left; // X relative to overlay
                const offsetY = selectionRect.top - overlayRect.top; // Y relative to overlay

                // Convert coordinates to the image's natural dimensions
                const adjustedStartX = (offsetX / overlayRect.width) * naturalWidth;
                const adjustedStartY = (offsetY / overlayRect.height) * naturalHeight;
                const adjustedWidth = (selectionRect.width / overlayRect.width) * naturalWidth;
                const adjustedHeight = (selectionRect.height / overlayRect.height) * naturalHeight;

            // Store these coordinates and crop the image

            // let x = parseInt(selection.style.left) * dpr;
            // let y = parseInt(selection.style.top) * dpr;
            // let width = parseInt(selection.style.width) * dpr;
            // let height = parseInt(selection.style.height) * dpr;

            cropImage(dataUrl, adjustedStartX, adjustedStartY, adjustedWidth, adjustedHeight, function (croppedDataUrl) {
                chrome.runtime.sendMessage(
                    { action: "storeCroppedImage", dataUrl: croppedDataUrl, cropCoordinates: { x: adjustedStartX, y:adjustedStartY, width:adjustedWidth, height:adjustedHeight } },
                    function (response) {
                        if (response.status === "stored") {
                            console.log("Cropped image stored.", croppedDataUrl);
                        }
                    }
                );
                document.body.style.overflow = "";
                document.body.removeChild(overlay);
                document.body.removeChild(selection);
            });
            }
        });
    }
});

function cropImage(imageDataUrl :any, x :any, y :any, width :any, height :any, callback :any) {
    const img = new Image();
    img.onload = function () {
        const canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;

        // Get the 2D drawing context
        const ctx = canvas.getContext("2d");

        // Check if the context is not null before using it
        if (ctx) {
            // Draw the cropped image
            ctx.drawImage(img, x, y, width, height, 0, 0, width, height);

            // Convert the cropped image to a Data URL and pass it to the callback
            const croppedDataUrl = canvas.toDataURL("image/png");
            callback(croppedDataUrl);
        } else {
            console.error("Unable to get 2D context for the canvas.");
        }
    };
    img.src = imageDataUrl;
}

Can anyone suggest a solution to get the coordinates properly which can then be used on other files to get the exact crop in the same place.

How to implement react window in Shadcnui combobox?

I have very large lists of items that I need to show on the ui inside a Combobox of shadcn ui but due to lists being large, it takes too much time.

So I wanted to virtualize the list and only render the items on dom that are in the view.

I tried implementing react window and while it works, when I search something in the search box, the scroll doesn’t work

type ComboboxItem = {
  value: string;
  label: string;
};

interface MultiselectComboboxProps {
  items: ComboboxItem[];
  placeholder?: string;
  selectedValues: string[];
  onValueChange: (values: string[]) => void;
  width?: string;
  showSearch?: boolean;
}

export function MultiselectCombobox({
  items,
  placeholder = "Select options...",
  selectedValues,
  onValueChange,
  width = "200px", 
  showSearch = true, 
}: MultiselectComboboxProps) {
  const [open, setOpen] = React.useState(false);

  const [filteredOptions, setFilteredOptions] =
    React.useState<ComboboxItem[]>(items);

  const [tempSelectedValues, setTempSelectedValues] =
    React.useState<string[]>(selectedValues);

  const allSelected = tempSelectedValues.length === items.length;

  // Toggle selection for individual items
  const toggleSelection = (value: string) => {
    setTempSelectedValues(
      (prev) =>
        prev.includes(value)
          ? prev.filter((v) => v !== value) // Remove if already selected
          : [...prev, value] // Add if not selected
    );
  };

  // Toggle "Select All" option
  const toggleSelectAll = () => {
    setTempSelectedValues(
      allSelected ? [] : filteredOptions.map((item) => item.value)
    );
  };

  const handleSearch = (search: string) => {
    if (search.length) {
      const filteredItems = items.filter((item) =>
        item.value.toLowerCase().includes(search.toLowerCase())
      );

      setFilteredOptions(filteredItems);
    } else {
      setFilteredOptions(items);
    }
  };

  const Row = ({
    index,
    style,
  }: {
    index: number;
    style: React.CSSProperties;
  }) => {
    const item = filteredOptions[index];
    const isChecked = tempSelectedValues.includes(item.value);

    return (
      <div style={style}>
        <CommandItem
          key={item.value}
          value={item.value}
          onSelect={() => toggleSelection(item.value)}>
          <Checkbox checked={isChecked} />
          <span
            style={{
              display: "inline-block",
              maxWidth: "calc(100% - 40px)", // Adjust for checkbox and padding
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
            title={item.label} // Tooltip to show the full label
          >
            {item.label}
          </span>
        </CommandItem>
      </div>
    );
  };

  return (
    <Popover modal={true} open={open} onOpenChange={handlePopoverClose}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className={cn(
            "justify-between text-small font-normal",
            width && `w-[${width}]`
          )}
        >
          {tempSelectedValues.length > 0
            ? `${tempSelectedValues.length} out of ${items.length} selected`
            : placeholder}
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className={`p-0 w-[--radix-popover-trigger-width]`}>
        <Command>
          {showSearch && (
            <CommandInput
              onValueChange={handleSearch}
              placeholder={`Search ${placeholder.toLowerCase()}`}
            />
          )}
          <CommandList>
            <CommandEmpty>No options found.</CommandEmpty>
            {filteredOptions.length ? (
              <div
                className="sticky top-0 bg-white z-10 font-bold flex gap-2 h-[26px] items-center mx-3 my-0 pt-[6px] text-sm"
                onClick={toggleSelectAll}>
                <Checkbox checked={allSelected} />
                Select all
              </div>
            ) : (
              ""
            )}

            <CommandGroup>
              <div className="max-h-[200px] overflow-y-auto">
                <List
                  height={200} // Visible height of the list
                  itemCount={filteredOptions.length} // Total number of items
                  itemSize={32} // Height of each row in px
                  width="100%" // Full width
                  itemData={filteredOptions}>
                  {Row}
                </List>
              </div>
            </CommandGroup>
          </CommandList>

          <div className="p-2 border-t flex justify-end gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                setTempSelectedValues(selectedValues); // Reset state on Cancel
                setOpen(false);
              }}>
              Cancel
            </Button>
            <Button size="sm" onClick={applySelection}>
              Apply
            </Button>
          </div>
        </Command>
      </PopoverContent>
    </Popover>
  );
}

What mistake am I making in here? I am filtering the list on the basis of the search input and the list is being filtered. But then the scroll stops working.

Can pm2 make RAM problem like giving BDOS (BLUE SCREEN) with MEMORY MANAGMENT ERROR?

I run pm2 10 proccess with Puppeteer browser to make some quick parsing. After that several times in week I got BDOS error with MEMORY MANAGEMENT.

In Windows task manager I don’t see any problem while running the script. I have 32gb RAM and Intel i3 12-th generation
Here is my task manager

But I have to add that on my second more weak computer there are not any problem with the same script like BDOS

I try to reinstall the windows 11, but there is the same BDOS screen. I also try to check memory with several tools, but in microsoft support says that it is the RAM problem

How do i auto import json files only using js?

How do I automatically import Json files that are in a folder/folders only using JS

Hello I am trying to automatically import Json files that are in a folder only using JS but i can’t find a solution

(by the way this is what the file structure is)

Mainfolder
-Folder1
--file.json
-Folder2
--file.json
main.js
index.html

edit: the json files all have the same name but the folder there in don’t have the same name(that’s why the folders in a main folder)

Tracking User Interactions in HubSpot iframe with Google Tag Manager

I’m working on tracking a page with Google Tag Manager that contains a HubSpot iframe, which is used for selecting a date and time for an appointment. I want to track the following user actions when interacting with the page:

  • Choosing a date: Click on the button with the classname
    “date-picker-btn valid”.
  • Choosing a time: Click on the div element with the classname
    “time-picker-btn”.
  • Starting to fill in their details: Input in a field with the
    classname “form-control”.
  • Submitting the form: Click on the button with the
    data-test-id=”forward-btn” attribute.

Thanks in advance for your help!