How do I read an excel upload in a blob storage

I have a table and a form that allows for a file to be uploaded. I then save this file to a column in my datatable in blob format. And then display this on a table on the front end. When i download this file from the table in my frontend, I end up with not an .XLXS file, but instead a weird file that I cannot open with excel. What are the steps I need to take to either save in blob as excel file, or to read it as an excel file?

Not 2 sure how to approach it, I might need to convert to different datatype ?

Unclear about what is SWR subscription

I’m going through each of SWR’s features and have encountered one that am unfamiliarized with: SWR-subscription. I don’t understand what they mean by “subscribing to real-time data sources with SWR”. I am trying to look for an explanation and a simple example to understand this feature better and how would I apply it in the real world.

jQuery – Load html or php data from the file and integrate with the index file

I’m using jQuery in my small site project and to make it look elegant I wanted to not load all the page everytime but only the content into the proper div element. This is how my script.js file looks like:

$(window).on('load', function(){
    
$(document).ready(function(){
    
    $("#contents").load("/home.html", function(responseTxt, statusTxt, xhr){

  });
  
});
});

function contents_load_func(element_id){
    
    $("#contents").fadeOut(200);
    
    setTimeout(function(){
        $('#contents').html('')
        }, 500);
    
    setTimeout(function(){
    $("#contents").load("/"+element_id+".html"),
    $("#contents").fadeIn();    
    }, 500);
}

$(document).ready(function(){
$("a").click(function() {
    contents_load_func(event.target.id);
})

});

I’m linking jQuery as a file, same as mine script.js inside the index.html:

<script src="/jquery/jquery-3.6.4.js"> </script>
<script src="/script/script_main.js"> </script>

It works perfect when using menu which is written inside index.html file, but I want to have possiblity to change the <div id = "contents" class="content"></div> when clicking proper <a> element inside the loaded content – unfortunately it doesn’t work. Looks like CSS styles are inherited properly but I’m aware jQuery doesn’t treat the loaded content as linked with index.html and I don’t have any warning or errors in browser console.

Node version : v18.15.0 mongodb version v6.0.5

app.post(“/”,(req,res)=>{

const user = new model.User({
    username:req.body.username,
    createAt: new Date()
})

user.save().then((savedUser)=>{
    res.status(201).send("Done");
}).catch((error)=>{
    res.status(500).send(error);
});

});
TypeError: model.User is not a constructor

How nestjs graphql FileUpload accept ReactNativeFile()

I am trying to upload a image from my react native app. As far as I know, I need to use class/package ReactNativeFile() with a uri then append the file to the graphql varible. The following is a minimum reproduce example:

The way that I upload file:

function generateRNFile(uri, name) {
  return uri ? new ReactNativeFile({
    uri,
    type: mime.lookup(uri) || 'image',
    name,
  }) : null;
}

 async function onUploadPress() {
  status && setStatus(null);
  const file = generateRNFile(image, `picture-${Date.now()}`);
  try {
  await uploadImage({
      variables: { image: file },
    });
    setStatus('Uploaded')
  } catch (e) {
    setStatus('Error')
  }
}

This graphql is tested through playground which I am sure that there is no bug.

However, I am geting such error

"message": "Variable "$file" got invalid value { uri: "file:///var/mobile/Containers/Data/Application/xxxx/Library/Caches/ExponentExperienceData/xxx.jpg", name: "picture-xxx", type: "image/jpeg" }; Upload value invalid.",

Is there anyone that could help me to figure out the reason?
Much Thanks

js help on blur on exception

I’m working on a web site but now I have a issue were I can change the first input but not the second one whiteout triggering the on blur.
I expect when I click outside of the inputs it will trigger the Ajax and but hen I click on the input I can change it.

my code:

