问:
Build Windows RCP Application on Unix Machine
We're trying to do an Eclipse PDE build for a RCP Application via Hudson/Jenkins. We were doing this so far successfully on a Windows machine (Hudson running on Windows Server 2003). We have decided to move our CI system to a unix machine.
When executing the same build on the unix machine our build fails with the following error:

```
!SESSION 2011-04-12 01:00:49.497 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.6.0_23
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=sparc, WS=win32, NL=en_US
Framework arguments:  -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -Ddummy=true
Command-line arguments:  -ws win32 -os win32 -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -data /appl/midw/jenkins/jobs/AP_NAPF/workspace/ap_build/workspace -Ddummy=true

!ENTRY org.eclipse.osgi 4 0 2011-04-12 01:00:58.961
!MESSAGE An error occurred while automatically activating bundle org.eclipse.ui.workbench (687).
!STACK 0
org.osgi.framework.BundleException: The activator org.eclipse.ui.internal.WorkbenchPlugin for bundle org.eclipse.ui.workbench is invalid
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:146)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.core.runtime.internal.adaptor.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:111)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:427)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.SingleSourcePackage.loadClass(SingleSourcePackage.java:33)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:443)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.defineClass(DefaultClassLoader.java:165)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.defineClass(ClasspathManager.java:554)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassImpl(ClasspathManager.java:524)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClassImpl(ClasspathManager.java:455)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass_LockClassLoader(ClasspathManager.java:443)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:423)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:446)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.loadClass(BundleLoader.java:315)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:227)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:139)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:234)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1274)
    at org.eclipse.ant.core.AntCorePreferences$WrappedClassLoader.findClass(AntCorePreferences.java:115)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.internal.core.AntClassLoader.loadClassPlugins(AntClassLoader.java:69)
    at org.eclipse.ant.internal.core.AntClassLoader.findClass(AntClassLoader.java:47)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.core.AntRunner.run(AntRunner.java:510)
    at org.eclipse.ant.core.AntRunner.start(AntRunner.java:600)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:193)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:386)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
Caused by: java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.newInstance0(Class.java:326)
    at java.lang.Class.newInstance(Class.java:308)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:141)
    ... 61 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.swt.SWTError
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:483)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 67 more
Root exception:
java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError
```

I've already tried a couple of things after moving to the new infrastructure, with no avail:

 Use a different rt.jar (one coming from a windows JRE) for the PDE build using the bootclasspath property.

Changning the -os command line argument to: solaris

Is it at all possible to do a RCP build for a Windows application on a Unix machine?
If yes, is it necessary to change any parameters when launching the PDE build?

Note: We're using pluginbuilder to setup the PDE build.

答:
The Eclipse you are using to execute the PDE build (i.e. the org.eclipse.ant.core.antRunner application) must be executable in your build server environment. You said that you are executing the build on a Unix machine, but the ws and os parameters are set to win32. So it seems that you use a Windows version of Eclipse on your Unix build server. This can't work since the Unix-specific fragments usually are not available there (needed for example for SWT, that's why the class SWTError is not found).

You should download an Eclipse from eclipse.org which is specific to your environment on your build server (OS, windowing system and processor architecture) and use it to run the PDE build.

Body:
We're trying to do an Eclipse PDE build for a RCP Application via Hudson/Jenkins. We were doing this so far successfully on a Windows machine (Hudson running on Windows Server 2003). We have decided to move our CI system to a unix machine.
When executing the same build on the unix machine our build fails with the following error:

!SESSION 2011-04-12 01:00:49.497 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.6.0_23
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=sparc, WS=win32, NL=en_US
Framework arguments:  -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -Ddummy=true
Command-line arguments:  -ws win32 -os win32 -application org.eclipse.ant.core.antRunner -buildfile /appl/midw/jenkins/jobs/AP_NAPF/workspace/TP/plugins/org.eclipse.pde.build_3.4.1.R34x_v20081217/scripts/build.xml main -data /appl/midw/jenkins/jobs/AP_NAPF/workspace/ap_build/workspace -Ddummy=true

!ENTRY org.eclipse.osgi 4 0 2011-04-12 01:00:58.961
!MESSAGE An error occurred while automatically activating bundle org.eclipse.ui.workbench (687).
!STACK 0
org.osgi.framework.BundleException: The activator org.eclipse.ui.internal.WorkbenchPlugin for bundle org.eclipse.ui.workbench is invalid
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:146)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.core.runtime.internal.adaptor.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:111)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:427)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.SingleSourcePackage.loadClass(SingleSourcePackage.java:33)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:443)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.defineClass(DefaultClassLoader.java:165)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.defineClass(ClasspathManager.java:554)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findClassImpl(ClasspathManager.java:524)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClassImpl(ClasspathManager.java:455)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass_LockClassLoader(ClasspathManager.java:443)
    at org.eclipse.osgi.baseadaptor.loader.ClasspathManager.findLocalClass(ClasspathManager.java:423)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.findLocalClass(DefaultClassLoader.java:193)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findLocalClass(BundleLoader.java:370)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:446)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.loadClass(BundleLoader.java:315)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:227)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:139)
    at org.eclipse.osgi.framework.internal.core.BundleContextImpl.start(BundleContextImpl.java:980)
    at org.eclipse.osgi.framework.internal.core.BundleHost.startWorker(BundleHost.java:346)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.start(AbstractBundle.java:265)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:400)
    at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:234)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1274)
    at org.eclipse.ant.core.AntCorePreferences$WrappedClassLoader.findClass(AntCorePreferences.java:115)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.internal.core.AntClassLoader.loadClassPlugins(AntClassLoader.java:69)
    at org.eclipse.ant.internal.core.AntClassLoader.findClass(AntClassLoader.java:47)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.eclipse.ant.core.AntRunner.run(AntRunner.java:510)
    at org.eclipse.ant.core.AntRunner.start(AntRunner.java:600)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:193)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:386)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
Caused by: java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.newInstance0(Class.java:326)
    at java.lang.Class.newInstance(Class.java:308)
    at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadBundleActivator(AbstractBundle.java:141)
    ... 61 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.swt.SWTError
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClassInternal(BundleLoader.java:483)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:399)
    at org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:387)
    at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:87)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 67 more
Root exception:
java.lang.NoClassDefFoundError: org/eclipse/swt/SWTError

I've already tried a couple of things after moving to the new infrastructure, with no avail:

 Use a different rt.jar (one coming from a windows JRE) for the PDE build using the bootclasspath property.

