问:
Robolectric Unit Testing ClassCastException on Custom Layout
I have "ClassCastException" on Robolectric Unit Testing when I test Activity or Fragment with Custom Layout or Custom Component on an android app.
Example :
CrumbView that extends LinearLayout. When I start a fragment I got an error :
java.lang.ClassCastException: com.app.test.ui.view.CrumbView cannot be cast to com.app.test.ui.view.CrumbView
Does Anyone knows how to fix it? or it's not yet supported by Robolectric?

```<code>java.lang.ClassCastException: com.app.test.ui.view.DrawerView cannot be cast to com.app.test.ui.view.DrawerView

at com.app.test.ui.activity.equipements.EquipementsActivity.onCreate(EquipementsActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6975)
at org.robolectric.util.ReflectionHelpers.callInstanceMethod(ReflectionHelpers.java:232)
at org.robolectric.android.controller.ActivityController$1.run(ActivityController.java:58)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:364)
at org.robolectric.shadows.CoreShadowsAdapter$1.runPaused(CoreShadowsAdapter.java:26)
at org.robolectric.android.controller.ActivityController.create(ActivityController.java:55)
at org.robolectric.android.controller.ActivityController.create(ActivityController.java:65)
at com.app.test.ui.activity.equipements.EquipementsActivityTest.setUp(EquipementsActivityTest.java:24)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:83)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:810)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:675)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.AbstractClassloaderExecutor.getResult(AbstractClassloaderExecutor.java:76)
at org.powermock.classloading.AbstractClassloaderExecutor.invokeWithClassLoader(AbstractClassloaderExecutor.java:64)
at org.powermock.classloading.AbstractClassloaderExecutor.executeWithClassLoader(AbstractClassloaderExecutor.java:56)
at org.powermock.classloading.SingleClassloaderExecutor.execute(SingleClassloaderExecutor.java:33)
at org.powermock.classloading.AbstractClassloaderExecutor.execute(AbstractClassloaderExecutor.java:40)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:75)
at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:226)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:108)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:35)
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.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:62)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:149)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:132)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
</code>```

The Line onCreate(EquipementsActivity.java:61) is pointing :
DrawerView drawerView = findViewById(R.id.drawer);

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_equipements);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    DrawerView drawerView = findViewById(R.id.drawer);
    ActionBarDrawerToggle toggle .......
