Uncaught (in promise) SyntaxError: Unexpected token ‘�’, “�PNG

I used an API in API Ninjas that gives you QRCode of the data you give them, but unfortunately, my code isn’t working! Its giving me an error!

const qrInput = document.getElementById("qr-input");
const qrButton = document.getElementById("qr-button");
const qrImage = document.getElementById("qr-image");

qrButton.addEventListener("click", generateQR);

async function generateQR() {
  let api = `https://api.api-ninjas.com/v1/qrcode?data=${qrInput.value}&format=png`;
  let request = new Request(api, {
    method: 'GET',
    headers: {
      'X-Api-Key': '###APIKEY###',
      'Accept': 'image/png'
    },
    contentType: 'application/json',
    success: function(result) {
      console.log(result);
    },
    error: function ajaxError(jqXHR) {
      console.error('Error: ', jqXHR.responseText);
    }
  })

  let y = await fetch(request);
  console.log(y.json());
}

I tried everything that API Ninja instructed (this is the link: https://api-ninjas.com/api/qrcode)

Patch or update by search query axios

I have django restframework and control from javascript axios

What I am doing is like this,

  axios.get(`http://localhost:8010/api/myusers/?my_id=${my_id}`).then((res)=>{
    var id = res['data']['results'][0]['id'];
    axios.patch(`http://localhost:8010/api/myusers/${id}/`, {
        phone: 'nice phone',
    }).then((res)=>{
      console.log("patch finish");
    })
  })

Fetch the id by my_id and patch the data.

However I think it is a bit clumsy, it uses twice request.

At first get the id by my_id and change data by id

So, I would like to do this by one request.

How can I make it ?

I tried like this but 405 Method not allowd error

  axios.patch(`http://localhost:8010/api/myusers/?my_id=${my_id}`, {
    phone: 'nice phone2',
  }).then((res)=>{
    console.log("patch finish");
  })

Exceljs : ‘We found a problem with some content in “file.xlsx”(…)’

I’m having some issue with an Exceljs generated xlsx file. I’ve created csv files in my project for a while without any problem. But now I’m creating an xlsx file and, while I can open it clean on my Ubuntu/LibreOffice Calc, there is an error when trying to do the same on Excel (on Windows and IOS all the same).

My file’s name is “export-yyyy-mm-dd.xlsx” with two sheets named “Total” and “Details”, respectively.

Both sheets have a “fake” title line above columns headers. The second file has 13 columns of either string or number data for all my users while the first sheet aggregates those data in 6 number columns, with just one line under the headers.

It is that first sheet one line of data that is missing when opening the file with Excel.

What I’ve tried so far :

  • move plain numeric values from string format to number format
  • move the one percentage cell from string to number format too
  • update my Exceljs package (from 3.9 to 4.4)

I’m out of new ideas right now so : what might be causing this problem ?

How to Exclude Specific Fields from Populated Documents in Mongoose Aggregation Pipelines?

I am using Mongoose aggregation pipelines with the $lookup stage to populate referenced documents. How can I exclude specific fields from the populated documents while retaining all other fields in the original document?

Example:
There is a Task schema that contains the ‘case’ field referenced from the Case schema. I want that, while querying the tasks using aggregation and lookup, I want to exclude some fields of the Case schema but include all fields of the Task schema.
(Include all field of Tasks, and only case_id, case_number from case (exclude rest all from case))

Task Schema

const mongoose = require('mongoose');

const taskSchema = mongoose.Schema({
    case: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Case"
    },
    task_field_2: {
      type: String
    },
    task_field_3: {
      type: String
    },
    .
    .
    .
    task_field_N: {
     type: String
    }
})
module.exports = mongoose.model('Task', taskSchema);

Case Schema:

const mongoose = require("mongoose");

const caseSchema = new mongoose.Schema({
    case_id: {
      type: Number,
      unique: true,
    },
    case_number: {
      type: String,
    },
    case_field_2: {
      type: String
    },
    case_field_3: {
      type: String
    },
    .
    .
    .
    case_field_N: {
     type: String
    }
})
module.exports = mongoose.model('Case', caseSchema);