Changning the -os command line argument to: solaris

Is it at all possible to do a RCP build for a Windows application on a Unix machine?
If yes, is it necessary to change any parameters when launching the PDE build?

Note: We're using pluginbuilder to setup the PDE build.


来源: stackexchange

问:
Mongoose validation err: Invalid schema configuration
Trying to model a relationship between collections by embedding documents
but when validating in the schema and setting "required" to True, here comes the err

once I comment the required in genre object in movies schema the problem is solved
but I want the validation

```<code>const Movie = mongoose.model(
  'Movies',
  new mongoose.Schema({
    title: {
      type: String,
      required: true,
      trim: true,
      minlength: 1,
      maxlength: 255
    },
    numberInStock: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    dailyRentalRate: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    genre: genreSchema
    required: true
  })
);

const genreSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  }
});

</code>```

TypeError: Invalid schema configuration: True is not a valid type at path required

答:
Try giving the message next to true.
For example-->  required: [true, "Title required"]</p>

ContentLicense: CC BY-SA 4.0

Body:
Trying to model a relationship between collections by embedding documents
but when validating in the schema and setting "required" to True, here comes the err

once I comment the required in genre object in movies schema the problem is solved
but I want the validation

const Movie = mongoose.model(
  'Movies',
  new mongoose.Schema({
    title: {
      type: String,
      required: true,
      trim: true,
      minlength: 1,
      maxlength: 255
    },
    numberInStock: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    dailyRentalRate: {
      type: Number,
      required: true,
      min: 0,
      max: 255
    },
    genre: genreSchema
    required: true
  })
);

const genreSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 50
  }
});

TypeError: Invalid schema configuration: True is not a valid type at path required


问:
How to unbind an onload event on an external SVG after it was initially completed?
I have a rather complex and special issue. I have a div container which is initially hidden (display: none) and which is shown when a user clicks a button (using the jQuery function show()). Within this div is a svg visualization.

HTML

    <object id='myObject' type="image/svg+xml"></object>

```

<p><strong>Javascript</strong></p>

<p>The SVG vis I am loading with the following code:</p>

```fetch('LINK TO THE SVG FILE')
    .then(function(r) {return r.blob()})
    .then(function(b) { return myObject.data = URL.createObjectURL(b)})

myObject.onload = function() { // wait for the svg has loaded

    var myObject = this; // we're in the object's load event handler.
    var svg = d3.select(myObject.contentDocument) // get the contentDocument
        .select("svg"); // then get the svg inside
    //...some more styling things happen here
}

```

<p>My issue is, that I don't know how (a.k.a. <em>where</em>) I should unbind the onload event because it gets triggered each time the user clicks on the button to change the <code>display</code> mode of the parent <code>div</code>. When I use the following code ...</p>

```fetch('LINK TO THE SVG FILE')
    .then(function(r) {return r.blob()})
    .then(function(b) { return myObject.data = URL.createObjectURL(b)})
    .then(function() {return myObject.onload = null})
```

... it never applies the style settings I perform within the onload function. Also when I add the myObject.onload = null setting to the end of my button's click event it won't fire the onload function.

What am I missing here?

答:
Have you tried something like this?</p>

```<code>fetch('LINK TO THE SVG FILE')
  .then(function(r) {return r.blob()})
  .then(function(b) {
     myObject.onload = function() { // wait for the svg has loaded
       // ...do what you need to...
       myObject.unload = null;
     }
     myObject.data = URL.createObjectURL(b)
  });
</code>```

Body:
I have a rather complex and special issue. I have a div container which is initially hidden (display: none) and which is shown when a user clicks a button (using the jQuery function show()). Within this div is a svg visualization.

HTML

    <object id='myObject' type="image/svg+xml"></object>

Javascript

The SVG vis I am loading with the following code:

fetch('LINK TO THE SVG FILE')
    .then(function(r) {return r.blob()})
    .then(function(b) { return myObject.data = URL.createObjectURL(b)})

myObject.onload = function() { // wait for the svg has loaded

    var myObject = this; // we're in the object's load event handler.
    var svg = d3.select(myObject.contentDocument) // get the contentDocument
        .select("svg"); // then get the svg inside
    //...some more styling things happen here
}

My issue is, that I don't know how (a.k.a. where) I should unbind the onload event because it gets triggered each time the user clicks on the button to change the display mode of the parent div. When I use the following code ...

fetch('LINK TO THE SVG FILE')
    .then(function(r) {return r.blob()})
    .then(function(b) { return myObject.data = URL.createObjectURL(b)})
    .then(function() {return myObject.onload = null})

... it never applies the style settings I perform within the onload function. Also when I add the myObject.onload = null setting to the end of my button's click event it won't fire the onload function.

What am I missing here?

Body:
Have you tried something like this?

fetch('LINK TO THE SVG FILE')
  .then(function(r) {return r.blob()})
  .then(function(b) {
     myObject.onload = function() { // wait for the svg has loaded
       // ...do what you need to...
       myObject.unload = null;
     }
     myObject.data = URL.createObjectURL(b)
  });


问:
Delete file from firebase storage using sketchware
I managed to get files to upload to my firebase storage bucked but how can I delete the file within sketchwere.

I enter the URL of the storage bucket where the file is located but my application keeps crashing with error "The storage URI cannot be parsed."

Any ideas?
I think I am entering the wrong URL.

答:
According to the documentation, here's an example on how to delete file in your firebase storage using the Android SDK : Delete.

```<code>// Create a storage reference from our app
StorageReference storageRef = storage.getReference();

// Create a reference to the file to delete
StorageReference desertRef = storageRef.child("images/desert.jpg");

// Delete the file
desertRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // File deleted successfully
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Uh-oh, an error occurred!
    }
});
</code>```

Body:
According to the documentation, here's an example on how to delete file in your firebase storage using the Android SDK : Delete.

// Create a storage reference from our app
StorageReference storageRef = storage.getReference();

// Create a reference to the file to delete
StorageReference desertRef = storageRef.child("images/desert.jpg");

// Delete the file
desertRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // File deleted successfully
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Uh-oh, an error occurred!
    }
});


问:
How to format a number to a string in javascript
I'm working with Stripe Checkout, and feed the amount as a number like so 11999. How can I show this number as a string like $119.99?

I tried new Intl.NumberFormat('en-IN', { currency: 'USD' }).format(11999)

But it's show as $ 11,999

I tried http://numeraljs.com as well, but same issue. Any one have an idea?

答:
Firstly, change the cents to dollars by dividing by 100 (the number of cents in a dollar). Then prepend the $.

const num = 11999;
const res = "$" + (num / 100);
console.log(res);```