</code>```

答:
Just add "com.app.test.ui.view." to @PowerMockIgnore for your unit test.
e.g:
@PowerMockIgnore({"org.mockito.", "org.robolectric.", "android.", "com.app.test.ui.view.*"})

Body:
I have "ClassCastException" on Robolectric Unit Testing when I test Activity or Fragment with Custom Layout or Custom Component on an android app.
Example :
CrumbView that extends LinearLayout. When I start a fragment I got an error :
java.lang.ClassCastException: com.app.test.ui.view.CrumbView cannot be cast to com.app.test.ui.view.CrumbView
Does Anyone knows how to fix it? or it's not yet supported by Robolectric?

java.lang.ClassCastException: com.app.test.ui.view.DrawerView cannot be cast to com.app.test.ui.view.DrawerView

at com.app.test.ui.activity.equipements.EquipementsActivity.onCreate(EquipementsActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6975)
at org.robolectric.util.ReflectionHelpers.callInstanceMethod(ReflectionHelpers.java:232)
at org.robolectric.android.controller.ActivityController$1.run(ActivityController.java:58)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:364)
at org.robolectric.shadows.CoreShadowsAdapter$1.runPaused(CoreShadowsAdapter.java:26)
at org.robolectric.android.controller.ActivityController.create(ActivityController.java:55)
at org.robolectric.android.controller.ActivityController.create(ActivityController.java:65)
at com.app.test.ui.activity.equipements.EquipementsActivityTest.setUp(EquipementsActivityTest.java:24)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:83)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:810)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:675)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
at org.powermock.classloading.AbstractClassloaderExecutor.getResult(AbstractClassloaderExecutor.java:76)
at org.powermock.classloading.AbstractClassloaderExecutor.invokeWithClassLoader(AbstractClassloaderExecutor.java:64)
at org.powermock.classloading.AbstractClassloaderExecutor.executeWithClassLoader(AbstractClassloaderExecutor.java:56)
at org.powermock.classloading.SingleClassloaderExecutor.execute(SingleClassloaderExecutor.java:33)
at org.powermock.classloading.AbstractClassloaderExecutor.execute(AbstractClassloaderExecutor.java:40)
at org.powermock.modules.junit4.rule.PowerMockStatement.evaluate(PowerMockRule.java:75)
at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:226)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:108)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:35)
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.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:62)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:149)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:132)
at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:141)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

The Line onCreate(EquipementsActivity.java:61) is pointing :
DrawerView drawerView = findViewById(R.id.drawer);

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_equipements);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    DrawerView drawerView = findViewById(R.id.drawer);
    ActionBarDrawerToggle toggle .......


来源: stackexchange

问:
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") is NOT working
I have the following method to write an XMLDom to a stream:

```<code>public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception {
    fDoc.setXmlStandalone(true);
    DOMSource docSource = new DOMSource(fDoc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.transform(docSource, new StreamResult(out));
}
</code>```

I am testing some other XML functionality, and this is just the method that I use to write to a file.  My test program generates 33 test cases where files are written out.  28 of them have the following header:

```<code><?xml version="1.0" encoding="UTF-8"?>...
</code>```

But for some reason, 1 of the test cases now produce:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>...
</code>```

And four more produce:

```<code><?xml version="1.0" encoding="Windows-1252"?>...
</code>```

As you can clearly see, I am setting ENCODING output key to UTF-8.   These tests used to work on an earlier version of Java.  I have not run the tests in a while (more than a year) but running today on "Java(TM) SE Runtime Environment (build 1.6.0_22-b04)" I get this funny behavior.

I have verified that the documents causing the problem were read from files that originally had those encoding.  It seems that the new versions of the libraries are attempting to preserve the encoding of the source file that was read.  But that is not what I want ... I really do want the output to be in UTF-8.

Does anyone know of any other factor that might cause the transformer to ignore the UTF-8 encoding setting?  Is there anything else that has to be set on the document to say to forget the encoding of the file that was originally read?

UPDATE:

I checked out the same project out on another machine, built and ran the tests there.  On that machine all the tests pass!  All the files have "UTF-8" in their header.  That machine has "Java(TM) SE Runtime Environment (build 1.6.0_29-b11)"   Both machines are running Windows 7.  On the new machine that works correctly, jdk1.5.0_11 is used to make the build, but on the old machine jdk1.6.0_26 is used to make the build.  The libraries used for both builds are exactly the same.  Can it be a JDK 1.6 incompatibility with 1.5 at build time?

UPDATE:

After 4.5 years, the Java library is still broken, but due to the suggestion by Vyrx below, I finally have a proper solution!

```<code>public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception {
    fDoc.setXmlStandalone(true);
    DOMSource docSource = new DOMSource(fDoc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes("UTF-8"));
    transformer.transform(docSource, new StreamResult(out));
}
</code>```

The solution is to disable the writing of the header, and to write the correct header just before serializing the XML to the output steam.   Lame, but it produces the correct results.  Tests broken over 4 years ago are now running again!

答:
I had the same problem on Android when serializing emoji characters.  When using UTF-8 encoding in the transformer the output was HTML character entities (UTF-16 surrogate pairs), which would subsequently break other parsers that read the data.

This is how I ended up solving it:

```<code>StringWriter sw = new StringWriter();
sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
Transformer t = TransformerFactory.newInstance().newTransformer();

// this will work because we are creating a Java string, not writing to an output
t.setOutputProperty(OutputKeys.ENCODING, "UTF-16");
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(elementNode), new StreamResult(sw));

return IOUtils.toInputStream(sw.toString(), Charset.forName("UTF-8"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following method to write an XMLDom to a stream:

public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception {
    fDoc.setXmlStandalone(true);
    DOMSource docSource = new DOMSource(fDoc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.transform(docSource, new StreamResult(out));
}

I am testing some other XML functionality, and this is just the method that I use to write to a file.  My test program generates 33 test cases where files are written out.  28 of them have the following header:

<?xml version="1.0" encoding="UTF-8"?>...

But for some reason, 1 of the test cases now produce:

<?xml version="1.0" encoding="ISO-8859-1"?>...

And four more produce:

<?xml version="1.0" encoding="Windows-1252"?>...

As you can clearly see, I am setting ENCODING output key to UTF-8.   These tests used to work on an earlier version of Java.  I have not run the tests in a while (more than a year) but running today on "Java(TM) SE Runtime Environment (build 1.6.0_22-b04)" I get this funny behavior.

I have verified that the documents causing the problem were read from files that originally had those encoding.  It seems that the new versions of the libraries are attempting to preserve the encoding of the source file that was read.  But that is not what I want ... I really do want the output to be in UTF-8.

Does anyone know of any other factor that might cause the transformer to ignore the UTF-8 encoding setting?  Is there anything else that has to be set on the document to say to forget the encoding of the file that was originally read?

UPDATE:

I checked out the same project out on another machine, built and ran the tests there.  On that machine all the tests pass!  All the files have "UTF-8" in their header.  That machine has "Java(TM) SE Runtime Environment (build 1.6.0_29-b11)"   Both machines are running Windows 7.  On the new machine that works correctly, jdk1.5.0_11 is used to make the build, but on the old machine jdk1.6.0_26 is used to make the build.  The libraries used for both builds are exactly the same.  Can it be a JDK 1.6 incompatibility with 1.5 at build time?

UPDATE:

After 4.5 years, the Java library is still broken, but due to the suggestion by Vyrx below, I finally have a proper solution!

public void writeToOutputStream(Document fDoc, OutputStream out) throws Exception {
    fDoc.setXmlStandalone(true);
    DOMSource docSource = new DOMSource(fDoc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes("UTF-8"));
    transformer.transform(docSource, new StreamResult(out));
}

The solution is to disable the writing of the header, and to write the correct header just before serializing the XML to the output steam.   Lame, but it produces the correct results.  Tests broken over 4 years ago are now running again!

Body:
I had the same problem on Android when serializing emoji characters.  When using UTF-8 encoding in the transformer the output was HTML character entities (UTF-16 surrogate pairs), which would subsequently break other parsers that read the data.

This is how I ended up solving it:

StringWriter sw = new StringWriter();
sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
Transformer t = TransformerFactory.newInstance().newTransformer();

// this will work because we are creating a Java string, not writing to an output
t.setOutputProperty(OutputKeys.ENCODING, "UTF-16");
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.transform(new DOMSource(elementNode), new StreamResult(sw));

return IOUtils.toInputStream(sw.toString(), Charset.forName("UTF-8"));


问:
change variable for a target in a Makefile
In a Makefile I've a target called objects and if I run make objects it produces .o from every .cpp. Now I want to introduce a target check-syntax that call the target object but before change the variable CFLAGS from -Wall -O2 to -Wall -O0 -fsyntax-only.

How to do it?

答:
(IN GNUMake, anyway, and I'll assume you meant CFLAGS)

```<code>CFLAGS = -Wall -O2

objects: ...
    whatever

check-syntax: CFLAGS = -Wall -O0 -fsyntax-only

check-syntax: objects
</code>```

ContentLicense: CC BY-SA 2.5

Body:
(IN GNUMake, anyway, and I'll assume you meant CFLAGS)

CFLAGS = -Wall -O2

objects: ...
    whatever

check-syntax: CFLAGS = -Wall -O0 -fsyntax-only

check-syntax: objects


问:
Numba vs Cython loop optimization
Consider the following four functions (python, numba, cython and smart), which calculate identical responses when given the same integer inputs

```<code>def python(n):
    total = 0
    for m in range(1,n+1):
        total += m
    return total

from numba import jit
numba = jit(python)

cpdef int cython(int n):
    cdef int total = 0
    cdef int m
    for m in range(1, n+1):
        total += m
    return total

def smart(n):
    return n * (n + 1) // 2
</code>```

Timing their execution I was somewhat surprised to discover that

numba's run-time is independent of n (while cython's is linear in n)

numba is slower than smart

This immediately raises two questions:

Why is Numba, but not Cython, able to turn it into a constant-time algorithm?

Given that Numba does manage to turn it into a contstant-time algorithm, why is it slower than the pure Python constant-time function smart?

As I am no assembler maven, looking at the generated code doesn't really give me much of a clue, beyond that the intermediate LLVM code generated by Numba still appears (I might have misunderstood, though) to contain a loop ... and I get hopelessly lost in the x64 that is eventually generated from that. (Unless someone asks, I won't post the generated codes, as they are rather long.)

I am running this on a x64 Linux, in a Jupyter notebook, so I suspect that Cython is using the GCC 4.4.7 which was used to compile Python; and llvmlite 0.20.0, which would imply LLVM 4.0.x.

Edit:

I have also timed

```<code>smart_numba = jit(smart)
</code>```

and

```<code>cpdef int smart_cython(int n):
    return n * (n + 1) // 2
</code>```

smart_numba and numba give identical timings, which are 25% slower than smart (pure-Python) and 175% slower than smart_cython.

Does this indicate that Cython does a very good job of efficiently crossing the Python/low-level boundary, while Numba does a poor job? Or is there something else to it?

答:
This appears to be a LLVM vs GCC thing - see example in compiler explorer here, which is less noisy than what numba spits out.  I get a bit lost in the assembly, but fairly clear that the GCC output has a loop (the jge to .L6) and the clang output does not.  See also this issue on the GCC bugtracker.

On my machine (Windows x64) numba is not significantly slower than smart, only about 9 ns.  This overhead appears to be due to the type dispatch mechanism of numba - if you elide it by picking a specific overload, the numba version is faster than the python one

Here are my timings

```<code>In [73]: %timeit numba_sum(10000)
182 ns ± 1.69 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [74]: %timeit smart(10000)
171 ns ± 2.26 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

# pick out int64 overload
i64_numba_sum = numba_sum.get_overload((numba.int64,))

In [75]: %timeit i64_numba_sum(10000)
94 ns ± 1.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
</code>```

Title: Numba vs Cython loop optimization

Body:
Consider the following four functions (python, numba, cython and smart), which calculate identical responses when given the same integer inputs

def python(n):
    total = 0
    for m in range(1,n+1):
        total += m
    return total

from numba import jit
numba = jit(python)

cpdef int cython(int n):
    cdef int total = 0
    cdef int m
    for m in range(1, n+1):
        total += m
    return total

def smart(n):
    return n * (n + 1) // 2

Timing their execution I was somewhat surprised to discover that

numba's run-time is independent of n (while cython's is linear in n)

numba is slower than smart

This immediately raises two questions:

Why is Numba, but not Cython, able to turn it into a constant-time algorithm?

Given that Numba does manage to turn it into a contstant-time algorithm, why is it slower than the pure Python constant-time function smart?

As I am no assembler maven, looking at the generated code doesn't really give me much of a clue, beyond that the intermediate LLVM code generated by Numba still appears (I might have misunderstood, though) to contain a loop ... and I get hopelessly lost in the x64 that is eventually generated from that. (Unless someone asks, I won't post the generated codes, as they are rather long.)

I am running this on a x64 Linux, in a Jupyter notebook, so I suspect that Cython is using the GCC 4.4.7 which was used to compile Python; and llvmlite 0.20.0, which would imply LLVM 4.0.x.

Edit:

I have also timed

smart_numba = jit(smart)

and

cpdef int smart_cython(int n):
    return n * (n + 1) // 2

smart_numba and numba give identical timings, which are 25% slower than smart (pure-Python) and 175% slower than smart_cython.

Does this indicate that Cython does a very good job of efficiently crossing the Python/low-level boundary, while Numba does a poor job? Or is there something else to it?

Body:
This appears to be a LLVM vs GCC thing - see example in compiler explorer here, which is less noisy than what numba spits out.  I get a bit lost in the assembly, but fairly clear that the GCC output has a loop (the jge to .L6) and the clang output does not.  See also this issue on the GCC bugtracker.

On my machine (Windows x64) numba is not significantly slower than smart, only about 9 ns.  This overhead appears to be due to the type dispatch mechanism of numba - if you elide it by picking a specific overload, the numba version is faster than the python one

Here are my timings

In [73]: %timeit numba_sum(10000)
182 ns ± 1.69 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [74]: %timeit smart(10000)
171 ns ± 2.26 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

# pick out int64 overload
i64_numba_sum = numba_sum.get_overload((numba.int64,))

In [75]: %timeit i64_numba_sum(10000)
94 ns ± 1.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


问:
Extra Observations When Merging Datasets
I am trying to merge two datasets (Datasets A and B) but when I merge Dataset A (407 Obs) with Dataset B (1462 Obs) I merged them by:

```<code>C <- merge(A, B, by=ID, all.x=TRUE)
</code>```

It creates 416 observations in Dataset C.

Is there a reason why?

答:
See Why does the result from merge have more rows than original file?.

Looks like there were multiple matches in the ID column. Since you didn't specify what your goal is, I recommend going through the full documentation:
https://www.rdocumentation.org/packages/base/versions/3.4.1/topics/merge

Body:
I am trying to merge two datasets (Datasets A and B) but when I merge Dataset A (407 Obs) with Dataset B (1462 Obs) I merged them by:

C <- merge(A, B, by=ID, all.x=TRUE)

It creates 416 observations in Dataset C.

Is there a reason why?


问:
What is the benefit to using typing library classes vs. types in Python type hints?
I'm starting to learn type hints in Python to ease the future porting of code from Python to C. I am wondering what the difference is, if any, between using types directly in type hints vs. using the classes defined in the typing module.

For example, the difference between

```<code>def somefn(a: list[int]) -> tuple[str, int]:
    ...
</code>```

and

```<code>from typing import List, Tuple

def somefn(a: List[int]) -> Tuple[str, int]:
    ...
</code>```

It seems like some classes like Union, Any, Callable, and Iterable would be useful, but the utility of classes for data types that already exist as keywords in python is unclear to me.

答:
It's useful for writing annotations that can be legally evaluated; list[int] will explode if you try to actually run it, while typing.List[int] returns a new generic type that knows the type of both container and contents. This is particularly important in the case of type aliases, where a specialized version of a generic is defined at the top level, then reused as annotation further on:

```<code>Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
     ...
</code>```

is legal, while:

```<code>Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
     ...
</code>```

blows up in your face. You'll note that non-container/generic types typically don't have a typing type (exceptions like Text are for porting concerns), because type aliases would only use them as "leaf" type, not root or branch types.

Update: As of 3.9, the standard collections can serve as type hints, so the typing types aren't strictly necessary; you can continue to use them if you like (necessary for code that must run on pre-3.9 Python), but it's not necessary if you can rely on 3.9+.

Body:
I'm starting to learn type hints in Python to ease the future porting of code from Python to C. I am wondering what the difference is, if any, between using types directly in type hints vs. using the classes defined in the typing module.

For example, the difference between

def somefn(a: list[int]) -> tuple[str, int]:
    ...

and

from typing import List, Tuple

def somefn(a: List[int]) -> Tuple[str, int]:
    ...

It seems like some classes like Union, Any, Callable, and Iterable would be useful, but the utility of classes for data types that already exist as keywords in python is unclear to me.

Body:
It's useful for writing annotations that can be legally evaluated; list[int] will explode if you try to actually run it, while typing.List[int] returns a new generic type that knows the type of both container and contents. This is particularly important in the case of type aliases, where a specialized version of a generic is defined at the top level, then reused as annotation further on:

Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
     ...

is legal, while:

Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
     ...

blows up in your face. You'll note that non-container/generic types typically don't have a typing type (exceptions like Text are for porting concerns), because type aliases would only use them as "leaf" type, not root or branch types.

Update: As of 3.9, the standard collections can serve as type hints, so the typing types aren't strictly necessary; you can continue to use them if you like (necessary for code that must run on pre-3.9 Python), but it's not necessary if you can rely on 3.9+.

ContentLicense: CC BY-SA 4.0


问:
Wait for pending operations to finish without blocking UI thread
I have a MVP like application, all expensive operations are using Async calls and display an Ajax like gif that indicates the user that something is happening without blocking the main thread.

Example:
Data entry form, user clicks Save, an async operation takes place and when it finishes restores the screen to an editable form without blocking the UI thread (in other terms, not blocking other visible windows in the application).

Everything works fine in here, but given the following scenario:

User tries to close the Form, and gets a confirmation message that asks the user if he is sure that he is going to close if he prefers to Save before closing.
When the users clicks 'Save' the same logic explained before takes place, but I'm forced to wait for this call to finish in the UI thread (in case there are any errors in the async call or whatever) and I can`t find any way of doing it other way without blocking the UI thread.

Any suggestions? Thanks!

--- Edit ----
What I'm doing right now is waiting on all my WaitHandles in the Presenter with this loop:

```<code>while (!WaitHandles.All(h => h.WaitOne(1)))
    Application.DoEvents();
</code>```

It feels a little dirty.. but at least it simulates non blocking the thread. Is this something that for some reason I should not be doing?

答:
Here is an example of the "hide method". Granted, it's not MVP, it's just an example.</p>

```<code>using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    public Form1()
    {
        Text = "First Form";
        Button button;
        Controls.Add(button = new Button { Text = "Launch 2nd Form", AutoSize = true, Location = new Point(10, 10) });
        button.Click += (s, e) => new Form2 { StartPosition = FormStartPosition.Manual, Location = new Point(Right, Top) }.Show(this);
    }
}

class Form2 : Form
{
    public Form2()
    {
        Text = "Second Form";
        dirty = true;
    }

    private bool dirty;

    protected override void OnClosing(CancelEventArgs e)
    {
        DialogResult result;
        if (dirty && (result = new ConfirmSaveForm().ShowDialog(this)) != DialogResult.No)
        {
            if (Owner != null)
                Owner.Activate();
            Hide();
            e.Cancel = true;
            SaveAsync(result == DialogResult.Cancel);
        }
        base.OnClosing(e);
    }

    protected override void OnClosed(EventArgs e)
    {
        Trace.WriteLine("Second Form Closed");
        base.OnClosed(e);
    }

    private void SaveAsync(bool fail)
    {
        SaveAsyncBegin();
        var sad = new Action<bool>(PerformAsyncSave);
        sad.BeginInvoke(fail, (ar) =>
        {
            try { sad.EndInvoke(ar); }
            catch (Exception ex) { Invoke(new Action<Exception>(SaveAsyncException), ex); return; }
            Invoke(new Action(SaveAsyncEnd));
        }, null);
    }

    private void SaveAsyncBegin()
    {
        // Update UI for save
    }

    private void PerformAsyncSave(bool fail)
    {
        Trace.WriteLine("Begin Saving");
        Thread.Sleep(1000); // Do some work
        if (fail)
        {
            Trace.WriteLine("Failing Save");
            throw new Exception("Save Failed");
        }
        dirty = false;
    }

    private void SaveAsyncEnd()
    {
        Trace.WriteLine("Save Succeeded");
        Close();
    }

    private void SaveAsyncException(Exception ex)
    {
        Trace.WriteLine("Save Failed");
        Show();
        MessageBox.Show(this, ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Stop);
    }
}

class ConfirmSaveForm : Form
{
    public ConfirmSaveForm()
    {
        Text = "Confirm Save";
        FormBorderStyle = FormBorderStyle.FixedDialog;
        ControlBox = false;
        ClientSize = new Size(480, 50);
        StartPosition = FormStartPosition.CenterParent;
        Controls.Add(new Button { Text = "Yes, Fail", DialogResult = DialogResult.Cancel, Size = new Size(150, 30), Location = new Point(10, 10) });
        Controls.Add(new Button { Text = "Yes, Succeed", DialogResult = DialogResult.Yes, Size = new Size(150, 30), Location = new Point(160, 10) });
        Controls.Add(new Button { Text = "No", DialogResult = DialogResult.No, Size = new Size(150, 30), Location = new Point(320, 10) });
        AcceptButton = Controls[0] as IButtonControl;
    }
}
</code>```

Body:
I have a MVP like application, all expensive operations are using Async calls and display an Ajax like gif that indicates the user that something is happening without blocking the main thread.

Example:
Data entry form, user clicks Save, an async operation takes place and when it finishes restores the screen to an editable form without blocking the UI thread (in other terms, not blocking other visible windows in the application).

Everything works fine in here, but given the following scenario:

User tries to close the Form, and gets a confirmation message that asks the user if he is sure that he is going to close if he prefers to Save before closing.
When the users clicks 'Save' the same logic explained before takes place, but I'm forced to wait for this call to finish in the UI thread (in case there are any errors in the async call or whatever) and I can`t find any way of doing it other way without blocking the UI thread.

Any suggestions? Thanks!

--- Edit ----
What I'm doing right now is waiting on all my WaitHandles in the Presenter with this loop:

while (!WaitHandles.All(h => h.WaitOne(1)))
    Application.DoEvents();

It feels a little dirty.. but at least it simulates non blocking the thread. Is this something that for some reason I should not be doing?

Body:
Here is an example of the "hide method". Granted, it's not MVP, it's just an example.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    public Form1()
    {
        Text = "First Form";
        Button button;
        Controls.Add(button = new Button { Text = "Launch 2nd Form", AutoSize = true, Location = new Point(10, 10) });
        button.Click += (s, e) => new Form2 { StartPosition = FormStartPosition.Manual, Location = new Point(Right, Top) }.Show(this);
    }
}

