问:
ActiveRecord saves object when adding to association collection
From the Rails docs:

Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object (the owner of the collection) is not yet stored in the database.

I would like to prevent this save from occurring (for better or worse). I've come up with three strategies and would be curious to hear which one is recommended.

Block access to the DB during "<<". I posed the question of how best to accomplish this in another question: How can I prevent ActiveRecord from writing to the DB?. The proposed solution seems quite feasible.

Leveraging the caveat of "except if the parent object is not yet stored in the db". Looking at the rails code, this condition is determined with the new_record? method. I wrote a little method that makes an object think it's new for the duration of a block.

```<code># model.rb
def appear_as_new_record
  instance_eval { alias :old_new_record? :new_record? }
  instance_eval { alias :new_record? :present? }
  yield
  instance_eval { alias :new_record? :old_new_record? }
end

# used like this:
model.appear_as_new_record do
   model.gadgets << gadget
end
</code>```

Using the 'build' method, to attach the object to the collection. This would like something like this (I know this doesn't cover all the edge cases)

```<code>new_gadget = model.gadgets.build(gadget.attributes)
new_gadget.id = gadget.id
</code>```

there are quites a few scary things about this approach... but namely, it won't do a copy by reference. So if gadget also had a collection of objects already loaded, they wouldn't be accessible via the model without having to hit the db.

ContentLicense: CC BY-SA 3.0

Body:
From the Rails docs:

Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object (the owner of the collection) is not yet stored in the database.

I would like to prevent this save from occurring (for better or worse). I've come up with three strategies and would be curious to hear which one is recommended.

Block access to the DB during "<<". I posed the question of how best to accomplish this in another question: How can I prevent ActiveRecord from writing to the DB?. The proposed solution seems quite feasible.

Leveraging the caveat of "except if the parent object is not yet stored in the db". Looking at the rails code, this condition is determined with the new_record? method. I wrote a little method that makes an object think it's new for the duration of a block.

# model.rb
def appear_as_new_record
  instance_eval { alias :old_new_record? :new_record? }
  instance_eval { alias :new_record? :present? }
  yield
  instance_eval { alias :new_record? :old_new_record? }
end

# used like this:
model.appear_as_new_record do
   model.gadgets << gadget
end

Using the 'build' method, to attach the object to the collection. This would like something like this (I know this doesn't cover all the edge cases)

new_gadget = model.gadgets.build(gadget.attributes)
new_gadget.id = gadget.id

there are quites a few scary things about this approach... but namely, it won't do a copy by reference. So if gadget also had a collection of objects already loaded, they wouldn't be accessible via the model without having to hit the db.


来源: stackexchange

问:
VisionKit Barcode Scanner Enabling Highlights Using Swift
I am learning how to create a barcode scanner and would like to add highlighting (the yellow square that goes around the numbers when the camera recognizes it)

I believe I should use isHighlightingEnabled: true

But I am not sure what line to put it on in my code. Where should I be placing it and do I need to add anything to make it work?

```<code>import UIKit
import Vision
import AVFoundation
import SafariServices

@objc class CMWSTVisionReader: UIViewController {
  // MARK: - Private Variables
  var captureSession = AVCaptureSession()

    @IBOutlet weak var cameraView: UIView!
    @IBOutlet weak var barcodeResult: UILabel!

    // TODO: Make VNDetectBarcodesRequest variable
  lazy var detectBarcodeRequest = VNDetectBarcodesRequest { request, error in
    guard error == nil else {
//      self.showAlert(
//        withTitle: "Barcode error",
//        message: error?.localizedDescription ?? "error")
      return
    }
    self.processClassification(request)
  }

  // MARK: - Override Functions
  override func viewDidLoad() {
    super.viewDidLoad()
    checkPermissions()
    setupCameraLiveView()
  }
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // TODO: Stop Session
    captureSession.stopRunning()

  }
}

extension CMWSTVisionReader {
  // MARK: - Camera
  private func checkPermissions() {
    // TODO: Checking permissions
    switch AVCaptureDevice.authorizationStatus(for: .video) {
    // 1
    case .notDetermined:
      AVCaptureDevice.requestAccess(for: .video) { [self] granted in
        if !granted {
          showPermissionsAlert()
        }
      }

    // 2
    case .denied, .restricted:
      showPermissionsAlert()

    // 3
    default:
      return
    }

  }

  private func setupCameraLiveView() {
    // TODO: Setup captureSession
    captureSession.sessionPreset = .hd1280x720

    // TODO: Add input
    // 1
    let videoDevice = AVCaptureDevice
      .default(.builtInWideAngleCamera, for: .video, position: .back)

    // 2
    guard
      let device = videoDevice,
      let videoDeviceInput = try? AVCaptureDeviceInput(device: device),
      captureSession.canAddInput(videoDeviceInput)
      else {
        // 3
        showAlert(
          withTitle: "Cannot Find Camera",
          message: "There seems to be a problem with the camera on your device.")
        return
      }

    // 4
    captureSession.addInput(videoDeviceInput)

    // TODO: Add output
    let captureOutput = AVCaptureVideoDataOutput()
    // TODO: Set video sample rate
    captureOutput.videoSettings =
      [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
    captureOutput.setSampleBufferDelegate(
      self,
      queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))

    captureSession.addOutput(captureOutput)

    configurePreviewLayer()

    // TODO: Run session
    captureSession.startRunning()

  }

  // MARK: - Vision
  func processClassification(_ request: VNRequest) {
    // TODO: Main logic
    // 1
    guard let barcodes = request.results else { return }
    DispatchQueue.main.async { [self] in
      if captureSession.isRunning {
        view.layer.sublayers?.removeSubrange(1...)

        // 2
        for barcode in barcodes {
          guard
            // TODO: Check for QR Code symbology and confidence score
            let potentialQRCode = barcode as? VNBarcodeObservation,
            potentialQRCode.confidence > 0.9
            else { return }

          // 3
          observationHandler(payload: potentialQRCode.payloadStringValue)

        }
      }
    }

  }

  // MARK: - Handler
  func observationHandler(payload: String?) {
    // TODO: Open it in Safari
    // 1

      barcodeResult.text = payload
//      guard
//      let payloadString = payload,
//      let url = URL(string: payloadString),
//      ["http", "https"].contains(url.scheme?.lowercased())
//      else { return }
//
//    // 2
//    let config = SFSafariViewController.Configuration()
//    config.entersReaderIfAvailable = true
//
//    // 3
//    let safariVC = SFSafariViewController(url: url, configuration: config)
//    safariVC.delegate = self
//    present(safariVC, animated: true)

  }
}

// MARK: - AVCaptureDelegation
extension CMWSTVisionReader: AVCaptureVideoDataOutputSampleBufferDelegate {
  func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    // TODO: Live Vision
    // 1
    guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
      return
    }

    // 2
    let imageRequestHandler = VNImageRequestHandler(
      cvPixelBuffer: pixelBuffer,
      orientation: .right)

    // 3
    do {
      try imageRequestHandler.perform([detectBarcodeRequest])
    } catch {
      print(error)
    }

  }
}

// MARK: - Helper
extension CMWSTVisionReader {
  private func configurePreviewLayer() {
    let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer.videoGravity = .resizeAspectFill
    cameraPreviewLayer.connection?.videoOrientation = .portrait
    cameraPreviewLayer.frame = cameraView.frame
    cameraView.layer.insertSublayer(cameraPreviewLayer, at: 0)
  }

  private func showAlert(withTitle title: String, message: String) {
    DispatchQueue.main.async {
      let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
      alertController.addAction(UIAlertAction(title: "OK", style: .default))
      self.present(alertController, animated: true)
    }
  }

  private func showPermissionsAlert() {
    showAlert(
      withTitle: "Camera Permissions",
      message: "Please open Settings and grant permission for this app to use your camera.")
  }
}

// MARK: - SafariViewControllerDelegate
extension CMWSTVisionReader: SFSafariViewControllerDelegate {
  func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    captureSession.startRunning()
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am learning how to create a barcode scanner and would like to add highlighting (the yellow square that goes around the numbers when the camera recognizes it)

I believe I should use isHighlightingEnabled: true

But I am not sure what line to put it on in my code. Where should I be placing it and do I need to add anything to make it work?

import UIKit
import Vision
import AVFoundation
import SafariServices

@objc class CMWSTVisionReader: UIViewController {
  // MARK: - Private Variables
  var captureSession = AVCaptureSession()

    @IBOutlet weak var cameraView: UIView!
    @IBOutlet weak var barcodeResult: UILabel!

    // TODO: Make VNDetectBarcodesRequest variable
  lazy var detectBarcodeRequest = VNDetectBarcodesRequest { request, error in
    guard error == nil else {
//      self.showAlert(
//        withTitle: "Barcode error",
//        message: error?.localizedDescription ?? "error")
      return
    }
    self.processClassification(request)
  }

  // MARK: - Override Functions
  override func viewDidLoad() {
    super.viewDidLoad()
    checkPermissions()
    setupCameraLiveView()
  }
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // TODO: Stop Session
    captureSession.stopRunning()

  }
}

extension CMWSTVisionReader {
  // MARK: - Camera
  private func checkPermissions() {
    // TODO: Checking permissions
    switch AVCaptureDevice.authorizationStatus(for: .video) {
    // 1
    case .notDetermined:
      AVCaptureDevice.requestAccess(for: .video) { [self] granted in
        if !granted {
          showPermissionsAlert()
        }
      }

    // 2
    case .denied, .restricted:
      showPermissionsAlert()

    // 3
    default:
      return
    }

  }

  private func setupCameraLiveView() {
    // TODO: Setup captureSession
    captureSession.sessionPreset = .hd1280x720

    // TODO: Add input
    // 1
    let videoDevice = AVCaptureDevice
      .default(.builtInWideAngleCamera, for: .video, position: .back)

    // 2
    guard
      let device = videoDevice,
      let videoDeviceInput = try? AVCaptureDeviceInput(device: device),
      captureSession.canAddInput(videoDeviceInput)
      else {
        // 3
        showAlert(
          withTitle: "Cannot Find Camera",
          message: "There seems to be a problem with the camera on your device.")
        return
      }

    // 4
    captureSession.addInput(videoDeviceInput)

    // TODO: Add output
    let captureOutput = AVCaptureVideoDataOutput()
    // TODO: Set video sample rate
    captureOutput.videoSettings =
      [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
    captureOutput.setSampleBufferDelegate(
      self,
      queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))

    captureSession.addOutput(captureOutput)

    configurePreviewLayer()

    // TODO: Run session
    captureSession.startRunning()

  }

  // MARK: - Vision
  func processClassification(_ request: VNRequest) {
    // TODO: Main logic
    // 1
    guard let barcodes = request.results else { return }
    DispatchQueue.main.async { [self] in
      if captureSession.isRunning {
        view.layer.sublayers?.removeSubrange(1...)

        // 2
        for barcode in barcodes {
          guard
            // TODO: Check for QR Code symbology and confidence score
            let potentialQRCode = barcode as? VNBarcodeObservation,
            potentialQRCode.confidence > 0.9
            else { return }

          // 3
          observationHandler(payload: potentialQRCode.payloadStringValue)

        }
      }
    }

  }

  // MARK: - Handler
  func observationHandler(payload: String?) {
    // TODO: Open it in Safari
    // 1

      barcodeResult.text = payload
//      guard
//      let payloadString = payload,
//      let url = URL(string: payloadString),
//      ["http", "https"].contains(url.scheme?.lowercased())
//      else { return }
//
//    // 2
//    let config = SFSafariViewController.Configuration()
//    config.entersReaderIfAvailable = true
//
//    // 3
//    let safariVC = SFSafariViewController(url: url, configuration: config)
//    safariVC.delegate = self
//    present(safariVC, animated: true)

  }
}

// MARK: - AVCaptureDelegation
extension CMWSTVisionReader: AVCaptureVideoDataOutputSampleBufferDelegate {
  func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    // TODO: Live Vision
    // 1
    guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
      return
    }

    // 2
    let imageRequestHandler = VNImageRequestHandler(
      cvPixelBuffer: pixelBuffer,
      orientation: .right)

    // 3
    do {
      try imageRequestHandler.perform([detectBarcodeRequest])
    } catch {
      print(error)
    }

  }
}

// MARK: - Helper
extension CMWSTVisionReader {
  private func configurePreviewLayer() {
    let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer.videoGravity = .resizeAspectFill
    cameraPreviewLayer.connection?.videoOrientation = .portrait
    cameraPreviewLayer.frame = cameraView.frame
    cameraView.layer.insertSublayer(cameraPreviewLayer, at: 0)
  }

  private func showAlert(withTitle title: String, message: String) {
    DispatchQueue.main.async {
      let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
      alertController.addAction(UIAlertAction(title: "OK", style: .default))
      self.present(alertController, animated: true)
    }
  }

  private func showPermissionsAlert() {
    showAlert(
      withTitle: "Camera Permissions",
      message: "Please open Settings and grant permission for this app to use your camera.")
  }
}

// MARK: - SafariViewControllerDelegate
extension CMWSTVisionReader: SFSafariViewControllerDelegate {
  func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    captureSession.startRunning()
  }
}


问:
Cannot use "stop" to debug asp classic page on one web but can another
I have two web sites run in IIS on a Windows 2019 server.  I've been able to debug both by typing "stop" in the VBscript and it pops up a dialog box that says a "script breakpoint" occurred and which debugger do I want to use.  I select Visual Studio 2022 and away we go.

Until now... all of a sudden, I can't debug one of them (development) but I can the other (production).  There is NO ERROR, it just doesn't pop up the debug dialog box.  I've changed a few pages in dev (asp and aspx) but nothing that should affect any settings.  Both are on the same server and the only two web sites in IIS.  They "should" be mirror images of each other when development is moved to production.

Compared IIS, ASP, Debugging properties and they are the same.

Run iisreset and rebooted numerous times.

Made sure web.config's are the same.

Started VS and attached to the development w3wp.exe...   just ignores the stop command.

Put stop in a second page of the root of each web, production stops, dev doesn't

Checked registry - Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug

```<code>  Debugger string is "C:\windows\system32\vsjitdebugger.exe" -p %ld -e %ld -j 0x%p
</code>```

Coded a divide by zero in each page

production opens debug dialog and then gives HTTP Error 500.19 - Internal Server Error

dev shows white page with absolutely nothing in view source

I'm reasonably sure this is not a VS thing since both webs are built in the same VS... and actually the default page I'm putting the stop in was "hand" built, not in VS and the only pages in the root folder.  So it seems like some setting in IIS, but what one?

Web.config is minimal for both:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="true" />
    </system.webServer>
</configuration>
</code>```

Any direction here would be greatly appreciated.

Body:
I have two web sites run in IIS on a Windows 2019 server.  I've been able to debug both by typing "stop" in the VBscript and it pops up a dialog box that says a "script breakpoint" occurred and which debugger do I want to use.  I select Visual Studio 2022 and away we go.

Until now... all of a sudden, I can't debug one of them (development) but I can the other (production).  There is NO ERROR, it just doesn't pop up the debug dialog box.  I've changed a few pages in dev (asp and aspx) but nothing that should affect any settings.  Both are on the same server and the only two web sites in IIS.  They "should" be mirror images of each other when development is moved to production.

Compared IIS, ASP, Debugging properties and they are the same.

Run iisreset and rebooted numerous times.

Made sure web.config's are the same.

Started VS and attached to the development w3wp.exe...   just ignores the stop command.

Put stop in a second page of the root of each web, production stops, dev doesn't

Checked registry - Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug

  Debugger string is "C:\windows\system32\vsjitdebugger.exe" -p %ld -e %ld -j 0x%p

Coded a divide by zero in each page

production opens debug dialog and then gives HTTP Error 500.19 - Internal Server Error

dev shows white page with absolutely nothing in view source

I'm reasonably sure this is not a VS thing since both webs are built in the same VS... and actually the default page I'm putting the stop in was "hand" built, not in VS and the only pages in the root folder.  So it seems like some setting in IIS, but what one?

Web.config is minimal for both:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="true" />
    </system.webServer>
</configuration>

Any direction here would be greatly appreciated.


问:
How can i obtain the actions of an attached policy in AWS using SDK V3?
I've been having problems for days looking for a way to get the actions from the attached policies. I need to list the actions that a permission set has. Now I'm using SDK V3 with javascript. Could someone guide me on how to get them?

I have tried with various functions of the IAM client and the SSO Admin client but without any success to date..


问:
Django-Stripe how to get the product data in the checkout session
I am still new to django and I am working on a django website whereby users can purchase goods and pay through Stripe. I have been following a tutorial and the tutorial has managed to make a payment but the problem is that the figures they are using are hard coded. My issue currently is how to get the values of what I am selling from the database.
Here is my views.py:

```<code>def bookService(request, gig_id):
    gig = Gig.objects.get(gig_id = gig_id)
    context = {'gig':gig}
    return render(request, 'payments/book.html', context)

@csrf_exempt
def create_checkout_session(request):
    #Updated- creating Order object
    order=Order(email=" ",paid="False",amount=0,description=" ", buyer=request.user.profile)
    order.save()
    session = stripe.checkout.Session.create(
    client_reference_id=request.user.id if request.user.is_authenticated else None,
    payment_method_types=['card'],
    line_items=[{
    'price_data': {
    'currency': 'usd',
    'product_data': {
    'name': 'Intro to Django Course',
    },
    'unit_amount': 10000,
    },
    'quantity': 1,
    }],
    #Update - passing order ID in checkout to update the order object in webhook
    metadata={
    "order_id":order.id
    },
    mode='payment',
    success_url=YOUR_DOMAIN + '/success.html',
    cancel_url=YOUR_DOMAIN + '/cancel.html',
    )
    return JsonResponse({'id': session.id})
</code>```

Here is the URLs file

```<code>urlpatterns = [
  path('seller/<str:gig_id>/', views.bookService, name='home'),
  path('create-checkout-session/', views.create_checkout_session, name='checkout'),
  path('success.html/', views.success,name='success'),
  path('cancel.html/', views.cancel,name='cancel'),
]
</code>```

And here is the template whereby I am viewing the details and also whereby the button that redirects users to pay is located:

```<code><script type="text/javascript">
        // Create an instance of the Stripe object with your publishable API key
        var stripe = Stripe('');
        var checkoutButton = document.getElementById('checkout-button');

        checkoutButton.addEventListener('click', function() {
        // Create a new Checkout Session using the server-side endpoint you
        // created in step 3.
        fetch('/create-checkout-session/', {
        method: 'POST',
        data: JSON.stringify({
              amount: "{{ gig.service_cost }}" * 100,
              description: "{{ gig.title }}",
              gig_id: "{{ gig.gig_id }}",
            }),
        })
        .then(function(response) {
        return response.json();
        })
        .then(function(session) {
        return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function(result) {
        // If `redirectToCheckout` fails due to a browser or network
        // error, you should display the localized error message to your
        // customer using `error.message`.
        if (result.error) {
        alert(result.error.message);
        }
        })
        .catch(function(error) {
        console.error('Error:', error);
        });
        });
        </script>
</code>```

Also here is the model whereby I want to save the order:

```<code>class Order(models.Model):
    buyer = models.ForeignKey(Profile, on_delete=models.CASCADE)
    # product = models.ForeignKey(Gig, on_delete=models.CASCADE)
    email = models.EmailField(max_length=254)
    paid = models.BooleanField(default="False")
    delivered = models.BooleanField(default="False")
    amount = models.IntegerField(default=0)
    description = models.CharField(default=None,max_length=800)

    def __str__(self):
        return self.email
</code>```

I have commented out the product line as I try to look for solutions. Any assistance will be highly appreciated.

I have tried loading json from the template but it seems not to work. Here is the json line I added to the script;

```<code>method: 'POST',
        data: JSON.stringify({
              amount: "{{ gig.service_cost }}" * 100,
              description: "{{ gig.title }}",
              gig_id: "{{ gig.gig_id }}",
            }),
</code>```

Body:
I am still new to django and I am working on a django website whereby users can purchase goods and pay through Stripe. I have been following a tutorial and the tutorial has managed to make a payment but the problem is that the figures they are using are hard coded. My issue currently is how to get the values of what I am selling from the database.
Here is my views.py:

def bookService(request, gig_id):
    gig = Gig.objects.get(gig_id = gig_id)
    context = {'gig':gig}
    return render(request, 'payments/book.html', context)

@csrf_exempt
def create_checkout_session(request):
    #Updated- creating Order object
    order=Order(email=" ",paid="False",amount=0,description=" ", buyer=request.user.profile)
    order.save()
    session = stripe.checkout.Session.create(
    client_reference_id=request.user.id if request.user.is_authenticated else None,
    payment_method_types=['card'],
    line_items=[{
    'price_data': {
    'currency': 'usd',
    'product_data': {
    'name': 'Intro to Django Course',
    },
    'unit_amount': 10000,
    },
    'quantity': 1,
    }],
    #Update - passing order ID in checkout to update the order object in webhook
    metadata={
    "order_id":order.id
    },
    mode='payment',
    success_url=YOUR_DOMAIN + '/success.html',
    cancel_url=YOUR_DOMAIN + '/cancel.html',
    )
    return JsonResponse({'id': session.id})

Here is the URLs file

urlpatterns = [
  path('seller/<str:gig_id>/', views.bookService, name='home'),
  path('create-checkout-session/', views.create_checkout_session, name='checkout'),
  path('success.html/', views.success,name='success'),
  path('cancel.html/', views.cancel,name='cancel'),
]

And here is the template whereby I am viewing the details and also whereby the button that redirects users to pay is located:

Also here is the model whereby I want to save the order:

class Order(models.Model):
    buyer = models.ForeignKey(Profile, on_delete=models.CASCADE)
    # product = models.ForeignKey(Gig, on_delete=models.CASCADE)
    email = models.EmailField(max_length=254)
    paid = models.BooleanField(default="False")
    delivered = models.BooleanField(default="False")
    amount = models.IntegerField(default=0)
    description = models.CharField(default=None,max_length=800)

    def __str__(self):
        return self.email

I have commented out the product line as I try to look for solutions. Any assistance will be highly appreciated.

I have tried loading json from the template but it seems not to work. Here is the json line I added to the script;

method: 'POST',
        data: JSON.stringify({
              amount: "{{ gig.service_cost }}" * 100,
              description: "{{ gig.title }}",
              gig_id: "{{ gig.gig_id }}",
            }),


问:
How do i resolve this error on flutter admit
Hello everyone I try to put the ads on my app in flutter but with each ad viewed it gives me an error message and I can't find how to correct it

this is my error message :

[I-ACS800014] Cannot get flag for unregistered flag. SDK name, flag name: app_measurement, session_stitching_token_feature_enabled

here is my code

```<code>    if (_rewardedAd != null) {
      _rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
        onAdDismissedFullScreenContent: (ad) {
          ad.dispose();
          _createRewardedAd();
        },
        onAdFailedToShowFullScreenContent: (ad, error) => {
          ad.dispose(),
          _createRewardedAd(),
        },
      );
      _rewardedAd!.show(
          onUserEarnedReward: (ad, reward) => setState(() => rewardfct()));
      HapticFeedback.heavyImpact();
      _rewardedAd = null;
    }
  }

  // Fonction qui va permettre de récompenser l'utilisateur et a sauvegarder son solde

  rewardfct() async {
    setState(() {
      userdata.coin++;
      ammounteneuro = userdata.coin * 0.05;
      print(userdata.coin);
    });
    try {
      await update();
    } catch (e) {
      print(e);
    }
  }

  // Fonction qui va chercher la pub
  void _createRewardedAd() {
    RewardedAd.load(
        adUnitId: AdMobService.rewardedAdUnitId,
        request: const AdRequest(),
        rewardedAdLoadCallback: RewardedAdLoadCallback(
          onAdLoaded: (ad) => setState(() => _rewardedAd = ad),
          onAdFailedToLoad: (error) => setState((() => _rewardedAd = null)),
        ));
  }

class AdMobService {
  static String get rewardedAdUnitId {
    if (Platform.isIOS) {
      return "ca-app-pub-3940256099942544/1712485313";
    }
    return "";
  }
}
</code>```

I'm trying to build an app

Body:
Hello everyone I try to put the ads on my app in flutter but with each ad viewed it gives me an error message and I can't find how to correct it

this is my error message :

[I-ACS800014] Cannot get flag for unregistered flag. SDK name, flag name: app_measurement, session_stitching_token_feature_enabled

here is my code

    if (_rewardedAd != null) {
      _rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
        onAdDismissedFullScreenContent: (ad) {
          ad.dispose();
          _createRewardedAd();
        },
        onAdFailedToShowFullScreenContent: (ad, error) => {
          ad.dispose(),
          _createRewardedAd(),
        },
      );
      _rewardedAd!.show(
          onUserEarnedReward: (ad, reward) => setState(() => rewardfct()));
      HapticFeedback.heavyImpact();
      _rewardedAd = null;
    }
  }

  // Fonction qui va permettre de récompenser l'utilisateur et a sauvegarder son solde

  rewardfct() async {
    setState(() {
      userdata.coin++;
      ammounteneuro = userdata.coin * 0.05;
      print(userdata.coin);
    });
    try {
      await update();
    } catch (e) {
      print(e);
    }
  }

  // Fonction qui va chercher la pub
  void _createRewardedAd() {
    RewardedAd.load(
        adUnitId: AdMobService.rewardedAdUnitId,
        request: const AdRequest(),
        rewardedAdLoadCallback: RewardedAdLoadCallback(
          onAdLoaded: (ad) => setState(() => _rewardedAd = ad),
          onAdFailedToLoad: (error) => setState((() => _rewardedAd = null)),
        ));
  }