答:
you can use references and use populate when fetching

```<code>genre: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'genreSchema',
        required: true
    }],
</code>```

Refer: Model Referenced one to Many Relationship between documents
for better schema design

Title: Mongoose validation err: Invalid schema configuration

Body:
you can use references and use populate when fetching

genre: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'genreSchema',
        required: true
    }],

Refer: Model Referenced one to Many Relationship between documents
for better schema design


问:
How to ask permission on splash screen and quit if denied?
I'm trying to make my Xamarin.Android app ask for permission on the splash screen which is the first activity to be launched.

I'm using the permission plugin for Xamarin.
I'm also using an async modal dialog implementation.

Here is the permission related code for the splash screen activity:

```<code>public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

private async Task<bool> RequestPermissionsAndTellIfWeShouldContinueAsync()
{
    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
    if (status != PermissionStatus.Granted)
    {
        if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
        {
            await Utilities.MessageBox.Show(this, Resources.GetString(Resource.String.explain_external_storage_permission_title), Resources.GetString(Resource.String.explain_external_storage_permission_text), true);
        }
        var newStatus = await CrossPermissions.Current.RequestPermissionsAsync(new Permission[] { Permission.Storage });

        var result = newStatus.Values.ElementAt(0);
        if (result == PermissionStatus.Granted)
        {
            return true;
        }
        if (result == PermissionStatus.Denied)
        {
            await Utilities.MessageBox.Show(this, Resources.GetString(Resource.String.cant_continue_without_permission_title), Resources.GetString(Resource.String.cant_continue_without_permission_text), true);
            return false;
        }

        return false;
    }
    else
        return true;
}
</code>```

}

Next is the code that tries to ask for permission on the OnResume callback

```<code>    protected override async void OnResume()
    {
        base.OnResume();

        bool shallWeContinue = await RequestPermissionsAndTellIfWeShouldContinueAsync();

        if ( shallWeContinue)
        {
          // Start Main activity

        }
        else
        {
            // End current activity and go back to android launcher
            Finish();
        }

    }
</code>```

This is working fine as long as I accept the permission request.
If I deny it twice, my problem is that I'm entering an infinite loop displaying the last Messagebox that explains that the permission should now be granted by hand in the application options.

答: This is probably because onResume is called each time after the permission dialog disappears - it's a standard Android behavior. Move the onResume logic to onStart or onCreate method to avoid the loop.

Body:
I'm trying to make my Xamarin.Android app ask for permission on the splash screen which is the first activity to be launched.

I'm using the permission plugin for Xamarin.
I'm also using an async modal dialog implementation.

Here is the permission related code for the splash screen activity:

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

private async Task<bool> RequestPermissionsAndTellIfWeShouldContinueAsync()
{
    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
    if (status != PermissionStatus.Granted)
    {
        if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage))
        {
            await Utilities.MessageBox.Show(this, Resources.GetString(Resource.String.explain_external_storage_permission_title), Resources.GetString(Resource.String.explain_external_storage_permission_text), true);
        }
        var newStatus = await CrossPermissions.Current.RequestPermissionsAsync(new Permission[] { Permission.Storage });

        var result = newStatus.Values.ElementAt(0);
        if (result == PermissionStatus.Granted)
        {
            return true;
        }
        if (result == PermissionStatus.Denied)
        {
            await Utilities.MessageBox.Show(this, Resources.GetString(Resource.String.cant_continue_without_permission_title), Resources.GetString(Resource.String.cant_continue_without_permission_text), true);
            return false;
        }

        return false;
    }
    else
        return true;
}

}

Next is the code that tries to ask for permission on the OnResume callback

    protected override async void OnResume()
    {
        base.OnResume();

        bool shallWeContinue = await RequestPermissionsAndTellIfWeShouldContinueAsync();

        if ( shallWeContinue)
        {
          // Start Main activity

        }
        else
        {
            // End current activity and go back to android launcher
            Finish();
        }

    }

This is working fine as long as I accept the permission request.
If I deny it twice, my problem is that I'm entering an infinite loop displaying the last Messagebox that explains that the permission should now be granted by hand in the application options.


问:
Spring Security How to check if login form credentials are valid?
How to proceed if I want to check if credentials are valid ?

For example, I want to be sure that username is valid (valid email, limited size and so on) so I can display the error to the user before even attempting to authenticate using Spring Security.

1) Make sure credentials are valid before authentication
2) Authenticate
3) Rock-n-roll

Btw, I'm using Spring Security 3.1.0 RC.

Thank you in advance for your help,
Adnan

Update:
Actually I'm talking about validation: making sure that  username is in valid email format, or make sure that the passwords is at least 8 characters and so on.
Only when I'm sure that it is in "valid" format I will submit it to the Security authentication & authorization else I just want to display the login form again with error message (for example: "password must be at least 8 characters").

答:
You may want to skip validation on login and only do validation on registration/edit profile/change password.   When they attempt to login with a bad username/password it just won't be found.

I can see two ways to do what you want.   Normally the login page POSTs to /j_spring_security_check with j_username and j_password.  The UsernamePasswordAuthenticationFilter intercepts this POST and delegates to the AuthenticationManager and its AuthenticationProviders (usually the DaoAuthenticationProvider).

If you really want to do validation before it hits any Spring Security code you will need to add a Filter before the UsernamePasswordAuthenticationFilter and do your validation there.

Alternatively, subclass DaoAuthenticationProvider and override retreiveUser().   In retrieveUser() do your extra validation, throwing an exception if the validation fails.

Configure your subclass as the authentication provider like so:

```<code><authentication-manager>
  <authentication-provider ref='myAuthenticationProvider'/>
</authentication-manager>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You may want to skip validation on login and only do validation on registration/edit profile/change password.   When they attempt to login with a bad username/password it just won't be found.

I can see two ways to do what you want.   Normally the login page POSTs to /j_spring_security_check with j_username and j_password.  The UsernamePasswordAuthenticationFilter intercepts this POST and delegates to the AuthenticationManager and its AuthenticationProviders (usually the DaoAuthenticationProvider).

If you really want to do validation before it hits any Spring Security code you will need to add a Filter before the UsernamePasswordAuthenticationFilter and do your validation there.

Alternatively, subclass DaoAuthenticationProvider and override retreiveUser().   In retrieveUser() do your extra validation, throwing an exception if the validation fails.

Configure your subclass as the authentication provider like so:

<authentication-manager>
  <authentication-provider ref='myAuthenticationProvider'/>
</authentication-manager>


问:
Session based service bus with Azure Function
I am using session queue on Azure and when I push some data on queue,I write one Azure function to trigger.

Please note that I have created statefull/session based queue.

The problem is when I push data to queue at that moment I got error like

The listener for function 'xxx' was unable to start.
  Microsoft.ServiceBus: It is not possible for an entity that requires
  sessions to create a non-sessionful message receiver

So my question is am I not able to use function with queue/topic with session?

答:
I think its actually possible now, using the beta package Microsoft.Azure.WebJobs.Extensions.ServiceBus/3.1.0-beta2.

```<code>public static void Run([ServiceBusTrigger("core-test-queue1-sessions",
    Connection = "AzureWebJobsServiceBus",
    IsSessionsEnabled = true)]string myQueueItem,
    IMessageSession messageSession,
    ILogger log)
</code>```

Also you can specify new SessionHandlerOptions section in host.json:

```<code>{
    "version": "2.0",
    "extensions": {
        "serviceBus": {
            "SessionHandlerOptions":
             {
                "MaxAutoRenewDuration": "00:01:00",
                "MessageWaitTimeout": "00:05:00",
                "MaxConcurrentSessions": 16,
                "AutoComplete": true,
             }
        }
    }
}
</code>```

https://github.com/azure/azure-webjobs-sdk/issues/529#issuecomment-491113458

Body:
I think its actually possible now, using the beta package Microsoft.Azure.WebJobs.Extensions.ServiceBus/3.1.0-beta2.

public static void Run([ServiceBusTrigger("core-test-queue1-sessions",
    Connection = "AzureWebJobsServiceBus",
    IsSessionsEnabled = true)]string myQueueItem,
    IMessageSession messageSession,
    ILogger log)

Also you can specify new SessionHandlerOptions section in host.json:

{
    "version": "2.0",
    "extensions": {
        "serviceBus": {
            "SessionHandlerOptions":
             {
                "MaxAutoRenewDuration": "00:01:00",
                "MessageWaitTimeout": "00:05:00",
                "MaxConcurrentSessions": 16,
                "AutoComplete": true,
             }
        }
    }
}

https://github.com/azure/azure-webjobs-sdk/issues/529#issuecomment-491113458


问:
Drag and Drop incorrect behaviour
I'm making an app using phonegap and jquery mobile and I have one page with a drag & drop system.

The draggables are created dynamically. All is working fine, I can drag the items from a jquery Panel to a Containner DIV.

The problem: for some reason I can't explain some of the times I drop a new draggable in the container the droppable randomly changes the position of some of the others draggables already dropped inside the container.

Here is my code:

```<code>jQuery.ajax({
           url: '<my_url_request>',
           type: 'GET',
           dataType: 'jsonp',
           success: function(data) {
               console.log(data);

               var players = [];

               $.each(data.posts, function(i, item) {
                     players.push('<div id="player_' + item.id + '" class="ui-draggable player" data-id="' + item.id + '"><img src="' + item.thumbnail_images.medium_large.url + '" width="100%" /><div id="player_name">' + item.title + '</div></div>');
               });  // close each()

               $('#jogadores').append( players.join('') );
               $('#jogadores').trigger('create');

               $( ".ui-draggable" ).draggable({
                            containment: "#soccer_container",
                            cursor: "move",
                            zIndex: 100
               });

               $("#soccer_container").droppable({
                    accept: ".ui-draggable",
                    drop: function(event, ui) {
                        $(this).append($(ui.draggable));
                    }
               });
           },

           error: function(data){
             console.log(data);
           }
});
</code>```

EDIT 1:

You can check the behaviour here: here

答: Your post with index zero doesn't have an thumbnail_images entry

Title: Drag and Drop incorrect behaviour

Body:
I'm making an app using phonegap and jquery mobile and I have one page with a drag & drop system.

The draggables are created dynamically. All is working fine, I can drag the items from a jquery Panel to a Containner DIV.

The problem: for some reason I can't explain some of the times I drop a new draggable in the container the droppable randomly changes the position of some of the others draggables already dropped inside the container.

Here is my code:

jQuery.ajax({
           url: '<my_url_request>',
           type: 'GET',
           dataType: 'jsonp',
           success: function(data) {
               console.log(data);

               var players = [];

               $.each(data.posts, function(i, item) {
                     players.push('

' + item.title + '

');
               });  // close each()

               $('#jogadores').append( players.join('') );
               $('#jogadores').trigger('create');

               $( ".ui-draggable" ).draggable({
                            containment: "#soccer_container",
                            cursor: "move",
                            zIndex: 100
               });

               $("#soccer_container").droppable({
                    accept: ".ui-draggable",
                    drop: function(event, ui) {
                        $(this).append($(ui.draggable));
                    }
               });
           },

           error: function(data){
             console.log(data);
           }
});

EDIT 1:

You can check the behaviour here: here


问:
ValueError when returning z-value from contour
I am trying to return the z-value of a contour. The specific point I want to use to return the z-value is called from ['C1_X'],['C1_Y'] in the df. The code works when these coordinates are in ascending order but it throws an error when in descending order.

Error:

```<code>raise ValueError("Error code returned by bispev: %s" % ier)
ValueError: Error code returned by bispev: 10
</code>```

The code used to return the z-value is:

```<code>    # Return z-value for C coordinate
    f = RectBivariateSpline(X[0, :], Y[:, 0], normPDF.T)
    z = f(d['C1_X'], d['C1_Y'])
    print(z)
</code>```

答:
The error code 10 means that input is invalid (Google search!).

Create toy data. Your code is doing a lot of things and I would like to isolate the part that causes error.

X,Y = np.meshgrid(np.linspace(0, 20), np.linspace(0, 20))
```

<p>Create a callable to interpolate values at input.</p>

<pre class="lang-py prettyprint-override"><code>from scipy.interpolate import RectBivariateSpline
f = RectBivariateSpline(X[0, :], Y[:, 0], z = X**2+Y**2)
</code>```

Try to run code.

f([10,10,10,10,10,10,10,10,10,10], [10,10,10,10,10,10,10,10,10,9])
```

<p>Truncated output</p>

```---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-84-73aaa29ad73f> in <module>
----> 1 f([10,10,10,10,10,10,10,10,10,10], [10,10,10,10,10,10,10,10,10,9])
```