let shiftId = 0;
let userId = 0;
let date = 0;
$(document).ready(function () {
  $(document).on("dblclick", ".shift", function () {
    let cell = $(this);
    shiftId = cell.find(".shift-value").attr("id");
    userId = cell.find(".shift-value").attr("user-id");
    date = cell.find(".shift-value").attr("date");
    console.log(userId);
    let currentValue = cell.text().trim();
    let inputs =
      '<input type="time" class="start" value="' +
      currentValue.split("-")[0] +
      '"> - <input type="time" class="end" value="' +
      currentValue.split("-")[1] +
      '">';
    cell.html(
      "<div class='shift-value' date=" +
        date +
        " user-id=" +
        userId +
        "  id=" +
        shiftId +
        ">" +
        inputs +
        "</div>"
    );
    cell.find(".start").focus();
  });

  $(document).on("blur", ".shift input", function () {
    let cell = $(this).parent();
    let start = cell.find(".start").val();
    let end = cell.find(".end").val();
    console.log(shiftId);
    let currentValue = start + "-" + end;

    if (currentValue !== "00:00-00:00") {
      // Create new shift if it was previously empty
      cell.html(currentValue);
      $.ajax({
        url: "rooster/create_shift.php",
        method: "POST",
        data: {
          start_time: start,
          date: date,
          end_time: end,
          user_id: userId,
          shiftId: shiftId,
        },
        success: function (response) {
          console.log(response);
        },
        error: function (xhr, status, error) {
          console.error(xhr.responseText);
        },
      });
      return;
    } else if (currentValue == "00:00-00:00") {
      // Delete shift if it was previously not empty
      cell.html(currentValue);
      $.ajax({
        url: "rooster/delete_shift.php",
        method: "POST",
        data: {
          shift_id: shiftId,
        },
        success: function (response) {
          console.log(response);
        },
        error: function (xhr, status, error) {
          console.error(xhr.responseText);
        },
      });
    } else {
      // Reset cell to previous value
      cell.html(currentValue);
    }
  });
});

Is there any way to connect two dragable cards with a dynamic line segment (with symbols at end points) in ReactJs?

React rnd dragable component

I want a dynamic line segment to connect two react rnd components. The line segment end points should be symbols. Also whenever I move these components the line segment should move with them and if in case a 3rd component comes in between the line segment should choose some route avoiding the 3rd or any other card.

Is it possible to create such thing in reactJS?

Cordova can’t read files with FileRead

I’m using JavaScript’s FileReader API to try to get the blob of a file inside a Cordova application.

My code is like the example below:

let reader = new FileReader();

reader.onload = function (event) {
    console.log(reader.result);
    console.log(event);
}
reader.onloadstart = function (event) {
    console.log(reader.result);
    console.log(event);
}
reader.onloadend = function (event) {
    console.log(reader.result);
    console.log(event);
}
reader.onprogress = function (event) {
    console.log(reader.result);
    console.log(event);
}
reader.onerror = function (event) {
    console.log(reader.result);
    console.log(event);
    const error = reader.error;
    console.log(error);
}
reader.onabort = function (event) {
    console.log(reader.result);
    console.log(event);
}
reader.readAsArrayBuffer(file);

When reading an image, the API works correctly, obtaining the content, but with files that are not images, the FileReader’s onerror event always returns the message “FileError {code: 1}”.

The location of files on the smartphone.

  • Image before resolveLocalFileSystemURL: content://com.android.externalstorage.documents/document/primary%3ADownload%2F1671641692909.jpg

  • Image after resolveLocalFileSystemURL: https://com.example.mobile.app.myapp/__cdvfile_sdcard__/Download/1671641692909.jpg – Success

  • File before resolveLocalFileSystemURL: content://com.android.externalstorage.documents/document/primary%3ADownload%2FExample.pptx

  • File after resolveLocalFileSystemURL: https://com.example.mobile.app.myapp/__cdvfile_sdcard__/Download/Example.pptx – Error

What could possibly be happening?

I already tried to read using all possible ways (readAsArrayBuffer, readAsBinaryString, readAsDataURL,readAsText)

