问:
Synthesis (Top Level Function Warnings)
I am new in vivado HLS , I'm trying to convert a c++ code to vhdl and I have some synthesis problems.  I hope that someone can help me.

Here is a listing of the errors:

@E [SYNCHK-42] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\bits/stl_construct.h:80: pointer comparison is not supported.  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-11] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\bits/stl_vector.h:113: Variable 'this.assign.3' has an unsynthesizable type 'vector >' (possible cause(s): pointer to pointer or global pointer).  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-41] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\ext/new_allocator.h:89: unsupported pointer reinterpretation from type 'i8*' to type 'pointer'.  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-71] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\ext/new_allocator.h:89: function 'operator new(unsigned long long)' has no function body.  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-11] filtre/filtre/filtre_passhautbutter.cpp:16: Argument 'y' of function 'filtre_passhautbutter' (filtre/filtre/filtre_passhautbutter.cpp:12) has an unsynthesizable type (possible cause(s): structure variable cannot be decomposed due to unsupported type conversion or memory copy operation).  projethls:solution1  7 juin 2017 11:53:27

here is the code:

// function

```<code>#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <vector>

using namespace std;

//Definier la fonction filtre_passhautbutter(x)  qui retouren un matrice de type double

vector <vector <double> > filtre_passhautbutter(vector <vector <double> > x)
{
    int heigth=6;
    int width=1;
    vector <vector <double> > y (heigth,vector<double>(width, 0.0));
    //Definir le vecteur b
    vector <double> b;
    b.push_back(0.9691);
    b.push_back(-2.9072);
    b.push_back(2.9072);
    b.push_back(-0.9691);
    //Definir le vecteur a
    vector <double> a;
    a.push_back(1.0000);
    a.push_back(-2.9372);
    a.push_back(2.8763);
    a.push_back(-0.9391);

    //Remplir le vecteur y par les valeurs correspondentes
    for (int n=4; n< x.size() ;n++)
    {

        double calcul= (b[0]*x[n-1][0]) + (b[1]*x[n-2][0]) + (b[2]*x[n-3][0]) +(b[3]*x[n-4][0]) - (a[1]*y[n-2][0]) - (a[2]*y[n-3][0]) - (a[3]*y[n-4][0]);
        y[0].push_back(calcul);
    }
    return y;
}
</code>```

//main:

```<code>#include <stdio.h>
#include <math.h>
#include <vector>

using namespace std;
vector <vector <double> > filtre_passhautbutter(vector <vector <double> > x);

int main()
{
    int heigth=6;
    int width=1;
    vector <vector <double> > x;
    x.push_back(vector<double>(12.5));
    x.push_back(vector<double>(19.5));
    x.push_back(vector<double>(6));
    x.push_back(vector<double>(12));
    x.push_back(vector<double>(14.5));
    x.push_back(vector<double>(15));

    vector <vector <double> > y (heigth,vector<double>(width));
    y =filtre_passhautbutter(x);

    return 0;
}
</code>```

答:
The simple answer is: you cannot convert any random snippet of C/C++ code to (V)HDL. At least: Xilinx HLS cannot. The code has to be written in a specific way, using compatible data types, etc.

What do you want to achieve? Is your current approach (C++-to-HDL) the best approach? (Did you know that Xilinx has a filter design wizard? i.e. FIR Compiler)

If you really want to use HLS, you should start simple. Use a learning guide, which you can find online.

Title: Synthesis (Top Level Function Warnings)

Body:
I am new in vivado HLS , I'm trying to convert a c++ code to vhdl and I have some synthesis problems.  I hope that someone can help me.

Here is a listing of the errors:

@E [SYNCHK-42] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\bits/stl_construct.h:80: pointer comparison is not supported.  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-11] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\bits/stl_vector.h:113: Variable 'this.assign.3' has an unsynthesizable type 'vector >' (possible cause(s): pointer to pointer or global pointer).  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-41] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\ext/new_allocator.h:89: unsupported pointer reinterpretation from type 'i8*' to type 'pointer'.  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-71] C:/Xilinx/Vivado_HLS/2013.4/win64/tools/clang/bin..\lib\clang\3.1/../../../include/c++/4.5.2\ext/new_allocator.h:89: function 'operator new(unsigned long long)' has no function body.  projethls:solution1  7 juin 2017 11:53:27

@E [SYNCHK-11] filtre/filtre/filtre_passhautbutter.cpp:16: Argument 'y' of function 'filtre_passhautbutter' (filtre/filtre/filtre_passhautbutter.cpp:12) has an unsynthesizable type (possible cause(s): structure variable cannot be decomposed due to unsupported type conversion or memory copy operation).  projethls:solution1  7 juin 2017 11:53:27

here is the code:

// function

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <vector>

using namespace std;

//Definier la fonction filtre_passhautbutter(x)  qui retouren un matrice de type double

vector <vector <double> > filtre_passhautbutter(vector <vector <double> > x)
{
    int heigth=6;
    int width=1;
    vector <vector <double> > y (heigth,vector<double>(width, 0.0));
    //Definir le vecteur b
    vector <double> b;
    b.push_back(0.9691);
    b.push_back(-2.9072);
    b.push_back(2.9072);
    b.push_back(-0.9691);
    //Definir le vecteur a
    vector <double> a;
    a.push_back(1.0000);
    a.push_back(-2.9372);
    a.push_back(2.8763);
    a.push_back(-0.9391);

    //Remplir le vecteur y par les valeurs correspondentes
    for (int n=4; n< x.size() ;n++)
    {

        double calcul= (b[0]*x[n-1][0]) + (b[1]*x[n-2][0]) + (b[2]*x[n-3][0]) +(b[3]*x[n-4][0]) - (a[1]*y[n-2][0]) - (a[2]*y[n-3][0]) - (a[3]*y[n-4][0]);
        y[0].push_back(calcul);
    }
    return y;
}

//main:

#include <stdio.h>
#include <math.h>
#include <vector>

using namespace std;
vector <vector <double> > filtre_passhautbutter(vector <vector <double> > x);

int main()
{
    int heigth=6;
    int width=1;
    vector <vector <double> > x;
    x.push_back(vector<double>(12.5));
    x.push_back(vector<double>(19.5));
    x.push_back(vector<double>(6));
    x.push_back(vector<double>(12));
    x.push_back(vector<double>(14.5));
    x.push_back(vector<double>(15));

    vector <vector <double> > y (heigth,vector<double>(width));
    y =filtre_passhautbutter(x);

    return 0;
}


来源: stackexchange

问:
Not able to link a Carthage framework to Xcode project
I am trying to link a new framework downloaded via Carthage to one of my project but getting a linker error:

I'm following these steps:

Updated the Cartfile with the framework location.

Run carthage update command to fetch the framework.

Under project target -> Build Phase added a new Run script and renamed it to Framework Copy.

Added the script to copy the framework from the file system : $(SRCROOT)/Carthage/Build/iOS/CleanroomLogger.framework.

Dragged and dropped the framework from the mentioned location under Link Binary With Libraries section of project target -> Build Phase.

Double checked the Framework Search Path under build settings and it seems to be set correctly : $(PROJECT_DIR)/Carthage/Build/iOS.

Am I missing something?

答: Eventually it turned out to be deployment target issue. The framework I was linking was supported with minimum deployment target as 8 and I was running with 7 :). I wish the build error could be more descriptive.</p>

ContentLicense: CC BY-SA 3.0


问:
Error on run of NoraUi DEMO with Internet Explorer
When I run by Chrome or PhantomJs the NoraUi DEMO is OK but by Internet explorer, I have this error:</p>

```<code>[2017-06-08 10:34:02]: HTML title Exception
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for condition to not be valid: title to be "". Current title: "" (tried for 20 second(s) with 500 MILLISECONDS interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:232)
    at noraui.utils.Context.waitUntil(Context.java:426)
    at noraui.application.page.demo.DemoPage.checkPage(DemoPage.java:43)
    at noraui.application.steps.demo.HelloByeSteps.checkDemoPortalPage(HelloByeSteps.java:44)
    at noraui.application.steps.demo.HelloByeSteps$$EnhancerByGuice$$35e140d9.CGLIB$checkDemoPortalPage$6(<generated>)
    at noraui.application.steps.demo.HelloByeSteps$$EnhancerByGuice$$35e140d9$$FastClassByGuice$$928eba72.invoke(<generated>)
    at com.google.inject.internal.cglib.proxy.$MethodProxy.invokeSuper(MethodProxy.java:228)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:75)
    at noraui.cucumber.interceptor.StepInterceptor.invoke(StepInterceptor.java:63)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:75)
    at com.google.inject.internal.InterceptorStackCallback.intercept(InterceptorStackCallback.java:55)
    at noraui.application.steps.demo.HelloByeSteps$$EnhancerByGuice$$35e140d9.checkDemoPortalPage(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:48)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.ExamplesRunner.run(ExamplesRunner.java:59)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.ScenarioOutlineRunner.run(ScenarioOutlineRunner.java:53)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)
Caused by: org.openqa.selenium.NoSuchWindowException: Unable to get browser (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 17 milliseconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'ITEM-72885', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{se:ieOptions={browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=false, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, ignoreZoomSetting=true, ie.fileUploadDialogTimeout=3000, ie.useLegacyFileUploadDialogHandling=false, nativeEvents=true, ie.ensureCleanSession=true, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=true, initialBrowserUrl=http://localhost:6546/, ignoreProtectedModeSettings=true, enableElementCacheCleanup=true}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, version=11, platform=WINDOWS, unexpectedAlertBehaviour=accept}]
</code>```