<p>Check the docstring of <code>f</code> to see if there is some information there. I am doing this in a Jupyter notebook.</p>

<pre class="lang-py prettyprint-override"><code>f?
</code>```

Truncated output

```<code>Signature:      f(x, y, dx=0, dy=0, grid=True)
Type:           RectBivariateSpline
String form:    <scipy.interpolate.fitpack2.RectBivariateSpline object at 0x7f5a4a7f9cc0>
File:           ~/bin/anaconda3/envs/py37a/lib/python3.7/site-packages/scipy/interpolate/fitpack2.py
Docstring:
Bivariate spline approximation over a rectangular mesh.

Can be used for both smoothing and interpolating data.

Parameters
----------
x,y : array_like
    1-D arrays of coordinates in strictly ascending order.
...
...
...
</code>```

Oh. It wants the points to be evaluated at also in strictly ascending order. So will ordering the points to be evaluated work?

f([10,10,10,10,10,10,10,10,10,10], [9, 10,10,10,10,10,10,10,10,10])
```

<p>Output</p>

```array([[181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.]])
```

<p>Will sorting the points at which the interpolations are to be performed before calling the interpolation function work in your code work?</p>

<p>Hope this helps.</p>

<hr>

<p><strong>EDIT</strong></p>

<p>Here is what I mean:</p>

<pre class="lang-py prettyprint-override"><code>f = RectBivariateSpline(X[0, :], Y[:, 0], normPDF.T)
# z = f(d['C1_X'], d['C1_Y'])
x_ip = d['C1_X']
y_ip = d['C1_Y']
z = np.empty((len(x_ip), len(y_ip)), dtype=np.float64)
for i, x in enumerate(x_ip):
    z[i, :] = f([x], y_ip) # ASSUME THAT y_ip IS SORTED.
print(z)
</code>```

I got your code running on my machine with this change: it shows some animation of contours. Adapt this idea to other situations where x and y can't be both in ascending order. You could loop over both x and y but that will increase the number of function calls.

Body:
I am trying to return the z-value of a contour. The specific point I want to use to return the z-value is called from ['C1_X'],['C1_Y'] in the df. The code works when these coordinates are in ascending order but it throws an error when in descending order.

Error:

raise ValueError("Error code returned by bispev: %s" % ier)
ValueError: Error code returned by bispev: 10

The code used to return the z-value is:

    # Return z-value for C coordinate
    f = RectBivariateSpline(X[0, :], Y[:, 0], normPDF.T)
    z = f(d['C1_X'], d['C1_Y'])
    print(z)

Body:
The error code 10 means that input is invalid (Google search!).

Create toy data. Your code is doing a lot of things and I would like to isolate the part that causes error.

X,Y = np.meshgrid(np.linspace(0, 20), np.linspace(0, 20))

Create a callable to interpolate values at input.

from scipy.interpolate import RectBivariateSpline
f = RectBivariateSpline(X[0, :], Y[:, 0], z = X**2+Y**2)

Try to run code.

f([10,10,10,10,10,10,10,10,10,10], [10,10,10,10,10,10,10,10,10,9])

Truncated output

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-84-73aaa29ad73f> in <module>
----> 1 f([10,10,10,10,10,10,10,10,10,10], [10,10,10,10,10,10,10,10,10,9])

Check the docstring of f to see if there is some information there. I am doing this in a Jupyter notebook.

f?

Truncated output

Signature:      f(x, y, dx=0, dy=0, grid=True)
Type:           RectBivariateSpline
String form:    <scipy.interpolate.fitpack2.RectBivariateSpline object at 0x7f5a4a7f9cc0>
File:           ~/bin/anaconda3/envs/py37a/lib/python3.7/site-packages/scipy/interpolate/fitpack2.py
Docstring:
Bivariate spline approximation over a rectangular mesh.

Can be used for both smoothing and interpolating data.

Parameters
----------
x,y : array_like
    1-D arrays of coordinates in strictly ascending order.
...
...
...

Oh. It wants the points to be evaluated at also in strictly ascending order. So will ordering the points to be evaluated work?

f([10,10,10,10,10,10,10,10,10,10], [9, 10,10,10,10,10,10,10,10,10])

Output

array([[181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.],
       [181., 200., 200., 200., 200., 200., 200., 200., 200., 200.]])

Will sorting the points at which the interpolations are to be performed before calling the interpolation function work in your code work?

Hope this helps.

EDIT

Here is what I mean:

f = RectBivariateSpline(X[0, :], Y[:, 0], normPDF.T)
# z = f(d['C1_X'], d['C1_Y'])
x_ip = d['C1_X']
y_ip = d['C1_Y']
z = np.empty((len(x_ip), len(y_ip)), dtype=np.float64)
for i, x in enumerate(x_ip):
    z[i, :] = f([x], y_ip) # ASSUME THAT y_ip IS SORTED.
print(z)

I got your code running on my machine with this change: it shows some animation of contours. Adapt this idea to other situations where x and y can't be both in ascending order. You could loop over both x and y but that will increase the number of function calls.


问:
Why the function can't return the correct answer?
I try to verify the impact of the Variable parameter of the function. here I defined the function test:

```<code>t = ["test"]
def test(x):
    return x.append("test")
print(test(t))
</code>```

The resulte is None.

And I change this function to the following style:

```<code> def test(x):
   x.append("test")
   return x
print(test(t))
</code>```

This time the function give the correct result ['test', 'test'].

So I want to know what's the different about the two function styles?

答: It is because append method doesn't return anything. It just modifies the list.

Body:
I try to verify the impact of the Variable parameter of the function. here I defined the function test:

t = ["test"]
def test(x):
    return x.append("test")
print(test(t))

The resulte is None.

And I change this function to the following style:

 def test(x):
   x.append("test")
   return x
print(test(t))

This time the function give the correct result ['test', 'test'].

So I want to know what's the different about the two function styles?


问:
unable to get the video on web browser using GCDWebServer in swift
I created a small demo app where app access the image and videos from iPhone using UIImagePickerController.
When I select any image or video, app creates a copy of it( image or video) in document directory.
And  create a web server on iPhone using GCDWebserver and need to expose the selected image or video.
But it does not work.

Here is the sample code, not sure where I could be wrong.

```<code>class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var btnselect: UIButton!
let videoPicker = UIImagePickerController()