class Form2 : Form
{
    public Form2()
    {
        Text = "Second Form";
        dirty = true;
    }

    private bool dirty;

    protected override void OnClosing(CancelEventArgs e)
    {
        DialogResult result;
        if (dirty && (result = new ConfirmSaveForm().ShowDialog(this)) != DialogResult.No)
        {
            if (Owner != null)
                Owner.Activate();
            Hide();
            e.Cancel = true;
            SaveAsync(result == DialogResult.Cancel);
        }
        base.OnClosing(e);
    }

    protected override void OnClosed(EventArgs e)
    {
        Trace.WriteLine("Second Form Closed");
        base.OnClosed(e);
    }

    private void SaveAsync(bool fail)
    {
        SaveAsyncBegin();
        var sad = new Action<bool>(PerformAsyncSave);
        sad.BeginInvoke(fail, (ar) =>
        {
            try { sad.EndInvoke(ar); }
            catch (Exception ex) { Invoke(new Action<Exception>(SaveAsyncException), ex); return; }
            Invoke(new Action(SaveAsyncEnd));
        }, null);
    }

    private void SaveAsyncBegin()
    {
        // Update UI for save
    }

    private void PerformAsyncSave(bool fail)
    {
        Trace.WriteLine("Begin Saving");
        Thread.Sleep(1000); // Do some work
        if (fail)
        {
            Trace.WriteLine("Failing Save");
            throw new Exception("Save Failed");
        }
        dirty = false;
    }

    private void SaveAsyncEnd()
    {
        Trace.WriteLine("Save Succeeded");
        Close();
    }

    private void SaveAsyncException(Exception ex)
    {
        Trace.WriteLine("Save Failed");
        Show();
        MessageBox.Show(this, ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Stop);
    }
}

class ConfirmSaveForm : Form
{
    public ConfirmSaveForm()
    {
        Text = "Confirm Save";
        FormBorderStyle = FormBorderStyle.FixedDialog;
        ControlBox = false;
        ClientSize = new Size(480, 50);
        StartPosition = FormStartPosition.CenterParent;
        Controls.Add(new Button { Text = "Yes, Fail", DialogResult = DialogResult.Cancel, Size = new Size(150, 30), Location = new Point(10, 10) });
        Controls.Add(new Button { Text = "Yes, Succeed", DialogResult = DialogResult.Yes, Size = new Size(150, 30), Location = new Point(160, 10) });
        Controls.Add(new Button { Text = "No", DialogResult = DialogResult.No, Size = new Size(150, 30), Location = new Point(320, 10) });
        AcceptButton = Controls[0] as IButtonControl;
    }
}


问:
Writing to the downloads folder in a sandboxed app
A related question asks how to write to the Downloads folder in a sandboxed app.

I have code that does that and works at my end. However, upon submitting my app to the App Store, Apple told me I'm only allowed to write to /Downloads/[App-Identifier], not to /Downloads.

What's the app identifier? Is it the bundle identifier? And where's the documentation pertaining to this? I've looked in the App Store Review Guidelines (Apple referred to 2.4.5(i)), in the Sandbox guide, used Google, ... no luck so far.

答:
The App-Identifier will be the Bundle ID. As to where this restriction to write to a subfolder of ~/Downloads comes from I've no idea (it does not appear to be in the Review Guidelines, the App Sandbox Guide, etc. as you found out). You could query the review, but going another way might be easier...

