问:
jQuery - How to pass 'this' to a function?
How do I pass $(this) into a function. In my example below I want to populate the address textbox with the value of the selected drop-down option label but only if the value selected is not empty.

The following doesn't work?

$("#AddressId").change(function () {
  $("#Address").val(function(index, val) {
      val = $(this).val();
      return val === "" ? "" : $('option:selected', this).text();
  }, this).trigger("change");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="AddressId">
 <option value="">-- Please select --</option>
 <option value="1">xyz street</option>
 ...
</select>

<input id="Address" name="Address" value="" type="text"></code>```

答:
To achieve this store the this reference of #AddressId in a variable the change event handler. You can then use that variable in the inner val() function, like this:

$("#AddressId").change(function() {
  var $addressId = $(this);

  $("#Address").val(function(index, val) {
    val = $addressId.val();
    return val === "" ? "" : $('option:selected', $addressId).text();
  }, this).trigger("change");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
   <option value="">-- Please select --</option>
   <option value="1">xyz street</option>
 </select>

<input id="Address" name="Address" value="" type="text"></code>```

Although note that the function you provide to val() is not required, and is the cause of your problem. You can simplify the code to just this:

$("#AddressId").change(function() {
  var address = $(this).val() ? $(this).find('option:selected').text() : '';
  $("#Address").val(address).trigger("change");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
   <option value="">-- Please select --</option>
   <option value="1">xyz street</option>
 </select>

<input id="Address" name="Address" value="" type="text"></code>```

Body:
How do I pass $(this) into a function. In my example below I want to populate the address textbox with the value of the selected drop-down option label but only if the value selected is not empty.

The following doesn't work?

$("#AddressId").change(function () {
  $("#Address").val(function(index, val) {
      val = $(this).val();
      return val === "" ? "" : $('option:selected', this).text();
  }, this).trigger("change");
});

<select id="AddressId">
 <option value="">-- Please select --</option>
 <option value="1">xyz street</option>
 ...
</select>

<input id="Address" name="Address" value="" type="text">

Body:
To achieve this store the this reference of #AddressId in a variable the change event handler. You can then use that variable in the inner val() function, like this:

$("#AddressId").change(function() {
  var $addressId = $(this);

  $("#Address").val(function(index, val) {
    val = $addressId.val();
    return val === "" ? "" : $('option:selected', $addressId).text();
  }, this).trigger("change");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
   <option value="">-- Please select --</option>
   <option value="1">xyz street</option>
 </select>

<input id="Address" name="Address" value="" type="text">

Although note that the function you provide to val() is not required, and is the cause of your problem. You can simplify the code to just this:

$("#AddressId").change(function() {
  var address = $(this).val() ? $(this).find('option:selected').text() : '';
  $("#Address").val(address).trigger("change");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
   <option value="">-- Please select --</option>
   <option value="1">xyz street</option>
 </select>

<input id="Address" name="Address" value="" type="text">


来源: stackexchange

问:
how to install sbt without internet connection
I am trying to install sbt on our RedHat Linux server (RHEL6.8). The server doesn't have internet connection.
I downloaded sbt-1.0.x.zip from github but I don't see installation instruction. In README.md file, it points to http://www.scala-sbt.org/release/docs/Getting-Started/Setup which tells me to use yum command. But that would require Internet connection.
Can anyone help?
Thank you.</p>

答:
You need to download the RPM from bintray. See the instructions here:

Source: http://www.scala-sbt.org/0.13/docs/Installing-sbt-on-Linux.html

Depending on what dependencies are unfulfilled, you may need to download additional RPM files that sbt depends on.

ContentLicense: CC BY-SA 3.0


问:
RoboGuice android injection module not working in test
I have created a TestModule class to inject a test implementation class and it fails with a classCastException.

I am using Robolectric 2.4.

Here is my custom TestApplication that gets created via a custom robolectric runner

```<code>public class AppApplicationTest extends MyApplication {

@Override
protected void attachBaseContext(Context base) {
    configureModuleInjection();
    System.out.println(this.getClass().getSimpleName() + " attached and initialised AppApplicationTest ");

    try {
        MultiDex.install(base);
        super.attachBaseContext(base);
    } catch (RuntimeException ignored) {
        // Multidex support doesn't play well with Robolectric yet
        System.out.println(this.getClass().getSimpleName() + " runtime exception = " + ignored.toString());
    }
}

private void configureModuleInjection() {
//fails below with classCastException
    RoboGuice.getOrCreateBaseApplicationInjector(this,
            RoboGuice.DEFAULT_STAGE,
            RoboGuice.newDefaultRoboModule(this),
            new TestModule());
}
}
</code>```

Here is my custom RobolectricTestRunner

```<code>    public class MyRoboTestRunner extends RobolectricTestRunner {

    ....

    @Override
    protected Class<? extends TestLifecycle> getTestLifecycleClass() {
        return ApplicationTest.class;
    }

    public  static class ApplicationTest extends DefaultTestLifecycle{
        @Override
        public Application createApplication(Method method, AndroidManifest appManifest, Config config) {
            return new AppApplicationTest();
        }
    }

    @Override
    protected ClassLoader createRobolectricClassLoader(Setup setup, SdkConfig sdkConfig) {
        return super.createRobolectricClassLoader(new ExtraShadows(setup), sdkConfig);
    }

    class ExtraShadows extends Setup{
        private  Setup setup;

        public ExtraShadows(Setup setup) {
            this.setup = setup;
        }

        @Override
        public boolean shouldInstrument(ClassInfo classInfo) {
            boolean shouldInstrument = setup.shouldInstrument(classInfo);
            return shouldInstrument || classInfo.getName().equals(MultiDex.class.getName());
        }
    }
}
</code>```

Here is the full stacktrace error

```<code>    WARNING: no system properties value for ro.build.date.utc
java.lang.ClassNotFoundException: AnnotationDatabaseImpl
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.getByteCode(AsmInstrumentingClassLoader.java:172)
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.findClass(AsmInstrumentingClassLoader.java:126)
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.loadClass(AsmInstrumentingClassLoader.java:98)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:191)
    at com.google.inject.AnnotationDatabaseFinder.getAnnotationDatabaseInstance(AnnotationDatabaseFinder.java:73)
    at com.google.inject.AnnotationDatabaseFinder.<init>(AnnotationDatabaseFinder.java:36)
    at com.google.inject.Guice.setAnnotationDatabasePackageNames(Guice.java:133)
    at roboguice.RoboGuice.initializeAnnotationDatabaseFinderAndHierarchyTraversalFilterFactory(RoboGuice.java:288)
    at roboguice.RoboGuice.getOrCreateBaseApplicationInjector(RoboGuice.java:113)
    at com.jr.AppApplicationTest.configureModuleInjection(AppApplicationTest.java:33)
    at com.jr.AppApplicationTest.attachBaseContext(AppApplicationTest.java:20)
    at android.app.Application.$$robo$$Application_0b64_attach(Application.java:181)
    at android.app.Application.attach(Application.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.robolectric.internal.ReflectionHelpers$3.run(ReflectionHelpers.java:64)
    at org.robolectric.internal.ReflectionHelpers.traverseClassHierarchy(ReflectionHelpers.java:114)
    at org.robolectric.internal.ReflectionHelpers.callInstanceMethodReflectively(ReflectionHelpers.java:59)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:119)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:440)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:222)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
java.lang.IllegalStateException: Unable to use annotation database(s)
    at roboguice.RoboGuice.initializeAnnotationDatabaseFinderAndHierarchyTraversalFilterFactory(RoboGuice.java:292)
    at roboguice.RoboGuice.getOrCreateBaseApplicationInjector(RoboGuice.java:113)
    at com.jr.AppApplicationTest.configureModuleInjection(AppApplicationTest.java:33)
    at com.jr.AppApplicationTest.attachBaseContext(AppApplicationTest.java:20)
    at android.app.Application.attach(Application.java:181)
    at org.robolectric.internal.ReflectionHelpers$3.run(ReflectionHelpers.java:64)
    at org.robolectric.internal.ReflectionHelpers.traverseClassHierarchy(ReflectionHelpers.java:114)
    at org.robolectric.internal.ReflectionHelpers.callInstanceMethodReflectively(ReflectionHelpers.java:59)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:119)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:440)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:222)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</code>```

答:
Because of this line
    java.lang.IllegalStateException: Unable to use annotation database(s)

Can you try to use RoboGuice.setUseAnnotationDatabases(false);

```<code>private void configureModuleInjection() {

    RoboGuice.setUseAnnotationDatabases(false);

    RoboGuice.getOrCreateBaseApplicationInjector(this,
        RoboGuice.DEFAULT_STAGE,
        RoboGuice.newDefaultRoboModule(this),
        new TestModule());
</code>```

}

Body:
I have created a TestModule class to inject a test implementation class and it fails with a classCastException.

I am using Robolectric 2.4.

Here is my custom TestApplication that gets created via a custom robolectric runner

public class AppApplicationTest extends MyApplication {

@Override
protected void attachBaseContext(Context base) {
    configureModuleInjection();
    System.out.println(this.getClass().getSimpleName() + " attached and initialised AppApplicationTest ");

    try {
        MultiDex.install(base);
        super.attachBaseContext(base);
    } catch (RuntimeException ignored) {
        // Multidex support doesn't play well with Robolectric yet
        System.out.println(this.getClass().getSimpleName() + " runtime exception = " + ignored.toString());
    }
}

private void configureModuleInjection() {
//fails below with classCastException
    RoboGuice.getOrCreateBaseApplicationInjector(this,
            RoboGuice.DEFAULT_STAGE,
            RoboGuice.newDefaultRoboModule(this),
            new TestModule());
}
}

Here is my custom RobolectricTestRunner

    public class MyRoboTestRunner extends RobolectricTestRunner {

    ....

    @Override
    protected Class<? extends TestLifecycle> getTestLifecycleClass() {
        return ApplicationTest.class;
    }

    public  static class ApplicationTest extends DefaultTestLifecycle{
        @Override
        public Application createApplication(Method method, AndroidManifest appManifest, Config config) {
            return new AppApplicationTest();
        }
    }

    @Override
    protected ClassLoader createRobolectricClassLoader(Setup setup, SdkConfig sdkConfig) {
        return super.createRobolectricClassLoader(new ExtraShadows(setup), sdkConfig);
    }

    class ExtraShadows extends Setup{
        private  Setup setup;

        public ExtraShadows(Setup setup) {
            this.setup = setup;
        }

        @Override
        public boolean shouldInstrument(ClassInfo classInfo) {
            boolean shouldInstrument = setup.shouldInstrument(classInfo);
            return shouldInstrument || classInfo.getName().equals(MultiDex.class.getName());
        }
    }
}

Here is the full stacktrace error

    WARNING: no system properties value for ro.build.date.utc
java.lang.ClassNotFoundException: AnnotationDatabaseImpl
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.getByteCode(AsmInstrumentingClassLoader.java:172)
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.findClass(AsmInstrumentingClassLoader.java:126)
    at org.robolectric.bytecode.AsmInstrumentingClassLoader.loadClass(AsmInstrumentingClassLoader.java:98)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:191)
    at com.google.inject.AnnotationDatabaseFinder.getAnnotationDatabaseInstance(AnnotationDatabaseFinder.java:73)
    at com.google.inject.AnnotationDatabaseFinder.<init>(AnnotationDatabaseFinder.java:36)
    at com.google.inject.Guice.setAnnotationDatabasePackageNames(Guice.java:133)
    at roboguice.RoboGuice.initializeAnnotationDatabaseFinderAndHierarchyTraversalFilterFactory(RoboGuice.java:288)
    at roboguice.RoboGuice.getOrCreateBaseApplicationInjector(RoboGuice.java:113)
    at com.jr.AppApplicationTest.configureModuleInjection(AppApplicationTest.java:33)
    at com.jr.AppApplicationTest.attachBaseContext(AppApplicationTest.java:20)
    at android.app.Application.$$robo$$Application_0b64_attach(Application.java:181)
    at android.app.Application.attach(Application.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.robolectric.internal.ReflectionHelpers$3.run(ReflectionHelpers.java:64)
    at org.robolectric.internal.ReflectionHelpers.traverseClassHierarchy(ReflectionHelpers.java:114)
    at org.robolectric.internal.ReflectionHelpers.callInstanceMethodReflectively(ReflectionHelpers.java:59)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:119)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:440)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:222)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
java.lang.IllegalStateException: Unable to use annotation database(s)
    at roboguice.RoboGuice.initializeAnnotationDatabaseFinderAndHierarchyTraversalFilterFactory(RoboGuice.java:292)
    at roboguice.RoboGuice.getOrCreateBaseApplicationInjector(RoboGuice.java:113)
    at com.jr.AppApplicationTest.configureModuleInjection(AppApplicationTest.java:33)
    at com.jr.AppApplicationTest.attachBaseContext(AppApplicationTest.java:20)
    at android.app.Application.attach(Application.java:181)
    at org.robolectric.internal.ReflectionHelpers$3.run(ReflectionHelpers.java:64)
    at org.robolectric.internal.ReflectionHelpers.traverseClassHierarchy(ReflectionHelpers.java:114)
    at org.robolectric.internal.ReflectionHelpers.callInstanceMethodReflectively(ReflectionHelpers.java:59)
    at org.robolectric.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:119)
    at org.robolectric.RobolectricTestRunner.setUpApplicationState(RobolectricTestRunner.java:440)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:222)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Body:
Because of this line
    java.lang.IllegalStateException: Unable to use annotation database(s)

Can you try to use RoboGuice.setUseAnnotationDatabases(false);

private void configureModuleInjection() {

    RoboGuice.setUseAnnotationDatabases(false);

    RoboGuice.getOrCreateBaseApplicationInjector(this,
        RoboGuice.DEFAULT_STAGE,
        RoboGuice.newDefaultRoboModule(this),
        new TestModule());

}


问:
morris.js dashed grid lines
I am trying to customize the grid lines for morris.js to have a dashed style similiar to the revenue graph in http://dribbble.com/shots/947782-Freebie-PSD-Flat-UI-Kit/attachments/107093, Is this even possible? It seems that the documentation is not very complete, gridLineColor is not listed as an option yet it does change the color when I add it to my graph. Morris.js seemed to be highly recommended but I cant seem to adjust simple things like this.

I would also like to have each grid line the same weight and not have the center line emphasized while the others lighter. I cant seem to find anything in the documentation for that either.

Thanks for any help!

答:
Here is the line that needed changing in Graeme's answer:     </p>

```<code>Grid.prototype.drawGridLine = function(path) {
    return this.raphael.path(path).attr('stroke', this.options.gridLineColor).attr('stroke-width', this.options.gridStrokeWidth).attr('stroke-dasharray', this.options.gridDashed);
};
</code>```

Title: morris.js dashed grid lines

Body:
Here is the line that needed changing in Graeme's answer:

Grid.prototype.drawGridLine = function(path) {
    return this.raphael.path(path).attr('stroke', this.options.gridLineColor).attr('stroke-width', this.options.gridStrokeWidth).attr('stroke-dasharray', this.options.gridDashed);
};


问:
Is the better solution create classes for each file xml?
I create a simple app with a start menu and an other page.
I have connected them with a button and i have write the function in the same file java. I would know if It is the right solution or not.</p>

答:
You can find the answer in the oficial documentation : https://developer.android.com/guide/topics/ui/declaring-layout.html.

According the best practices, you have to declare one xml layout for each activity or fragment.


问:
Trouble Getting JSON Data
I am pretty new to back end programming with JavaScript and have written some code to query a database and return the results as JSON. It seems to be working correctly in the browser, but my iOS code isn't getting any data from it. I have it running locally for now while testing. If you look in my Swift that gets the data from the URL, I'm getting the NO JSON from the print statement in the catch.

JavaScript

```<code>'use strict';
var util = require('util');
var sql = require("mssql");
var express = require('express');
var port = process.env.PORT || 1337;

var membershipNumber;
var queryString;

var app = express();

app.get('/membership/:number', function (req, res) {
    console.log("\nPARAMS:");
    console.log(req.params.number);

    membershipNumber = req.params.number;
    queryString = util.format('SELECT major_key, company, status, paid_thru FROM name WHERE major_key = \'%s\' and member_record = 1', membershipNumber);
    console.log("\nQUERY:");
    console.log(queryString);

    res.setHeader('Content-Type', 'application/json');
    res.set('Content-Type', 'application/json');
    membershipStatusQuery(queryString, res);
});

app.get('/', function (req, res) {
    var dictionary = [];
    dictionary.push({
        key: "none"
    });
    var jsonDict = JSON.stringify(dictionary);

    res.setHeader('Content-Type', 'application/json');
    res.set('Content-Type', 'application/json');
    res.send(jsonDict);
});

function membershipStatusQuery(query, response) {
    var config = {
        server: 'DB_Server',
        database: 'testDB',
        user: 'sa',
        password: 'password',
        port: 1433
    };

    var connection = new sql.Connection(config);

    connection.connect().then(function () {
        var req = new sql.Request(connection);
        req.query(query).then(function (recordset) {
            connection.close();
            response.send(results);
        })
            .catch(function (err) {
                console.log(err);
                connection.close();
                response.send(err);
            });
    })
        .catch(function (err) {
            console.log(err);
            response.send(err);
        });
}

app.listen(port, function () {
    console.log("Listening on port %s", port);
});
</code>```

RESULTS

```<code>[{"major_key":"0001354648","company":"Membership of David Metzgar","status":"A","paid_thru":"2017-10-31T00:00:00.000Z"}]
</code>```

iOS Swift Code
Class to get JSON from URL:

```<code>import UIKit

class GetJSON: NSObject {

    func getJSONFrom(urlString: String) -> JSON {
        let url = URL(string: urlString)
        var data = Data()

        do {
            data = try Data(contentsOf: url!)
        } catch {
            print("No JSON")
            // TODO: Display error
        }

        let json = JSON(data: data)
        return json
    }
}
</code>```

Method from another class to use JSON:

```<code>func getQueryResultsJSON() {
        print("http://localhost:1337/membership/\(memberNumberTextField.text!)")
        // let jsonURL = "http://localhost:1337/membership/\(memberNumberTextField.text!)"
        let jsonURL = "http://localhost:1337/membership/0001354648"
        let getJSON = GetJSON()
        self.resultsArray = getJSON.getJSONFrom(urlString: jsonURL)
        if let dictionary = resultsArray?[0].dictionaryObject {
            if let status = dictionary["status"] {
                if status as! String == "A" {
                    print(dictionary)
                    print("Provided membership is active")
                    // membership is active
                    // TODO: save info and display membership card
                } else {
                    print(dictionary)
                    print("Provided membership is NOT active")
                    // membership is not active
                    // TODO: display alert
                }
            } else {
                print("DOESN'T EXIST!")
                // membership number does not exist
                // TODO: display alert
            }
        } else {
            print("NOTHING!")
        }
    }
</code>```

答:
```<code>        let url = NSURL(string: "your url")!
        let request = NSMutableURLRequest(url: url as URL)
        // request.httpMethod = "POST"
        // request.httpBody = jsonData
        //request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
            if error != nil {

                return
            }

            do {
                let userObject = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: String]
                if userObject != nil {

                    // do something
                }

            } catch let jsonError {
                print(jsonError)
                print(String(data: data!, encoding: String.Encoding.utf8)!)
            }
        }

        task.resume()