@IBAction func btnSelect(_ sender: Any) {

        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let myPickerController = UIImagePickerController()
            myPickerController.delegate = self;
            myPickerController.sourceType = .photoLibrary
            myPickerController.allowsEditing = false
            self.present(myPickerController, animated: true, completion: nil)
        }

    }

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    // 1. saving video to documents directory

      let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as! NSURL
            let videoData = NSData(contentsOf: videoURL as URL)
            let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)

            let newPath = path.appendingPathComponent("/myTestVideo.mp4")
            do {
                try videoData?.write(to: newPath)
            } catch {
                print(error)
            }

 // 2. Create web server on iPhone using GCDWebServer

        let webServer = GCDWebServer()
        webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: {request in
        return GCDWebServerDataResponse(newPath)

       })
       webServer.start(withPort: 8080, bonjourName: "GCD Web Server")

}
}
</code>```

I need this selected (image or video) to be hosted/accessible by this GCD Web Server.

答:
Assuming it could be according wrong path

let newPath = path.appendingPathComponent("/myTestVideo.mp4")

producing ..../Documents//myTestVideo.mp4

Try to remove backslash from appending path component.

let newPath = path.appendingPathComponent("myTestVideo.mp4")

Also there is small chance that the problem could be related to "file://" prefix. If previous suggestion will not help try to remove prefix.

Body:
I created a small demo app where app access the image and videos from iPhone using UIImagePickerController.
When I select any image or video, app creates a copy of it( image or video) in document directory.
And  create a web server on iPhone using GCDWebserver and need to expose the selected image or video.
But it does not work.

Here is the sample code, not sure where I could be wrong.

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var btnselect: UIButton!
let videoPicker = UIImagePickerController()

@IBAction func btnSelect(_ sender: Any) {

        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let myPickerController = UIImagePickerController()
            myPickerController.delegate = self;
            myPickerController.sourceType = .photoLibrary
            myPickerController.allowsEditing = false
            self.present(myPickerController, animated: true, completion: nil)
        }

    }

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    // 1. saving video to documents directory

      let videoURL = info[UIImagePickerController.InfoKey.mediaURL] as! NSURL
            let videoData = NSData(contentsOf: videoURL as URL)
            let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)

            let newPath = path.appendingPathComponent("/myTestVideo.mp4")
            do {
                try videoData?.write(to: newPath)
            } catch {
                print(error)
            }

 // 2. Create web server on iPhone using GCDWebServer

        let webServer = GCDWebServer()
        webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: {request in
        return GCDWebServerDataResponse(newPath)

       })
       webServer.start(withPort: 8080, bonjourName: "GCD Web Server")

}
}

I need this selected (image or video) to be hosted/accessible by this GCD Web Server.


问:
Saving output to variable not working in Azure-CLI DevOps task
Trying to save an output of azure advisor recommendation on to a variable so that i can pass on to next task.

However no matter what syntax I try, and believe me i have tried all possible combinations, the variable doesn't get saved.
Interestingly, these work in cloud shell (bash)
for E.g.

```<code>rgName="$(az group list --query "[?tags.Test=='yes'].name" --output tsv)"
az group show -n $rgName
</code>```

This works just fine in cloud shell. But not in DevOps azurecli task.
I also referred to multiple examples given in stack overflow itself, but none of them work.
Using task version 1.*

```<code>rgName' is not recognised as an internal or external command,
</code>```

Can someone give an working example for DevOps Task?

Note: BTW the whole reason for me using cli is because cant find Advisor RM module and the Az module wont load correctly in task version 4.*

答:
As Shayki mentioned above, task.setvariable can help with setting a variable from a script. The same has been detailed in this document. In a nutshell, you would have to do this:

```<code>rgName=$(az group list --query "[?tags.Test=='yes'].name" -o tsv | tr '\n' ' ')
echo "##vso[task.setvariable variable=RESULT]$rgName"
</code>```

The task.setvariable is a logging command and does not update the environment variables, but it does make the new variable available to downstream steps within the same job. Notice that the results are separated by CRLF and not spaces, and hence the trimming tr '\n' ' '. Now, in the subsequent tasks where you need the variable, you may use it in this way:

```<code>echo "Result: $(RESULT)"
</code>```

Refer to this blog to get a detailed walkthrough. Hope this helps!

Body:
Trying to save an output of azure advisor recommendation on to a variable so that i can pass on to next task.

However no matter what syntax I try, and believe me i have tried all possible combinations, the variable doesn't get saved.
Interestingly, these work in cloud shell (bash)
for E.g.

rgName="$(az group list --query "[?tags.Test=='yes'].name" --output tsv)"
az group show -n $rgName

This works just fine in cloud shell. But not in DevOps azurecli task.
I also referred to multiple examples given in stack overflow itself, but none of them work.
Using task version 1.*

rgName' is not recognised as an internal or external command,

Can someone give an working example for DevOps Task?

Note: BTW the whole reason for me using cli is because cant find Advisor RM module and the Az module wont load correctly in task version 4.*

Body:
As Shayki mentioned above, task.setvariable can help with setting a variable from a script. The same has been detailed in this document. In a nutshell, you would have to do this:

rgName=$(az group list --query "[?tags.Test=='yes'].name" -o tsv | tr '\n' ' ')
echo "##vso[task.setvariable variable=RESULT]$rgName"

The task.setvariable is a logging command and does not update the environment variables, but it does make the new variable available to downstream steps within the same job. Notice that the results are separated by CRLF and not spaces, and hence the trimming tr '\n' ' '. Now, in the subsequent tasks where you need the variable, you may use it in this way:

echo "Result: $(RESULT)"

Refer to this blog to get a detailed walkthrough. Hope this helps!


问:
Commit Asynchronously a message just after reading from topic
I'm trying to commit a message just after reading it from the topic. I've followed this link (https://www.confluent.io/blog/apache-kafka-spring-boot-application) to create a Kafka consumer with spring. Normally it works perfect and the consumer gets the message and waits till anotherone enters in the queue. But the problem is that when I process this messages it takes a lot of time (circa 10 minutes) the kafka queue thinks that the message is not consumed (commited) and the consumers reads it again and again. I have to say that when my process time is less than 5 minutes it works well but when it lastas longer it doesn't commit the message.

I've looked for some answers around but it doesn't help me because I'm not using the same source code (and of course a different structure). I've tried to send asynchronous methods and also to commit asynchronously the message but I've failed.
Some of the sources are:

Spring Boot Kafka: Commit cannot be completed since the group has already rebalanced

https://www.confluent.io/blog/tutorial-getting-started-with-the-new-apache-kafka-0-9-consumer-client/

https://dzone.com/articles/kafka-clients-at-most-once-at-least-once-exactly-o

Kafka 0.10 Java consumer not reading message from topic

https://github.com/confluentinc/confluent-kafka-dotnet/issues/470

The main class is here :

```<code>
@SpringBootApplication
@EnableAsync
public class SpringBootKafkaApp {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootKafkaApp .class, args);
    }