答: Going to Internet Options --> Security --> "Enable Protected Mode" on ALL zones should either be checked or ALL unchecked.

Body:
When I run by Chrome or PhantomJs the NoraUi DEMO is OK but by Internet explorer, I have this error:

[2017-06-08 10:34:02]: HTML title Exception
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for condition to not be valid: title to be "". Current title: "" (tried for 20 second(s) with 500 MILLISECONDS interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:80)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:232)
    at noraui.utils.Context.waitUntil(Context.java:426)
    at noraui.application.page.demo.DemoPage.checkPage(DemoPage.java:43)
    at noraui.application.steps.demo.HelloByeSteps.checkDemoPortalPage(HelloByeSteps.java:44)
    at noraui.application.steps.demo.HelloByeSteps$$EnhancerByGuice$$35e140d9.CGLIB$checkDemoPortalPage$6(<generated>)
    at noraui.application.steps.demo.HelloByeSteps$$EnhancerByGuice$$35e140d9$$FastClassByGuice$$928eba72.invoke(<generated>)
    at com.google.inject.internal.cglib.proxy.$MethodProxy.invokeSuper(MethodProxy.java:228)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:75)
    at noraui.cucumber.interceptor.StepInterceptor.invoke(StepInterceptor.java:63)
    at com.google.inject.internal.InterceptorStackCallback$InterceptedMethodInvocation.proceed(InterceptorStackCallback.java:75)
    at com.google.inject.internal.InterceptorStackCallback.intercept(InterceptorStackCallback.java:55)
    at noraui.application.steps.demo.HelloByeSteps$$EnhancerByGuice$$35e140d9.checkDemoPortalPage(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at cucumber.runtime.Utils$1.call(Utils.java:40)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:34)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:48)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.ExamplesRunner.run(ExamplesRunner.java:59)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.ScenarioOutlineRunner.run(ScenarioOutlineRunner.java:53)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:367)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:274)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:161)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:290)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:242)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:121)