class AdMobService {
  static String get rewardedAdUnitId {
    if (Platform.isIOS) {
      return "ca-app-pub-3940256099942544/1712485313";
    }
    return "";
  }
}

I'm trying to build an app


问:
Raising a float to a very large number Python (matrix powers) with modulo (knowing that end product is an integer)
I'm trying to find the power of a 2x2 integer matrix M^n. This can be done to a very high power (e10000 for example). Normally, I would be taking the modulo of a max size matrix directly, which could take O(N) time with numpy.linalg.matrix_power or some trickery could give you O(logN) time.

But matrix diagonalization shouldn't be too hard to theoretically turn this into an O(1) problem which could speed this problem up pretty significantly. Conceptually this should be pretty easy by just getting the power of 2 constant numbers. However, when the integer is diagonalized, the two constants are irrational numbers.

So, I go into an overflow state when trying to get the power of the diagonal matrix. Knowing that the final result will be some very large integer that I need to take a modulo of, I'm trying to figure out a good way to take the power of this irrational number.

Is there any way to do this in a way quicker than just multiplying the 2x2 matrix by itself?


问:
Weird results with topojson.merge
I am trying to draw realistic (non-straight) borders of randomly generated countries using d3.geoVoronoi and topojson.merge. This is what I am doing:

I create 3 Voronoi diagrams, say A, B and C, respectively with 100, 1000, and 10000 cells.