Code to Resolve URL:

originalLocation = 'content://com.android.externalstorage.documents/document/primary%3ADownload%2F1671641692909.jpg';

window.FilePath.resolveNativePath(originalLocation, function (newFilepath) { resolveFilePath(newFilepath) });

function resolveFilePath(location) {
    window.resolveLocalFileSystemURL(location, function (fileEntry) {

        fileEntry.file(function (file) {

            let reader = new FileReader();

            reader.onload = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onloadstart = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onloadend = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onprogress = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            reader.onerror = function (event) {
                console.log(reader.result);
                console.log(event);
                const error = reader.error;
                console.log(error);
            }
            reader.onabort = function (event) {
                console.log(reader.result);
                console.log(event);
            }
            console.log(file);
            reader.readAsArrayBuffer(file);
        });
    });
}

Leaflet issue with grid lines over a map vs. chatGPT

No laughing. I reached out to chatGPT for a lesson on how to build a map in Leaflet that highlighted two counties and put a grid over both. The code after more than an hour of conversation with chatGPT gave me the code below. The problem is and always was it does not include the grid lines on the counties. It (chatGPT) and I tried many different ways to do this including the use Leaflet.Grid but nothing worked. So I told It I would go to you guys for an answer. Can anyone see the solution, please let me know.

<!DOCTYPE html>
<!-- Just a test map of Platte and Clay counties -->
<!-- Suggested by ChatGPT -->
<!-- map.setView([39.3172, -94.5123], 10); -->



<html>
<head>
  <title>Leaflet Map Example</title>
  
  <!-- Include Leaflet CSS -->
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
  
  <!-- Include Leaflet JavaScript -->
  <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
  
  <style>
    #map {
      height: 800px;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  
  <script>
    // Create a new map instance
    var map = L.map('map');

    // Set the map view to Platte County
    map.setView([39.3621, -94.7722], 10);

    // Add the OpenStreetMap tile layer to the map
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
      maxZoom: 18
    }).addTo(map);

    // Load the GeoJSON data for Platte County from OpenStreetMap
    fetch('https://nominatim.openstreetmap.org/search.php?q=Platte+County+Missouri&polygon_geojson=1&format=geojson')
      .then(function(response) {
        return response.json();
      })
      .then(function(data) {
        // Create a new GeoJSON layer with the county boundary data
        var countyLayer = L.geoJSON(data);

        // Add the county layer to the map
        countyLayer.addTo(map);

        // Calculate the bounds of the county layer
        var countyBounds = countyLayer.getBounds();

        // Fit the map to the bounds of the county layer
        map.fitBounds(countyBounds);
      });
      
    // Load the GeoJSON data for Clay County from OpenStreetMap
    fetch('https://nominatim.openstreetmap.org/search.php?q=Clay+County+Missouri&polygon_geojson=1&format=geojson')
      .then(function(response) {
        return response.json();
      })
      .then(function(data) {
        // Create a new GeoJSON layer with the county boundary data
        var countyLayer = L.geoJSON(data);

        // Add the county layer to the map
        countyLayer.addTo(map);

        // Calculate the bounds of the county layer
        var countyBounds = countyLayer.getBounds();

        // Fit the map to the bounds of the county layer
        map.fitBounds(countyBounds);
      });

    // Create a new Graticule instance with the desired options
    var graticule = L.latLngGraticule({
      interval: 1,
      showLabel: true,
      opacity: 0.5,
      fontColor: '#333'
    });

    // Add the Graticule layer to the map
    graticule.addTo(map);

    // Bring the Graticule layer to the front of the map
    graticule.bringToFront();

  </script>
</body>
</html>

why does a ActionEventListener click event act differently via an anonymous and non-anonymous function