Caused by: org.openqa.selenium.NoSuchWindowException: Unable to get browser (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 17 milliseconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'ITEM-72885', ip: '192.168.56.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{se:ieOptions={browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=false, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, ignoreZoomSetting=true, ie.fileUploadDialogTimeout=3000, ie.useLegacyFileUploadDialogHandling=false, nativeEvents=true, ie.ensureCleanSession=true, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=true, initialBrowserUrl=http://localhost:6546/, ignoreProtectedModeSettings=true, enableElementCacheCleanup=true}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, version=11, platform=WINDOWS, unexpectedAlertBehaviour=accept}]


问:
Service Bus Queue nightmare. Messages disappeared
We are running a cloud service on two different instances. This cloud service spins up a receiver on a service bus queue. This receiver is configured as:
1. Peek and lock mode
2. Auto complete = true
3. RenewLockTimeout = 10 mins
4. MaxConcurrentMessages = 1
5. PrefetchCount = default (should be 0)

For what I know this means that a maximum of two messages are processed at the same time (one per instance) and messages are automatically removed from the queue as soon as the message handler is completed.

Now, few days ago Azure decided to update our instances. I've seen from the log that at 18.18 the first instance was requested to stop. At 18.24 the instance was stopped and at 18.27 came back online. At 18.28 the second instance was requested to stop and at 18.35 it was back online.

Seven messages has been enqueued at 18.23. One of them produced the expected record on the DB (i.e. the handler was executed successfully). The other 6, NO. Dead letter queue is enabled, but empty.

In theory my code should stop receiving messages as soon as the roles enter in the OnStop method. A cancellation token is canceled and the message handler is "paused" introducing a delay for 10 mins (so, for what I know, the message shouldn't be completed and then it should be processed again). So I cannot say If the first message has been processed by the first or the second machine. But it was processed. And I'm sure that the other 6 were in the queue.

If there is an exception in the message handler, I send it to Application Insights and rethrow (to let the handler fail and process the message again). But I have no evidence of that.

I think I've checked everything, and I cannot tell why those messages disappeared. In your experience, what should that be?

Is that normal that Azure waits for 5 minutes after shutting down? Or is that a signal that I'm not honoring the cancellation token?

Thanks

答:
As we know, the receiver can read a message from a Service Bus queue in two different ways:  ReceiveAndDelete and Peek-lock. The ReceiveAndDelete mode, if the receiver crashes before it finishes processing the message, the message will be lost. The Peek-lock mode, if the receiver crashes before it finishes processing the message and do not complete the message, the message will not be lost/disappear. </p>

<p>As others said, not seeing your code, it is hard to find the issue. If possible, please modify your code to set OnMessageOptions.AutoComplete property to false, and explicitly call Complete() after the receiver finishes processing the message and creating record on your DB, and then check if it could solve the issue. </p>

Body:
As we know, the receiver can read a message from a Service Bus queue in two different ways:  ReceiveAndDelete and Peek-lock. The ReceiveAndDelete mode, if the receiver crashes before it finishes processing the message, the message will be lost. The Peek-lock mode, if the receiver crashes before it finishes processing the message and do not complete the message, the message will not be lost/disappear.

As others said, not seeing your code, it is hard to find the issue. If possible, please modify your code to set OnMessageOptions.AutoComplete property to false, and explicitly call Complete() after the receiver finishes processing the message and creating record on your DB, and then check if it could solve the issue.


问:
SQLException can't delete database [database_name]
Some time when I run my c# mvc web-project

SQLException  can't delete  database [database_name] . [database_name] is in Use

on the line where I am try to retrieve my data from DBContextex Object . But the error is obsoleted when I deleted the database and restarting  the project . It is happening suddenly . After happening the error I restarted the project again then error still exist when ever I deleted the database and restart .
Suppose controller Action has following line

```<code>List<entityname> listent=new DbContext().entitynames.toList();
</code>```

is executing then I am geeting the error on the following line .
I have a database Initializer also.

What may be the problem ?

答:
If you have one of the drop-create initializers set in your constructor like below then EF will recreate the database each time the context is initialized.

```<code>public MyDbContext() : base("MyDbConnectionString")
{
    //TODO: Remove initializer
    Database.SetInitializer<MyDbContext>(new DropCreateDatabaseAlways<MyDbContext>());
    Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());
}
</code>```

If you do want entity framework to do this then make sure that your user account has the required access in SQL Server to do this.

If your database has been created and you only want to apply updates, remove the initializer and use EF migrations instead.

Body:
Some time when I run my c# mvc web-project

SQLException  can't delete  database [database_name] . [database_name] is in Use

on the line where I am try to retrieve my data from DBContextex Object . But the error is obsoleted when I deleted the database and restarting  the project . It is happening suddenly . After happening the error I restarted the project again then error still exist when ever I deleted the database and restart .
Suppose controller Action has following line

List<entityname> listent=new DbContext().entitynames.toList();

is executing then I am geeting the error on the following line .
I have a database Initializer also.

What may be the problem ?

Body:
If you have one of the drop-create initializers set in your constructor like below then EF will recreate the database each time the context is initialized.

public MyDbContext() : base("MyDbConnectionString")
{
    //TODO: Remove initializer
    Database.SetInitializer<MyDbContext>(new DropCreateDatabaseAlways<MyDbContext>());
    Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());
}

If you do want entity framework to do this then make sure that your user account has the required access in SQL Server to do this.

If your database has been created and you only want to apply updates, remove the initializer and use EF migrations instead.


问:
delete if key = value Groovy
I have a ruby script that I need to convert to Groovy, its a simple case of removing a collection if key: value.

So in my setup I make a request to the github api

```<code>def jsonParse(def json) {
  new groovy.json.JsonSlurperClassic().parseText(json)
}

def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
return list
</code>```

This returns output like so

```<code>[
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]
</code>```

In Ruby i would do the following

```<code>array.delete_if { |key| key['prerelease'] == true }
</code>```

How would I approach this with Groovy, if an explanation could be provided that would also be great so i can learn from it

Update

Using the approach from @Rao my list is exactly the same

```<code>def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
list.removeAll(list.findAll{it.prerelease == 'true'})
return list
</code>```

Raw response

```<code>[
  {"prerelease": true, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"],
  {"prerelease": false, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"]
]
</code>```

答:
e. g. with

```<code>array = array.findAll { it.prerelease != 'true' }
</code>```

I guess you don't need anymore explanation?

Title: delete if key = value Groovy

Body:
I have a ruby script that I need to convert to Groovy, its a simple case of removing a collection if key: value.

So in my setup I make a request to the github api

def jsonParse(def json) {
  new groovy.json.JsonSlurperClassic().parseText(json)
}

def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
return list

This returns output like so

[
  [prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
  [prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]

In Ruby i would do the following

array.delete_if { |key| key['prerelease'] == true }

How would I approach this with Groovy, if an explanation could be provided that would also be great so i can learn from it

Update

Using the approach from @Rao my list is exactly the same

def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
list.removeAll(list.findAll{it.prerelease == 'true'})
return list

Raw response

[
  {"prerelease": true, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"],
  {"prerelease": false, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"]
]

Body:
e. g. with

array = array.findAll { it.prerelease != 'true' }

I guess you don't need anymore explanation?


问:
Informatica Powerecenter 9.1.0 Decimal Scale Issue
I am having issues while converting the decimal values to varchar through Informatica 9.1. Both my source and target are in Oracle.
It automatically reduces the value of the digit by "0.01" when I use truncate function.
My Source data type is Amount(Decimal(38,15)); I am using the following expression to convert it to string after I truncate it as follows: TO_CHAR(TRUNC(Amount,2)).
Source

My target data type is varchar(255). And below is the snap of data in target.
For 9.52 amount after truncation the value changed to 9.51 as seen in snap shot.
Target

Could anyone help to sort out the issue?

答:
As stated before is the way to_char function behave and how number round is handled in Informatica.
This could help if you want more "precision" and have a less rounding

From Informatica PowerCenter Guide:

The PowerCenter Integration Service converts decimal ports with
  precision greater than 15 to a double and returns TO_CHAR values in
  scientific notation.

To avoid this, you must enable high precision. When you enable high
  precision, PowerCenter supports decimals up to a precision of 28.

Note the high precision is a check box into the workflow under propety tab

To resolve this issue select the enable high precision for the session as follows:

In Workflow Manager, open the session task for editing.
Click the Properties tab.
Select the Enable high precision option.
Close the session and save.

PowerCenter session using TO_CHAR on decimal field


问:
How to choose number of hidden layers and nodes in neural network?
What does number of hidden layers in a multilayer perceptron neural network do to the way neural network behaves? Same question for number of nodes in hidden layers?

Let's say I want to use a neural network for hand written character recognition. In this case I put pixel colour intensity values as input nodes, and character classes as output nodes.

How would I choose number of hidden layers and nodes to solve such problem?

答:
All the above answers are of course correct but just to add some more ideas:
Some general rules are the following based on this paper: 'Approximating Number of Hidden layer neurons in Multiple Hidden Layer BPNN Architecture' by Saurabh Karsoliya

In general:

The number of hidden layer neurons are 2/3 (or 70% to 90%) of the size of the input layer. If this is insufficient then number of output layer neurons can be added later on.

The number of hidden layer neurons should be less than twice of the number of neurons in input layer.

The size of the hidden layer neurons is between the input layer size and the output layer size.

Keep always in mind that you need to explore and try a lot of different combinations. Also, using GridSearch you could find the "best model and parameters".

E.g. we can do a GridSearch in order to determine the "best" size of the hidden layer.

ContentLicense: CC BY-SA 4.0


问:
how to declare global variable in python
I am actually learning phase in python and I didn't get the help from google as well about it so guys please help me about global variable on specific requirement.

I use python 3.5 in ubuntu OS 16.04 and I have to declare a global variable in one file and initialise with a default value and import that into another python file in the same package but when to declare that and import that I get the following error in that file where import the global variable:

AttributeError: module 'App.views' has no attribute 'request_dict'

Don't worry, I have code as well which is given below:

views.py:

```<code>from collections import OrderedDict

request_dict = OrderedDict()

def hello():
    print("hello from views file")
</code>```

task.py:

```<code>from . import views

def addQueueTask():
    print('from task.py: ', views.request_dict)
</code>```

答:
```<code>from views import *
</code>```

will import all objects and methods from views. However it generally something you shouldn't do

Please consider

```<code>from views import request_dict
</code>```

to only import the variable(s) you need and avoid polluting your namespace.

Body:
I am actually learning phase in python and I didn't get the help from google as well about it so guys please help me about global variable on specific requirement.

I use python 3.5 in ubuntu OS 16.04 and I have to declare a global variable in one file and initialise with a default value and import that into another python file in the same package but when to declare that and import that I get the following error in that file where import the global variable:

AttributeError: module 'App.views' has no attribute 'request_dict'

Don't worry, I have code as well which is given below:

views.py:

from collections import OrderedDict

request_dict = OrderedDict()

def hello():
    print("hello from views file")

task.py:

from . import views

def addQueueTask():
    print('from task.py: ', views.request_dict)

Body:
from views import *

will import all objects and methods from views. However it generally something you shouldn't do

Please consider

from views import request_dict

to only import the variable(s) you need and avoid polluting your namespace.


问:
cron tab not working with virtual env django
I am using python django community ami from bitnami and i am not able to execute python script in cron via virtual env

Directly executing script in terminal works e.g.

/path/to/env/bin/python /path/to/script.py (works)

crontab (non sudo)

*/opt/bitnami/python/bin/python /path/to/script.py (works)

/path/to/env/bin/python /path/to/script.py >> /tmp/log.out 2>&1 (not working)*

"Cannot locate wrapped file"

答:
One possible error is forgetting to enable the virtual environment.

I'd have expected to see a crontab line along the lines of the following (taken from django-cron) which includes a call to '.../bin/activate'.

```<code>> crontab -e */5 * * * * source /home/ubuntu/.bashrc && source /home/ubuntu/work/your-project/bin/activate && python /home/ubuntu/work/your-project/src/manage.py runcrons > /home/ubuntu/cronjob.log
</code>```

Body:
One possible error is forgetting to enable the virtual environment.

I'd have expected to see a crontab line along the lines of the following (taken from django-cron) which includes a call to '.../bin/activate'.

> crontab -e */5 * * * * source /home/ubuntu/.bashrc && source /home/ubuntu/work/your-project/bin/activate && python /home/ubuntu/work/your-project/src/manage.py runcrons > /home/ubuntu/cronjob.log


问:
Android Firebase "UserProfileChangeRequest" is working, but not after user sign out and sign in again
I'm trying learn Android Firebase. When I program a code of Register user, it work successfully. But when I called "userProfileChangeRequest" method
to change username OR profile picture uri  it is work successfully, but new data isn't view to user before he log out and sign in again.

Why? What is the problem?

Here is my code:

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

     if(uriImage == null){
            //user didn't select profile picture
          return;
        }
        else if(!App.isOnline(this)) {
             Toast.makeText(this, getResources().getString(R.string.checkInternetConnection), Toast.LENGTH_SHORT).show();
             return;
         }else{
         mStorage = FirebaseStorage.getInstance().getReference();

         //upload picture to get Path
         Log.e(TAG,"test3");
            StorageReference path = mStorage.child("ProfilePicture").child(uriImage.getLastPathSegment()
                    + "_"
                    + App.randomNumber()
                    + "_"
                    + App.randomNumber());

         Log.e(TAG,"test4"+path);
            path.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Log.e(TAG,"Upload success");
                    @SuppressWarnings("VisibleForTests") Uri downloadUrl= taskSnapshot.getDownloadUrl();

                    //Preview profile picture before set it to user
                    Picasso.with(Setting.this).load(downloadUrl).into(profilePicture);
                    setUserProfilePicture(downloadUrl);

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    TF=false;
                    Toast.makeText(Setting.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();

                }
            });
        }

    }

private void setUserProfilePicture(Uri downloadUrl) {

        //mProgress.setMessage(getResources().getString(R.string.updateProfile));

        FirebaseUser user = mAuth.getCurrentUser();

        if(user != null) {
            Log.e(TAG,"test6");
            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                    .setPhotoUri(downloadUrl)
                    .build();
            user.updateProfile(profileUpdates)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Log.e(TAG, "Update Profile Successful");
                                Toast.makeText(Setting.this, getResources().getString(R.string.updateSuccessful), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "Update Failure");
                    Toast.makeText(Setting.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
</code>```

答: Maybe you could try to update the user image in UI inside onCompleteListener ? As there are no view update actions done after you UserProfileChangeRequest. </p>

Body:
I'm trying learn Android Firebase. When I program a code of Register user, it work successfully. But when I called "userProfileChangeRequest" method
to change username OR profile picture uri  it is work successfully, but new data isn't view to user before he log out and sign in again.

Why? What is the problem?

Here is my code:

private void getUriPicture() {

     if(uriImage == null){
            //user didn't select profile picture
          return;
        }
        else if(!App.isOnline(this)) {
             Toast.makeText(this, getResources().getString(R.string.checkInternetConnection), Toast.LENGTH_SHORT).show();
             return;
         }else{
         mStorage = FirebaseStorage.getInstance().getReference();

         //upload picture to get Path
         Log.e(TAG,"test3");
            StorageReference path = mStorage.child("ProfilePicture").child(uriImage.getLastPathSegment()
                    + "_"
                    + App.randomNumber()
                    + "_"
                    + App.randomNumber());

         Log.e(TAG,"test4"+path);
            path.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Log.e(TAG,"Upload success");
                    @SuppressWarnings("VisibleForTests") Uri downloadUrl= taskSnapshot.getDownloadUrl();

                    //Preview profile picture before set it to user
                    Picasso.with(Setting.this).load(downloadUrl).into(profilePicture);
                    setUserProfilePicture(downloadUrl);

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    TF=false;
                    Toast.makeText(Setting.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();

                }
            });
        }

    }

private void setUserProfilePicture(Uri downloadUrl) {

        //mProgress.setMessage(getResources().getString(R.string.updateProfile));

        FirebaseUser user = mAuth.getCurrentUser();

        if(user != null) {
            Log.e(TAG,"test6");
            UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                    .setPhotoUri(downloadUrl)
                    .build();
            user.updateProfile(profileUpdates)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Log.e(TAG, "Update Profile Successful");
                                Toast.makeText(Setting.this, getResources().getString(R.string.updateSuccessful), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "Update Failure");
                    Toast.makeText(Setting.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }


问:
Merging text files line for line batch file
I began with an excel spreadsheet with a couple of columns (a Date of Birth, and a Last Name column). I extrapolated and used a batch file to modify just the date of birth column so that I now have a text file with the following (to be used in a SQL query):

```<code>BirthDateTime = '01/01/2017' AND Name LIKE '
BirthDateTime = '01/01/2016' AND Name LIKE '
</code>```

I now want to take the second column (by creating a separate lastname.txt file) and concatonate it into the output file above line for line so that my last name file, which looks like:

```<code>SMITH
JONES
</code>```

Will merge to a new output file that will look like:

```<code>(BirthDateTime = '01/01/2017' AND Name LIKE '%SMITH%') OR
(BirthDateTime = '01/01/2016' AND Name LIKE '%JONES%') OR
</code>```

Unfortunately I'm a newbie on batch files and I just don't know where to start. I'm including the batch file I used to create the first part below.

Batch File:

```<code>@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo BirthDateTime = '%%a' AND Name LIKE '>>output.txt
)
</code>```

答:
Your question is a bit confusing. You show two textfiles, but your code seems to use some other files (Dates only). Anyway - I covered both possibilities; just use the right echo line.

To read and merge two files use a little trick (using two different methods to read a file):

```<code>@echo off
setlocal enabledelayedexpansion
<t2.txt (
  for /f "delims=" %%a in (t1.txt) do (
    set /p name=
    echo (%%a!name!'^) OR
    REM echo (BirthDateTime = '%%a' AND Name LIKE '!name!'^) OR
  )
)>out.txt
type out.txt
</code>```

The other trick is escaping the closing paranthese in the echo statement with a ^. If you don't, the parser takes it for the loop end, which will result in a crippled output and an errormessage "OR" is not recognized as a valid command ...

Body:
I began with an excel spreadsheet with a couple of columns (a Date of Birth, and a Last Name column). I extrapolated and used a batch file to modify just the date of birth column so that I now have a text file with the following (to be used in a SQL query):

BirthDateTime = '01/01/2017' AND Name LIKE '
BirthDateTime = '01/01/2016' AND Name LIKE '

I now want to take the second column (by creating a separate lastname.txt file) and concatonate it into the output file above line for line so that my last name file, which looks like:

SMITH
JONES

Will merge to a new output file that will look like:

(BirthDateTime = '01/01/2017' AND Name LIKE '%SMITH%') OR
(BirthDateTime = '01/01/2016' AND Name LIKE '%JONES%') OR

Unfortunately I'm a newbie on batch files and I just don't know where to start. I'm including the batch file I used to create the first part below.

Batch File:

@echo off
setLocal EnableDelayedExpansion
for /f "tokens=* delims= " %%a in (input.txt) do (
set /a N+=1
echo BirthDateTime = '%%a' AND Name LIKE '>>output.txt
)

Body:
Your question is a bit confusing. You show two textfiles, but your code seems to use some other files (Dates only). Anyway - I covered both possibilities; just use the right echo line.

To read and merge two files use a little trick (using two different methods to read a file):

@echo off
setlocal enabledelayedexpansion
<t2.txt (
  for /f "delims=" %%a in (t1.txt) do (
    set /p name=
    echo (%%a!name!'^) OR
    REM echo (BirthDateTime = '%%a' AND Name LIKE '!name!'^) OR
  )
)>out.txt
type out.txt

The other trick is escaping the closing paranthese in the echo statement with a ^. If you don't, the parser takes it for the loop end, which will result in a crippled output and an errormessage "OR" is not recognized as a valid command ...


问:
Azure storage account displays: No blobs found
I have created a storage account in azure portal and a stream-analytics job that receives data from Iot-Hub and sends it's output to a blob in the storage account.
When I tested the input and output connections in the stream-analytics job account, it verified me that the connections are o.k.

But After sending telematric data to Iot-Hub, I see that the data was indeed received in the storage account, but when entering the blob container and clicking the blob, it displays: No blobs found.

I would be glad to hear any suggestions to what might be the problem,
thanks.

答:
But After sending telematric data to Iot-Hub, I see that the data was indeed received in the storage account, but when entering the blob container and clicking the blob, it displays: No blobs found.

According to your description, I assumed that your job has no output data. I recommend that you could follow the steps below to check with this issue:

Click "MONITORING > Metrics" under your Stream Analytics job;

Check the metrics for Input Events, Runtime Errors, Data Conversion Errors.

If Input Events > 0, the ASA job is able to read data. If not, then you need to check with your input.

If Runtime Errors > 0, means that the ASA Job is able to receive the data but is getting errors while processing the query. Go to the Operation Logsand filter on "Failed" status to find all these errors.

If InputEvents > 0 and OutputEvents = 0, means one of the following:

Query processing resulted in zero output events.

Events or its fields may be malformed, so resulted in zero output after query processing.

Unable to push data to the output sink for connectivity/authentication reasons.

In all of these error cases, operations log messages explain additional details (including what is happening), except for the cases the query logic filtered out all events. If the processing of multiple events generates errors, Stream Analytics logs the first 3 error messages of the same type within 10 minutes to Operations logs and then suppress additional identical errors with a message that reads "Errors are happening too rapidly, these are being suppressed".

Additionally, if you are still not able to figure out the cause, you could go to operations log, select one of the latest entries and click Details button then provide all the details, then we could help you to troubleshoot this issue.


问:
R code to determine the combination of ni and nj that produce the smallest LSD, and assign these to the variable best.n_i and best.n_j
Calculate values of LSD from(lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j))), for values of ni from 2, . . . , 8 and nj from 8, . . . , 2, by creating two different vectors for ni and nj . Use these to compute LSD for combinations of (ni, nj) = (2, 8), (3, 7), . . . , (7, 3), (8, 2). You should be able to do this by redefining n_i and n_j from the first exercise and copying the code that assigns a value to lsd.

Write code to determine the combination of ni and nj that produce the smallest LSD, and assign these to the variable best.n_i and best.n_j. Assign the minimum LSD value to best.LSD. (Hint - use the functions min and which).

Solution: I have solved it partially but Im not able to understand how to find best.n_i and best.n_j. I know I need to use which function. Here is my solution:

```<code>n_i<-c(2:8)

n_i

n_j<-c(8:2)

n_j

print(lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j)))

best.lsd <-min((lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j))))

best.lsd

best.n_i <- which.min(lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j)))
</code>```

答:
In your code best.n_i tells you the position in the vector with the minimum value. It results in 4, meaning the 4th element. So to get the best value for n_i you use:

n_i[best.n_i]

which should result in 5. Similarly the best value for n_j would be:

n_j[best.n_i]

Body:
Calculate values of LSD from(lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j))), for values of ni from 2, . . . , 8 and nj from 8, . . . , 2, by creating two different vectors for ni and nj . Use these to compute LSD for combinations of (ni, nj) = (2, 8), (3, 7), . . . , (7, 3), (8, 2). You should be able to do this by redefining n_i and n_j from the first exercise and copying the code that assigns a value to lsd.

Write code to determine the combination of ni and nj that produce the smallest LSD, and assign these to the variable best.n_i and best.n_j. Assign the minimum LSD value to best.LSD. (Hint - use the functions min and which).

Solution: I have solved it partially but Im not able to understand how to find best.n_i and best.n_j. I know I need to use which function. Here is my solution:

n_i<-c(2:8)

n_i

n_j<-c(8:2)

n_j

print(lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j)))

best.lsd <-min((lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j))))

best.lsd

best.n_i <- which.min(lsd <- 2.085963447*sqrt(0.124611*(1/n_i + 1/n_j)))


问:
Odoo One2many relation with VIEW table in postgresql
I have the following report model:

```<code>class crm_purchased_products(models.Model):
    _name = "crm.purchased_products"
    _description = "Most purchased products report"
    _auto = False

    partner_id = fields.Many2one('res.partner', string='Customer')
    product_id = fields.Many2one('product.product', string='Product')
    invoice_qty = fields.Integer('Number of invoices')
    quantity = fields.Integer('Quantity')
    total_amount_untaxed = fields.Float(string='Total amount', digits=dp.get_precision('Account'))

    def init(self, cr):
        tools.drop_view_if_exists(cr, self._table)
        _query = """CREATE OR REPLACE VIEW crm_purchased_products AS (
            SELECT ail.partner_id AS partner_id, ail.product_id AS product_id,
                COUNT(ail.invoice_id) AS invoice_qty, SUM(ail.quantity) AS quantity,
                SUM(ail.price_subtotal) AS total_amount_untaxed, MAX(ai.date_invoice) AS last_purchase,
                (MAX(ai.date_invoice) - MIN(ai.date_invoice))/COUNT(ail.invoice_id) AS days_between_purchases
            FROM account_invoice_line AS ail
            JOIN account_invoice AS ai ON ail.invoice_id = ai.id
            WHERE ai.type = 'out_invoice' AND ai.state IN ('open','paid')
            GROUP BY ail.partner_id, ail.product_id HAVING ail.product_id > 0 ORDER BY ail.partner_id ASC
        );
        """

    def search(self, cr, uid, args, offset=0, limit=None, order=None,context=None, count=False):
        return super(crm_purchased_products, self).search(cr, uid, args=args, offset=offset, limit=limit, order=order,
        context=context, count=count)