I merge the voronoi cells of B (1000 cells) if their centroid is contained in the same cell of A (100 cells). In this way I obtain B', with 100 cells having irregular borders.

I repeat point 2, this time merging the cells of C (10000) if their centroid belongs to B'. I thus obtain B'', with 100 cells with even more realistic borders.

In principle the procedure could be repeated to obtain even more detailed borders, but I am already running into problems. When I draw B'' (black lines in the figures), it looks weird.
Why? Does it have to do with the winding order of B'? How can I fix this?

Figures:
Figure 1, Figure 2, Figure 3

```<code>const v_land = d3.geoVoronoi(land_Points);
    let countries_polygons_land = v_land.polygons(land_Points);

    const countries_topology2 = {
        type: "Topology",
        polygons: countries_polygons_land
    };
    const countries_topoJSON_land = topojson.topology(countries_topology2);
    const countries_geojson_land = topojson.feature(countries_topoJSON_land, countries_topoJSON_land.objects.polygons);

    // MERGE
    let mergedGeoJSON = countries_geojson_land;
    let featureCluster = create2DArray(mergedGeoJSON.features.length);
    let newFeature;

    for (let k=1; k<points.length; k++) {

        // Merge smaller states within greater boundaries
        for (let i=0; i < mergedGeoJSON.features.length; i++) {
            for (let j=0; j < countries_geojson[k].features.length; j++) {
                if(d3.geoContains(mergedGeoJSON.features[i], d3.geoCentroid(countries_geojson[k].features[j]))) {
                    featureCluster[i].push(countries_topoJSON[k].objects.polygons.geometries[j]);
                }
            }
        }
        // Create geoJSON
        mergedGeoJSON = {
            type: "FeatureCollection",
            features: []
        }
        for (let i=0; i < featureCluster.length; i++) {
            newFeature = {
                type: "Feature",
                geometry: topojson.merge(countries_topoJSON[k], featureCluster[i])
            }
            mergedGeoJSON.features.push(newFeature);
        }
        // Draw Polygons (realistic)
        ctx.beginPath(),
        path(mergedGeoJSON),
        ctx.strokeStyle = `rgba(0, 0, 0, 1)`,
        ctx.lineWidth = 0.5*k,
        ctx.lineJoin = 'round',
        ctx.stroke();
    }
</code>```