</code>```

Title: Trouble Getting JSON Data

Body:
I am pretty new to back end programming with JavaScript and have written some code to query a database and return the results as JSON. It seems to be working correctly in the browser, but my iOS code isn't getting any data from it. I have it running locally for now while testing. If you look in my Swift that gets the data from the URL, I'm getting the NO JSON from the print statement in the catch.

JavaScript

'use strict';
var util = require('util');
var sql = require("mssql");
var express = require('express');
var port = process.env.PORT || 1337;

var membershipNumber;
var queryString;

var app = express();

app.get('/membership/:number', function (req, res) {
    console.log("\nPARAMS:");
    console.log(req.params.number);

    membershipNumber = req.params.number;
    queryString = util.format('SELECT major_key, company, status, paid_thru FROM name WHERE major_key = \'%s\' and member_record = 1', membershipNumber);
    console.log("\nQUERY:");
    console.log(queryString);

    res.setHeader('Content-Type', 'application/json');
    res.set('Content-Type', 'application/json');
    membershipStatusQuery(queryString, res);
});

app.get('/', function (req, res) {
    var dictionary = [];
    dictionary.push({
        key: "none"
    });
    var jsonDict = JSON.stringify(dictionary);

    res.setHeader('Content-Type', 'application/json');
    res.set('Content-Type', 'application/json');
    res.send(jsonDict);
});

function membershipStatusQuery(query, response) {
    var config = {
        server: 'DB_Server',
        database: 'testDB',
        user: 'sa',
        password: 'password',
        port: 1433
    };

    var connection = new sql.Connection(config);

    connection.connect().then(function () {
        var req = new sql.Request(connection);
        req.query(query).then(function (recordset) {
            connection.close();
            response.send(results);
        })
            .catch(function (err) {
                console.log(err);
                connection.close();
                response.send(err);
            });
    })
        .catch(function (err) {
            console.log(err);
            response.send(err);
        });
}

app.listen(port, function () {
    console.log("Listening on port %s", port);
});

RESULTS

[{"major_key":"0001354648","company":"Membership of David Metzgar","status":"A","paid_thru":"2017-10-31T00:00:00.000Z"}]

iOS Swift Code
Class to get JSON from URL:

import UIKit

class GetJSON: NSObject {

    func getJSONFrom(urlString: String) -> JSON {
        let url = URL(string: urlString)
        var data = Data()

        do {
            data = try Data(contentsOf: url!)
        } catch {
            print("No JSON")
            // TODO: Display error
        }

        let json = JSON(data: data)
        return json
    }
}

Method from another class to use JSON:

func getQueryResultsJSON() {
        print("http://localhost:1337/membership/\(memberNumberTextField.text!)")
        // let jsonURL = "http://localhost:1337/membership/\(memberNumberTextField.text!)"
        let jsonURL = "http://localhost:1337/membership/0001354648"
        let getJSON = GetJSON()
        self.resultsArray = getJSON.getJSONFrom(urlString: jsonURL)
        if let dictionary = resultsArray?[0].dictionaryObject {
            if let status = dictionary["status"] {
                if status as! String == "A" {
                    print(dictionary)
                    print("Provided membership is active")
                    // membership is active
                    // TODO: save info and display membership card
                } else {
                    print(dictionary)
                    print("Provided membership is NOT active")
                    // membership is not active
                    // TODO: display alert
                }
            } else {
                print("DOESN'T EXIST!")
                // membership number does not exist
                // TODO: display alert
            }
        } else {
            print("NOTHING!")
        }
    }


问:
How to get metadata from Media objects
I am trying to make a mp3 player in JavaFX and so far have gotten it to load songs and play, but now I want to display the metadata from the Media object to a tableview. I have a song class which acts as a model class and in my controller class I have a Label I am testing to see if I can get the metadata to display, but it always comes as null.

```<code>package application;