You will probably be better off using a bookmark, see Security-Scoped Bookmarks and Persistent Resource Access, and an entitlement as your linked question suggests. This will also allow you to directly store into ~/Downloads without question - if the user selects it (put up a standard file dialog styled as a permission request, only allow folders, and preset to show the home directory; you can if you wish restrict selection to only Downloads).

HTH


问:
how to initialize array using type.NewArray in golang?
Basically, I want to use the Array type struct in the types module but I'm unable to initialize it. What do you have to pass in the Type as the first argument?

```<code>package main

import (
    "fmt"
    "go/types"
)

func main() {
    var a *types.Array
    a = types.NewArray(types.Int, 2) //error here
    fmt.Println(a)
}
</code>```

答:
I'm also new in go. And for me the question doesn't look stupid. Unfortunately no one has explained how to use NewArray yet. It seems to me that golang community is not very friendly I've met more downvoting than real help for now.

Btw I took course of Go tour :) But anyway I was confused that question how to get type of an object bring you to reflect package usually (type in google something like golang get type of an object) which has nothing in common with types.Type. I spent some time to figure out how to get types.Type object, and it's not obvious I think for people who has experience in other languages.

So to use NewArray method you neeed to pass an object which implements types.Type as mkopriva pointed. I end up with

```<code>package main

import (
    "fmt"
    "go/types"
)

type NewType int

func (v NewType) String() string {
    return string(v)
}

func (v NewType) Underlying() types.Type {
    return types.Type(v)
}

func main() {
    var a *types.Array
    a = types.NewArray(NewType(0), 2)
    fmt.Println(a)
}
</code>```

There is used new type with underlying int. I guess I don't understand something yet in golang since for using such simple thing I had to write such useless methods as String and Underlying, they are useless because of implementation, I don't see the reason to be forced write such code. I appriciate if golang experts explain this stuff!

Body:
Basically, I want to use the Array type struct in the types module but I'm unable to initialize it. What do you have to pass in the Type as the first argument?

package main

import (
    "fmt"
    "go/types"
)

func main() {
    var a *types.Array
    a = types.NewArray(types.Int, 2) //error here
    fmt.Println(a)
}

Body:
I'm also new in go. And for me the question doesn't look stupid. Unfortunately no one has explained how to use NewArray yet. It seems to me that golang community is not very friendly I've met more downvoting than real help for now.

Btw I took course of Go tour :) But anyway I was confused that question how to get type of an object bring you to reflect package usually (type in google something like golang get type of an object) which has nothing in common with types.Type. I spent some time to figure out how to get types.Type object, and it's not obvious I think for people who has experience in other languages.

So to use NewArray method you neeed to pass an object which implements types.Type as mkopriva pointed. I end up with

package main

import (
    "fmt"
    "go/types"
)

type NewType int

func (v NewType) String() string {
    return string(v)
}

func (v NewType) Underlying() types.Type {
    return types.Type(v)
}

func main() {
    var a *types.Array
    a = types.NewArray(NewType(0), 2)
    fmt.Println(a)
}

There is used new type with underlying int. I guess I don't understand something yet in golang since for using such simple thing I had to write such useless methods as String and Underlying, they are useless because of implementation, I don't see the reason to be forced write such code. I appriciate if golang experts explain this stuff!


问:
How do I show the % completed with ng-bootstrap NgbProgressBar?
I have a 5 to 15 seconds initialization operation in my angular app, and want to use NgbProgressBar to show the progress in %. Currently I use Angular Http provider functions to retrieve the data which is a single call operation does not help to get the % done.

How can the Browser know the % completed using Http service, and update the NgbProgressBar? Is there a different JavaScript framework that I can use to achieve this if I can't do with http?

答: I don't think you can do this. Neither your Angular app nor the browser knows how much data needs to be retrieved, so it wouldn't be able to calculate a percentage. You need some hook that you can tie into and asynchronously update your progress bar. Now, if you know the upper limits of the payload size, I guess you could spoof the progress by just adding X percent every Y seconds, assuming your http call is non-blocking.</p>


问:
Firing an event across 2 controllers AngularJS with two-way binding
This is a question about Angular 1, not Angular 2.

My setup is somewhat complex: I have a controller (controller A) responsible for a specific page. On this page, I have a custom directive that takes input drawn from the controller on the page. This custom directive, however, also has its own controller (controller B), that I pass information into via bindings on the attribute. Much of the information I pass into this directive and into controller B is generated by and handled via controller A.

Controller A can essentially be described as controller B's parent.

However, the bindings into this directive with controller B are two-way bindings (=), so information changed in controller B in the directive should bubble back up and into controller A, due to the two-way binding, and because the initial attributes passed in are bound pieces of information for controller A.

While complex, this works about 99% of the time for me. I have a button on the page that I want to disable in this way: ng-disabled=CtrlA.buttonDisabled().

buttonDisabled() is a function on controller A that takes information from the two-way bounded values in the directive to controller B in order to return true, disable the button, or false, do not disable the button.

In one specific instance, even when changing the values on controller B that should impact this function, the function itself does not fire, so my button is enabled when it should be disabled.

I want to know how to force buttonDisabled() on controller A to execute from changing values inside of controller B. Is this possible? Can I do this via $watch? If so, which controller(s) should I place this information?

Here's a very simplified version of my code:

Controller A:

```<code>$scope.userName = "";
$scope.buttonDisabled = function() {
    if($scope.userName){
        return false;
    }
    return true;
};
</code>```

Controller B:

```<code>$scope.userName = "";
$scope.clearUserName = function(){
    $scope.userName = "";
    //I want to call disableButton from controller A here
}
</code>```

HTML for the main page:

```<code><div ng-controller="CtrlA">
    <specialDirective username="{{userName}}"></specialDirective>
    <button ng-disabled="buttonDisabled()" ></button>
</div>
</code>```

HTML for specialDirective template

```<code>    <input ng-model="userName" />
    <button ng-click="clearUserName()" ></button>
</code>```

Directive setup:

```<code>app.component("specialDirective",{
    controller: CtrlB,
    bindings: {
        userName: "="
    },
    template: "directiveTemplate.html"
});
</code>```

userName is two-way bound in specialDirective.

I can't move clearUserName() or buttonDisabled() into the other controller directly, due to other requirements.