Title: Weird results with topojson.merge

Body:
I am trying to draw realistic (non-straight) borders of randomly generated countries using d3.geoVoronoi and topojson.merge. This is what I am doing:

I create 3 Voronoi diagrams, say A, B and C, respectively with 100, 1000, and 10000 cells.

I merge the voronoi cells of B (1000 cells) if their centroid is contained in the same cell of A (100 cells). In this way I obtain B', with 100 cells having irregular borders.

I repeat point 2, this time merging the cells of C (10000) if their centroid belongs to B'. I thus obtain B'', with 100 cells with even more realistic borders.

In principle the procedure could be repeated to obtain even more detailed borders, but I am already running into problems. When I draw B'' (black lines in the figures), it looks weird.
Why? Does it have to do with the winding order of B'? How can I fix this?

Figures:
Figure 1, Figure 2, Figure 3

const v_land = d3.geoVoronoi(land_Points);
    let countries_polygons_land = v_land.polygons(land_Points);

    const countries_topology2 = {
        type: "Topology",
        polygons: countries_polygons_land
    };
    const countries_topoJSON_land = topojson.topology(countries_topology2);
    const countries_geojson_land = topojson.feature(countries_topoJSON_land, countries_topoJSON_land.objects.polygons);

    // MERGE
    let mergedGeoJSON = countries_geojson_land;
    let featureCluster = create2DArray(mergedGeoJSON.features.length);
    let newFeature;

    for (let k=1; k<points.length; k++) {

        // Merge smaller states within greater boundaries
        for (let i=0; i < mergedGeoJSON.features.length; i++) {
            for (let j=0; j < countries_geojson[k].features.length; j++) {
                if(d3.geoContains(mergedGeoJSON.features[i], d3.geoCentroid(countries_geojson[k].features[j]))) {
                    featureCluster[i].push(countries_topoJSON[k].objects.polygons.geometries[j]);
                }
            }
        }
        // Create geoJSON
        mergedGeoJSON = {
            type: "FeatureCollection",
            features: []
        }
        for (let i=0; i < featureCluster.length; i++) {
            newFeature = {
                type: "Feature",
                geometry: topojson.merge(countries_topoJSON[k], featureCluster[i])
            }
            mergedGeoJSON.features.push(newFeature);
        }
        // Draw Polygons (realistic)
        ctx.beginPath(),
        path(mergedGeoJSON),
        ctx.strokeStyle = `rgba(0, 0, 0, 1)`,
        ctx.lineWidth = 0.5*k,
        ctx.lineJoin = 'round',
        ctx.stroke();
    }


问:
WordPress custom post meta filter not displaying options when filter is set
I have two custom post types set up - "Books" and "Authors". I am using custom metadata which allows you to link a book to an author via a select box (by querying posts from the authors post type to create the select options).

This works fine, but I'm also trying to create a custom filter on the posts screen for the books post type that allows you to filter by author, which isn't behaving as expected. Here's the code I'm using to add the filter:

```<code>function book_filter() {
  global $typenow;
  global $wp_query;
    if ( $typenow == 'book' ) {
      $authors = new WP_Query(
        array(
          'post_type' => 'author',
          'nopaging' => true
        )
      );
      wp_reset_postdata();

      /*
      $authors = get_posts( array(
        'post_type' => 'author',
        'numberposts' => -1
      ));
      */

      $current_author = '';
      if( isset( $_GET['author'] ) ) {
        $current_author = $_GET['author'];
      } ?>
      <select name="author" id="author">
        <option value="all" <?php selected( 'all', $current_author ); ?>>All authors</option>
        <?php
        if ($authors->have_posts()) {
            while ($authors->have_posts()) {
                $authors->the_post();
                if ($current_author == get_the_ID()) {
                  echo '<option value="' . get_the_ID() . '" selected>' . get_the_title() . '</option>';
                } else {
                  echo '<option value="' . get_the_ID() . '">' . get_the_title() . '</option>';
                }
            }
        }

        /* foreach( $authors as $author ) { ?>
          <option value="<?php echo $author->ID; ?>" <?php selected( $author->ID, $current_author ); ?>><?php echo get_the_title($author->ID); ?></option>
        <?php } */

        ?>
      </select>
  <?php }
}
add_action( 'restrict_manage_posts', 'book_filter' );

function do_book_filter( $query ) {
  global $pagenow;
  $post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
  if ( is_admin() && $pagenow=='edit.php' && $post_type == 'book' ) {
    if (isset( $_GET['author'] ) && $_GET['author'] !='all' ) {
      $query->query_vars['meta_key'] = 'author';
      $query->query_vars['meta_value'] = $_GET['author'];
      $query->query_vars['meta_compare'] = '=';
    }
  }
}
add_filter( 'parse_query', 'do_book_filter' );
</code>```