import java.io.File;

import javafx.collections.MapChangeListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class Song {
private File file;
private String title;
private String artist;
private String album;
private Media music;
private MediaPlayer mp;

public Song(File file) {
    music = new Media(file.toURI().toString());
    mp = new MediaPlayer(music);
    getMeta();
    artist = (String) mp.getMedia().getMetadata().get("artist");
    title = (String) music.getMetadata().get("title");
    album = (String) music.getMetadata().get("album");
    //artist = "test";
    //album = "test";
    //title = "test";
}

public void play() {
    mp.play();
}

public void pause() {
    mp.pause();
}

public void stop() {
    mp.stop();
}

public String getTitle(){
    return title;
}

public String getArtist(){
    return artist;
}

public String getAlbum(){
    return album;
}

}
</code>```

In my controller class

```<code>// Event Listener on Button[#loadBtn].onAction
@FXML
public void loadFile(ActionEvent event) {
    Node source = (Node) event.getSource();
    Window theStage = source.getScene().getWindow();
    //set fileChooser filter
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("MP3 files", "*.mp3");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Select MP3 files");
    //File file = fileChooser.showOpenDialog(theStage);
    //mySong = new Song(file);
    list = fileChooser.showOpenMultipleDialog(theStage);
    if(list!=null){
        for(File x: list) {
            mySong = new Song(x);
        }
    }
    label.setText(mySong.getTitle());
}
</code>```

In the last line I am testing if the metadata was retrieved correctly and it is always null. I have the label to be set as initially to say "test" so I would know if it was making any changes and it does, but not to what I want.

答:
As per the documentation (my emphasis):

Information about the media such as duration, metadata, tracks, and video resolution may be obtained from a Media instance. The media information is obtained asynchronously and so not necessarily available immediately after instantiation of the class. All information should however be available if the instance has been associated with a MediaPlayer and that player has transitioned to MediaPlayer.Status.READY status. To be notified when metadata or Tracks are added, observers may be registered with the collections returned by getMetadata()and getTracks(), respectively.

So you can do something like this:

```<code>public Song(File file) {
    music = new Media(file.toURI().toString());

    music.getMetadata().addListener((Change<? extends String, ? extends Object> c) -> {
        if (c.wasAdded()) {
            if ("artist".equals(c.getKey())) {
                artist = c.getValueAdded().toString();
            } else if ("title".equals(c.getKey())) {
                title = c.getValueAdded().toString();
            } else if ("album".equals(c.getKey())) {
                album = c.getValueAdded().toString();
            }
        }
    });

    mp = new MediaPlayer(music);

}
</code>```

Title: How to get metadata from Media objects

Body:
I am trying to make a mp3 player in JavaFX and so far have gotten it to load songs and play, but now I want to display the metadata from the Media object to a tableview. I have a song class which acts as a model class and in my controller class I have a Label I am testing to see if I can get the metadata to display, but it always comes as null.

package application;

import java.io.File;

import javafx.collections.MapChangeListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class Song {
private File file;
private String title;
private String artist;
private String album;
private Media music;
private MediaPlayer mp;

public Song(File file) {
    music = new Media(file.toURI().toString());
    mp = new MediaPlayer(music);
    getMeta();
    artist = (String) mp.getMedia().getMetadata().get("artist");
    title = (String) music.getMetadata().get("title");
    album = (String) music.getMetadata().get("album");
    //artist = "test";
    //album = "test";
    //title = "test";
}

public void play() {
    mp.play();
}

public void pause() {
    mp.pause();
}

public void stop() {
    mp.stop();
}

public String getTitle(){
    return title;
}

public String getArtist(){
    return artist;
}

public String getAlbum(){
    return album;
}

}

In my controller class

// Event Listener on Button[#loadBtn].onAction
@FXML
public void loadFile(ActionEvent event) {
    Node source = (Node) event.getSource();
    Window theStage = source.getScene().getWindow();
    //set fileChooser filter
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("MP3 files", "*.mp3");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Select MP3 files");
    //File file = fileChooser.showOpenDialog(theStage);
    //mySong = new Song(file);
    list = fileChooser.showOpenMultipleDialog(theStage);
    if(list!=null){
        for(File x: list) {
            mySong = new Song(x);
        }
    }
    label.setText(mySong.getTitle());
}

In the last line I am testing if the metadata was retrieved correctly and it is always null. I have the label to be set as initially to say "test" so I would know if it was making any changes and it does, but not to what I want.

Body:
As per the documentation (my emphasis):

Information about the media such as duration, metadata, tracks, and video resolution may be obtained from a Media instance. The media information is obtained asynchronously and so not necessarily available immediately after instantiation of the class. All information should however be available if the instance has been associated with a MediaPlayer and that player has transitioned to MediaPlayer.Status.READY status. To be notified when metadata or Tracks are added, observers may be registered with the collections returned by getMetadata()and getTracks(), respectively.

So you can do something like this:

public Song(File file) {
    music = new Media(file.toURI().toString());

    music.getMetadata().addListener((Change<? extends String, ? extends Object> c) -> {
        if (c.wasAdded()) {
            if ("artist".equals(c.getKey())) {
                artist = c.getValueAdded().toString();
            } else if ("title".equals(c.getKey())) {
                title = c.getValueAdded().toString();
            } else if ("album".equals(c.getKey())) {
                album = c.getValueAdded().toString();
            }
        }
    });

    mp = new MediaPlayer(music);

}


问:
How to preview a file on the server in JBoss
I need some ideas on how I can best solve this problem.

I have a JBoss Seam application running on JBoss 4.3.3
What a small portion of this application does is generate an html and a pdf document based on an Open Office template.

The files that are generated I put inside /tmp/ on the filesystem.
I have tried with System.getProperties("tmp.dir") and some other options, and they always return $JBOSS_HOME/bin
I would like to choose the path $JBOSS_HOME/$DEPLOY/myEAR.ear/myWAR.war/WhateverLocationHere/

However, I don't know how I can programatically choose path without giving an absolute path, or setting $JBOSS_HOME and $DEPLOY.

```Anybody know how I can do this?```

The second question;
I want to easily preview these generated files. Either through JavaScript, or whatever is the easiest way. However, JavaScript cannot access the filesystem on the server, so I cannot open the file through JavaScript.

```Any easy solutions out there?```

答:
First, most platforms use java.io.tmpdir to set a temporary directory. Some servlet containers redefine this property to be something underneath their tree. Why do you care where the file gets written?

Second, I agree with Nicholas: After generating the PDF on the server side, you can generate a URL that, when clicked, sends the file to the browser. If you use MIME type application/pdf, the browser should do the right thing with it.

OwnerDisplayName: Shervin

ContentLicense: CC BY-SA 2.5

Body:
I need some ideas on how I can best solve this problem.

I have a JBoss Seam application running on JBoss 4.3.3
What a small portion of this application does is generate an html and a pdf document based on an Open Office template.

The files that are generated I put inside /tmp/ on the filesystem.
I have tried with System.getProperties("tmp.dir") and some other options, and they always return $JBOSS_HOME/bin
I would like to choose the path $JBOSS_HOME/$DEPLOY/myEAR.ear/myWAR.war/WhateverLocationHere/

However, I don't know how I can programatically choose path without giving an absolute path, or setting $JBOSS_HOME and $DEPLOY.

Anybody know how I can do this?

The second question;
I want to easily preview these generated files. Either through JavaScript, or whatever is the easiest way. However, JavaScript cannot access the filesystem on the server, so I cannot open the file through JavaScript.

Any easy solutions out there?

OwnerDisplayName: Brian Clapper


问:
Get request to Google Search
I'm trying to get HTML with search results from Google. With sending GET request for example to:

```<code>https://www.google.ru/?q=1111
</code>```

But if in browser all is ok, when I'm trying to use it with curl or to get source with "View source" in Google, there is only some Javascript code, no search result. Is that some type of protection? What can I do?

答:
To add a bit more sauce to the answers as they are not correct and do not even respond to your problem.

First of all, it's perfectly legal to scrape Google as long as you do not harm their service through it (DoS-like).

Also the methods have not been blocked, it's just not that simple.

The speed depends on your methods, it does not have to be very slow..

You can scrape ten thousands of keyword pages in a minute if needed.

You will find a better answer to the topic here:    Is it ok to scrape data from Google results?

Your problem with curl comes indeed from protection, Google does not allow automated access and it has a very sophisticated set of detection algorithms.

They go from simple user agent checks (that's what stopped you directly) up to artificial intelligence that tries to detect unusual queries or related queries.

Title: Get request to Google Search

Body:
I'm trying to get HTML with search results from Google. With sending GET request for example to:

https://www.google.ru/?q=1111

But if in browser all is ok, when I'm trying to use it with curl or to get source with "View source" in Google, there is only some Javascript code, no search result. Is that some type of protection? What can I do?


问:
How to access a request parameter in EL
I'd like to check values of a request parameter in EL.

Supposing to have an url like page.jsp?par1=test I've tried something like:

```<code><c:if test='{"test".equals(par1)} >
    [...]