EDIT: Thank you to the commenters who pointed out my flaws--I've done my best to correct them in this and my answer post. I wrote this example from scratch since it would have been too complicated to copy-paste my exact code, which doesn't use the $scope object directly, etc, so I apologize for my incorrect syntax. Please correct me if I missed anything else. (:

答:
With some searching and now seeing Georgeawg's comment, I was able to figure out how to do what I wanted with using one-way callback binding.

By using <, I was able to bind to a callback function that I could call from Controller B that would send the message back up to Controller A. In my case, I was able to set setDisabled() as my function that would execute during callback. This is better than using $watch, because $watch is a big resource drain.

See the Catching Output section of this blog post as an example of what I did: http://blog.krawaller.se/posts/dissecting-bindings-in-angularjs/

Controller A:

```<code>$scope.userName = "";
var buttonDisabled = function() {
    if($scope.userName){
        return false;
    }
    return true;
};
</code>```

Controller B:

```<code>$scope.userName = "";
$scope.clearUserName = function(){
    $scope.userName = "";
    $scope.out(); //calling the callback the directive was bound to, ultimately calling buttonDisabled() from Controller A
}
</code>```

HTML for the main page:

```<code><div ng-controller="CtrlA">
    <specialDirective username="{{userName}}" out="buttonDisabled()"></specialDirective>
    <button ng-disabled="buttonDisabled()"></button>
</div>
</code>```

HTML template for the directive:

```<code><input ng-model="userName" />
<button ng-click="clearUserName()"></button>
</code>```

Directive set up:

```<code>app.component("specialDirective",{
    controller: CtrlB,
    bindings: {
        out: "<",
        userName: "="
    },
    template: "directiveTemplate.html"
});
</code>```

Body:
This is a question about Angular 1, not Angular 2.

My setup is somewhat complex: I have a controller (controller A) responsible for a specific page. On this page, I have a custom directive that takes input drawn from the controller on the page. This custom directive, however, also has its own controller (controller B), that I pass information into via bindings on the attribute. Much of the information I pass into this directive and into controller B is generated by and handled via controller A.

Controller A can essentially be described as controller B's parent.

However, the bindings into this directive with controller B are two-way bindings (=), so information changed in controller B in the directive should bubble back up and into controller A, due to the two-way binding, and because the initial attributes passed in are bound pieces of information for controller A.

While complex, this works about 99% of the time for me. I have a button on the page that I want to disable in this way: ng-disabled=CtrlA.buttonDisabled().

buttonDisabled() is a function on controller A that takes information from the two-way bounded values in the directive to controller B in order to return true, disable the button, or false, do not disable the button.

In one specific instance, even when changing the values on controller B that should impact this function, the function itself does not fire, so my button is enabled when it should be disabled.

I want to know how to force buttonDisabled() on controller A to execute from changing values inside of controller B. Is this possible? Can I do this via $watch? If so, which controller(s) should I place this information?

Here's a very simplified version of my code:

Controller A:

$scope.userName = "";
$scope.buttonDisabled = function() {
    if($scope.userName){
        return false;
    }
    return true;
};

Controller B:

$scope.userName = "";
$scope.clearUserName = function(){
    $scope.userName = "";
    //I want to call disableButton from controller A here
}

HTML for the main page:

    <specialDirective username="{{userName}}"></specialDirective>
    <button ng-disabled="buttonDisabled()" ></button>

HTML for specialDirective template

    <input ng-model="userName" />
    <button ng-click="clearUserName()" ></button>

Directive setup:

app.component("specialDirective",{
    controller: CtrlB,
    bindings: {
        userName: "="
    },
    template: "directiveTemplate.html"
});

userName is two-way bound in specialDirective.

I can't move clearUserName() or buttonDisabled() into the other controller directly, due to other requirements.

EDIT: Thank you to the commenters who pointed out my flaws--I've done my best to correct them in this and my answer post. I wrote this example from scratch since it would have been too complicated to copy-paste my exact code, which doesn't use the $scope object directly, etc, so I apologize for my incorrect syntax. Please correct me if I missed anything else. (:

Body:
With some searching and now seeing Georgeawg's comment, I was able to figure out how to do what I wanted with using one-way callback binding.

By using <, I was able to bind to a callback function that I could call from Controller B that would send the message back up to Controller A. In my case, I was able to set setDisabled() as my function that would execute during callback. This is better than using $watch, because $watch is a big resource drain.

See the Catching Output section of this blog post as an example of what I did: http://blog.krawaller.se/posts/dissecting-bindings-in-angularjs/

Controller A:

$scope.userName = "";
var buttonDisabled = function() {
    if($scope.userName){
        return false;
    }
    return true;
};

Controller B:

$scope.userName = "";
$scope.clearUserName = function(){
    $scope.userName = "";
    $scope.out(); //calling the callback the directive was bound to, ultimately calling buttonDisabled() from Controller A
}

HTML for the main page:

<div ng-controller="CtrlA">
    <specialDirective username="{{userName}}" out="buttonDisabled()"></specialDirective>
    <button ng-disabled="buttonDisabled()"></button>
</div>

HTML template for the directive:

<input ng-model="userName" />
<button ng-click="clearUserName()"></button>

Directive set up:

app.component("specialDirective",{
    controller: CtrlB,
    bindings: {
        out: "<",
        userName: "="
    },
    template: "directiveTemplate.html"
});


问:
Filtering values within nested data column using dplyr
I want to filter out outliers (above or below mean +- 3 * sem) in a nested data frame using dplyr. I don't know how to formulate the code to refer to values within the nested $data column below. For example,

```<code>df <- tibble(
  a = rep(c('x', 'y', 'z'),100),
  value = c(1:298, 999, 1000)) %>%
  nest(value) %>%
  mutate(mn = map_dbl(data, ~mean(.$value, na.rm = T)),
         sem = map_dbl(data, ~sqrt(var(.$value,na.rm=T)/length(na.omit(.$value)))),
         upper = mn + 3*sem,
         lower = mn - 3*sem)
</code>```

How do I now filter the 'value' column in the data column based on these upper and lower bounds?

答:
You can use Map to loop over data, lower and upper columns in parallel and then filter nested data based on the value column:

```<code>df %>%
    mutate(data = Map(function(data, upper, lower) filter(data, data$value < upper, data$value > lower), data, upper, lower))

# A tibble: 3 x 6
#      a              data    mn       sem    upper    lower
#  <chr>            <list> <dbl>     <dbl>    <dbl>    <dbl>
#1     x <tibble [18 x 1]> 149.5  8.703448 175.6103 123.3897
#2     y <tibble [24 x 1]> 157.5 12.072696 193.7181 121.2819
#3     z <tibble [24 x 1]> 158.5 12.072696 194.7181 122.2819
</code>```

Body:
I want to filter out outliers (above or below mean +- 3 * sem) in a nested data frame using dplyr. I don't know how to formulate the code to refer to values within the nested $data column below. For example,

df <- tibble(
  a = rep(c('x', 'y', 'z'),100),
  value = c(1:298, 999, 1000)) %>%
  nest(value) %>%
  mutate(mn = map_dbl(data, ~mean(.$value, na.rm = T)),
         sem = map_dbl(data, ~sqrt(var(.$value,na.rm=T)/length(na.omit(.$value)))),
         upper = mn + 3*sem,
         lower = mn - 3*sem)

How do I now filter the 'value' column in the data column based on these upper and lower bounds?

Body:
You can use Map to loop over data, lower and upper columns in parallel and then filter nested data based on the value column:

df %>%
    mutate(data = Map(function(data, upper, lower) filter(data, data$value < upper, data$value > lower), data, upper, lower))

# A tibble: 3 x 6
#      a              data    mn       sem    upper    lower
#  <chr>            <list> <dbl>     <dbl>    <dbl>    <dbl>
#1     x <tibble [18 x 1]> 149.5  8.703448 175.6103 123.3897
#2     y <tibble [24 x 1]> 157.5 12.072696 193.7181 121.2819
#3     z <tibble [24 x 1]> 158.5 12.072696 194.7181 122.2819


问:
Debugging C# application - Visual Studio
I am trying to learn C# and have followed the instructions in this tutorial

I have created a project, added the controls to the design surface and added code to the button click event. When I get to the part which asks me to test the application, I click "start debugging" and I get an error message saying

There were build errors, would you like to continue and run the last successful build?

If I click no, nothing happens. If I click yes I get another error saying:

Visual Studio cannot start debugging because the debug target 'C:\Users\hp\source\repos\HelloWPFApp\HelloWPFApp\bin\Debug\HelloWPFApp.exe' is missing.

As a complete beginner I have no idea why this exe file is missing or how to fix it. Could someone point me in the right direction at all?

答: It's possible that your code has never compiled. Press Ctrl-Shift-B and try again (or look in the Build menu).</p>


问:
run C++ UDF in Spark
I am trying to find a way to run C++ UDF in Spark. So far I can only find the way to run Java UDF and cannot find anything about running C++ UDF.

Anyone knows how to do it in Spark (either Scala or PySpark)?

答:
C++ is not supported as as a guest language so you cannot write C++ UDF. What you can do is to call you C++ code from Scala or Python within support UDF.

In Scala you can use Java Native Interface. Intefaced code has to be thread safe.

In Python you can write a C/C++ Extension, Swig inteface or Cython. Workers are isolated so thread safety is not required.

Title: run C++ UDF in Spark


问:
Run vue project getaddrinfo ENOTFOUND localhost error
I have initialized a nuxt project and when I try to run it with npm run dev or yarn dev command it returns this error : </p>

```<code>    build [==================  ] 91%Error: getaddrinfo ENOTFOUND localhost
    at errnoException (dns.js:50:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
error Command failed with exit code 1.
</code>```

<p>Any idea where does it come from ? </p>

答: add 127.0.0.1   localhost to /etc/hosts</p>

Body:
I have initialized a nuxt project and when I try to run it with npm run dev or yarn dev command it returns this error :

    build [==================  ] 91%Error: getaddrinfo ENOTFOUND localhost
    at errnoException (dns.js:50:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
error Command failed with exit code 1.

Any idea where does it come from ?

Body: add 127.0.0.1   localhost to /etc/hosts


问:
How do you call a text UI (whiptail or dialog) within a Java application?
There are two Linux command line programs (whiptail and dialog) that provide the ability to display a text UI to the user.  I would like to call one of these (preferably whiptail) from within my Java application so that the user can select an option from a predefined list.  The following SO questions were helpful to me in figuring out how to call a Linux command from within my code:

How to run linux commands in java code?

Want to invoke a linux shell command from Java

These give helpful tips on how to run a typical Linux command (e.g. "ls"), but my case is a little more complicated (I think) due to the text UI that I would like to have display to the user.

To give an idea of what whiptail does and looks like see this.

答:
Start with ProcessBuilder.  Each parameter you want to send the command is a separate element in the command list, for example...

```<code>import java.io.IOException;
import java.io.InputStream;

public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(
                "whiptail", "--title", "Check list example", " --checklist",
                "Choose user's permissions", "20", "78", "4",
                "NET_OUTBOUND", "Allow connections to other hosts", "ON",
                "NET_INBOUND", "Allow connections from other hosts", "OFF",
                "LOCAL_MOUNT", "Allow mounting of local devices", "OFF",
                "REMOTE_MOUNT", "Allow mounting of remote devices", "OFF");
        pb.redirectInput(Redirect.INHERIT);
        // I tend to use pb.redirectErrorStream(true);
        // which sends the error stream to the input stream, but
        // then you'd need to still consume it to get the result
        Process p = pb.start();
        InputStreamConsumer errorConsumer = new InputStreamConsumer(p.getErrorStream());

        Scanner input = new Scanner(System.in);
        String option = input.nextLine();

        p.getOutputStream().write(option.getBytes());
        p.getOutputStream().flush();

        int exitCode = p.waitFor();
        System.out.println(exitCode);

        errorConsumer.join();

        System.out.println(errorConsumer.getContent());
    }

    public static class InputStreamConsumer extends Thread {

        private InputStream is;
        private StringBuilder content;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
            content = new StringBuilder(128);
        }

        public String getContent() {
            return content.toString();
        }

        @Override
        public void run() {

            try {
                int value = -1;
                while ((value = is.read()) != -1) {
                    content.append((char)value);
                }
            } catch (IOException exp) {
                exp.printStackTrace();
            }

        }

    }
}
</code>```

This is very basic, it simply executes the command, consumes it's output into a StringBuilder (to be retrieved later), waits till the command exists and displays the basic results.

Since I don't have access to whiptail, I can't test the code, but if the command is available in the default search path of the OS, it should work, otherwise you'll need to supply the path to the command as part of the first element in the command list

Body:
Start with ProcessBuilder.  Each parameter you want to send the command is a separate element in the command list, for example...

import java.io.IOException;
import java.io.InputStream;

public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(
                "whiptail", "--title", "Check list example", " --checklist",
                "Choose user's permissions", "20", "78", "4",
                "NET_OUTBOUND", "Allow connections to other hosts", "ON",
                "NET_INBOUND", "Allow connections from other hosts", "OFF",
                "LOCAL_MOUNT", "Allow mounting of local devices", "OFF",
                "REMOTE_MOUNT", "Allow mounting of remote devices", "OFF");
        pb.redirectInput(Redirect.INHERIT);
        // I tend to use pb.redirectErrorStream(true);
        // which sends the error stream to the input stream, but
        // then you'd need to still consume it to get the result
        Process p = pb.start();
        InputStreamConsumer errorConsumer = new InputStreamConsumer(p.getErrorStream());

        Scanner input = new Scanner(System.in);
        String option = input.nextLine();

        p.getOutputStream().write(option.getBytes());
        p.getOutputStream().flush();

        int exitCode = p.waitFor();
        System.out.println(exitCode);

        errorConsumer.join();

        System.out.println(errorConsumer.getContent());
    }

    public static class InputStreamConsumer extends Thread {

        private InputStream is;
        private StringBuilder content;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
            content = new StringBuilder(128);
        }

        public String getContent() {
            return content.toString();
        }

        @Override
        public void run() {

            try {
                int value = -1;
                while ((value = is.read()) != -1) {
                    content.append((char)value);
                }
            } catch (IOException exp) {
                exp.printStackTrace();
            }

        }

    }
}