Initially, all the authors are shown in the filter, and selecting an author to filter by does actually work. The problem is that, once it's been filtered, the authors disappear from the select box dropdown. I tried adding an else statement to if ($authors->have_posts()) {... and this confirmed that it isn't fetching posts from the authors post type after a filter has been set.

I'm also using another custom filter (removed from the code for simplicity) which just uses a standard array variable rather than a query and that one is working fine, so I guess it must something to do with the custom post type query.

You'll see in the code that I've tried get_posts (commented) as well as WP_Query but they both present the same issue.

Where am I going wrong here?

Body:
I have two custom post types set up - "Books" and "Authors". I am using custom metadata which allows you to link a book to an author via a select box (by querying posts from the authors post type to create the select options).

This works fine, but I'm also trying to create a custom filter on the posts screen for the books post type that allows you to filter by author, which isn't behaving as expected. Here's the code I'm using to add the filter:

function book_filter() {
  global $typenow;
  global $wp_query;
    if ( $typenow == 'book' ) {
      $authors = new WP_Query(
        array(
          'post_type' => 'author',
          'nopaging' => true
        )
      );
      wp_reset_postdata();

      /*
      $authors = get_posts( array(
        'post_type' => 'author',
        'numberposts' => -1
      ));
      */

      $current_author = '';
      if( isset( $_GET['author'] ) ) {
        $current_author = $_GET['author'];
      } ?>
      <select name="author" id="author">
        <option value="all" <?php selected( 'all', $current_author ); ?>>All authors</option>
        <?php
        if ($authors->have_posts()) {
            while ($authors->have_posts()) {
                $authors->the_post();
                if ($current_author == get_the_ID()) {
                  echo '<option value="' . get_the_ID() . '" selected>' . get_the_title() . '</option>';
                } else {
                  echo '<option value="' . get_the_ID() . '">' . get_the_title() . '</option>';
                }
            }
        }

        /* foreach( $authors as $author ) { ?>
          <option value="<?php echo $author->ID; ?>" <?php selected( $author->ID, $current_author ); ?>><?php echo get_the_title($author->ID); ?></option>
        <?php } */

        ?>
      </select>
  <?php }
}
add_action( 'restrict_manage_posts', 'book_filter' );

function do_book_filter( $query ) {
  global $pagenow;
  $post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : '';
  if ( is_admin() && $pagenow=='edit.php' && $post_type == 'book' ) {
    if (isset( $_GET['author'] ) && $_GET['author'] !='all' ) {
      $query->query_vars['meta_key'] = 'author';
      $query->query_vars['meta_value'] = $_GET['author'];
      $query->query_vars['meta_compare'] = '=';
    }
  }
}
add_filter( 'parse_query', 'do_book_filter' );

Initially, all the authors are shown in the filter, and selecting an author to filter by does actually work. The problem is that, once it's been filtered, the authors disappear from the select box dropdown. I tried adding an else statement to if ($authors->have_posts()) {... and this confirmed that it isn't fetching posts from the authors post type after a filter has been set.

I'm also using another custom filter (removed from the code for simplicity) which just uses a standard array variable rather than a query and that one is working fine, so I guess it must something to do with the custom post type query.

You'll see in the code that I've tried get_posts (commented) as well as WP_Query but they both present the same issue.

Where am I going wrong here?


问:
How can I automatically remove the 'v' prefix from draft tags uploaded by electron-builder?
I'm using the electron-builder and electron-updater modules to build and distribute updates for my app. These things all work just fine, except the fact that when electron-builder drafts a new release, it prefixes the version number with "v" in the tag (so version "1.2.3" is given the tag v1.2.3). This is the old SemVer protocol; the new SemVer protocol does not use this prefix. The only reason this matters to me is because electron-updater uses the new protocol. If the version tag for the release on GitHub has this prefix, then electron-updater will not recognize it and will not update.

I can fix this manually on GitHub – I have to visit the draft page anyways to publish it. But occasionally I do forget to change the tag, and it has caused confusion already when I tell my users an update is available and from their end, the app is refusing to update.

I have not been able to find anything on the electron-builder docs about changing the tag it uses. Is there any way to force the module to not use this 'v' prefix in the version tags?


问:
`TypeError: Couldn't build proto file into descriptor pool: duplicate symbol 'edu.stanford.nlp.pipeline.Language'` while importing corenlp in Python
TypeError: Couldn't build proto file into descriptor pool: duplicate symbol 'edu.stanford.nlp.pipeline.Language'

I am getting this error for this code in Python:
import corenlp

I've been on this issue for over 5 hours now, I am just not able to import corenlp in python for some reason. I have followed all the steps:

pip install corenlp

I also installed protobuf and added it to my path as some solution said that.

My Stanford CoreNLP library version is 4.5.1 which is compatible with the corenlp library.

I am guessing there's some issue with protobuf. Let me know if anybody can fix this!


问:
Python telegram bot does not working when launched along with uvicorn server [v20.0]
python-telegram-bot==20.0

I'm trying to run a telegram bot that proxies messages retrieved via HTTP to telegram. I found the example that does a very similar thing that I want to do and most of the code I've copied from it

Here's my code (handlers are not included. They worked before I added the webserver to the code):

```<code>
async def main() -> NoReturn:

    async def webhook_update(update: WebhookUpdate, context: CallbackContext) -> None:
        """Callback that handles the custom updates."""
        await context.bot.send_message(
            chat_id=update.user_id,
            text=update.payload,
            parse_mode=ParseMode.HTML
        )
    async def custom_updates(request: Request) -> JSONResponse:
        """
        Handle incoming webhook updates by also putting them into the `update_queue` if
        the required parameters were passed correctly.
        """
        data = await request.json()
        user_id = data["user_id"]
        payload = data['payload']

        await telegram_bot_application.update_queue.put(WebhookUpdate(user_id=user_id, payload=payload))
        return JSONResponse({'success': True})

    telegram_bot_application = ApplicationBuilder() \
        .token(settings.TELEGRAM_TOKEN) \
        .build()
    # .updater(None) \
    telegram_bot_application.add_handler(CommandHandler('start', command.start_handler))
    telegram_bot_application.add_handler(CallbackQueryHandler(button.button_handler))
    telegram_bot_application.add_handler(TypeHandler(type=WebhookUpdate, callback=webhook_update))
    telegram_bot_application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), message.message_handler))
    logging.info('telegram bot is configured')

    await telegram_bot_application.bot.set_webhook(url=f"{settings.BASE_HOST}/external_message")
    starlette_app = Starlette(
        routes=[
            Route("/external_message", custom_updates, methods=["POST"]),
        ]
    )
    webserver = uvicorn.Server(
        config=uvicorn.Config(
            app=starlette_app,
            port=8080,
            use_colors=False,
            host="0.0.0.0",
        )
    )
    logging.info('webserver configured')

    async with telegram_bot_application:
        await telegram_bot_application.start()
        logging.info('bot started')
        await webserver.serve()
        await telegram_bot_application.stop()

if __name__ == "__main__":
    asyncio.run(main())

</code>```

The code runs without errors but never logs the messages placed inside handlers (all of them are async).

Body:
python-telegram-bot==20.0

I'm trying to run a telegram bot that proxies messages retrieved via HTTP to telegram. I found the example that does a very similar thing that I want to do and most of the code I've copied from it

Here's my code (handlers are not included. They worked before I added the webserver to the code):