crm_purchased_products()
</code>```

I want to insert as a tree field in res.partner form view to show only the products associated to the contact:

```<code><page name="internal_notes" string="Internal Notes">
                        <field name="purchased_products">
                            <tree string="Most purchased products">
                                <field name="partner_id" invisible="1"/>
                                <field name="product_id"/>
                                <field name="invoice_qty"/>
                                <field name="quantity"/>
                                <field name="total_amount_untaxed"/>
                            </tree>
                        </field>
                    </page>
</code>```

But, when I try to relate it from res.partner:

```<code>purchased_products = fields.One2many('crm.purchased_products', 'partner_id', string='Purchased products', readonly=True, copy=True)
</code>```

I get this error:

ProgrammingError: relation "crm_purchased_products" does not exist
  LINE 1: SELECT "crm_purchased_products".id FROM "crm_purchased_produ...

答:
ID field is auto added to all models from models.Model, so you must get it. Try this:

```<code>def init(self, cr):
    tools.drop_view_if_exists(cr, self._table)
    _query = """CREATE OR REPLACE VIEW crm_purchased_products AS (
        SELECT row_number() OVER () AS id, ail.partner_id AS partner_id, ail.product_id AS product_id,
            COUNT(ail.invoice_id) AS invoice_qty, SUM(ail.quantity) AS quantity,
            SUM(ail.price_subtotal) AS total_amount_untaxed, MAX(ai.date_invoice) AS last_purchase,
            (MAX(ai.date_invoice) - MIN(ai.date_invoice))/COUNT(ail.invoice_id) AS days_between_purchases
        FROM account_invoice_line AS ail
        JOIN account_invoice AS ai ON ail.invoice_id = ai.id
        WHERE ai.type = 'out_invoice' AND ai.state IN ('open','paid')
        GROUP BY row_number() OVER (), ail.partner_id, ail.product_id HAVING ail.product_id > 0 ORDER BY ail.partner_id ASC
    );
    """