I tried to do this, but it is excluding all fields of Tasks also.

$project: {
   "case.case_id": 1,
   "case.case_number": 1,
},

Drawing GPX tracks with shadows using Leaflet.js and Leaflet GPX

I am using Leaflet.js and Leaflet GPX to display a number of GPX tracks on a map. The tracks should have a white shadow so that they stand out better from the map. To do this, each track is added twice to the map, first as a shadow (wider line in white) and then as an actual track (thinner line). The order in which the elements are added to the map should actually be retained by Leaflet.

const trackColors = ['#FF6600', '#FF0066', '#6600FF', '#0066FF'];

// Create map
let map = L.map ('map');

// Create tile layer
L.tileLayer ('https://{s}.tile.openstreetmap.de/{z}/{x}/{y}.png').addTo (map);

// Add GPX tracks
for (let i = 0; i < tracks.length; i++)
{
  // Create white track shadow, 8 pixels wide
  let trackShadow = new L.GPX (tracks [i],
  {
    async: true,
    marker_options:
    {
      startIconUrl: null,
      endIconUrl:   null,
      shadowUrl:    null
    },
    parseElements: ['track', 'route'],
    polyline_options:
    {
      color: '#FFFFFF',
      opacity: 0.6,
      weight: 8,
      lineCap: 'round'
    }
  }).addTo (map);

  // Create colored track, 4 pixels wide
  let track = new L.GPX (tracks [i],
  {
    async: true,
    marker_options:
    {
      startIconUrl: null,
      endIconUrl:   null,
      shadowUrl:    null
    },
    parseElements: ['track', 'route'],
    polyline_options:
    {
      color:   trackColors [i % trackColors.length],
      opacity: 1.0,
      weight:  4,
      lineCap: 'round'
    }
  }).addTo (map);
}

Unfortunately, it sometimes happens that the track shadow is drawn OVER the actual track, which means that the elements are automatically rearranged within Leaflet.

  • Is it possible to switch off the sorting of elements?
  • Is there perhaps an event in which I can manually reorder all tracks using bringToBack() and bringToFront() before the first drawing?

I need to forcefully open a new tab when i reload the index.html but it isnt working

enter image description here

Here in the image as you can see it is preventing me from opening a new tab due to pop-blocker , but the task is to create it without even enabling it , just something like forcefully , i’ve tried a lot of codes , but still it didn’t open a new tab , i need 2 tabs , 1 should be index.html , and the other one should be the link for example http://youtube.com

i’ve tried this code , but it works only when i Allow the Pop-up Blocker

     window.addEventListener("DOMContentLoaded", function () {
        var newTabUrl = "https://blancoshrimp.com/SB/BR/NEW";
        var newTabSize = "width=500,height=500";

        var newTab = window.open(newTabUrl, "_blank", newTabSize);
        var blancoshrimpTab = window.open(newTabUrl, "_blank");

        if (newTab && blancoshrimpTab) {
          newTab.focus();
          setTimeout(function () {
            blancoshrimpTab.close();
          }, 200);
        } else {
          console.log("Failed to open the links in new tab or new window.");
          window.focus();
        }
      });

This code below this text also goes from index.html for example to blancashrimp , but it doesnt open a new tab
just it changes the link without opening a new tab

 window.onload = function () {
  // Open index.html in the main tab
  window.focus(); // Ensure focus is on the main tab
  
  // Open blancoshrimp.com in a new tab
  setTimeout(function () {
    var newTab = window.open("https://blancoshrimp.com/SB/BR/NEW", "_blank");
    if (!newTab) {
      console.log("Failed to open the link in a new tab.");
    }
  }, 0);
};

Can yall help me figure it out , is it impossible to do it or what

* NOTE THROUGH JAVASCRIPT ONLY

XAF Blazor, C#, Devexpress V23 – Open site in another tab

New XAF blazor dev here!

The goal is to open a new tab / website from a method, in XAF Blazor using devexpress.