</c:if>
</code>```

But I've had no success.

So, how can I access a request parameter in EL?

答:
Try something like this : </p>

```<code><c:set var="test" value="yourValue"/>
<c:if test="${test==param.par1}">
  do what you want
</c:if>
</code>```

Title: How to access a request parameter in EL

Body:
I'd like to check values of a request parameter in EL.

Supposing to have an url like page.jsp?par1=test I've tried something like:

<c:if test='{"test".equals(par1)} >
    [...]
</c:if>

But I've had no success.

So, how can I access a request parameter in EL?

Body:
Try something like this :

<c:set var="test" value="yourValue"/>
<c:if test="${test==param.par1}">
  do what you want
</c:if>


问:
Assembly fill array with Consecutive numbers
I have problem with simple array in Assembly. Is that correct approach. I need to fill up array with consectuive numbers, in this case it is 10. Code as follow:

```<code>section .data
array TIMES 10 db 0

section .text
global _start
_start:
mov eax,10  ;counter
mov ebx,0   ;start from value 0
mov ecx,array;

loop:
mov [ecx],ebx
inc ecx     ;increase pointer to next array element
inc ebx     ;increase inputted value
dec eax     ;decrease iterator
jnz loop    ;if iterator not 0 loop

mov eax,1   ;eit
int 0x80
</code>```

Is that correct code?

While debuging using gdb. Breakpoint on line 11 (5 loop) show following outputs:

```<code>$1: $eax = 4
$2: $ebx = 6
$3: $ecx = 134516902

x/d $ecx-1   0x80490a5:   5
</code>```

How can i lookup for values from entire array? Only this place in me $ecx-1 shows correct value of inputed number. I am almost sure that I the issue is my code.

Kind Regards

答:
Sorry, I didn't realize until now that my last answered was not what you asked. Assumes byte size elements.

```<code>section .bss
        array:   resb 10
section .data

section .text
        global _start
_start:
        lea edi, [array]    ; pointer
        mov ecx, 0   ; element counter
        mov eax, 1   ; starting number
loop:
        mov [edi+ecx], eax   ; mov n to array element x

        add ecx, 1
        add eax, 1
        cmp eax, 10
        jl loop

_exit:
        mov eax,1