</code>```

The consumer class (where I need to commit my message)

```<code>@Service
public class Consumer {

@Autowired
    AppPropert prop;

   Consumer cons;
@KafkaListener(topics = "${app.topic.pro}", groupId = "group_id")
    public void consume(String message) throws IOException {
        /*HERE I MUST CONSUME THE MESSAGE AND COMMIT IT */

        Properties  props=prope.startProp();//just getting my properties from my config-file
        ControllerPRO pro = new ControllerPRO();

        List<Future<String>> async= new ArrayList<Future<String>>();//call this method asynchronous, doesn't help me
        try {

            CompletableFuture<String> ret=pro.processLaunch(message,props);//here I call the process method
            /*This works fine when the processLaunch method takes less than 5 minutes,
            if it takes longer the consumer will get the same message from the topic and start again with this operation
            */

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("End of consumer method ");

    }

    }

</code>```

How can I commit the message just after I read it from the queue.

I want to be sure that when I receive the message I commit the message immediately. Right now the message is commited when I finish to execute the method just after the   (System.out.println). So can anybody tell me how to do this?

----- update -------

Sorry for the late reply but as @GirishB suggested I've been looking to the configuration of GirishB but I don't see where I can define the topic I want to read/listen from my configuration file (applications.yml). All the examples that I see use a structure similar to this (http://tutorials.jenkov.com/java-util-concurrent/blockingqueue.html). Is there any option that I can read a topic that is declared in other server? Using something similar to this @KafkaListener(topics = "${app.topic.pro}", groupId = "group_id")

===========  SOLUTION 1 ========================================

I followed @victor gallet advice and included the declaration of the confumer porperties in oder to accomodate the "Acknowledgment" object in the consume method. I've also followed this link (https://www.programcreek.com/java-api-examples/?code=SpringOnePlatform2016/grussell-spring-kafka/grussell-spring-kafka-master/s1p-kafka/src/main/java/org/s1p/CommonConfiguration.java) to get all the methods that I've used to declare and set all the properties (consumerProperties, consumerFactory, kafkaListenerContainerFactory). The only problem I found is the
"new SeekToCurrentErrorHandler() " declaration because I'm getting an error and for the moment I'm not able to resolve it (would be great if someone explain it to me).

```<code>
@Service
public class Consumer {

@Autowired
    AppPropert prop;

   Consumer cons;

   @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory();

        factory.setConsumerFactory(consumerFactory());
        factory.getContainerProperties().setAckOnError(false);
        factory.getContainerProperties().setAckMode(AckMode.MANUAL_IMMEDIATE);
        //factory.setErrorHandler(new SeekToCurrentErrorHandler());//getting error here despite I've loaded the library
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerProperties());
    }

     @Bean
    public Map<String, Object> consumerProperties() {
        Map<String, Object> props = new HashMap<>();
        Properties  propsManu=prop.startProperties();// here I'm getting my porperties file where I retrive the configuration from a remote server (you have to trust that this method works)
        //props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.configProperties.getBrokerAddress());
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, propsManu.getProperty("bootstrap-servers"));
        //props.put(ConsumerConfig.GROUP_ID_CONFIG, "s1pGroup");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, propsManu.getProperty("group-id"));
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 15000);
        //props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, propsManu.getProperty("key-deserializer"));
        //props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, propsManu.getProperty("value-deserializer"));
        return props;
    }

    @KafkaListener(topics = "${app.topic.pro}", groupId = "group_id")
    public void consume(String message) throws IOException {
        /*HERE I MUST CONSUME THE MESSAGE AND COMMIT IT */
        acknowledgment.acknowledge();// commit immediately
        Properties  props=prop.startProp();//just getting my properties from my config-file
        ControllerPRO pro = new ControllerPRO();

        List<Future<String>> async= new ArrayList<Future<String>>();//call this method asynchronous, doesn't help me
        try {

            CompletableFuture<String> ret=pro.processLaunch(message,props);//here I call the process method
            /*This works fine when the processLaunch method takes less than 5 minutes,
            if it takes longer the consumer will get the same message from the topic and start again with this operation
            */

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("End of consumer method ");

    }

    }