</code>```

Body:
I have the following report model:

class crm_purchased_products(models.Model):
    _name = "crm.purchased_products"
    _description = "Most purchased products report"
    _auto = False

    partner_id = fields.Many2one('res.partner', string='Customer')
    product_id = fields.Many2one('product.product', string='Product')
    invoice_qty = fields.Integer('Number of invoices')
    quantity = fields.Integer('Quantity')
    total_amount_untaxed = fields.Float(string='Total amount', digits=dp.get_precision('Account'))

    def init(self, cr):
        tools.drop_view_if_exists(cr, self._table)
        _query = """CREATE OR REPLACE VIEW crm_purchased_products AS (
            SELECT ail.partner_id AS partner_id, ail.product_id AS product_id,
                COUNT(ail.invoice_id) AS invoice_qty, SUM(ail.quantity) AS quantity,
                SUM(ail.price_subtotal) AS total_amount_untaxed, MAX(ai.date_invoice) AS last_purchase,
                (MAX(ai.date_invoice) - MIN(ai.date_invoice))/COUNT(ail.invoice_id) AS days_between_purchases
            FROM account_invoice_line AS ail
            JOIN account_invoice AS ai ON ail.invoice_id = ai.id
            WHERE ai.type = 'out_invoice' AND ai.state IN ('open','paid')
            GROUP BY ail.partner_id, ail.product_id HAVING ail.product_id > 0 ORDER BY ail.partner_id ASC
        );
        """

    def search(self, cr, uid, args, offset=0, limit=None, order=None,context=None, count=False):
        return super(crm_purchased_products, self).search(cr, uid, args=args, offset=offset, limit=limit, order=order,
        context=context, count=count)

crm_purchased_products()

I want to insert as a tree field in res.partner form view to show only the products associated to the contact:

<page name="internal_notes" string="Internal Notes">
                        <field name="purchased_products">
                            <tree string="Most purchased products">
                                <field name="partner_id" invisible="1"/>
                                <field name="product_id"/>
                                <field name="invoice_qty"/>
                                <field name="quantity"/>
                                <field name="total_amount_untaxed"/>
                            </tree>
                        </field>
                    </page>

But, when I try to relate it from res.partner:

purchased_products = fields.One2many('crm.purchased_products', 'partner_id', string='Purchased products', readonly=True, copy=True)

I get this error:

ProgrammingError: relation "crm_purchased_products" does not exist
  LINE 1: SELECT "crm_purchased_products".id FROM "crm_purchased_produ...

Body:
ID field is auto added to all models from models.Model, so you must get it. Try this:

def init(self, cr):
    tools.drop_view_if_exists(cr, self._table)
    _query = """CREATE OR REPLACE VIEW crm_purchased_products AS (
        SELECT row_number() OVER () AS id, ail.partner_id AS partner_id, ail.product_id AS product_id,
            COUNT(ail.invoice_id) AS invoice_qty, SUM(ail.quantity) AS quantity,
            SUM(ail.price_subtotal) AS total_amount_untaxed, MAX(ai.date_invoice) AS last_purchase,
            (MAX(ai.date_invoice) - MIN(ai.date_invoice))/COUNT(ail.invoice_id) AS days_between_purchases
        FROM account_invoice_line AS ail
        JOIN account_invoice AS ai ON ail.invoice_id = ai.id
        WHERE ai.type = 'out_invoice' AND ai.state IN ('open','paid')
        GROUP BY row_number() OVER (), ail.partner_id, ail.product_id HAVING ail.product_id > 0 ORDER BY ail.partner_id ASC
    );
    """


问:
Unsplash API integration in CakePHP
Can any one suggest me how to integrate UnSplash API in cakePHP.

I have already downloaded lib and paste it in vendor folder.But further more please suggest any one.

I have downloaded lib reference from https://github.com/unsplash/unsplash-php.

答:
As per the documentation of unsplash. If you want to get only images then no need to use authentication of unsplash . You can easly get images after hitting API with app id like this:

https://api.unsplash.com/photos/?client_id=YOUR_APPLICATION_ID

So if anyone want to implement search for getting images only developer can access api like this :

https://api.unsplash.com/search/photos?page=1&query=office&client_id=YOUR_APPLICATION_ID

By this you can easily get images and no authorisation required. Further if you want to use more feature then you can use auth of particular unsplash user.

Title: Unsplash API integration in CakePHP


问:
How do you call a function once a day at a certain time in c++?
Well i need to figure out how to call a function at a certain time if my application is running.

it will probably be in a while loop and check the time but i don't want it to check the time every minute but i don't want it to miss the exact time, say 18:00.

is there any way do to this?

答:
If you want to call a specific function from within a program that's already running, use Boost's Date Time library and Asio.

```<code>#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/asio.hpp>

namespace gregorian = boost::gregorian;
namespace posix_time = boost::posix_time;
namespace asio = boost::asio;

asio::io_service io_service_;
asio::deadline_timer timer_ (io_service_);
</code>```

Then set the time. This is an example using a string of the desired time, like "18:00:00". (Note that Boost defaults to UTC for the timestamps!)

```<code>gregorian::date today = gregorian::day_clock::local_day();
posix_time::time_duration usertime = posix_time::duration_from_string(time)
posix_time::ptime expirationtime (today, usertime);
</code>```

Now set the timer to call foo():

```<code>timer_.expires_at (expirationtime);
timer_.async_wait (foo);    // use Boost::bind() if you want a member function
</code>```

You can add as many timers as you want to timer_ by using the above two code snippets. When everything is ready:

```<code>io_service_.run ();
</code>```

Note that this will take over the current thread. So you must call run() from a different thread if you want the rest of your program to keep going. (Obviously, use Boost's Thread library for that.)

ContentLicense: CC BY-SA 2.5

Body:
If you want to call a specific function from within a program that's already running, use Boost's Date Time library and Asio.

#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/asio.hpp>

namespace gregorian = boost::gregorian;
namespace posix_time = boost::posix_time;
namespace asio = boost::asio;

asio::io_service io_service_;
asio::deadline_timer timer_ (io_service_);

Then set the time. This is an example using a string of the desired time, like "18:00:00". (Note that Boost defaults to UTC for the timestamps!)

gregorian::date today = gregorian::day_clock::local_day();
posix_time::time_duration usertime = posix_time::duration_from_string(time)
posix_time::ptime expirationtime (today, usertime);

Now set the timer to call foo():

timer_.expires_at (expirationtime);
timer_.async_wait (foo);    // use Boost::bind() if you want a member function

You can add as many timers as you want to timer_ by using the above two code snippets. When everything is ready:

io_service_.run ();

Note that this will take over the current thread. So you must call run() from a different thread if you want the rest of your program to keep going. (Obviously, use Boost's Thread library for that.)


问:
Does a method's signature in Java include its return type?
Does the method signature in a Java class/interface include its return type?

Example:

Does Java know the difference between those two methods:

```<code>public class Foo {
    public int  myMethod(int param) {}
    public char myMethod(int param) {}
}
</code>```

Or is it maybe only the method name and parameters list that matter?

答:
THE METHOD SIGNATURE INCLUDES THE RETURN TYPE.

The compiler ignores it when has to check for duplicates. For Java is illegal to have two methods with the signature differing only by the return type.

Try that:

```<code>public class Called {
    public String aMethod() {
        return "";
    }
}