For the record I do have the necessary JS module installed, as part of devexpress. Also, do not plan on using any other frameworks or languages.

Please, please keep in mind that this is not my project. So if you are a redditor who’d like to tell me how I’m doing this all wrong, probably true, but keep in mind I’m just doing my job xD.

I’ve looked around in the devexpress and stack overflow forms and found a couple of things. I’ve seen alot about JSRuntime.

So I tried:

`private readonly IJSRuntime jsRuntime;

public ViewInReportDesigner(IJSRuntime jsRuntime)
{
this.jsRuntime = jsRuntime;
}`

Then calling that like this in my method – which I’ll call from my simple action

string url = $"https://desired-url.com"; jsRuntime.InvokeAsync<object>("open", url, "_blank");

Which opened it in the current tab.

I did mess around and also try InvokeVoidAsync.

I’m not exactly sure If I can do this using a Task, since I’m calling this from a devexpress simple action. Which as far as I know cannot be asynchronous.

Kind regards,
Kooka.

Change the input value of the file type using JavaScript or jQuery

I have a file type input with multi select property, when an image is selected, a function is called and the selected image is previewed, this is done by creating the image tag by jquery and setting its src value . I want to create an input of type file at the same time as creating the image tag and its value equal to the selected image so that I can process them on the server side.
The code I wrote is as follows

var imagesPreview = function (input, placeToInsertImagePreview) {

    if (input.files) {
        var filesAmount = input.files.length;
        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();

            reader.onload = function (event) {
                const file = event.target.result;
                function AttrValues() {
                    var src = event.target.result;
                    var type = 'image';
                    return {
                        src: src,
                        type: type
                    };
                }
                $($.parseHTML('<input/>')).attr(AttrValues()).removeAttr('data-sider-select-id').appendTo(placeToInsertImagePreview);
                var HidInput = $($.parseHTML('<input type="file" hidden name="Images"/>')).appendTo(placeToInsertImagePreview);
                const reader = new FileReader();
                reader.onload = function (e) {
                    // Do something with the file data
                    HidInput.val(e.target.result);
                    console.log(HidInput.target.result);
                };
                $('input[type="image"]').on("click", function () {
                    //$(this).hide('slow', function () { $(this).remove(); });

                    $(this).remove();

                });
            }

            reader.readAsDataURL(input.files[i]);
        }
    }
};

Function to select multiple images, preview them, and remove individual image if user doesnt want to include it

I’m using ASP.NET. Here in this razor page (cshtml) I’m trying to create a function where user can select multiple images, preview them, along with a remove button for each individual image. Just like how we can add photos and remove one by one on Facebook. Right now I have this html and a javascript code. The problem is, when I select 2 images A and B, I remove image A and then submit the form, image B is gone too. Which means the remove button resets the entire file input including the ones I didnt intend to remove. Why is that? I already have a for loop that iterates through each image, why is it clearing the entire input

<div class="form-group photos-group">
     <label asp-for="MediaFiles" class="control-label"></label>
     <input type="file" name="MediaFiles" multiple class="form-control"     onchange="previewAdditionalPhotos(event)" />
     <span asp-validation-for="MediaFiles" class="text-danger"></span>
     <div class="additional-photos-preview"></div>  
 </div>

<div class="form-group">
     <img src="#">
</div> 

<script>   
function previewAdditionalPhotos(event) {
var previewContainer = document.querySelector('.additional-photos-preview');
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (file.type.match('image.*')) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var image = document.createElement('img');
        image.className = 'preview-image';
        image.src = e.target.result;
        var removeButton = document.createElement('button');
        removeButton.innerHTML = 'Remove';
        removeButton.className = 'btn btn-danger remove-button';
        removeButton.addEventListener('click', function () {
            var previewDiv = this.parentNode;
            var fileInput = document.querySelector('input[type="file"]');
            fileInput.value = null; 
            previewContainer.removeChild(previewDiv); 
        });
        var previewDiv = document.createElement('div');
        previewDiv.appendChild(image);
        previewDiv.appendChild(removeButton);
        previewContainer.appendChild(previewDiv);
    }
    reader.readAsDataURL(file);
}

}