async def main() -> NoReturn:

    async def webhook_update(update: WebhookUpdate, context: CallbackContext) -> None:
        """Callback that handles the custom updates."""
        await context.bot.send_message(
            chat_id=update.user_id,
            text=update.payload,
            parse_mode=ParseMode.HTML
        )
    async def custom_updates(request: Request) -> JSONResponse:
        """
        Handle incoming webhook updates by also putting them into the `update_queue` if
        the required parameters were passed correctly.
        """
        data = await request.json()
        user_id = data["user_id"]
        payload = data['payload']

        await telegram_bot_application.update_queue.put(WebhookUpdate(user_id=user_id, payload=payload))
        return JSONResponse({'success': True})

    telegram_bot_application = ApplicationBuilder() \
        .token(settings.TELEGRAM_TOKEN) \
        .build()
    # .updater(None) \
    telegram_bot_application.add_handler(CommandHandler('start', command.start_handler))
    telegram_bot_application.add_handler(CallbackQueryHandler(button.button_handler))
    telegram_bot_application.add_handler(TypeHandler(type=WebhookUpdate, callback=webhook_update))
    telegram_bot_application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), message.message_handler))
    logging.info('telegram bot is configured')

    await telegram_bot_application.bot.set_webhook(url=f"{settings.BASE_HOST}/external_message")
    starlette_app = Starlette(
        routes=[
            Route("/external_message", custom_updates, methods=["POST"]),
        ]
    )
    webserver = uvicorn.Server(
        config=uvicorn.Config(
            app=starlette_app,
            port=8080,
            use_colors=False,
            host="0.0.0.0",
        )
    )
    logging.info('webserver configured')

    async with telegram_bot_application:
        await telegram_bot_application.start()
        logging.info('bot started')
        await webserver.serve()
        await telegram_bot_application.stop()

if __name__ == "__main__":
    asyncio.run(main())

The code runs without errors but never logs the messages placed inside handlers (all of them are async).


问:
Why is my app showing unexpected token '{' import call expects exactly one argument . No stack on Expo go
I keep getting this error on my expo go when I try to run an application I'm currently working on.
unexpected token '{' import call expects exactly one argument. No stack

I've tried re editing some imported statements


问:
How to overlay two mp3 audio files with different bitrates using fluent-ffmpeg
I am trying to overlay one mp3 file (a speech track, the file name for which is passed into the below function) on top of another (a background music track, the url of which is passed into the function), so that they both play simultaneously, using NodeJS and fluent-ffmpeg.

What happens when I call the function is that I get an output file which 1) only plays the background audio track, and 2) upon opening the output track, the time seeker skips straight to where the end of the first audio track would have been (around 1 minute 30 seconds).

I'd like to in the first instance have them play at the same time as each other in the output file, without this skipping ahead effect (even if I drag the slider back to within the first 1 minute 30, it just jumps straight back to 1 minute 31 seconds - as if somehow there was no data in that first minute and a half).

In the second instance, I'd also like to have the background audio track loop until the first track finishes, so any help with that as part of an answer would be very much appreciated. But the immediate problem is just getting the two audios to actually play simultaneously starting from 0 seconds.

I have tried the below to get to this point:

```<code>const fs = require('fs');
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
const ffmpeg = require('fluent-ffmpeg');
ffmpeg.setFfmpegPath(ffmpegPath);
var ffprobe = require('ffprobe-static');
ffmpeg.setFfprobePath(ffprobe.path);
const axios = require('axios');
const crypto = require('crypto');
const path = require('path');

const overlayBackgroundAudio = async (inputFileName, backgroundFileUrl) => {

    const backgroundTrack = await axios({
        method: 'GET',
        url: backgroundFileUrl,
        responseType: 'arraybuffer'
    });

    // write a file with the retrieved background audio track
    const backgroundTrackFileName = crypto.randomBytes(12).toString('hex');
    fs.writeFileSync(`${backgroundTrackFileName}.mp3`, backgroundTrack.data); //todo - delete after

    // set the name of the output file
    const newFileName = crypto.randomBytes(12).toString('hex');
    const outputFileName = `${newFileName}.mp3`;

    // run the relevant ffmpeg commands

    const overlayTracks = async () => {

        return new Promise((resolve, reject) => {
            ffmpeg()
                .input(`${inputFileName}.mp3`)
                .input(`${backgroundTrackFileName}.mp3`)
                .complexFilter([
                    {
                      filter: 'volume',
                      options: '1',
                      inputs: '[0:0]',
                      outputs: '[a]'
                    },
                    {
                      filter: 'volume',
                      options: '1',
                      inputs: '[1:0]',
                      outputs: '[b]'
                    },
                    {
                        filter: 'adelay',
                        options: '0',
                        inputs: '[a]',
                        outputs: '[a1]'
                    },
                    {
                        filter: 'adelay',
                        options: '0|0',
                        inputs: '[b]',
                        outputs: '[b1]'
                    },
                    {
                      filter: 'amix',
                      options: 'inputs=2:duration=first',
                      inputs: '[a1][b1]',
                      outputs: '[out]'
                    }
                ])
                .outputOptions(['-map', '[out]', outputFileName])
                .output(outputFileName)
                .on('end', function() {
                    resolve(outputFileName);
                })
                .on('stderr', console.log) // log ffmpeg output to console
                .on('error', function(err) {
                    console.log(`An error occurred overlaying tracks: ${err.message}`);
                    reject(err);
                })
                .run()
        })
    }

    const overlaidTracksFileName = await overlayTracks();

    console.log('overlaid file name:', overlaidTracksFileName)

    return overlaidTracksFileName;

}

module.exports = overlayBackgroundAudio;
</code>```

Here is what the ffmpeg library is logging to my console (which may help in figuring out why this is not working as intended):

```<code>Input #0, mp3, from '95c8ec8ccbb100d2bfe81ffd.mp3':
  Metadata:
    encoder         : Lavf58.24.101
  Duration: 00:02:41.42, start: 0.046042, bitrate: 48 kb/s
    Stream #0:0: Audio: mp3, 24000 Hz, mono, fltp, 48 kb/s
[mp3 @ 000002c77978ddc0] Estimating duration from bitrate, this may be inaccurate
Input #1, mp3, from '14e70bbd339b612e96f29017.mp3':
  Metadata:
    date            : 2022-12-30 17:56
    id3v2_priv.XMP  : <?xpacket begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>\x0a<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 7.1-c000 79.b0f8be9, 2021/12/08-19:11:22        ">\x0a <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\x0a  <rd
  Duration: 00:01:31.85, start: 0.000000, bitrate: 192 kb/s
    Stream #1:0: Audio: mp3, 48000 Hz, stereo, fltp, 192 kb/s
Stream mapping:
  Stream #0:0 (mp3float) -> volume (graph 0)
  Stream #1:0 (mp3float) -> volume (graph 0)
  amix (graph 0) -> Stream #0:0 (libmp3lame)
  Stream #1:0 -> #1:0 (mp3 (mp3float) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
Output #0, mp3, to '0c0404b793d488bf38e882a0.mp3':
  Metadata:
    TSSE            : Lavf58.24.101
    Stream #0:0: Audio: mp3 (libmp3lame), 24000 Hz, mono, fltp (default)
    Metadata:
      encoder         : Lavc58.42.102 libmp3lame
Output #1, mp3, to '0c0404b793d488bf38e882a0.mp3':
  Metadata:
    TSSE            : Lavf58.24.101
    Stream #1:0: Audio: mp3 (libmp3lame), 48000 Hz, stereo, fltp
    Metadata:
      encoder         : Lavc58.42.102 libmp3lame

</code>```

Thank you very much in advance for any help that you can try to provide!

Body:
I am trying to overlay one mp3 file (a speech track, the file name for which is passed into the below function) on top of another (a background music track, the url of which is passed into the function), so that they both play simultaneously, using NodeJS and fluent-ffmpeg.

What happens when I call the function is that I get an output file which 1) only plays the background audio track, and 2) upon opening the output track, the time seeker skips straight to where the end of the first audio track would have been (around 1 minute 30 seconds).

I'd like to in the first instance have them play at the same time as each other in the output file, without this skipping ahead effect (even if I drag the slider back to within the first 1 minute 30, it just jumps straight back to 1 minute 31 seconds - as if somehow there was no data in that first minute and a half).

In the second instance, I'd also like to have the background audio track loop until the first track finishes, so any help with that as part of an answer would be very much appreciated. But the immediate problem is just getting the two audios to actually play simultaneously starting from 0 seconds.

I have tried the below to get to this point:

const fs = require('fs');
const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;
const ffmpeg = require('fluent-ffmpeg');
ffmpeg.setFfmpegPath(ffmpegPath);
var ffprobe = require('ffprobe-static');
ffmpeg.setFfprobePath(ffprobe.path);
const axios = require('axios');
const crypto = require('crypto');
const path = require('path');