public class Caller {
    public static void main(String[] main) {
        aMethod();
    }
    public static void aMethod() {
        Called x = new Called();
        x.aMethod();
    }
}
</code>```

Build the project, go to bin directory, copy the Caller.cass somewhere. Then change the called method:

```<code>public int aMethod() {
    return 0;
}
</code>```

Build the project, you will see that both Called.class and Caller.class have a new timestamp. Replace the Caller.class above and run the project. You'll have an exception:

```<code>java.lang.NoSuchMethodError: it.prova.Called.aMethod()Ljava/lang/String;
</code>```

Body:
Does the method signature in a Java class/interface include its return type?

Example:

Does Java know the difference between those two methods:

public class Foo {
    public int  myMethod(int param) {}
    public char myMethod(int param) {}
}

Or is it maybe only the method name and parameters list that matter?

Body:
THE METHOD SIGNATURE INCLUDES THE RETURN TYPE.

The compiler ignores it when has to check for duplicates. For Java is illegal to have two methods with the signature differing only by the return type.

Try that:

public class Called {
    public String aMethod() {
        return "";
    }
}

public class Caller {
    public static void main(String[] main) {
        aMethod();
    }
    public static void aMethod() {
        Called x = new Called();
        x.aMethod();
    }
}

Build the project, go to bin directory, copy the Caller.cass somewhere. Then change the called method:

public int aMethod() {
    return 0;
}

Build the project, you will see that both Called.class and Caller.class have a new timestamp. Replace the Caller.class above and run the project. You'll have an exception:

java.lang.NoSuchMethodError: it.prova.Called.aMethod()Ljava/lang/String;


问:
UITextField should accept only positive integers and give alert message for rest
What Code I need to write to make my UITextField accept only positive integers(Whole numbers) other than setting keyboard Type to numbers only. And it should alert user when they input characters/fractions/Negative numbers/Special Characters. Kindly, Let me know. Thank you.</p>

答: I don't know if there is a better way, but you can use the UITextFieldDelegate - textFieldDidEndEditing and prove the entered text yourself and in case somebody entered something 'wrong' show an AlertController</p>


问:
How can I sync Activate Directory users between SharePoint 2013 vs SharePoint Online?
I work on Windows Server 2012 with SharePoint 2013. How can sync AD users from SharePoint 2013 to SharePoint Online?

答:
For syncing AD Users from your local farm to SharePoint Online you need to setup directory synchronization (DirSync).

Here is step by step guide: Set up directory synchronization for Office 365

Or you can use for much broader approach: Azure AD Connect


问:
producer-consumer using synchronization
I wrote code to implement the Producer-Consumer problem and it seems to be working fine without the need to synchronize.Is it possible?

How do I test the code and check if it is actually working right or not? How do I know if deadlock will occur? Right now,I am not breaking out of the loops(i.e. the Producer keeps inserting and the consumer keeps consuming in an infinite loop).I am using a circular queue of size 3(for sake of simplicity) as the shared resource.

Here is my code:

```<code>import java.util.*;

public class PCImpl implements Runnable
{
Thread t;
QforPC qObj;

 public static void main(String[] args)
 {
     QforPC qObject=new QforPC();

     //These create 2 different objects! Each object has it's own thread of execution.
     //Synchronization is needed when 2 threads use the same object
    new PCImpl("Producer",qObject);
    new PCImpl("Consumer",qObject);
 }

 PCImpl(String name,QforPC qObj)
 {
     this.qObj=qObj;
     t=new Thread(this,name);
     t.start();
 }

 public void run()
 {
         if(Thread.currentThread().getName().equals("Producer"))
         {
             while(true)
             {
                  Random rgen=new Random();
                  int n=rgen.nextInt(100);
                  if(n!=0)
                              qObj.Producer(n);
                         try
                    {
                       Thread.sleep(200);
                     }
                      catch(InterruptedException e)
                    {

                    }
               }

            }

         if(Thread.currentThread().getName().equals("Consumer"))
         {
             while(true)
                  {
                 try
               {
                 Thread.sleep(1500);
               }
                catch(InterruptedException e)
               {
                  }
              qObj.Consumer();

              }
         }

  }
}

public class QforPC
{
int[] q={0,0,0};
int r=0,f=0;
  public void Producer(int item)
     {

         if(r!=q.length && canProducer())
         {
             q[r]=item;
             System.out.println("The item inserted into the queue is:"+ item);
             r++;
         }
         if(r==q.length && f>0)
             r=0;
         else if(r==q.length && f==q.length)
         {
             r=0;
             f=0;
         }
     }

     public void Consumer()
     {
         int item;
         System.out.println("The value of isQueue empty is:"+ isEmpty());

         if(f!=q.length && isEmpty()==false)
         {
             System.out.println("Entered the consumer method");
             item=q[f];
             System.out.println("The item fetched from the queue is:"+item);
             q[f]=0;
             f++;
         }
         if(f==q.length && r<f)
             f=0;

     }

     public boolean isEmpty()
     {
         for(int k=0;k<q.length;k++)
         {
             if(q[k]==0 && k==q.length-1)
                 return true;

         }
         return false;
     }

     public boolean canProducer()
     {
         for(int k=0;k<q.length;k++)
         {
                 if(q[k]==0)
                 return true;

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

答: It can be done with a lock free queue, but not like this, i recommend that you read Java Concurrency in Practice. If your code is access by multiple threads at the same time you will have many erros on that, you have publication and syncronizations problems!! But like Farlmarri said it depends on the usage of this code.</p>

Title: producer-consumer using synchronization

Body:
I wrote code to implement the Producer-Consumer problem and it seems to be working fine without the need to synchronize.Is it possible?

How do I test the code and check if it is actually working right or not? How do I know if deadlock will occur? Right now,I am not breaking out of the loops(i.e. the Producer keeps inserting and the consumer keeps consuming in an infinite loop).I am using a circular queue of size 3(for sake of simplicity) as the shared resource.

Here is my code:

import java.util.*;

public class PCImpl implements Runnable
{
Thread t;
QforPC qObj;

 public static void main(String[] args)
 {
     QforPC qObject=new QforPC();

     //These create 2 different objects! Each object has it's own thread of execution.
     //Synchronization is needed when 2 threads use the same object
    new PCImpl("Producer",qObject);
    new PCImpl("Consumer",qObject);
 }

 PCImpl(String name,QforPC qObj)
 {
     this.qObj=qObj;
     t=new Thread(this,name);
     t.start();
 }

 public void run()
 {
         if(Thread.currentThread().getName().equals("Producer"))
         {
             while(true)
             {
                  Random rgen=new Random();
                  int n=rgen.nextInt(100);
                  if(n!=0)
                              qObj.Producer(n);
                         try
                    {
                       Thread.sleep(200);
                     }
                      catch(InterruptedException e)
                    {

                    }
               }

            }

         if(Thread.currentThread().getName().equals("Consumer"))
         {
             while(true)
                  {
                 try
               {
                 Thread.sleep(1500);
               }
                catch(InterruptedException e)
               {
                  }
              qObj.Consumer();

              }
         }

  }
}

public class QforPC
{
int[] q={0,0,0};
int r=0,f=0;
  public void Producer(int item)
     {

         if(r!=q.length && canProducer())
         {
             q[r]=item;
             System.out.println("The item inserted into the queue is:"+ item);
             r++;
         }
         if(r==q.length && f>0)
             r=0;
         else if(r==q.length && f==q.length)
         {
             r=0;
             f=0;
         }
     }

     public void Consumer()
     {
         int item;
         System.out.println("The value of isQueue empty is:"+ isEmpty());

         if(f!=q.length && isEmpty()==false)
         {
             System.out.println("Entered the consumer method");
             item=q[f];
             System.out.println("The item fetched from the queue is:"+item);
             q[f]=0;
             f++;
         }
         if(f==q.length && r<f)
             f=0;

     }

     public boolean isEmpty()
     {
         for(int k=0;k<q.length;k++)
         {
             if(q[k]==0 && k==q.length-1)
                 return true;

         }
         return false;
     }

     public boolean canProducer()
     {
         for(int k=0;k<q.length;k++)
         {
                 if(q[k]==0)
                 return true;

         }
         return false;
     }
}


问:
How can I get variable from another function?
My case like this :

Html code (This is modal) :

```<code><div class="modal-body">
    ...
    <input type="file" id="change-image" name="replace">
    ...
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>
</div>
</code>```

If I click input type file, it will run the javascript code :

```<code>$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});
</code>```

There exist variable data image

If I run this :

```<code>$('#confirm-edit-image').on("click",function(){
    // get variable data
});
</code>```

I want to get the variable data image

How can I do it?

答:
Make sure that “data” is a global variable</p>

```<code>var data;

$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});

$('#confirm-edit-image').on("click",function(){
    console.log(data);
});
</code>```

Body:
My case like this :

Html code (This is modal) :

    ...
    <input type="file" id="change-image" name="replace">
    ...
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>

If I click input type file, it will run the javascript code :

$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});

There exist variable data image

If I run this :

$('#confirm-edit-image').on("click",function(){
    // get variable data
});

I want to get the variable data image

How can I do it?

Body:
Make sure that “data” is a global variable

var data;

$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});