document.addEventListener("DOMContentLoaded", function() {
  // Scenario 1 
  const btn = document.querySelector(".test");
  btn.addEventListener("click", () => {
    const fragment = document.createDocumentFragment();
    var x = document.createElement('p');
    x.className = "di";
    x.style.background = "aqua";
    for (var i = 1; i < 5; i++) {
      x.textContent = ' Change background color for ' + `${i}` + " element";
      x.id = 'para' + `${i}`;
      fragment.append(x.cloneNode(true));
    }
    document.body.append(fragment);
    document.getElementById("para0").addEventListener("click", () => {
      para0.style.background = "yellow"
    });
    document.getElementById("para1").addEventListener("click", () => {
      para1.style.background = "yellow"
    });

    function changeBackgroundColor(elem) {
      elem.style.background = "yellow";
    }
    document.getElementById("para2").addEventListener("click", changeBackgroundColor(para2));
    document.getElementById("para3").addEventListener("click", changeBackgroundColor(para3));
  });
});
<button class="test">create 4 elements</button>

Step 1: Click on the HTML Button ‘create 4 elements’ to create 4 <p> elements.

Observation 1: for the 1st and 2nd <p> elements which have anonymous function inside their actioneventlisteners , the individual <p> elements need to be explicitly clicked individually to change their background color from aqua to yellow.

Observation 2: for the 3rd and 4th <p>velements which dont have anonymous function inside their actioneventlistener ,the background color has defaulted to yellow without clicking on the 3rd or 4th <p> elements

So why does click behaviour differ between actioneventlistener having anonymous function and a non-anonymous function?

React and Chart.js displaying fetched data

I am having a problem understanding how I can get fetched data to be displayed on a chart using chart.js

const [backendData, setBackendData] = useState([{}])

useEffect(() => {
    Axios.get('http://localhost:3001/get').then((response) =>{
    console.log(response)
    setBackendData(response.data)
    })
}, [])

backendData.map((val) => {
    const total = val.total
})

mondayData.datasets.data = total

// monday chart data
var mondayData = {
    labels: ["7 AM", "8 AM", "9 AM", "10 AM", "11 AM", "12 PM", "1 PM", "2 PM", "3 PM"],
    datasets: [{
        data: [2, 1, 1, 6, 4, 7, 8, 14, 13],
        label: "Empty parking spaces",
        backgroundColor: "rgb(39, 63, 150, 0.5)",
    }]
}
// monday chart options
var mondayOptions = {

}



useEffect(() => {
    // var test = document.getElementById("0").getContext('2d');
    // test.destroy();
    // monday chart
    
    var mondayCtx = document.getElementById('mondayChart').getContext('2d');
    let mondayChartStatus = Chart.getChart("mondayChart");
    if (mondayChartStatus != undefined) {
        mondayChartStatus.destroy();
    }
    var mondayChart = new Chart(mondayCtx, {
        type: 'line',
        data: mondayData
    });

The backendData variable has one value {total: 22} which is pulled from the database
which is then (I think) getting used to set the const total variable

Right now what I am trying to do is get the 22 to be displayed as the first value on the chart.

I am using the mondayData.datasets[0].data = total to access it but I get an error “TypeError: Cannot read properties of undefined (reading ‘datasets’)”

I just want to use my fetched data from a database to be used as the data for the chart

How to dynamically load scripts from AWS bucket in your component(once the Dom finds the div related to scripts) in angular 11?

I have loaded the script through this method:

let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.body.appendChild(node);

Thus script has been loaded(checked with consoling through onload function) but the div related to this script is not showing any content in the inspect elements bar in browser.

What does the message “Request for font “Noto Sans” blocked at visibility level 1 (requires 3) – node.js” implies and how to prevent it?

My website always displays this warning in the console :

"Request for font "Noto Sans" blocked at visibility level 1 (requires 3) - node.js"

Noto Sans is not loaded by the website, it is only used as a backup font if other fonts do not display. Yet it is the only backup font where I get this warning.

What does this message mean and how to eventually prevent it ?