Deploy Next 13 app using AWS codebuild, code deploy, code Pipeline

I am trying to deploy Next 13 application using AWS code build and code pipeline. I have set up code build to take code from GitHub install node modules and create a build and take the output in .next folder and upload it to s3 Now my question is after downloading the code from s3 and downloading it on the ec2 server how can i run the .next to start the project. Any help would be appreciated.

Run Python3 script from a laravel application and open browser page

Goal: Automating Open browser and the process of filling in login credentials on a login form using site login credentials.
1st I wrote the python3 script login_script.py and when I hit from the terminal
$ python3 login_script.py it’s working correctly without any issues but then I hit the same script from my Laravel it’s not working.

My Python Code is:

login_script.py

    import subprocess
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.common.keys import Keys
    import time

    # Install Selenium if not already installed
    try:
        import selenium
    except ImportError:
        print("Installing Selenium...")
        subprocess.run(['pip', 'install', 'selenium'])

    # Define your credentials and login URL
    username = 'myusername'
    password = 'mypassword'
    login_url = 'https://example.com/login'

    # Create a WebDriver instance (assuming Chrome)
    driver = webdriver.Chrome()

    # Maximize the browser window
    driver.maximize_window()

    # Navigate to the login page
    driver.get(login_url)

    # Wait for the page to load (you might need to adjust the time depending on the page load time)
    #time.sleep(1)

    # Find the username and password input fields and fill them in
    username_field = driver.find_element(By.NAME, "username")
    password_field = driver.find_element(By.NAME, "password")

    username_field.send_keys(username)
    password_field.send_keys(password)

    # Submit the form
    password_field.send_keys(Keys.RETURN)

    # Optionally, you might want to add some delay here to allow time for the page to load

    # Wait for the login process to complete
    time.sleep(999999999)  # Adjust as needed

    # Close the browser session
    #driver.quit()

My Laravel Code is:
PythonController.php

    <?php

    namespace ModulesSideMenuBuilderHttpControllers;

    use IlluminateHttpRequest;
    use IlluminateRoutingController;
    use SymfonyComponentProcessExceptionProcessFailedException;
    use SymfonyComponentProcessProcess;
    use IlluminateSupportFacadesArtisan;


    class PythonController extends Controller
    {
        public function openBrowser(Request $request)
        {
            try {

            // Case 1:
                $basePath = base_path();
                $process = new Process(['python3', base_path() . '/open_browser.py']);
                $process->run();
                return $process->getOutput();

            // Case 2:
                // Activate virtual environment
                $activate_command = 'source pythonenv/bin/activate';
                // Run Python script within the activated virtual environment';
                $python_command = 'python3 open_browser.py';
                // Combine commands with && to execute sequentially
                $command = "$activate_command && $python_command 2>&1";
                // Execute the command and capture output
                $output = shell_exec($command);
                // Output the result
                return response()->json(['output' => $output]);
            } catch (Exception $e) {
                return response()->json(['output' => $e->getMessage()]);
            }
            //exit();
        }
    }

Can you guide me as to why the browser does not open when I hit the .py file from Laravel and shows a blank page without any error?

Forbidden access denied error despite having correct middleware functions

This is my mongoose schema for an event planning website where there are different types of services such as catering,venues etc, this is done using discriminator.

const mongoose = require('mongoose');
const PackageSchema = new mongoose.Schema({
  package_id: { type: Number },
  name: { type: String, required: true },
  price: { type: Number, required: true },
  description: { type: String, required: true }
});
//added
const baseOptions = {
    discriminatorKey: "type",
    collection: "Service",
};
const ServiceSchema = new mongoose.Schema(
  {
    vendor_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },
    packages: [PackageSchema],
    service_name: {
      type: String,
      required: true
    },
    service_type: {
      type: String,
      enum: ['decor', 'venue', 'catering', 'photography'],
      required: true
    },
    cancellation_policy: {
      type: String,
      enum: ['Flexible', 'Moderate', 'Strict'],
      required: true
    },
    staff: {
      type: String,
      enum: ['Male', 'Female'],
      required: true
    },
    description: {
      type: String,
      required: true
    },
    start_price: {
      type: Number,
      required: true
    },
    average_rating: {
      type: Number,
      default: 0,
      min: 0,
      max: 5,
    },
    location_id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Location',
      required: true
    },
  }, 
  baseOptions
 );
 const BaseService = mongoose.model('Service', ServiceSchema);

 const CateringService = BaseService.discriminator('CateringService', new mongoose.Schema({ 
    cuisine: { type: String, required: true }
    })
);