$('#confirm-edit-image').on("click",function(){
    console.log(data);
});


问:
xBest Practice to check for NullPointerException
To get better programming skills, I read some sources from others.
I ask myself everytime, what the best way of validation is.

Here you will find some seafile code snippets for android. I'm wondering, why nobody will check in line 109, if ActionBar is null.
On other posts here on SO, I found something like this:

```<code>TextView Foo = (TextView) findViewById(R.id.FooBar)
</code>```

In that post it was said, that this can result in a NullPointer or CastException. That's right. Unfortunately, even Google doesn't do this validation in its own reference.

Do you have any idea, how to deal with it? When should I check, if something is Null or not?

答:
In my opinion

```<code>TextView Foo = (TextView) findViewById(R.id.FooBar)
</code>```

is an example in which it's either always null or never null or CastException or no exception. So I'd not check it for null or check for that exception, since it never changes. If it runs once, it will always run ;)

I'd rather concentrate on checking for null whenever the result actually can be null or not null.

Body:
To get better programming skills, I read some sources from others.
I ask myself everytime, what the best way of validation is.

Here you will find some seafile code snippets for android. I'm wondering, why nobody will check in line 109, if ActionBar is null.
On other posts here on SO, I found something like this:

TextView Foo = (TextView) findViewById(R.id.FooBar)

In that post it was said, that this can result in a NullPointer or CastException. That's right. Unfortunately, even Google doesn't do this validation in its own reference.

Do you have any idea, how to deal with it? When should I check, if something is Null or not?

Body:
In my opinion

TextView Foo = (TextView) findViewById(R.id.FooBar)

is an example in which it's either always null or never null or CastException or no exception. So I'd not check it for null or check for that exception, since it never changes. If it runs once, it will always run ;)

I'd rather concentrate on checking for null whenever the result actually can be null or not null.


问:
QlikView Direct Discovery
hopefully someone can help me with QlikView direct discovery.

Problem:
I've a database with two different tables with the same structure and indexes. Within the tbl_kri (kri stands for key risk indicators) are non-confirmed data, within tbl_kri_archive are confirmed data.

```<code>Table extract:
customer_id, kri1, kri2, kri3, run_id
</code>```

run_id is related to a date in another table.

From a Qklikview point of view I would like to ask for all kri detail information for a selected customer and run_id, which is selectable in Qlikview.

In the MySQL database I can create a view like

```<code>SELECT * FROM tbl_kri
UNION ALL
SELECT * FROM tbl_kri_archive.
</code>```

However, the union all will not take indexes into account and the run time is very bad. Several millions of records will be searched without using an index.

The integration in Qlikview is like
 DIRECT QUERY

```<code>DIMENSION customer_id
 MEASURE kri1, kri2, kri3, run_id
 FROM tbl_kri;
</code>```

But how can I implement the union to the tbl_kri_archive?
Any idea?
Thank you very much in advance
Best regards
Andreas

答:
Fixed it!

Problem was an underlaying MySQL / MariaDB Version 10.1. I've updated it to Version 10.2 and in this version the UNION will take also indexes into account.

Best regards
Andreas

Title: QlikView Direct Discovery

Body:
hopefully someone can help me with QlikView direct discovery.

Problem:
I've a database with two different tables with the same structure and indexes. Within the tbl_kri (kri stands for key risk indicators) are non-confirmed data, within tbl_kri_archive are confirmed data.

Table extract:
customer_id, kri1, kri2, kri3, run_id

run_id is related to a date in another table.

From a Qklikview point of view I would like to ask for all kri detail information for a selected customer and run_id, which is selectable in Qlikview.

In the MySQL database I can create a view like

SELECT * FROM tbl_kri
UNION ALL
SELECT * FROM tbl_kri_archive.

However, the union all will not take indexes into account and the run time is very bad. Several millions of records will be searched without using an index.

The integration in Qlikview is like
 DIRECT QUERY

DIMENSION customer_id
 MEASURE kri1, kri2, kri3, run_id
 FROM tbl_kri;

But how can I implement the union to the tbl_kri_archive?
Any idea?
Thank you very much in advance
Best regards
Andreas


问:
Good use of memory
If i create a cell with 1000 matrices ( size of each matrix 800*1280), clearing each matrix after using it will speed up calculations ?

Example

```<code> A=cell(1000,1);
  for i=1:1000
      A{i}=rand(800,1280);
  end
  image=A{1};
  image2=A{2}; % I will use image and image2 with other functions
  A{1}=[];
  A{2}=[];
</code>```

EDIT

The real use of the cell will be like :

```<code>A=cell(1000,1);
parfor i=1:1000
    A{i}=function_that_creates_image(800,1280); % image with size 800*1280 px
end
for i=1:number_of_images   % number_of_images=1000 in this case
image1=A{1};
    image2=A{2};
    A{1}=[];
    A{2}=[];
    % image1 and image 2 will be used then in the next lines
    %next lines of code
end
</code>```

I noticed that calculating components of A in a parfor loop is faster than calculating each component for each loop inside the for

答:
If you fit everything in memory (you need at least 16GB to hold data and do some work on parts of it, to work on the full beast at the same time you should be having 32GB), clearing these won't change anything at all. If you don't, I would assume/hope Matlab and Windows are smart enough to optimize which chunk is held in memory and which is put on the disk, so again deleting won't help. But you might not want to rely on that.

What you can do is to have A{i} = 'path-to-file';, then load it in memory just for the time when needed. Why do you even need to first load all the images and then do work on them one by one? It would be much better for memory to simply have image1 = rand(...);, image2 = rand(...); in the loop itself, and reuse these image1 and image2. No need to even have this A.

In general, tall arrays are your memory friendly solution you should be using if you want to have tons of data at the same time. https://www.mathworks.com/help/matlab/tall-arrays.html

Title: Good use of memory

Body:
If i create a cell with 1000 matrices ( size of each matrix 800*1280), clearing each matrix after using it will speed up calculations ?

Example

 A=cell(1000,1);
  for i=1:1000
      A{i}=rand(800,1280);
  end
  image=A{1};
  image2=A{2}; % I will use image and image2 with other functions
  A{1}=[];
  A{2}=[];

EDIT

The real use of the cell will be like :

A=cell(1000,1);
parfor i=1:1000
    A{i}=function_that_creates_image(800,1280); % image with size 800*1280 px
end
for i=1:number_of_images   % number_of_images=1000 in this case
image1=A{1};
    image2=A{2};
    A{1}=[];
    A{2}=[];
    % image1 and image 2 will be used then in the next lines
    %next lines of code
end

I noticed that calculating components of A in a parfor loop is faster than calculating each component for each loop inside the for


问:
How to search a string for different types of numbers
I have multiple strings that each contain a year and some text. An example of one string is: "The year is 2004". But, another string may look like this "this was made in 2003.5". How would I check many strings like this and extract the correct number?

Body:
You can use regex here :

>>> str = "The year is 2004"
>>> re.findall(r"[-+]?\d*\.\d+|\d+", str)
['2004']

>>> str = "this was made in 2003.5"
>>> re.findall(r"[-+]?\d*\.\d+|\d+", str)
['2003.5']


问:
How to support Universal Links in iOS App and setup server for it?
How i can support Universal Links in my iOS application and setup my server in order to support Universal Links?

答:
If you complete all of Vineet's post and it still doesn't work, try to use a distribution provisioning profile. I did everything from the post above, but had to issue a distribution profile in order to make it work.

With development profile the app successfully downloaded the AASA file, but it never open my application when I was pressing the links.

Hope it helps.


问:
2-Dimentional Array
I need to design a cinema booking system.
it needs to have 4 screens.
2 screens holding 100 seats.
2 screens holding 64 seats.

what would be the best way at going about designing this?

what data structure should I use, and if you could explain why to use that one and also let me know the drawbacks of using that data structure it would be much appreciated.

Thanks.

答: The amount of data is so small that the most important fact is that you have to easily understand it. Arrays are fine but not flexible and if the array index is not the "seat index" this can be confusing. If the seats already have an identification system in reality it may be wise to take it over. Then you could store it in a Map - e.g. a TreeMap with a the identification (e.g. a string) as key.</p>

Title: 2-Dimentional Array


问:
How to prevent user log in from two devices
I am developing mobile application in ionic 2. I want to design mechanism when user log in my website i must log out from my mobile application at the same time if user logged in mobile application then website must be log out. I am using same database for mobile and website. I am using jsonwebtoken for my mobile authentication. what is the best way to implement this mechanism in my ionic 2 application.</p>

答:
you will need to create a session table that will store the session details and will also store the unique ID and status that will be used to identify these sessions and tell us weather it is active or not. This id will be used as a reference to validate session for different devices, once the user logs in you will query into this table and check whether any existing session is there or not. If it is there change the status to false.