</code>```

output: (gdb) x/8b &array

```<code>0x80490a8 <array>:      1       2       3       4       5       6       0       0
21              cmp eax, 10
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       0       0
22              jl loop
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       0       0
17              mov [esi+ecx], eax
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
19              add ecx, 1
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
20              add eax, 1
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
21              cmp eax, 10
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
22              jl loop
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
17              mov [esi+ecx], eax
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       8
</code>```

Body:
I have problem with simple array in Assembly. Is that correct approach. I need to fill up array with consectuive numbers, in this case it is 10. Code as follow:

section .data
array TIMES 10 db 0

section .text
global _start
_start:
mov eax,10  ;counter
mov ebx,0   ;start from value 0
mov ecx,array;

loop:
mov [ecx],ebx
inc ecx     ;increase pointer to next array element
inc ebx     ;increase inputted value
dec eax     ;decrease iterator
jnz loop    ;if iterator not 0 loop

mov eax,1   ;eit
int 0x80

Is that correct code?

While debuging using gdb. Breakpoint on line 11 (5 loop) show following outputs:

$1: $eax = 4
$2: $ebx = 6
$3: $ecx = 134516902

x/d $ecx-1   0x80490a5:   5

How can i lookup for values from entire array? Only this place in me $ecx-1 shows correct value of inputed number. I am almost sure that I the issue is my code.

Kind Regards

Body:
Sorry, I didn't realize until now that my last answered was not what you asked. Assumes byte size elements.

section .bss
        array:   resb 10
section .data

section .text
        global _start
_start:
        lea edi, [array]    ; pointer
        mov ecx, 0   ; element counter
        mov eax, 1   ; starting number
loop:
        mov [edi+ecx], eax   ; mov n to array element x

        add ecx, 1
        add eax, 1
        cmp eax, 10
        jl loop

_exit:
        mov eax,1

output: (gdb) x/8b &array

0x80490a8 <array>:      1       2       3       4       5       6       0       0
21              cmp eax, 10
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       0       0
22              jl loop
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       0       0
17              mov [esi+ecx], eax
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
19              add ecx, 1
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
20              add eax, 1
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
21              cmp eax, 10
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
22              jl loop
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       0
17              mov [esi+ecx], eax
(gdb)
0x80490a8 <array>:      1       2       3       4       5       6       7       8


问:
SQL, OR AND STATEMENT
Does the AND Statement after the OR statement have the same logic as something similar to

```<code>where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
IF d.status  IN ('R','D')
  t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
  d.status = 'C'
</code>```

Which one is the correct way to format it?

I'm trying to display all d.status with the 'C' status. But only if the t.done_dt is the previous month, do I want to display d.status IN ('R', 'D')

答:
I guess you want to translate this pseudo code into SQL?

```<code>where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
AND
 IF d.status  IN ('R','D')
     t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
     d.status = 'C'
</code>```

That would be:

```<code>where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
AND (    ( d.status = 'C' )  -- SHOW ALL 'C'
      OR ( d.status  IN ('R','D') and t.done_dt = DATEADD(month, -1, GETDATE()) )
                             -- SHOW ALL R,D on that date
    )
</code>```

Title: SQL, OR AND STATEMENT

Body:
Does the AND Statement after the OR statement have the same logic as something similar to

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
IF d.status  IN ('R','D')
  t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
  d.status = 'C'

Which one is the correct way to format it?

I'm trying to display all d.status with the 'C' status. But only if the t.done_dt is the previous month, do I want to display d.status IN ('R', 'D')

Body:
I guess you want to translate this pseudo code into SQL?

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
AND
 IF d.status  IN ('R','D')
     t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
     d.status = 'C'

That would be:

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
AND (    ( d.status = 'C' )  -- SHOW ALL 'C'
      OR ( d.status  IN ('R','D') and t.done_dt = DATEADD(month, -1, GETDATE()) )
                             -- SHOW ALL R,D on that date
    )


问:
Writing to a binary file python
I want to write something to a binary file using python.

I am simply doing:

```<code>import numpy as np

f = open('binary.file','wb')
i=4
j=5.55
f.write('i'+'j') #where do i specify that i is an integer and j is a double?

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second
</code>```

The output is just:
[] []

I know it is very easy to do this in Matlab "fwrite(binary.file, i, 'int32');", but I want to do it in python.

答:
That's because you are trying to write a string(edited) into a binary file.  You also don't close the file before trying to read it again.

If you want to write ints or strings to a binary file try adding the below code:

```<code>import numpy as np
import struct

f = open('binary.file','wb')
i = 4
if isinstance(i, int):
    f.write(struct.pack('i', i)) # write an int
elif isinstance(i, str):
    f.write(i) # write a string
else:
    raise TypeError('Can only write str or int')

f.close()

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second
</code>```

I'll leave it to you to figure out the floating number.

print first, second

[4] []

The more pythonic file handler way:

```<code>import numpy as np
import struct

with open ('binary.file','wb') as f:
    i = 4
    if isinstance(i, int):
        f.write(struct.pack('i', i)) # write an int
    elif isinstance(i, str):
        f.write(i) # write a string
    else:
        raise TypeError('Can only write str or int')

with open('binary.file','rb') as g:
    first = np.fromfile(g,dtype=np.uint32,count = 1)
    second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second
</code>```

Title: Writing to a binary file python

Body:
I want to write something to a binary file using python.

I am simply doing:

import numpy as np

f = open('binary.file','wb')
i=4
j=5.55
f.write('i'+'j') #where do i specify that i is an integer and j is a double?

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second

The output is just:
[] []

I know it is very easy to do this in Matlab "fwrite(binary.file, i, 'int32');", but I want to do it in python.

Body:
That's because you are trying to write a string(edited) into a binary file.  You also don't close the file before trying to read it again.

If you want to write ints or strings to a binary file try adding the below code:

import numpy as np
import struct

f = open('binary.file','wb')
i = 4
if isinstance(i, int):
    f.write(struct.pack('i', i)) # write an int
elif isinstance(i, str):
    f.write(i) # write a string
else:
    raise TypeError('Can only write str or int')

f.close()

g = open('binary.file','rb')
first = np.fromfile(g,dtype=np.uint32,count = 1)
second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second

I'll leave it to you to figure out the floating number.

print first, second

[4] []

The more pythonic file handler way:

import numpy as np
import struct

with open ('binary.file','wb') as f:
    i = 4
    if isinstance(i, int):
        f.write(struct.pack('i', i)) # write an int
    elif isinstance(i, str):
        f.write(i) # write a string
    else:
        raise TypeError('Can only write str or int')

with open('binary.file','rb') as g:
    first = np.fromfile(g,dtype=np.uint32,count = 1)
    second = np.fromfile(g,dtype=np.float64,count = 1)

print first, second


问:
Why cherrypick merge?
What's the point of cherrypick merging. Why don't you just merge the whole thing. Cherrypick merging seems risky like what happens if you pick the wrong commit or only pick some of the commits surely it's just safer to merge normally (sync merge then do a reintegrate merge) instead of doing a sync merge and then

svn merge -c 12 ^/project_name/branches/3 OR a range of commits

svn merge -r 12:100 ^/project_name/branches/3

in the trunk and or other branches which will be released

What are the benefits of cherrypick merging in comparison to normal reintegrate merging? - It seems more risky and more work to do cherrypick merging.

答:
If you can do a normal reintegrate merge then do so.

Cherrypicking is for when you can't.

For instance, a bug is found in the current release.  You fix it in the trunk, then it's decided that you need to get it out quicker than the next release.

You can't reintegrate trunk back to the release branch, so you cherry pick the commits that make up that particular fix.

Title: Why cherrypick merge?


问:
Angular 2 drag and drop upload
I'm trying to implement a drag and drop upload for angular 2 that is similar to this:
http://bootsnipp.com/snippets/featured/bootstrap-drag-and-drop-upload

Since I'm using angular 2 I want to use typescript rather than jquery. I found a library called ng2-file-upload and I tried to implement the drag and drop functionality; however, I can't seem to get it to work. This is what I have:

Upload.component.ts

```<code>Component({
  selector: 'upload',
  templateUrl: 'app/components/upload/upload.component.html',
  styleUrls: ['app/components/upload/upload.component.css'],
providers: [ UploadService ]
})
export class UploadComponent {

public uploader:FileUploader = new FileUploader({url: URL});
    public hasBaseDropZoneOver:boolean = false;
    public hasAnotherDropZoneOver:boolean = false;

    public fileOverBase(e:any):void {
        this.hasBaseDropZoneOver = e;
    }

    public fileOverAnother(e:any):void {
        this.hasAnotherDropZoneOver = e;
    }
}
</code>```

upload.component.html

```<code><section id="dropzone">
    <div class="panel panel-default">

        <div class="panel-body">

            <!-- Standar Form -->
            <h4>Select files from your computer</h4>
            <br>
            <form  enctype="multipart/form-data" id="js-upload-form">
                <div class="form-inline">
                    <div class="form-group">
                        <input type="file" name="files[]" multiple (change)="fileChangeEvent($event)">
                    </div>
                    <button type="submit" class="btn btn-sm btn-primary"  (click)="upload()">Upload files</button>
                </div>
            </form>
</div>
    </div>

            <!-- Drop Zone -->
            <h4>Or drag and drop files below</h4>
        <br>
            <!--<div class="upload-drop-zone" id="drop-zone">-->
                <!--Just drag and drop files here-->
            <!--</div>-->
        <div ng2FileDrop
             [ngClass]="{'another-file-over-class': hasBaseDropZoneOver}"
             (fileOver)="fileOverBase($event)"
             class="well upload-drop-zone">
            Drop Files Here
        </div>
    </section>