const overlayBackgroundAudio = async (inputFileName, backgroundFileUrl) => {

    const backgroundTrack = await axios({
        method: 'GET',
        url: backgroundFileUrl,
        responseType: 'arraybuffer'
    });

    // write a file with the retrieved background audio track
    const backgroundTrackFileName = crypto.randomBytes(12).toString('hex');
    fs.writeFileSync(`${backgroundTrackFileName}.mp3`, backgroundTrack.data); //todo - delete after

    // set the name of the output file
    const newFileName = crypto.randomBytes(12).toString('hex');
    const outputFileName = `${newFileName}.mp3`;

    // run the relevant ffmpeg commands

    const overlayTracks = async () => {

        return new Promise((resolve, reject) => {
            ffmpeg()
                .input(`${inputFileName}.mp3`)
                .input(`${backgroundTrackFileName}.mp3`)
                .complexFilter([
                    {
                      filter: 'volume',
                      options: '1',
                      inputs: '[0:0]',
                      outputs: '[a]'
                    },
                    {
                      filter: 'volume',
                      options: '1',
                      inputs: '[1:0]',
                      outputs: '[b]'
                    },
                    {
                        filter: 'adelay',
                        options: '0',
                        inputs: '[a]',
                        outputs: '[a1]'
                    },
                    {
                        filter: 'adelay',
                        options: '0|0',
                        inputs: '[b]',
                        outputs: '[b1]'
                    },
                    {
                      filter: 'amix',
                      options: 'inputs=2:duration=first',
                      inputs: '[a1][b1]',
                      outputs: '[out]'
                    }
                ])
                .outputOptions(['-map', '[out]', outputFileName])
                .output(outputFileName)
                .on('end', function() {
                    resolve(outputFileName);
                })
                .on('stderr', console.log) // log ffmpeg output to console
                .on('error', function(err) {
                    console.log(`An error occurred overlaying tracks: ${err.message}`);
                    reject(err);
                })
                .run()
        })
    }

    const overlaidTracksFileName = await overlayTracks();

    console.log('overlaid file name:', overlaidTracksFileName)

    return overlaidTracksFileName;

}

module.exports = overlayBackgroundAudio;

Here is what the ffmpeg library is logging to my console (which may help in figuring out why this is not working as intended):

Input #0, mp3, from '95c8ec8ccbb100d2bfe81ffd.mp3':
  Metadata:
    encoder         : Lavf58.24.101
  Duration: 00:02:41.42, start: 0.046042, bitrate: 48 kb/s
    Stream #0:0: Audio: mp3, 24000 Hz, mono, fltp, 48 kb/s
[mp3 @ 000002c77978ddc0] Estimating duration from bitrate, this may be inaccurate
Input #1, mp3, from '14e70bbd339b612e96f29017.mp3':
  Metadata:
    date            : 2022-12-30 17:56
    id3v2_priv.XMP  : <?xpacket begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>\x0a<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 7.1-c000 79.b0f8be9, 2021/12/08-19:11:22        ">\x0a <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\x0a  <rd
  Duration: 00:01:31.85, start: 0.000000, bitrate: 192 kb/s
    Stream #1:0: Audio: mp3, 48000 Hz, stereo, fltp, 192 kb/s
Stream mapping:
  Stream #0:0 (mp3float) -> volume (graph 0)
  Stream #1:0 (mp3float) -> volume (graph 0)
  amix (graph 0) -> Stream #0:0 (libmp3lame)
  Stream #1:0 -> #1:0 (mp3 (mp3float) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
Output #0, mp3, to '0c0404b793d488bf38e882a0.mp3':
  Metadata:
    TSSE            : Lavf58.24.101
    Stream #0:0: Audio: mp3 (libmp3lame), 24000 Hz, mono, fltp (default)
    Metadata:
      encoder         : Lavc58.42.102 libmp3lame
Output #1, mp3, to '0c0404b793d488bf38e882a0.mp3':
  Metadata:
    TSSE            : Lavf58.24.101
    Stream #1:0: Audio: mp3 (libmp3lame), 48000 Hz, stereo, fltp
    Metadata:
      encoder         : Lavc58.42.102 libmp3lame

Thank you very much in advance for any help that you can try to provide!


问:
How does vscode execute commands registered in an extension?
To register a command in vscode extension, you must import commands from vscode library and register command inside activate function as follows:

```<code>import { commands } from 'vscode';

export function activate() {
    commands.registerCommand('extension.myExtension.go', () => {
      ...
    })
}
</code>```

How does vscode API integrate the commands object in the first place since it's not in the app life cycle and it may even be an older version of vscode package?

Does it have anything to do with dependency injection?

If possible, please include simple code to better understand the solution.

Body:
To register a command in vscode extension, you must import commands from vscode library and register command inside activate function as follows:

import { commands } from 'vscode';

export function activate() {
    commands.registerCommand('extension.myExtension.go', () => {
      ...
    })
}

How does vscode API integrate the commands object in the first place since it's not in the app life cycle and it may even be an older version of vscode package?

Does it have anything to do with dependency injection?

If possible, please include simple code to better understand the solution.


问:
Is there a way to add a Firebase User object to NextJs middleware and use it for route protection
I am building a next JS application with a firebase backend. I use context for logging in, logging out and auth state changes. I would like to check if the Firebase user object exists in the middleware file and then redirect the visitor appropriately. My middleware is like below.

```<code>export default function middleware(req){
const { user
} = UserAuth;
</code>```

this however throws an error:

```<code>Cannot read properties of null (reading 'useContext')
</code>```

The app works and I can get the user object from other pages when i comment it on middleware
Help

Body:
I am building a next JS application with a firebase backend. I use context for logging in, logging out and auth state changes. I would like to check if the Firebase user object exists in the middleware file and then redirect the visitor appropriately. My middleware is like below.