In the UI you will use setinterval to request for this session at regular time it can be 10 seconds or anything based on your requirement then inside setinterval make a call to backend that will be checking this session, if this session status is false then logout.


问:
I am calling a parent funciton in base class but returns nothing
```<code>class ajay{
    function test(){
        return "sandeep";
    }
}

class Sandeep extends ajay{
    function testing(){
        parent::test();
    }
}
$objct = new Sandeep();echo $objct->testing();
</code>```

答:
```<code>There is no return data in testing function

<?php
class ajay{
    function test(){
        return "sandeep";
    }
}

class Sandeep extends ajay{
    function testing(){
        $data = parent::test();
        return $data;
    }
}
$objct = new Sandeep();
echo $objct->testing();
?>
</code>```


问:
Json.Net messes up timezones for DateTimeOffset when serializing
I have looked at a lot of related questions but none of them seem to be working for me.

I'm trying to serialize everything in UTC. Here's my code:

```<code>class Class1
{
    static void Main()
    {
        Class2 foo = new Class2();
        JObject json = JObject.Parse(JsonConvert.SerializeObject(foo, new JsonSerializerSettings()
        {
            DateParseHandling = DateParseHandling.DateTimeOffset,
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc
        }));

        Console.WriteLine(json.ToString());

        Console.Read();
    }
}

class Class2
{
    public DateTimeOffset time = new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(14663484000000000));

    public DateTimeOffset time2 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(14663484000000000);

    public DateTime time3 = new DateTime(14663484000000000);
}
</code>```

Here's the output:

```<code>{
    "time": "2016-06-19T08:00:00-07:00",
    "time2": "2016-06-19T08:00:00-07:00",
    "time3": "0047-06-20T15:00:00Z"
}
</code>```

Here's the output I'm trying to get:

```<code>{
    "time": "2016-06-19T15:00:00+00:00",
    "time2": "2016-06-19T15:00:00+00:00",
    "time3": "0047-06-20T15:00:00+00:00"
}
</code>```

As you can see, the DateTimeOffset properties are not converted at all. The DateTime is, but the timezone is indicated using Z whereas I'm trying to use +00:00.

答:
In your code, you are doing the following:

Serializing an instance of Class2 to a JSON string using specific DateTime-related serialization settings.

Deserializing to a JToken hierarchy without using those settings.

(Making additional modifications to the hierarchy - not shown.)

Serializing the JToken hierarchy to a final string (via json.ToString()) again without using those settings.

When you do, formatting settings for dates chosen in step #1 get lost.

To solve this, you need to apply the settings every time you serialize from or to a JSON string representation, since, as explained in this documentation page, JSON does not have an "official" format for dates.  Because of this, Json.NET applies heuristics for recognizing and formatting dates whenever it converts from and to a JSON string representation - which you are doing not once but thrice.

You could accomplish this by doing:

```<code>var settings = new JsonSerializerSettings()
{
    DateParseHandling = DateParseHandling.DateTimeOffset,
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

// Generate initial serialization
var initialString = JsonConvert.SerializeObject(foo, settings);

// Parse back to JToken
var json = JsonConvert.DeserializeObject<JObject>(initialString, settings);

// Make modifications as required
// json["foo"] = "bar";

// Generate final JSON.
var finalString = JsonConvert.SerializeObject(json, Formatting.Indented, settings);
</code>```

To improve efficiency, you could use JToken.FromObject() (or JObject.FromObject() if you prefer) to generate the JToken hierarchy without needing to create and parse an initial string representation:

```<code>var settings = new JsonSerializerSettings()
{
    DateParseHandling = DateParseHandling.DateTimeOffset,
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

var json = JToken.FromObject(foo, JsonSerializer.CreateDefault(settings));

// Make modifications as required
// json["foo"] = "bar";

// Generate final JSON.
var finalString = JsonConvert.SerializeObject(json, Formatting.Indented, settings);
</code>```

Note, however, that Json.NET will output a UTC DateTime in the format "0047-06-20T15:00:00Z" rather than "2016-06-19T15:00:00+00:00" for reasons explained here.  If you need your UTC DateTime properties to be serialized in DateTimeOffset format you might need to use a custom converter.

Body:
I have looked at a lot of related questions but none of them seem to be working for me.

I'm trying to serialize everything in UTC. Here's my code:

class Class1
{
    static void Main()
    {
        Class2 foo = new Class2();
        JObject json = JObject.Parse(JsonConvert.SerializeObject(foo, new JsonSerializerSettings()
        {
            DateParseHandling = DateParseHandling.DateTimeOffset,
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc
        }));

        Console.WriteLine(json.ToString());

        Console.Read();
    }
}

class Class2
{
    public DateTimeOffset time = new DateTimeOffset(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(14663484000000000));

    public DateTimeOffset time2 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(14663484000000000);

    public DateTime time3 = new DateTime(14663484000000000);
}

Here's the output:

{
    "time": "2016-06-19T08:00:00-07:00",
    "time2": "2016-06-19T08:00:00-07:00",
    "time3": "0047-06-20T15:00:00Z"
}

Here's the output I'm trying to get:

{
    "time": "2016-06-19T15:00:00+00:00",
    "time2": "2016-06-19T15:00:00+00:00",
    "time3": "0047-06-20T15:00:00+00:00"
}

As you can see, the DateTimeOffset properties are not converted at all. The DateTime is, but the timezone is indicated using Z whereas I'm trying to use +00:00.

Body:
In your code, you are doing the following:

Serializing an instance of Class2 to a JSON string using specific DateTime-related serialization settings.

Deserializing to a JToken hierarchy without using those settings.

(Making additional modifications to the hierarchy - not shown.)

Serializing the JToken hierarchy to a final string (via json.ToString()) again without using those settings.

When you do, formatting settings for dates chosen in step #1 get lost.

To solve this, you need to apply the settings every time you serialize from or to a JSON string representation, since, as explained in this documentation page, JSON does not have an "official" format for dates.  Because of this, Json.NET applies heuristics for recognizing and formatting dates whenever it converts from and to a JSON string representation - which you are doing not once but thrice.

You could accomplish this by doing:

var settings = new JsonSerializerSettings()
{
    DateParseHandling = DateParseHandling.DateTimeOffset,
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

// Generate initial serialization
var initialString = JsonConvert.SerializeObject(foo, settings);

// Parse back to JToken
var json = JsonConvert.DeserializeObject<JObject>(initialString, settings);

// Make modifications as required
// json["foo"] = "bar";

// Generate final JSON.
var finalString = JsonConvert.SerializeObject(json, Formatting.Indented, settings);

To improve efficiency, you could use JToken.FromObject() (or JObject.FromObject() if you prefer) to generate the JToken hierarchy without needing to create and parse an initial string representation:

var settings = new JsonSerializerSettings()
{
    DateParseHandling = DateParseHandling.DateTimeOffset,
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    DateTimeZoneHandling = DateTimeZoneHandling.Utc
};

var json = JToken.FromObject(foo, JsonSerializer.CreateDefault(settings));

// Make modifications as required
// json["foo"] = "bar";

// Generate final JSON.
var finalString = JsonConvert.SerializeObject(json, Formatting.Indented, settings);

Note, however, that Json.NET will output a UTC DateTime in the format "0047-06-20T15:00:00Z" rather than "2016-06-19T15:00:00+00:00" for reasons explained here.  If you need your UTC DateTime properties to be serialized in DateTimeOffset format you might need to use a custom converter.


问:
Redirect Standard Output Efficiently in .NET
I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow.

Do you have any idea on how I can make that faster? Any other technique?

```<code>    Dim oCGI As ProcessStartInfo = New ProcessStartInfo()
    oCGI.WorkingDirectory = "C:\Program Files\Application\php"
    oCGI.FileName = "php-cgi.exe"
    oCGI.RedirectStandardOutput = True
    oCGI.RedirectStandardInput = True
    oCGI.UseShellExecute = False
    oCGI.CreateNoWindow = True

    Dim oProcess As Process = New Process()

    oProcess.StartInfo = oCGI
    oProcess.Start()

    oProcess.StandardOutput.ReadToEnd()
</code>```

答:
The problem is due a bad php.ini config. I had the same problem and i downloaded the Windows installer from: http://windows.php.net/download/.

After that and commenting out not needed extensions, the conversion process is alà Speedy Gonzales, converting 20 php per second.

You can safely use "oProcess.StandardOutput.ReadToEnd()". It's more readable and alomost as fast as using the thread solution. To use the thread solution in conjunction with a string you need to introduce an event or something.

Cheers

OwnerDisplayName: Vincent

Body:
I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow.

Do you have any idea on how I can make that faster? Any other technique?

    Dim oCGI As ProcessStartInfo = New ProcessStartInfo()
    oCGI.WorkingDirectory = "C:\Program Files\Application\php"
    oCGI.FileName = "php-cgi.exe"
    oCGI.RedirectStandardOutput = True
    oCGI.RedirectStandardInput = True
    oCGI.UseShellExecute = False
    oCGI.CreateNoWindow = True

    Dim oProcess As Process = New Process()

    oProcess.StartInfo = oCGI
    oProcess.Start()

    oProcess.StandardOutput.ReadToEnd()

LastEditorDisplayName: Vincent