This is very basic, it simply executes the command, consumes it's output into a StringBuilder (to be retrieved later), waits till the command exists and displays the basic results.

Since I don't have access to whiptail, I can't test the code, but if the command is available in the default search path of the OS, it should work, otherwise you'll need to supply the path to the command as part of the first element in the command list


答: I do not have VS now, why don't you rebuild (or rebuild-all) your project, and if successfully rebuilds check whether the executable file exists in that folder, and also check the release folder, if it is there then change rebuild option to debug, as far as i remember you will see a drop down, on the toolbar,</p>

Title: Debugging C# application - Visual Studio

Body:
I am trying to learn C# and have followed the instructions in this tutorial

I have created a project, added the controls to the design surface and added code to the button click event. When I get to the part which asks me to test the application, I click "start debugging" and I get an error message saying

There were build errors, would you like to continue and run the last successful build?

If I click no, nothing happens. If I click yes I get another error saying:

Visual Studio cannot start debugging because the debug target 'C:\Users\hp\source\repos\HelloWPFApp\HelloWPFApp\bin\Debug\HelloWPFApp.exe' is missing.

As a complete beginner I have no idea why this exe file is missing or how to fix it. Could someone point me in the right direction at all?


问:
Mixed Language Programming, VB and C++, Understanding API and pointers
My problem is with understanding the finer point of mixed langage programming
and accessing API's in external libraries. My skills at C++ are nonexistent
and at VB, mediocre.

I have a c++ dll compiled (portaudio library), and am trying to access it from VB
(Visual Studio 2005).
I am getting MarshallDirectiveException errors when calling a function, I believe because
I am interacting incorrectly with the dll.

the C++ function and structures are defined as follows:

header info:

```<code>typedef int PaHostApiIndex;
...
typedef double PaTime;
...
typedef struct PaDeviceInfo
 {
     int structVersion;  /* this is struct version 2 */
     const char *name;
     PaHostApiIndex hostApi; /* note this is a host API index, not a type id*/
     int maxInputChannels;
     int maxOutputChannels;
     PaTime defaultLowInputLatency;
     PaTime defaultLowOutputLatency;
     PaTime defaultHighInputLatency;
     PaTime defaultHighOutputLatency;
     double defaultSampleRate;
 } PaDeviceInfo;
 ...
 const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device );
</code>```

program usage from docs:

```<code>const PaDeviceInfo* Pa_GetDeviceInfo    (   PaDeviceIndex   device   )
</code>```

Retrieve a pointer to a PaDeviceInfo structure containing information about the specified
device.

Returns:
A pointer to an immutable PaDeviceInfo structure. If the device parameter is out of range
the function returns NULL.

Parameters:
device  A valid device index in the range 0 to (Pa_GetDeviceCount()-1)

In the VB program I have:

```<code>Private Declare Function Pa_GetDeviceInfo Lib "portaudio_x86.dll" (ByVal dindex As Integer) As PaDeviceInfo
...
Private Structure PaDeviceInfo
        Dim structVersion As Integer
        <MarshalAs(Runtime.InteropServices.UnmanagedType.LPStr)> Dim name As String
        Dim hostapi As Integer
        Dim maxInputChannels As Integer
        Dim maxOutputChannels As Integer
        Dim defaultLowInputLatency As Double
        Dim defaultLowOutputLatency As Double
        Dim defaultHighInputLatency As Double
        Dim defaultHighOutputLatency As Double
        Dim defaultSampleRate As Double
End Structure
...
        Dim di As New PaDeviceInfo
        di = Pa_GetDeviceInfo(outputParameters.device)
</code>```

This feels wrong as docs state Pa_GetDeviceInfo returns a POINTER to a structure containing info
about the structure, implying function creates the structure initially.

I am completely new to mixed language programming, a c++ utter noob, and a poor VB programmer.
Can anyone guide me in the correct way to attack this problem ?
My feeling is that I need to understand how to get VB to reference a struct in memry created in
the dll, so I need to get vb to understand 'pointer to thing' as a function return.

Much appreciation for any assistance rendered. Please don't just say rtfm, I'm up to my eyes in FM's at
the minute, I just don't know where to look.

Many thanks,
David

答:
Yes, your structure is wrong. You indeed have to get a pointer and then read the memory to which it "points".

I've done external DLL calling in C++ before and it generally involves a huge wading-through of documentation. I don't think anyone here is going to do that for you but I'll try to point you in the proper direction.

First, a pointer is an address, a value which "points" to some location in memory. "dereferencing" a pointer is reading the memory that the pointers to (and if you read or write the wrong memory, the memory can get upset and kill your program).

Further, at a low level, calling a DLL involves copying bits of information to the stack and then having the function retrieve them. The "calling conventions" describe exactly how this is done - there are "c", pascal, and other such conventions.

You will want to call the DLL's function, get a pointer, copy the information pointed-to into your local structure and then continue. The hard thing will be figuring out exactly how to declare the DLL function. If your library documentation has some sample code, that might be where to start.

A short Google does not even show any consistent way to deal with pointers in VB at all. One idea would be to create a short C++ program which would call the DLL and return an object by value. I don't know if this would help but such kludges come up when dealing with external libraries.

Good Luck

OwnerDisplayName: WaveyDavey

Body:
My problem is with understanding the finer point of mixed langage programming
and accessing API's in external libraries. My skills at C++ are nonexistent
and at VB, mediocre.

I have a c++ dll compiled (portaudio library), and am trying to access it from VB
(Visual Studio 2005).
I am getting MarshallDirectiveException errors when calling a function, I believe because
I am interacting incorrectly with the dll.

the C++ function and structures are defined as follows:

header info:

typedef int PaHostApiIndex;
...
typedef double PaTime;
...
typedef struct PaDeviceInfo
 {
     int structVersion;  /* this is struct version 2 */
     const char *name;
     PaHostApiIndex hostApi; /* note this is a host API index, not a type id*/
     int maxInputChannels;
     int maxOutputChannels;
     PaTime defaultLowInputLatency;
     PaTime defaultLowOutputLatency;
     PaTime defaultHighInputLatency;
     PaTime defaultHighOutputLatency;
     double defaultSampleRate;
 } PaDeviceInfo;
 ...
 const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device );

program usage from docs:

const PaDeviceInfo* Pa_GetDeviceInfo    (   PaDeviceIndex   device   )

Retrieve a pointer to a PaDeviceInfo structure containing information about the specified
device.

Returns:
A pointer to an immutable PaDeviceInfo structure. If the device parameter is out of range
the function returns NULL.

Parameters:
device  A valid device index in the range 0 to (Pa_GetDeviceCount()-1)

In the VB program I have:

Private Declare Function Pa_GetDeviceInfo Lib "portaudio_x86.dll" (ByVal dindex As Integer) As PaDeviceInfo
...
Private Structure PaDeviceInfo
        Dim structVersion As Integer
        <MarshalAs(Runtime.InteropServices.UnmanagedType.LPStr)> Dim name As String
        Dim hostapi As Integer
        Dim maxInputChannels As Integer
        Dim maxOutputChannels As Integer
        Dim defaultLowInputLatency As Double
        Dim defaultLowOutputLatency As Double
        Dim defaultHighInputLatency As Double
        Dim defaultHighOutputLatency As Double
        Dim defaultSampleRate As Double
End Structure
...
        Dim di As New PaDeviceInfo
        di = Pa_GetDeviceInfo(outputParameters.device)

This feels wrong as docs state Pa_GetDeviceInfo returns a POINTER to a structure containing info
about the structure, implying function creates the structure initially.

I am completely new to mixed language programming, a c++ utter noob, and a poor VB programmer.
Can anyone guide me in the correct way to attack this problem ?
My feeling is that I need to understand how to get VB to reference a struct in memry created in
the dll, so I need to get vb to understand 'pointer to thing' as a function return.

Much appreciation for any assistance rendered. Please don't just say rtfm, I'm up to my eyes in FM's at
the minute, I just don't know where to look.

Many thanks,
David

OwnerDisplayName: Joe Solbrig


答:
First: You should  clean the project than Build project  again.

Second: Run project by pressing F5

Executable file you can find in bin/Debug folder in your root of  project.


问:
WebAPI Core 2 Multiple connection string with same context
I am developing webapi with some knowledge of Core 2.0
I need to create two link to produce different result from different database both database schema are the same.

Like https://localhost:5000/m/University

or https://localhost:5000/v/University

They both fire in different database with same webapi application and give result it. I can produced result but I have to either create two webapi project or change connection string ("MConn") in Start up class.