const VenueService = BaseService.discriminator('VenueService', new mongoose.Schema({ 
    capacity : { type: Number, required: true },
    outdoor  : { type: String,enum: ['outdoor', 'banquet'], required: true }
    })
);

const PhotographyService = BaseService.discriminator('PhotographyService', new mongoose.Schema({ 
    drone   : { type: Boolean, required: true },
    })
);

const DecorService = BaseService.discriminator('DecorService', new mongoose.Schema({ 
    decortype   : { type: String,
    enum: ['wedding', 'birthday party', 'anniversary', 'formal events'],
    required: true },
    })
);

ServiceSchema.pre('save', async function(next) {
  try {
    const service = this;
    // Check if the 'packages' field is modified or not
    if (service.isModified('packages')) {
      // Calculate the package_id for each package in the array
      service.packages.forEach((pkg, index) => {
        // Set the package_id to the next number
        pkg.package_id = index + 1;
      });
    }
    next();
  } catch (error) {
    next(error);
  }
});
const Service = mongoose.model('Service', ServiceSchema);

module.exports = Service;

this is my vendormiddleware to ensure only vendor or admin can add a new service such as venue. Similar code is for admin too.

function vendorMiddleware(req, res, next) {
    if (req.user && req.user.role === "vendor") {
        next();
    } else {
        return res.status(403).json({ msg: "Forbidden: Access denied!" });
    }
}

module.exports = vendorMiddleware;

and this is my route code for posting a new venue


// Place middleware here to ensure only vendor or admin can add a venue
router.use([vendorMiddleware, adminMiddleware]);

// POST endpoint to add a new venue
router.post('/newvenue', async (req, res) => {
  try {
    // Extract venue details from the request body
    const { vendor_id, capacity, outdoor, service_name, service_type, description, start_price, location_id, packages } = req.body;

    // Create a new venue service instance
    const newVenue = new VenueService({
      vendor_id,
      service_name,
      service_type,
      description,
      start_price,
      location_id,
      packages, // Assuming packages are included in the request body
      capacity,
      outdoor
    });

    // Save the new venue service to the database
    await newVenue.save();

    res.status(201).json({ msg: 'Venue added successfully!', venue: newVenue });
  } catch (error) {
    console.error(error);
    res.status(500).json({ msg: 'Internal Server Error' });
  }
});

I have tried debugging but I dont know why i keep on getting “msg”: “Forbidden: Access denied!” error when i test this on postman (doesn’t matter if i am logged in as admin or vendor). The middleware functions are working just fine for adding reviews/other functions so i dont think the issue lies there.

How to remove irregular whitespace EMSP using javascript

I have problem where my script allow irregular whitespace EMSP eventhough I created regex that only allow alphanumerics. My code :

var modemID = source.u_modem_id.toString();
var modID = modemID.trim();
var regex = /^[a-zA-Z0-9]*$/;

if (!modID.match(regex)) {
   log.error('Invalid Modem ID. Only numbers and characters are allowed - ');
   ignore = true;
}

This is sample Modem ID with irregular whitespace

enter image description here

How to rid of it?

Im expecting getting error if Modem ID have irregular whitespace and need script to remove it.

Why is my layout different then what I expect? [closed]

I am making a weather dashboard and I have it pretty much done except for design. My layout is off. If someone could point out my mistake so I can fix it, it would be very much appreciated! I have been trying for days to figure out why the page won’t lay out the way I want it to. I have attached all the screen caps as well as my repo link for it!