export default function middleware(req){
const { user
} = UserAuth;

this however throws an error:

Cannot read properties of null (reading 'useContext')

The app works and I can get the user object from other pages when i comment it on middleware
Help


问:
how to add dynamic urls (s3 presigned url) in dash.mpd file?
I have generated the dash.mpd file using python-ffmpeg-video-streaming python module.

```<code><?xml version="1.0" encoding="utf-8"?>
<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="urn:mpeg:dash:schema:mpd:2011"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd"
    profiles="urn:mpeg:dash:profile:isoff-live:2011"
    type="static"
    mediaPresentationDuration="PT24.5S"
    maxSegmentDuration="PT5.0S"
    minBufferTime="PT16.6S">
    <ProgramInformation>
    </ProgramInformation>
    <ServiceDescription id="0">
    </ServiceDescription>
    <Period id="0" start="PT0.0S">
        <AdaptationSet id="0" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="256" maxHeight="144" par="16:9" lang="und">
            <Representation id="0" mimeType="video/mp4" codecs="avc1.64000d" bandwidth="95000" width="256" height="144" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="1" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="1" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="64000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="2" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="426" maxHeight="240" par="71:40" lang="und">
            <Representation id="2" mimeType="video/mp4" codecs="avc1.64001e" bandwidth="150000" width="426" height="240" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="3" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="3" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="94000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="4" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="640" maxHeight="360" par="16:9" lang="und">
            <Representation id="4" mimeType="video/mp4" codecs="avc1.64001f" bandwidth="276000" width="640" height="360" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="5" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="5" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="128000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="6" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="854" maxHeight="480" par="427:240" lang="und">
            <Representation id="6" mimeType="video/mp4" codecs="avc1.64001f" bandwidth="750000" width="854" height="480" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="7" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="7" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="192000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="8" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="1280" maxHeight="720" par="16:9" lang="und">
            <Representation id="8" mimeType="video/mp4" codecs="avc1.640020" bandwidth="2048000" width="1280" height="720" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="9" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="9" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="10" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="1920" maxHeight="1080" par="16:9" lang="und">
            <Representation id="10" mimeType="video/mp4" codecs="avc1.64002a" bandwidth="4096000" width="1920" height="1080" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" />
                        <S d="120320" />
                        <S d="128000" />
                        <S d="768" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="11" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="11" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="12" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="2560" maxHeight="1440" par="16:9" lang="und">
            <Representation id="12" mimeType="video/mp4" codecs="avc1.640033" bandwidth="6144000" width="2560" height="1440" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" />
                        <S d="119552" />
                        <S d="128000" />
                        <S d="1536" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="13" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="13" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="14" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="3840" maxHeight="2160" par="16:9" lang="und">
            <Representation id="14" mimeType="video/mp4" codecs="avc1.640034" bandwidth="17408000" width="3840" height="2160" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="119808" />
                        <S d="101888" />
                        <S d="128000" />
                        <S d="27392" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="15" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="15" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
    </Period>
</MPD>
</code>```

how to add dynamic s3 presigned url as baseurl, so I can serve the small video files from s3 but only authenticated user can access dash.mpd file

I am using a backend server for authentication and s3 for serving the file, I am also using dash mpd technology to serve videos but I want to create dynamic dash.mpd file which can help me expire the s3 presigned url and add new presigned url again for security purpose.

Body:
I have generated the dash.mpd file using python-ffmpeg-video-streaming python module.

<?xml version="1.0" encoding="utf-8"?>
<MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="urn:mpeg:dash:schema:mpd:2011"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd"
    profiles="urn:mpeg:dash:profile:isoff-live:2011"
    type="static"
    mediaPresentationDuration="PT24.5S"
    maxSegmentDuration="PT5.0S"
    minBufferTime="PT16.6S">
    <ProgramInformation>
    </ProgramInformation>
    <ServiceDescription id="0">
    </ServiceDescription>
    <Period id="0" start="PT0.0S">
        <AdaptationSet id="0" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="256" maxHeight="144" par="16:9" lang="und">
            <Representation id="0" mimeType="video/mp4" codecs="avc1.64000d" bandwidth="95000" width="256" height="144" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="1" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="1" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="64000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="2" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="426" maxHeight="240" par="71:40" lang="und">
            <Representation id="2" mimeType="video/mp4" codecs="avc1.64001e" bandwidth="150000" width="426" height="240" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="3" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="3" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="94000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="4" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="640" maxHeight="360" par="16:9" lang="und">
            <Representation id="4" mimeType="video/mp4" codecs="avc1.64001f" bandwidth="276000" width="640" height="360" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="5" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="5" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="128000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="6" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="854" maxHeight="480" par="427:240" lang="und">
            <Representation id="6" mimeType="video/mp4" codecs="avc1.64001f" bandwidth="750000" width="854" height="480" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="7" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="7" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="192000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="8" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="1280" maxHeight="720" par="16:9" lang="und">
            <Representation id="8" mimeType="video/mp4" codecs="avc1.640020" bandwidth="2048000" width="1280" height="720" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" r="1" />
                        <S d="121088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="9" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="9" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="10" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="1920" maxHeight="1080" par="16:9" lang="und">
            <Representation id="10" mimeType="video/mp4" codecs="avc1.64002a" bandwidth="4096000" width="1920" height="1080" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" />
                        <S d="120320" />
                        <S d="128000" />
                        <S d="768" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="11" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="11" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="12" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="2560" maxHeight="1440" par="16:9" lang="und">
            <Representation id="12" mimeType="video/mp4" codecs="avc1.640033" bandwidth="6144000" width="2560" height="1440" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="128000" />
                        <S d="119552" />
                        <S d="128000" />
                        <S d="1536" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="13" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="13" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="14" contentType="video" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" frameRate="60/1" maxWidth="3840" maxHeight="2160" par="16:9" lang="und">
            <Representation id="14" mimeType="video/mp4" codecs="avc1.640034" bandwidth="17408000" width="3840" height="2160" sar="1:1">
                <SegmentTemplate timescale="15360" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="119808" />
                        <S d="101888" />
                        <S d="128000" />
                        <S d="27392" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
        <AdaptationSet id="15" contentType="audio" startWithSAP="1" segmentAlignment="true" bitstreamSwitching="true" lang="und">
            <Representation id="15" mimeType="audio/mp4" codecs="mp4a.40.2" bandwidth="288000" audioSamplingRate="48000">
                <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="1" />
                <SegmentTemplate timescale="48000" initialization="static/dash_init_$RepresentationID$.m4s" media="static/dash_chunk_$RepresentationID$_$Number%05d$.m4s" startNumber="1">
                    <SegmentTimeline>
                        <S t="0" d="239592" />
                        <S d="240640" r="2" />
                        <S d="217088" />
                    </SegmentTimeline>
                </SegmentTemplate>
            </Representation>
        </AdaptationSet>
    </Period>
</MPD>

how to add dynamic s3 presigned url as baseurl, so I can serve the small video files from s3 but only authenticated user can access dash.mpd file

I am using a backend server for authentication and s3 for serving the file, I am also using dash mpd technology to serve videos but I want to create dynamic dash.mpd file which can help me expire the s3 presigned url and add new presigned url again for security purpose.


问:
I get a TypeLoadException while trying to query my Oracle database, any explanations?
I use Oracle ODP in Unity to Query my db. This Exception only occurs in a Unity Script.

TypeLoadException: Invalid type OracleInternal.Common.ColumnDescribeInfo[] for instance field OracleInternal.Common.SQLMetaData:m_columnDescribeInfo
Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader (System.Boolean requery, System.Boolean fillRequest, System.Data.CommandBehavior behavior) (at <340e7d6204534b8c9f21dbff14575f84>:0)
Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader (System.Data.CommandBehavior behavior) (at <340e7d6204534b8c9f21dbff14575f84>:0)
(wrapper remoting-invoke-with-check) Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader(System.Data.CommandBehavior)

Code:

```<code>using (OracleConnection connection = new OracleConnection(conString))
        {
            OracleCommand command = new OracleCommand("SELECT * FROM PERSON", connection);
            connection.Open();
            OracleDataReader reader =
                command.ExecuteReader(CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                Console.Write(reader.GetString(0));
            }
            reader.Close();
        }
</code>```

Expectation was a simple SELECT Query Output. Maybe it has something to do with .NET Versions?

Body:
I use Oracle ODP in Unity to Query my db. This Exception only occurs in a Unity Script.

TypeLoadException: Invalid type OracleInternal.Common.ColumnDescribeInfo[] for instance field OracleInternal.Common.SQLMetaData:m_columnDescribeInfo
Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader (System.Boolean requery, System.Boolean fillRequest, System.Data.CommandBehavior behavior) (at <340e7d6204534b8c9f21dbff14575f84>:0)
Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader (System.Data.CommandBehavior behavior) (at <340e7d6204534b8c9f21dbff14575f84>:0)
(wrapper remoting-invoke-with-check) Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteReader(System.Data.CommandBehavior)

Code:

using (OracleConnection connection = new OracleConnection(conString))
        {
            OracleCommand command = new OracleCommand("SELECT * FROM PERSON", connection);
            connection.Open();
            OracleDataReader reader =
                command.ExecuteReader(CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                Console.Write(reader.GetString(0));
            }
            reader.Close();
        }

Expectation was a simple SELECT Query Output. Maybe it has something to do with .NET Versions?


问:
AWS Rate Limiting API Gateway Endpoints By IP Address. (e.g. 100 Calls To An Endpoint Per Week For Each IP Address)
I am developing an application that needs to rate limit / grant and deny users access to certain API gateway endpoints by IP address.

I want to have two limits placed on users:

One that is applied on an individual level (each user's ip address) restricting their access to certain endpoints.
e.g. each ip address can only access:

/endpoint1 (100 calls/week)

/endpoint2 (50 calls/week)

Another that is a global quota applied to all users.
e.g. the sum of all the requests for all ip address's for an endpoint can not exceed:

/endpoint1 (10000 calls/week)

/endpoint2 (5000 calls/week)

Originally, I planned on doing this by creating a lambda authorizer that would store users IP's and what endpoint they are attempting to access in a DynamoDB table and limit based off of that.

But I am wondering if there are pre-existing AWS solutions that do this.
One idea I had would be creating two usage plans for each endpoint. One with the global limit and another with the individual limit. I could then generate an API key for each new IP address that attempts to access the endpoint and store this in a DynamoDB table and return it using a lambda authorizer on each call by the same IP address. But I would also need to another api key for the global limit that is returned for all users which does not work because AWS does not allow for two api keys in the x-api-key header. Additionally, it seems that API keys are meant to be created manually rather than programmatically and also that there are limits on the number that can be created.

In summary, is my original idea (limiting with just DynamoDB and the lambda authorizer with no AWS API keys) a valid approach? I would essentially be reimplementing the same system AWS already offers with their API keys which is not ideal, so I am also wondering if there are any already existing solutions or AWS tools I could leverage to accomplish the rate limiting I am looking for.