```<code>  public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<IISOptions>(options => { options.AutomaticAuthentication = true; });
        services.AddDbContext<PIDBContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("MConn")));
        services.AddMvc();
    }
</code>```

Could you help me how to use same Webapi project with different connection string based on Https request?

Thanks

答:
Found the solution:

Create DbContextFactory

```<code>public static class DbContextFactory
{
    public static Dictionary<string, string> ConnectionStrings { get; set; }

    public static void SetConnectionString(Dictionary<string, string> connStrs)
    {
        ConnectionStrings = connStrs;
    }

    public static AppContext Create(string connid)
    {
        if (!string.IsNullOrEmpty(connid))
        {
            var connStr = ConnectionStrings[connid];
            var optionsBuilder = new DbContextOptionsBuilder<AppContext >();
            optionsBuilder.UseSqlServer(connStr);
            var db = new AppContext (optionsBuilder.Options);
            return db;
        }
        else
        {
            throw new ArgumentNullException("Connection failed becuase of no Connection ID");
        }
   }
}
</code>```

Project Json file:

```<code>{
    "ConnectionStrings": {
    "Sample1con": "your 1st connection string",
    "Sample2con": "your 2nd connection string"
    }
}
</code>```

In Configure method in Startup class declare Dictionary

```<code>Dictionary<string, string> connStrs = new Dictionary<string, string>();
connStrs.Add("p", Configuration.GetConnectionString("Sample1con"));
connStrs.Add("m", Configuration.GetConnectionString("Sample2con"));
DbContextFactory.SetConnectionString(connStrs);
</code>```

In action usage

```<code>var _context = DbContextFactory.Create(db); ///Db would be your URL string.
</code>```

Body:
I am developing webapi with some knowledge of Core 2.0
I need to create two link to produce different result from different database both database schema are the same.

Like https://localhost:5000/m/University

or https://localhost:5000/v/University

They both fire in different database with same webapi application and give result it. I can produced result but I have to either create two webapi project or change connection string ("MConn") in Start up class.

  public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<IISOptions>(options => { options.AutomaticAuthentication = true; });
        services.AddDbContext<PIDBContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("MConn")));
        services.AddMvc();
    }

Could you help me how to use same Webapi project with different connection string based on Https request?

Thanks

Body:
Found the solution:

Create DbContextFactory

public static class DbContextFactory
{
    public static Dictionary<string, string> ConnectionStrings { get; set; }

    public static void SetConnectionString(Dictionary<string, string> connStrs)
    {
        ConnectionStrings = connStrs;
    }

    public static AppContext Create(string connid)
    {
        if (!string.IsNullOrEmpty(connid))
        {
            var connStr = ConnectionStrings[connid];
            var optionsBuilder = new DbContextOptionsBuilder<AppContext >();
            optionsBuilder.UseSqlServer(connStr);
            var db = new AppContext (optionsBuilder.Options);
            return db;
        }
        else
        {
            throw new ArgumentNullException("Connection failed becuase of no Connection ID");
        }
   }
}

Project Json file:

{
    "ConnectionStrings": {
    "Sample1con": "your 1st connection string",
    "Sample2con": "your 2nd connection string"
    }
}

In Configure method in Startup class declare Dictionary

Dictionary<string, string> connStrs = new Dictionary<string, string>();
connStrs.Add("p", Configuration.GetConnectionString("Sample1con"));
connStrs.Add("m", Configuration.GetConnectionString("Sample2con"));
DbContextFactory.SetConnectionString(connStrs);

In action usage

var _context = DbContextFactory.Create(db); ///Db would be your URL string.


问:
Regexp filtering by custom dimensions in Google Analytics API in Python
I am querying the Google Analytic API in Python 2.7. Below are two examples of code. The first one works, but does not involve the filtering I want to do. The second chunk of code does not work, but represents my attempt to filter my results based on the content of a custom GA dimension, which in this case is whether pages contain a custom GA tag.

This is how I query the GA API, which works, but does not involve the filtering I need:

```<code>import datetime
import time
from datetime import timedelta

# get start and end dates in correct format
start_date = d1.strftime('%Y-%m-%d')
end_date   = d2.strftime('%Y-%m-%d')

# Create ReportRequest object
response = service.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': 'ga:32981293',

                'dateRanges': [{'startDate': start_date, 'endDate': end_date}],

                'metrics': [{'expression': 'ga:sessions'},
                            {'expression': 'ga:pageviews'},
                            {'expression': 'ga:users'},
                            {'expression': 'ga:exits'},
                            {'expression': 'ga:avgSessionDuration'},
                            {'expression': 'ga:avgTimeonPage'},
                            {'expression': 'ga:sessionsPerUser'},
                            {'expression': 'ga:percentNewSessions'},
                            {'expression': 'ga:bounceRate'}],

                'dimensions': [{"name": "ga:pagePath"}],

                'orderBys': [{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],

                'pageSize': 500

            }]
    }
).execute()
</code>```

So, the above could gives me an object where my Page Paths are sorted based on pageviews, and I'm getting the associated metrics that I asked for.

What I want to do is add a filter so that I only get this information for Page Paths that contain a certain tag. In this case, I have a custom GA dimension called "News Page Tags" and I want to get information only for Page Paths that have specific News Page Tags.

Here's one attempt at this, which does not work. I'm hoping there is some kind of syntax issue that someone can help me clear up.

```<code>import datetime
import time
from datetime import timedelta

# get start and end dates in correct format
start_date = d1.strftime('%Y-%m-%d')
end_date   = d2.strftime('%Y-%m-%d')

cur_tag = 'example string'

# Create ReportRequest object
response = service.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': 'ga:32981293',

                'dateRanges': [{'startDate': start_date, 'endDate': end_date}],

                'metrics': [{'expression': 'ga:sessions'},
                            {'expression': 'ga:pageviews'},
                            {'expression': 'ga:users'},
                            {'expression': 'ga:exits'},
                            {'expression': 'ga:avgSessionDuration'},
                            {'expression': 'ga:avgTimeonPage'},
                            {'expression': 'ga:sessionsPerUser'},
                            {'expression': 'ga:percentNewSessions'},
                            {'expression': 'ga:bounceRate'}],

                'dimensions': [{"name": "ga:pagePath"},
                               {"name": "ga:newsPageTags"}],

                'orderBys': [{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],

                'dimensionFilterClauses': [
                            {"filters": [{"dimensionName": "ga:newsPageTags",
                                          "operator": "REGEXP",
                                          "expressions": [cur_tag]}]
                            }
                                        ],

                'pageSize': 500

            }]
    }
).execute()
</code>```

So, in the above, I added "ga:newsPageTags" as a second dimension, with the intention of filtering pages so that I only get metrics for pages that have "cur_tag" as one of their News Page Tags.

Running that second chunk of code with the filter yields the following error:

Traceback (most recent call last):
  File "", line 31, in
  File "build/bdist.macosx-10.7-x86_64/egg/oauth2client/_helpers.py", line 133, in positional_wrapper
  File "build/bdist.macosx-10.7-x86_64/egg/googleapiclient/http.py", line 842, in execute
googleapiclient.errors.HttpError: https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "Unknown dimension(s): ga:newsPageTags
For details see https://developers.google.com/analytics/devguides/reporting/core/dimsmets.">

Obviously I am not specifying my custom dimension correctly, and I am hoping there is a way to query the GA API to filter based on custom tags, although I haven't had any luck finding good documentation to help me solve this problem.

Thanks!

答:
Custom dimensions in the API are specified by number rather than the name. So for example you would filter by ga:dimension15 rather than ga:newsPageTags

https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=custom_variables_or_columns

Body:
I am querying the Google Analytic API in Python 2.7. Below are two examples of code. The first one works, but does not involve the filtering I want to do. The second chunk of code does not work, but represents my attempt to filter my results based on the content of a custom GA dimension, which in this case is whether pages contain a custom GA tag.

This is how I query the GA API, which works, but does not involve the filtering I need:

import datetime
import time
from datetime import timedelta

# get start and end dates in correct format
start_date = d1.strftime('%Y-%m-%d')
end_date   = d2.strftime('%Y-%m-%d')

# Create ReportRequest object
response = service.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': 'ga:32981293',

                'dateRanges': [{'startDate': start_date, 'endDate': end_date}],

                'metrics': [{'expression': 'ga:sessions'},
                            {'expression': 'ga:pageviews'},
                            {'expression': 'ga:users'},
                            {'expression': 'ga:exits'},
                            {'expression': 'ga:avgSessionDuration'},
                            {'expression': 'ga:avgTimeonPage'},
                            {'expression': 'ga:sessionsPerUser'},
                            {'expression': 'ga:percentNewSessions'},
                            {'expression': 'ga:bounceRate'}],

                'dimensions': [{"name": "ga:pagePath"}],

                'orderBys': [{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],

                'pageSize': 500

            }]
    }
).execute()

So, the above could gives me an object where my Page Paths are sorted based on pageviews, and I'm getting the associated metrics that I asked for.

What I want to do is add a filter so that I only get this information for Page Paths that contain a certain tag. In this case, I have a custom GA dimension called "News Page Tags" and I want to get information only for Page Paths that have specific News Page Tags.

Here's one attempt at this, which does not work. I'm hoping there is some kind of syntax issue that someone can help me clear up.

import datetime
import time
from datetime import timedelta

# get start and end dates in correct format
start_date = d1.strftime('%Y-%m-%d')
end_date   = d2.strftime('%Y-%m-%d')

cur_tag = 'example string'