``````````````````````````````````````````````````````````
```

答: You may use a java.util.concurrent.BlockingQueue to push the message as you consume and commit the Kafka offset. Then using another thread get the message from the blockingQueue and process. This way you don't have to wait till processing completes.

Body:
I'm trying to commit a message just after reading it from the topic. I've followed this link (https://www.confluent.io/blog/apache-kafka-spring-boot-application) to create a Kafka consumer with spring. Normally it works perfect and the consumer gets the message and waits till anotherone enters in the queue. But the problem is that when I process this messages it takes a lot of time (circa 10 minutes) the kafka queue thinks that the message is not consumed (commited) and the consumers reads it again and again. I have to say that when my process time is less than 5 minutes it works well but when it lastas longer it doesn't commit the message.

I've looked for some answers around but it doesn't help me because I'm not using the same source code (and of course a different structure). I've tried to send asynchronous methods and also to commit asynchronously the message but I've failed.
Some of the sources are:

Spring Boot Kafka: Commit cannot be completed since the group has already rebalanced

https://www.confluent.io/blog/tutorial-getting-started-with-the-new-apache-kafka-0-9-consumer-client/

https://dzone.com/articles/kafka-clients-at-most-once-at-least-once-exactly-o

Kafka 0.10 Java consumer not reading message from topic

https://github.com/confluentinc/confluent-kafka-dotnet/issues/470

The main class is here :

@SpringBootApplication
@EnableAsync
public class SpringBootKafkaApp {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootKafkaApp .class, args);
    }

The consumer class (where I need to commit my message)

@Service
public class Consumer {

@Autowired
    AppPropert prop;

   Consumer cons;
@KafkaListener(topics = "${app.topic.pro}", groupId = "group_id")
    public void consume(String message) throws IOException {
        /*HERE I MUST CONSUME THE MESSAGE AND COMMIT IT */

        Properties  props=prope.startProp();//just getting my properties from my config-file
        ControllerPRO pro = new ControllerPRO();

        List<Future<String>> async= new ArrayList<Future<String>>();//call this method asynchronous, doesn't help me
        try {

            CompletableFuture<String> ret=pro.processLaunch(message,props);//here I call the process method
            /*This works fine when the processLaunch method takes less than 5 minutes,
            if it takes longer the consumer will get the same message from the topic and start again with this operation
            */

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("End of consumer method ");

    }

    }

How can I commit the message just after I read it from the queue.

I want to be sure that when I receive the message I commit the message immediately. Right now the message is commited when I finish to execute the method just after the   (System.out.println). So can anybody tell me how to do this?

----- update -------

Sorry for the late reply but as @GirishB suggested I've been looking to the configuration of GirishB but I don't see where I can define the topic I want to read/listen from my configuration file (applications.yml). All the examples that I see use a structure similar to this (http://tutorials.jenkov.com/java-util-concurrent/blockingqueue.html). Is there any option that I can read a topic that is declared in other server? Using something similar to this @KafkaListener(topics = "${app.topic.pro}", groupId = "group_id")

===========  SOLUTION 1 ========================================

I followed @victor gallet advice and included the declaration of the confumer porperties in oder to accomodate the "Acknowledgment" object in the consume method. I've also followed this link (https://www.programcreek.com/java-api-examples/?code=SpringOnePlatform2016/grussell-spring-kafka/grussell-spring-kafka-master/s1p-kafka/src/main/java/org/s1p/CommonConfiguration.java) to get all the methods that I've used to declare and set all the properties (consumerProperties, consumerFactory, kafkaListenerContainerFactory). The only problem I found is the
"new SeekToCurrentErrorHandler() " declaration because I'm getting an error and for the moment I'm not able to resolve it (would be great if someone explain it to me).

@Service
public class Consumer {

@Autowired
    AppPropert prop;

   Consumer cons;

   @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory();

        factory.setConsumerFactory(consumerFactory());
        factory.getContainerProperties().setAckOnError(false);
        factory.getContainerProperties().setAckMode(AckMode.MANUAL_IMMEDIATE);
        //factory.setErrorHandler(new SeekToCurrentErrorHandler());//getting error here despite I've loaded the library
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerProperties());
    }

     @Bean
    public Map<String, Object> consumerProperties() {
        Map<String, Object> props = new HashMap<>();
        Properties  propsManu=prop.startProperties();// here I'm getting my porperties file where I retrive the configuration from a remote server (you have to trust that this method works)
        //props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.configProperties.getBrokerAddress());
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, propsManu.getProperty("bootstrap-servers"));
        //props.put(ConsumerConfig.GROUP_ID_CONFIG, "s1pGroup");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, propsManu.getProperty("group-id"));
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 15000);
        //props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, propsManu.getProperty("key-deserializer"));
        //props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, propsManu.getProperty("value-deserializer"));
        return props;
    }

    @KafkaListener(topics = "${app.topic.pro}", groupId = "group_id")
    public void consume(String message) throws IOException {
        /*HERE I MUST CONSUME THE MESSAGE AND COMMIT IT */
        acknowledgment.acknowledge();// commit immediately
        Properties  props=prop.startProp();//just getting my properties from my config-file
        ControllerPRO pro = new ControllerPRO();

        List<Future<String>> async= new ArrayList<Future<String>>();//call this method asynchronous, doesn't help me
        try {

            CompletableFuture<String> ret=pro.processLaunch(message,props);//here I call the process method
            /*This works fine when the processLaunch method takes less than 5 minutes,
            if it takes longer the consumer will get the same message from the topic and start again with this operation
            */

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("End of consumer method ");

    }

    }

``````````````````````````````````````````````````````````


问:
How to set content mode when using FFImageLoading on button
I am not able to get the content mode working on button when I am setting the image using FFImageLoading library.I want to set the mode to ScaleAspectFill.

I tried setting the content mode of the button.imageview as well as the button itself.

```<code>button.ContentMode = UIViewContentMode.ScaleAspectFill;
button.ImageView.ContentMode = UIViewContentMode.ScaleAspectFill;
ImageService.Instance.LoadUrl(image_url).Into(button);
</code>```

The image is not scaling and is appearing as ScaleAspectFit rather than Fill

答:
Setting the button's ImageView's ContentMode will adjust the image's representation.

I used the code below to display two buttons. One has set the ContentMode and another doesn't:

```<code>UIButton btn = new UIButton(UIButtonType.Custom);
btn.Frame = new CoreGraphics.CGRect(50, 100, 100, 40);

btn.ImageView.ContentMode = UIViewContentMode.ScaleAspectFill;
ImageService.Instance.LoadUrl("https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1Mu3b?ver=5c31").Into(btn);

UIButton btn2 = new UIButton(UIButtonType.Custom);
btn2.Frame = new CoreGraphics.CGRect(50, 200, 100, 40);
ImageService.Instance.LoadUrl("https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1Mu3b?ver=5c31").Into(btn2);

View.AddSubview(btn);
View.AddSubview(btn2);
</code>```

They have different effects:

The first button doesn't have enough width to display this image so it clips the left and right edges due to the configuration of content mode. But the second button stretches the image to fit the whole space. Both buttons have the same size.

Body:
I am not able to get the content mode working on button when I am setting the image using FFImageLoading library.I want to set the mode to ScaleAspectFill.

I tried setting the content mode of the button.imageview as well as the button itself.

button.ContentMode = UIViewContentMode.ScaleAspectFill;
button.ImageView.ContentMode = UIViewContentMode.ScaleAspectFill;
ImageService.Instance.LoadUrl(image_url).Into(button);

The image is not scaling and is appearing as ScaleAspectFit rather than Fill

Body:
Setting the button's ImageView's ContentMode will adjust the image's representation.

I used the code below to display two buttons. One has set the ContentMode and another doesn't:

UIButton btn = new UIButton(UIButtonType.Custom);
btn.Frame = new CoreGraphics.CGRect(50, 100, 100, 40);

btn.ImageView.ContentMode = UIViewContentMode.ScaleAspectFill;
ImageService.Instance.LoadUrl("https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1Mu3b?ver=5c31").Into(btn);

UIButton btn2 = new UIButton(UIButtonType.Custom);
btn2.Frame = new CoreGraphics.CGRect(50, 200, 100, 40);
ImageService.Instance.LoadUrl("https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1Mu3b?ver=5c31").Into(btn2);

View.AddSubview(btn);
View.AddSubview(btn2);

They have different effects:

The first button doesn't have enough width to display this image so it clips the left and right edges due to the configuration of content mode. But the second button stretches the image to fit the whole space. Both buttons have the same size.