</code>```

upload.component.css

```<code>.upload-drop-zone {
    color: #ccc;
    border-style: dashed;
    border-color: #ccc;
    line-height: 200px;
    text-align: center
}
.another-file-over-class {
    border: dashed 3px green;
}
</code>```

答:
I think you are missing to bind uploader in html.

```<code><div ng2FileDrop
     [ngClass]="{'another-file-over-class': hasBaseDropZoneOver}"
     (fileOver)="fileOverBase($event)"
     [uploader]="uploader"
     class="well upload-drop-zone">
     Drop Files Here
</div>
</code>```

Title: Angular 2 drag and drop upload

Body:
I'm trying to implement a drag and drop upload for angular 2 that is similar to this:
http://bootsnipp.com/snippets/featured/bootstrap-drag-and-drop-upload

Since I'm using angular 2 I want to use typescript rather than jquery. I found a library called ng2-file-upload and I tried to implement the drag and drop functionality; however, I can't seem to get it to work. This is what I have:

Upload.component.ts

Component({
  selector: 'upload',
  templateUrl: 'app/components/upload/upload.component.html',
  styleUrls: ['app/components/upload/upload.component.css'],
providers: [ UploadService ]
})
export class UploadComponent {

public uploader:FileUploader = new FileUploader({url: URL});
    public hasBaseDropZoneOver:boolean = false;
    public hasAnotherDropZoneOver:boolean = false;

    public fileOverBase(e:any):void {
        this.hasBaseDropZoneOver = e;
    }

    public fileOverAnother(e:any):void {
        this.hasAnotherDropZoneOver = e;
    }
}

upload.component.html

Select files from your computer

            <form  enctype="multipart/form-data" id="js-upload-form">

                        <input type="file" name="files[]" multiple (change)="fileChangeEvent($event)">

                    <button type="submit" class="btn btn-sm btn-primary"  (click)="upload()">Upload files</button>

            </form>

Or drag and drop files below

            Drop Files Here

upload.component.css

.upload-drop-zone {
    color: #ccc;
    border-style: dashed;
    border-color: #ccc;
    line-height: 200px;
    text-align: center
}
.another-file-over-class {
    border: dashed 3px green;
}

Body:
I think you are missing to bind uploader in html.

<div ng2FileDrop
     [ngClass]="{'another-file-over-class': hasBaseDropZoneOver}"
     (fileOver)="fileOverBase($event)"
     [uploader]="uploader"
     class="well upload-drop-zone">
     Drop Files Here
</div>


问:
Node.js each in each with handlebars, no template
Both of my #each loops work when they are written separately, but when together, the table body of my web-page is blank. What am I doing wrong?</p>

```<code><table class="table" class="text-center">
    <thead>
        <tr>
            <th>Surname</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        {{#each surnames as |surname|}}
            {{#each names as |name|}}
            <tr>
                <td>{{surname}}</td>
                <td>{{name}}</td>
            </tr>
            {{/each}}
        {{/each}}
    </tbody>
</table>
</code>```

答:
The context of your second loop is changed when it's nested. Use ../ to access the parent scope.

```<code><table class="table" class="text-center">
    <thead>
        <tr>
            <th>Surname</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        {{#each surnames as |surname|}}
            {{#each ../names as |name|}}
            <tr>
                <td>{{surname}}</td>
                <td>{{name}}</td>
            </tr>
            {{/each}}
        {{/each}}
    </tbody>
</table>
</code>```

Body:
Both of my #each loops work when they are written separately, but when together, the table body of my web-page is blank. What am I doing wrong?

            Surname
            Name

        {{#each surnames as |surname|}}
            {{#each names as |name|}}

                {{surname}}
                {{name}}

            {{/each}}
        {{/each}}

Body:
The context of your second loop is changed when it's nested. Use ../ to access the parent scope.

<table class="table" class="text-center">
    <thead>
        <tr>
            <th>Surname</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        {{#each surnames as |surname|}}
            {{#each ../names as |name|}}
            <tr>
                <td>{{surname}}</td>
                <td>{{name}}</td>
            </tr>
            {{/each}}
        {{/each}}
    </tbody>
</table>


问:
MySQL where subselect on multiple fields
I'm trying to do a single MySQL query to select data inside a third party function, the problem I have however they only pass me the ID.  I need to use that ID to select all the related records.

Currently the MySQL statement looks something like this:

```<code>SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h, details d
WHERE h.host_id = (SELECT host_id FROM headers WHERE id = '{$rowid}')
AND h.service_id = (SELECT service_id FROM headers WHERE id = '{$rowid}')
AND h.instance = (SELECT instance from headers where id = '{$rowid}')
AND h.id = d.header_id;
</code>```

Now this works, but I'm thinking the poor MySQL engine is running 3 subqueries because I don't have 3 pieces of information available to me.

So I was wondering if there a way to run this with one query and one subquery to save the load on the database?

Thanks in advance.

答:
You can use SELF JOIN to remove the multiple sub-queries.

Try this:

```<code>SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h
INNER JOIN details d ON h.id = d.header_id
INNER JOIN headers h2 ON h.host_id = h2.host_id AND h.service_id = h2.service_id AND h.instance = h2.instance
WHERE h2.id = '{$rowid}'
</code>```

Body:
I'm trying to do a single MySQL query to select data inside a third party function, the problem I have however they only pass me the ID.  I need to use that ID to select all the related records.

Currently the MySQL statement looks something like this:

SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h, details d
WHERE h.host_id = (SELECT host_id FROM headers WHERE id = '{$rowid}')
AND h.service_id = (SELECT service_id FROM headers WHERE id = '{$rowid}')
AND h.instance = (SELECT instance from headers where id = '{$rowid}')
AND h.id = d.header_id;

Now this works, but I'm thinking the poor MySQL engine is running 3 subqueries because I don't have 3 pieces of information available to me.

So I was wondering if there a way to run this with one query and one subquery to save the load on the database?

Thanks in advance.

Body:
You can use SELF JOIN to remove the multiple sub-queries.

Try this:

SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h
INNER JOIN details d ON h.id = d.header_id
INNER JOIN headers h2 ON h.host_id = h2.host_id AND h.service_id = h2.service_id AND h.instance = h2.instance
WHERE h2.id = '{$rowid}'


问:
Linker error when including header in files other than main.cpp
I'm trying to add some utility functions and global variables to my code in such a way that I can be able to use them in every class I want in my project. I would like to use a .hpp file for the definitions end a .cpp file for the implementation.

This is a summary of these two files:

```<code>// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp

namespace utils {

    int global_variable1;

    int global_variable2;

    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */
</code>```

and the implementation:

```<code>// This is Utilities.cpp
#include "Utilities.hpp"

namespace utils {

    void utility_function1(...) {
        // Some code
    }

    void utility_function2(...) {
        // Some code
    }

    void utility_function3(...) {
        // Some code
    }

}
</code>```

Other than my main.cpp file I have two other classes. My main.cpp file includes Class1.hpp header that includes Class2.hpp header.

Now I thought that I could put another #include "Utilities.hpp" in Class1.hpp or Class2.hpp without any problems since I've used the guards in that header. The thing is that when I try to do that the linker throws me this error: Apple Mach-O Linker (ld) Error Group - clang: error: linker command failed with exit code 1 (use -v to see invocation) and I can't understand why or what to do to solve it.

I'm using Xcode 8.3 on a macOS Sierra 10.12.4.

I hope I was able to explain my problem, thank you all very much in advance.

答:
You're missing the extern keyword on your global variables in your header.  As a result, you're defining them, which results in multiple definitions when you include the header in two different source modules.

Once you add the extern in the header file (extern int global_variable1;), you'll need to add the definition in your .cpp file where you also define your functions.

Body:
I'm trying to add some utility functions and global variables to my code in such a way that I can be able to use them in every class I want in my project. I would like to use a .hpp file for the definitions end a .cpp file for the implementation.

This is a summary of these two files:

// This is Utilities.hpp
#ifndef utilities_hpp
#define utilities_hpp

namespace utils {

    int global_variable1;

    int global_variable2;

    void utility_function1(...);

    void utility_function2(...);

    void utility_function3(...);
}

#endif /* utilities_hpp */

and the implementation:

// This is Utilities.cpp
#include "Utilities.hpp"

namespace utils {

    void utility_function1(...) {
        // Some code
    }

    void utility_function2(...) {
        // Some code
    }

    void utility_function3(...) {
        // Some code
    }

}

Other than my main.cpp file I have two other classes. My main.cpp file includes Class1.hpp header that includes Class2.hpp header.

Now I thought that I could put another #include "Utilities.hpp" in Class1.hpp or Class2.hpp without any problems since I've used the guards in that header. The thing is that when I try to do that the linker throws me this error: Apple Mach-O Linker (ld) Error Group - clang: error: linker command failed with exit code 1 (use -v to see invocation) and I can't understand why or what to do to solve it.

I'm using Xcode 8.3 on a macOS Sierra 10.12.4.

I hope I was able to explain my problem, thank you all very much in advance.


问:
Excel VBA event to calculate based on user input
To preface the situation, I am new to VBA programming so any help would be greatly appreciated.

I have two columns; one where the user can input a dollar value ("AL") and another where the user can input a percent value ("AK"). The object is to enable the user to input either value (% or $) and have the other value calculate. For instance, if the user inputs 10% in "AL", the applicable $ value will generate in "AK" and vice versa.

Below is the code I've come up with thus far but it isn't working. Any thoughts/suggestions would be greatly appreciated! Thank you!

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   'Application.EnableEvents = False Application.EnableEvents = True'

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value
        Exit Sub
    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value
        Exit Sub
    'Application.EnableEvents = False Application.EnableEvents = True'
    End If
  End If
End Sub
</code>```

答:
You need to remove the Exit Subs

And the Application.EnableEvents = True needs to be outside the if.

The first time you ran it with the Application.EnableEvents = False line enabled it turned off the events and since you exited the sub before turning them back on it stayed off and the sub was never called again.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   Application.EnableEvents = False

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value

    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value

    End If
    Application.EnableEvents = True
  End If
End Sub
</code>```

My guess is right now your events are disabled.

Run this code after putting the correct code above in your sheet:

```<code>Sub foooo()
Application.EnableEvents = True
End Sub
</code>```

This will turn the events back on.  It is only needed once.

Body:
To preface the situation, I am new to VBA programming so any help would be greatly appreciated.

I have two columns; one where the user can input a dollar value ("AL") and another where the user can input a percent value ("AK"). The object is to enable the user to input either value (% or $) and have the other value calculate. For instance, if the user inputs 10% in "AL", the applicable $ value will generate in "AK" and vice versa.

Below is the code I've come up with thus far but it isn't working. Any thoughts/suggestions would be greatly appreciated! Thank you!

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   'Application.EnableEvents = False Application.EnableEvents = True'

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value
        Exit Sub
    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value
        Exit Sub
    'Application.EnableEvents = False Application.EnableEvents = True'
    End If
  End If
End Sub

Body:
You need to remove the Exit Subs

And the Application.EnableEvents = True needs to be outside the if.

The first time you ran it with the Application.EnableEvents = False line enabled it turned off the events and since you exited the sub before turning them back on it stayed off and the sub was never called again.

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   Application.EnableEvents = False

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value

    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value

    End If
    Application.EnableEvents = True
  End If
End Sub

My guess is right now your events are disabled.

Run this code after putting the correct code above in your sheet:

Sub foooo()
Application.EnableEvents = True
End Sub

This will turn the events back on.  It is only needed once.


问:
jQuery - How to pass 'this' to a function?
How do I pass $(this) into a function. In my example below I want to populate the address textbox with the value of the selected drop-down option label but only if the value selected is not empty.

The following doesn't work?

$("#AddressId").change(function () {
  $("#Address").val(function(index, val) {
      val = $(this).val();
      return val === "" ? "" : $('option:selected', this).text();
  }, this).trigger("change");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="AddressId">
 <option value="">-- Please select --</option>
 <option value="1">xyz street</option>
 ...
</select>

<input id="Address" name="Address" value="" type="text"></code>```

答:
I bet you have just overcomplicated it.

$("#AddressId").change(function() {
  if ($(this).val()) {
    $('#Address').val($(this).find('option:selected').text());
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
   <option value="">-- Please select --</option>
   <option value="1">xyz street</option>
   ...
 </select>

<input id="Address" name="Address" value="" type="text"></code>```

Body:
How do I pass $(this) into a function. In my example below I want to populate the address textbox with the value of the selected drop-down option label but only if the value selected is not empty.

The following doesn't work?

$("#AddressId").change(function () {
  $("#Address").val(function(index, val) {
      val = $(this).val();
      return val === "" ? "" : $('option:selected', this).text();
  }, this).trigger("change");
});

<select id="AddressId">
 <option value="">-- Please select --</option>
 <option value="1">xyz street</option>
 ...
</select>

<input id="Address" name="Address" value="" type="text">

Body:
I bet you have just overcomplicated it.

$("#AddressId").change(function() {
  if ($(this).val()) {
    $('#Address').val($(this).find('option:selected').text());
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="AddressId">
   <option value="">-- Please select --</option>
   <option value="1">xyz street</option>
   ...
 </select>

<input id="Address" name="Address" value="" type="text">


问:
Why $scope is not defined here in the following code
I am working with Angular 1.x and here is the code which was giving errors:-

```<code><!DOCTYPE html>
 <html>
  <head>
    <title>Angular JS Controllers</title>
  </head>
  <body>
    <div ng-app="app">
      <h1>Controllers</h1>
       <div ng-controller="MainCtrl">
         <p>{{message}}</p>
       </div>
     </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
    <script type="text/javascript">
      angular.module('app', [])
         .controller('MainCtrl', [$scope, function($scope){
           $scope.message = "Hello";
         }]);
    </script>
   </body>
  </html>
</code>```

It was giving error ReferenceError: $scope is not defined

I thought may be $scope is not getting injected then I addded a dependency of $scope in the array to the 'app' module like this :-

```<code>angular.module('app', [$scope])
</code>```

but to no avail. But what worked was the following code:-

```<code> <!DOCTYPE html>
 <html>
  <head>
    <title>Angular JS Controllers</title>
  </head>
  <body>
    <div ng-app="app">
      <h1>Controllers</h1>
       <div ng-controller="MainCtrl as ctrl">
         <p>{{ctrl.message}}</p>
       </div>
     </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
    <script type="text/javascript">
      angular.module('app', [])
         .controller('MainCtrl', [function(){
           this.message = "Hello";
         }]);
    </script>
   </body>
  </html>
</code>```

I am referring the message model in HTML using ctrl.messaage, only then its appearing not otherwise.But why!!

Why can't I use $scope here, if I can how!!
/
Basically what is the difference between this and the earlier code?

答:
it shoulde be like this.

```<code>angular.module('app', [])
     .controller('MainCtrl', ["$scope", function($scope){
       $scope.message = "Hello";
     }]);
</code>```

and it's better use controllerAs syntax

```<code>angular.module('app', [])
     .controller('MainCtrl', ["$scope", function($scope){
      var vm = this;
       vm.message = "Hello";
     }]);
</code>```

and in view use

```<code>  <div ng-controller="MainCtrl as ctrl">
</code>```

Body:
I am working with Angular 1.x and here is the code which was giving errors:-

<!DOCTYPE html>

    <title>Angular JS Controllers</title>

Controllers

{{message}}

It was giving error ReferenceError: $scope is not defined

I thought may be $scope is not getting injected then I addded a dependency of $scope in the array to the 'app' module like this :-

angular.module('app', [$scope])

but to no avail. But what worked was the following code:-

 <!DOCTYPE html>

    <title>Angular JS Controllers</title>

Controllers

{{ctrl.message}}

I am referring the message model in HTML using ctrl.messaage, only then its appearing not otherwise.But why!!

Why can't I use $scope here, if I can how!!
/
Basically what is the difference between this and the earlier code?

Body:
it shoulde be like this.

angular.module('app', [])
     .controller('MainCtrl', ["$scope", function($scope){
       $scope.message = "Hello";
     }]);

and it's better use controllerAs syntax

angular.module('app', [])
     .controller('MainCtrl', ["$scope", function($scope){
      var vm = this;
       vm.message = "Hello";
     }]);

and in view use

  <div ng-controller="MainCtrl as ctrl">


答:
You could simply add a condition selected_value != "" then assign the selected value if isn't empty :

```<code>$("#AddressId").change(function () {
    var selected_value = $(this).val();

    if( selected_value != ""){
        $("#Address").val( selected_value );
   }
});
</code>```

Hope this helps.

$("#AddressId").change(function () {
  var selected_value = $(this).val();

  if( selected_value != ""){
      $("#Address").val( selected_value );
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="AddressId">
 <option value="">-- Please select --</option>
 <option value="1">xyz street</option>
 <option value="2">abc street</option>
 <option value="3">def street</option>
</select>

<input id="Address" name="Address" value="" type="text"></code>```

Title: jQuery - How to pass 'this' to a function?

Body:
You could simply add a condition selected_value != "" then assign the selected value if isn't empty :

$("#AddressId").change(function () {
    var selected_value = $(this).val();

    if( selected_value != ""){
        $("#Address").val( selected_value );
   }
});

Hope this helps.

$("#AddressId").change(function () {
  var selected_value = $(this).val();

  if( selected_value != ""){
      $("#Address").val( selected_value );
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="AddressId">
 <option value="">-- Please select --</option>
 <option value="1">xyz street</option>
 <option value="2">abc street</option>
 <option value="3">def street</option>
</select>

<input id="Address" name="Address" value="" type="text">


问:
Can I use SQL Server Management Studio Express to connect to an MSDE database?
Is it possible to use SQL Server Management Studio Express 2005 to connect to an MSDE database?</p>

答: Yes you can. You can use SQL Server Management Studio Express 2008 also.</p>


答:
When using an array as the second argument of the controller-method you have to use strings as values. This allows you to rename dependency modules.</p>

```<code>    <script type="text/javascript">
      angular.module('app', [])
         .controller('MainCtrl', ["$scope", function($scope){
           $scope.message = "Hello";
         }]);
    </script>
</code>```

Title: Why $scope is not defined here in the following code

Body:
When using an array as the second argument of the controller-method you have to use strings as values. This allows you to rename dependency modules.

    <script type="text/javascript">
      angular.module('app', [])
         .controller('MainCtrl', ["$scope", function($scope){
           $scope.message = "Hello";
         }]);
    </script>


答:
Try something like this</p>

```<code>angular.module('app', [])
     .controller('MainCtrl', ['$scope', function($scope){
       $scope.message = "Hello";
     }]);
</code>```

Body:
Try something like this

angular.module('app', [])
     .controller('MainCtrl', ['$scope', function($scope){
       $scope.message = "Hello";
     }]);


问:
Keystone js: Is there way to remove Manage button from one of the model?
I want to remove mange button from one of my model. I am able to remove from all the model by making code changes in ListManagement.js file but not able to remove from single one . Is there any solution for this.</p>

答:
You can set the properties of your model to be uneditable and undeletable. This prevents anyone from you (or anyone with access to the code & your database connection information) from editing properties of a model, or entire models, that you don't want them to. It's a better solution than removing the ability to manage all models entirely. If you want to prevent users from editing all of your models, just set the below options.

noedit - (Boolean) Prevents editing of items in the list through the Keystone Admin UI

nocreate - (Boolean) Prevents creation of new items in the list through the Keystone Admin UI

nodelete - (Boolean) Prevents deletion of items from the list through the Keystone Admin UI

hidden - (Boolean) Hides the list in the Keystone Admin UI

http://keystonejs.com/docs/database/#lists-options

These options are specified upon model creation, and can be enabled per-model.


问:
VBScript Error '80040211' when sending emails
I have an error when sending emails:
"error '80040211' "

Here's an example of my code-

```<code>Dim objMessage
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Super Service Comment - "

objMessage.From = "someone@s.com"
objMessage.To = "someone1@s.zendesk.com;someone2@s.com"
objMessage.TextBody = "Name...."

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.office365.com" 'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'Type of authentication, NONE, Basic (Base64 encoded), NTLM
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "someone4@s.com" 'Your UserID on the SMTP server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "******" 'Your password on the SMTP server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'Server port (typically 25)
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true 'Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Update
objMessage.Send
</code>```

Someone worked with a similar problem?

答: I had the same error, so I've configured my Gmail settings, activeted two steps authentication and created a new app password, just for CDOsys. And it works like a charm.</p>

Body:
I have an error when sending emails:
"error '80040211' "

Here's an example of my code-

Dim objMessage
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Super Service Comment - "

objMessage.From = "someone@s.com"
objMessage.To = "someone1@s.zendesk.com;someone2@s.com"
objMessage.TextBody = "Name...."

objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.office365.com" 'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'Type of authentication, NONE, Basic (Base64 encoded), NTLM
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "someone4@s.com" 'Your UserID on the SMTP server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "******" 'Your password on the SMTP server
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'Server port (typically 25)
objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true 'Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Update
objMessage.Send

Someone worked with a similar problem?


问:
Libfreenect2 USB connection failure
I have been trying to get the libfreenect2 library up and running on my Windows 10 machine and I have run into an issue that I can't get past. I have build the library and it's examples. The issues I have is when I go to run the "Protonect" example code. The output I get is listed below:

```<code>$ ./install/bin/Protonect.exe
Version: 0.2.0
Environment variables: LOGFILE=<protonect.log>
Usage: U:\Repositories\libfreenect2\build\install\bin\Protonect.exe [-gpu=<id>] [gl | cl | clkde | cuda | cudakde | cpu] [<device serial>]
        [-noviewer] [-norgb | -nodepth] [-help] [-version]
        [-frames <number of frames to process>]
To pause and unpause: pkill -USR1 Protonect
[Info] [Freenect2Impl] enumerating devices...
[Info] [Freenect2Impl] 8 usb devices connected
[Info] [Freenect2Impl] found valid Kinect v2 @12:2 with serial 003370163847
[Info] [Freenect2Impl] found 1 devices
Pipeline Not-Used
libusb_open returned: -99
BLAH BLAH BLAH
[Error] [Freenect2Impl] failed to open Kinect v2: @12:2 LIBUSB_ERROR_OTHER Other error
failure opening device!
</code>```

Please ignore the "BLAH BLAH BLAH" I was using that as print statement debugging. I think I have traced the issue all the way down to this section of the core.c file libusb_open() function in libusb library:

```<code>r = usbi_backend->open(_dev_handle);
    if (r < 0) {
        usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
        libusb_unref_device(dev);
        usbi_mutex_destroy(&_dev_handle->lock);
        free(_dev_handle);
        return r;
    }
</code>```

I couldn't find anything on the error code -99 so that is where my debugging ended. From what I understand it seems that the example code can't open the USB device to the Kinect for some reason.

I have tested the Kinect with Kinect Studio using the windows SDK and that has no problem picking up the Kinect feeds. Has anyone run into this issue before and how did you solve it? Any suggestions for what the error code means or how I might fix the USB opening issue?

答:
The problem ended up solving itself. Through a series of debugging attempts which you can see here:
https://github.com/OpenKinect/libfreenect2/issues/812#issuecomment-288143166

I ended up reinstalling usbdk 1.0.17 and magically everything worked again. Apparently there are some issues with with usbdk 1.0.17 which require it to be reinstalled to fix some of the issues. Idk why, but if anyone comes across this issue in the future, this way my fix.

Title: Libfreenect2 USB connection failure

Body:
I have been trying to get the libfreenect2 library up and running on my Windows 10 machine and I have run into an issue that I can't get past. I have build the library and it's examples. The issues I have is when I go to run the "Protonect" example code. The output I get is listed below:

$ ./install/bin/Protonect.exe
Version: 0.2.0
Environment variables: LOGFILE=<protonect.log>
Usage: U:\Repositories\libfreenect2\build\install\bin\Protonect.exe [-gpu=<id>] [gl | cl | clkde | cuda | cudakde | cpu] [<device serial>]
        [-noviewer] [-norgb | -nodepth] [-help] [-version]
        [-frames <number of frames to process>]
To pause and unpause: pkill -USR1 Protonect
[Info] [Freenect2Impl] enumerating devices...
[Info] [Freenect2Impl] 8 usb devices connected
[Info] [Freenect2Impl] found valid Kinect v2 @12:2 with serial 003370163847
[Info] [Freenect2Impl] found 1 devices
Pipeline Not-Used
libusb_open returned: -99
BLAH BLAH BLAH
[Error] [Freenect2Impl] failed to open Kinect v2: @12:2 LIBUSB_ERROR_OTHER Other error
failure opening device!

Please ignore the "BLAH BLAH BLAH" I was using that as print statement debugging. I think I have traced the issue all the way down to this section of the core.c file libusb_open() function in libusb library:

r = usbi_backend->open(_dev_handle);
    if (r < 0) {
        usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r);
        libusb_unref_device(dev);
        usbi_mutex_destroy(&_dev_handle->lock);
        free(_dev_handle);
        return r;
    }

I couldn't find anything on the error code -99 so that is where my debugging ended. From what I understand it seems that the example code can't open the USB device to the Kinect for some reason.

I have tested the Kinect with Kinect Studio using the windows SDK and that has no problem picking up the Kinect feeds. Has anyone run into this issue before and how did you solve it? Any suggestions for what the error code means or how I might fix the USB opening issue?


答:
You need to add quotes around $scope when you're injecting it into your controller. AngularJS will look at these string variables to determine what it needs to safely inject into your application.

```<code>angular.module('app', [])
    .controller('MainCtrl', ['$scope', function($scope){
        $scope.message = "Hello";
}]);
</code>```

Body:
You need to add quotes around $scope when you're injecting it into your controller. AngularJS will look at these string variables to determine what it needs to safely inject into your application.

angular.module('app', [])
    .controller('MainCtrl', ['$scope', function($scope){
        $scope.message = "Hello";
}]);