# Create ReportRequest object
response = service.reports().batchGet(
    body={
        'reportRequests': [
            {
                'viewId': 'ga:32981293',

                'dateRanges': [{'startDate': start_date, 'endDate': end_date}],

                'metrics': [{'expression': 'ga:sessions'},
                            {'expression': 'ga:pageviews'},
                            {'expression': 'ga:users'},
                            {'expression': 'ga:exits'},
                            {'expression': 'ga:avgSessionDuration'},
                            {'expression': 'ga:avgTimeonPage'},
                            {'expression': 'ga:sessionsPerUser'},
                            {'expression': 'ga:percentNewSessions'},
                            {'expression': 'ga:bounceRate'}],

                'dimensions': [{"name": "ga:pagePath"},
                               {"name": "ga:newsPageTags"}],

                'orderBys': [{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],

                'dimensionFilterClauses': [
                            {"filters": [{"dimensionName": "ga:newsPageTags",
                                          "operator": "REGEXP",
                                          "expressions": [cur_tag]}]
                            }
                                        ],

                'pageSize': 500

            }]
    }
).execute()

So, in the above, I added "ga:newsPageTags" as a second dimension, with the intention of filtering pages so that I only get metrics for pages that have "cur_tag" as one of their News Page Tags.

Running that second chunk of code with the filter yields the following error:

Traceback (most recent call last):
  File "", line 31, in
  File "build/bdist.macosx-10.7-x86_64/egg/oauth2client/_helpers.py", line 133, in positional_wrapper
  File "build/bdist.macosx-10.7-x86_64/egg/googleapiclient/http.py", line 842, in execute
googleapiclient.errors.HttpError: https://analyticsreporting.googleapis.com/v4/reports:batchGet?alt=json returned "Unknown dimension(s): ga:newsPageTags
For details see https://developers.google.com/analytics/devguides/reporting/core/dimsmets.">

Obviously I am not specifying my custom dimension correctly, and I am hoping there is a way to query the GA API to filter based on custom tags, although I haven't had any luck finding good documentation to help me solve this problem.

Thanks!


问:
How do I read multiple txt file and save them as respective object names?
I have hundreds of .txt files. I want to automate a process to read them all and save them with their respective file name. For example, I want to save them in this order without typing the name of individual files.

```<code>mytext1.txt <-read.table("./mytext1.txt", sep = "\t")
mytext2.txt <-read.table("./mytext2.txt", sep = "\t")
</code>```

Here is the code I have tried which of course doesn't save the dataframe in a separate object name.

```<code>filelist = list.files(pattern = ".*.txt")
datalist = lapply(filelist, FUN=read.table, header=TRUE, sep = "\t")
</code>```

答:
This may not be the best way, but it should do what you want:

```<code>read.and.write.table <- function(files){
    for(fn in files){
        input <- read.table(file = fn, header = TRUE, sep = "\t")
        assign(x = fn, value = input, envir = .GlobalEnv)
    }
}

filelist = list.files(pattern = ".*.txt")
read.and.write.table(filelist)
</code>```

Will create separate global variables named after your .txt files. Of course you could include some string manipulation to pretty up the names.

Body:
I have hundreds of .txt files. I want to automate a process to read them all and save them with their respective file name. For example, I want to save them in this order without typing the name of individual files.

mytext1.txt <-read.table("./mytext1.txt", sep = "\t")
mytext2.txt <-read.table("./mytext2.txt", sep = "\t")

Here is the code I have tried which of course doesn't save the dataframe in a separate object name.

filelist = list.files(pattern = ".*.txt")
datalist = lapply(filelist, FUN=read.table, header=TRUE, sep = "\t")

Body:
This may not be the best way, but it should do what you want:

read.and.write.table <- function(files){
    for(fn in files){
        input <- read.table(file = fn, header = TRUE, sep = "\t")
        assign(x = fn, value = input, envir = .GlobalEnv)
    }
}

filelist = list.files(pattern = ".*.txt")
read.and.write.table(filelist)

Will create separate global variables named after your .txt files. Of course you could include some string manipulation to pretty up the names.


问:
Localization with NHibernate
Hi guys
I'm a new to NHibernate. I just started development of my next project using NHibernate. One of the requirements is that entity classes should be localized. I'm doing localization the following way:
 - Every entity which should be localized is split into 2 table and 2 entities. For example, I have an entity Service which holds some information, and another entity ServiceLocale which holds localized properties, such as Name, description etc. Same goes for tables.

Service has a protected field which holds a list of ServiceLocales. ServiceLocale has a property Culture which specifies which language the object belongs.

The list of ServiceLocale is loaded eagerly from xml mapping file. So when Service is loaded from database, all ServiceLocales also is loaded for this service object.

Service has public properties, Name and Description. From this properties, I check what's current culture, load appropriate ServiceLocale object and return ServiceLocale's Name and Description.

Service is persisted using a repository. The repository checks saves or updates the service, and also all of it's ServiceLocale objects.

So my question is: is there a better way to achieve this kind of transparent localization via NHibernate?
Thanks

答:
Ok guys, for whom whos interested in answer, I have one.
Jason Meckley wrote me about the solution on nhibernate newsgroup. Looks like it's best to use nhibernate filters.
Here's his answer:

if you mean to load all the locals any time you query the primary entity, that's a preformance problem waiting to happen. now it may work if you introduce a filter which can be set right after the session opens. this way only a single result is returned per localized resource. it would also bleed into your domain model.

```<code>//class
private ISet<string> localizedvalues;
public string Value{get{return localizedvalues.FirstOrDefault();}}

//mapping
<class name="myentity">
   <set name="localizedvalues" access="field" lazy="false" join="fetch">
         <filter name="CultureFilter" />
         ...
   </set>
</class>
<filter-def name="CultureFilter" condition="cultureId = :culture">
   <param name="culture" type="string" />
</filter-def>

//session configuration
var session = factory.Open();
session.EnableFilter("CultureFilter").SetParameter("culture", Thread.CurrentThread.CurrentCulture.LCID);
</code>```

this is similar to how ayende's examples works, except we are using a set instead of a formula to pull the locale.

Title: Localization with NHibernate

Body:
Ok guys, for whom whos interested in answer, I have one.
Jason Meckley wrote me about the solution on nhibernate newsgroup. Looks like it's best to use nhibernate filters.
Here's his answer:

if you mean to load all the locals any time you query the primary entity, that's a preformance problem waiting to happen. now it may work if you introduce a filter which can be set right after the session opens. this way only a single result is returned per localized resource. it would also bleed into your domain model.

//class
private ISet<string> localizedvalues;
public string Value{get{return localizedvalues.FirstOrDefault();}}

//mapping
<class name="myentity">
   <set name="localizedvalues" access="field" lazy="false" join="fetch">
         <filter name="CultureFilter" />
         ...
   </set>
</class>
<filter-def name="CultureFilter" condition="cultureId = :culture">
   <param name="culture" type="string" />
</filter-def>

//session configuration
var session = factory.Open();
session.EnableFilter("CultureFilter").SetParameter("culture", Thread.CurrentThread.CurrentCulture.LCID);

this is similar to how ayende's examples works, except we are using a set instead of a formula to pull the locale.


问:
How to insert text into terminal buffer of nvim by :normal command?
In a normal buffer of nvim, the following ex command works.

```<code>:normal! GAabcd
</code>```

This adds the text "abcd" to the current normal buffer.

But in a terminal buffer of nvim, the above ex command doesn't work!

```<code>:normal! GAabcd
</code>```

This just converts the terminal buffer into '-- TERMINAL --' mode and the "abcd" isn't added!

Why isn't the text added? How can I accomplish that?

答:
Your answer is correct in that it's not possible to append text using :normal! GAfoo. However, in the interests of answering your last question, you can do this:

```<code>:normal! "0p
</code>```

So if you happen to have what you need in a register, you can always paste it.

Body:
In a normal buffer of nvim, the following ex command works.

:normal! GAabcd

This adds the text "abcd" to the current normal buffer.

But in a terminal buffer of nvim, the above ex command doesn't work!

:normal! GAabcd

This just converts the terminal buffer into '-- TERMINAL --' mode and the "abcd" isn't added!

Why isn't the text added? How can I accomplish that?

Body:
Your answer is correct in that it's not possible to append text using :normal! GAfoo. However, in the interests of answering your last question, you can do this:

:normal! "0p

So if you happen to have what you need in a register, you can always paste it.


问:
Adding zero to my complex number class
I'm creating my own complex number class (not using Python's built in one) and I'm running into a problem when I try to add zero to my complex number. For reference this is the error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "display.py", line 25, in __init__
t.color(mandelbrot(c).getColor())
File "C:\Users\Joe\Desktop\Python\mandelbrot.py", line 10, in __init__
z = z*z + self.__starting_value
TypeError: unsupported operand type(s) for +: 'int' and 'complex'
</code>```

Where self.__starting_value is the complex number.

The addition definition goes as follows:

```<code>class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        return complex(self.__real + other.__real, self.__imag + other.__imag)
</code>```

The solution should be simple enough but I am still learning Python and could use the help.

答:
int + complex will first try to useint.__add__. complex + int will first try to use complex.__add__.

You need to implement complex.__radd__. See the related note in Emulating numeric types:

These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

You will need to handle the case where other is int in both complex.__add__ and complex.__radd__.

Title: Adding zero to my complex number class

Body:
I'm creating my own complex number class (not using Python's built in one) and I'm running into a problem when I try to add zero to my complex number. For reference this is the error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "display.py", line 25, in __init__
t.color(mandelbrot(c).getColor())
File "C:\Users\Joe\Desktop\Python\mandelbrot.py", line 10, in __init__
z = z*z + self.__starting_value
TypeError: unsupported operand type(s) for +: 'int' and 'complex'

Where self.__starting_value is the complex number.

The addition definition goes as follows:

class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        return complex(self.__real + other.__real, self.__imag + other.__imag)

The solution should be simple enough but I am still learning Python and could use the help.