问:
compileReleaseKotlin fails with java.lang.ClassNotFoundException: com.sun.tools.javac.util.Context
I'm trying to build my Android Project (which contains a library module) via terminal using gradlew. From within Android Studio, it compiles and installs successfully but, when I try to run ./gradlew assembleDebug I get the following stacktrace:

```<code>Using kotlin incremental compilation
e: java.lang.ClassNotFoundException: com.sun.tools.javac.util.Context
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at org.jetbrains.kotlin.gradle.tasks.JarSearchingUtilKt.findToolsJar(jarSearchingUtil.kt:48)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment$toolsJar$2.invoke(GradleCompilerEnvironment.kt:21)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment$toolsJar$2.invoke(GradleCompilerEnvironment.kt:15)
        at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:131)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment.getToolsJar(GradleCompilerEnvironment.kt)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment.getCompilerClasspath(GradleCompilerEnvironment.kt:24)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.getDaemonConnection(GradleKotlinCompilerRunner.kt:289)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemon(GradleKotlinCompilerRunner.kt:132)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemonOrFallback(GradleKotlinCompilerRunner.kt:112)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemonOrFallback(GradleKotlinCompilerRunner.kt:49)
        at org.jetbrains.kotlin.compilerRunner.KotlinCompilerRunner.runCompiler(KotlinCompilerRunner.kt:134)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompiler(GradleKotlinCompilerRunner.kt:73)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:259)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:160)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:141)
        at sun.reflect.GeneratedMethodAccessor530.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

e: Compiler terminated with internal error
:render-engine:compileReleaseKotlin FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':render-engine:compileReleaseKotlin'.
> Internal compiler error. See log for more details
</code>```

main build.gradle:

```<code>buildscript {
    ext.kotlin_version = '1.1.2-2'
    ext.anko_version = '0.9'
    ext.android_plugin_version = '2.3.1'
    ext.appcompat = '25.3.1'

    repositories {
        jcenter()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.android.tools.build:gradle:$android_plugin_version"
    }
}

allprojects {
    /**
     *  REQUIRED FOR IGNORING JAVADOCS FOR KT FILES
     */
    tasks.withType(Javadoc) {
        excludes = ['**/*.kt']
        options.addStringOption('Xdoclint:none', '-quiet')
        options.addStringOption('encoding', 'UTF-8')
    }

    repositories {
        maven { url "https://jitpack.io" }

        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots/'
        }

        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

module's build.gradle:

```<code>apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName version

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    // TEST
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'

    // GOOGLE
    compile 'com.google.code.gson:gson:2.8.0'
    compile "com.android.support:appcompat-v7:$appcompat"
    compile "com.android.support:cardview-v7:$appcompat"
    compile "com.android.support:design:$appcompat"

    // OTHER
    compile('org.simpleframework:simple-xml:2.7.+') {
        exclude module: 'stax'
        exclude module: 'stax-api'
        exclude module: 'xpp3'
    }
    compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'org.apache.commons:commons-io:1.3.2'

    // RX ANDROID
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'

    // KOTLIN
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    // ANKO
    compile "org.jetbrains.anko:anko-common:$anko_version"
    compile "org.jetbrains.anko:anko-sdk15:$anko_version"
    compile "org.jetbrains.anko:anko-support-v4:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
}

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

kapt {
    generateStubs = true
}
</code>```

IMPORTANT: I'm trying that on Elmentary OS (openjdk1.8.0) and the same project can be run on other computer using Ubuntu

答:
I got this exact issue on Windows when the JDK bin directory was not in my PATH.

The process is documented here: http://docs.oracle.com/javase/7/docs/webnotes/install/windows/jdk-installation-windows.html#path

Body:
I'm trying to build my Android Project (which contains a library module) via terminal using gradlew. From within Android Studio, it compiles and installs successfully but, when I try to run ./gradlew assembleDebug I get the following stacktrace:

Using kotlin incremental compilation
e: java.lang.ClassNotFoundException: com.sun.tools.javac.util.Context
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at org.jetbrains.kotlin.gradle.tasks.JarSearchingUtilKt.findToolsJar(jarSearchingUtil.kt:48)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment$toolsJar$2.invoke(GradleCompilerEnvironment.kt:21)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment$toolsJar$2.invoke(GradleCompilerEnvironment.kt:15)
        at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:131)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment.getToolsJar(GradleCompilerEnvironment.kt)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerEnvironment.getCompilerClasspath(GradleCompilerEnvironment.kt:24)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.getDaemonConnection(GradleKotlinCompilerRunner.kt:289)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemon(GradleKotlinCompilerRunner.kt:132)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemonOrFallback(GradleKotlinCompilerRunner.kt:112)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.compileWithDaemonOrFallback(GradleKotlinCompilerRunner.kt:49)
        at org.jetbrains.kotlin.compilerRunner.KotlinCompilerRunner.runCompiler(KotlinCompilerRunner.kt:134)
        at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompiler(GradleKotlinCompilerRunner.kt:73)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:259)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:160)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:141)
        at sun.reflect.GeneratedMethodAccessor530.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)

e: Compiler terminated with internal error
:render-engine:compileReleaseKotlin FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':render-engine:compileReleaseKotlin'.
> Internal compiler error. See log for more details

main build.gradle:

buildscript {
    ext.kotlin_version = '1.1.2-2'
    ext.anko_version = '0.9'
    ext.android_plugin_version = '2.3.1'
    ext.appcompat = '25.3.1'

    repositories {
        jcenter()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.android.tools.build:gradle:$android_plugin_version"
    }
}

allprojects {
    /**
     *  REQUIRED FOR IGNORING JAVADOCS FOR KT FILES
     */
    tasks.withType(Javadoc) {
        excludes = ['**/*.kt']
        options.addStringOption('Xdoclint:none', '-quiet')
        options.addStringOption('encoding', 'UTF-8')
    }

    repositories {
        maven { url "https://jitpack.io" }

        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots/'
        }

        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

module's build.gradle:

apply plugin: 'com.android.library'
apply plugin: 'maven-publish'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName version

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    // TEST
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'

    // GOOGLE
    compile 'com.google.code.gson:gson:2.8.0'
    compile "com.android.support:appcompat-v7:$appcompat"
    compile "com.android.support:cardview-v7:$appcompat"
    compile "com.android.support:design:$appcompat"

    // OTHER
    compile('org.simpleframework:simple-xml:2.7.+') {
        exclude module: 'stax'
        exclude module: 'stax-api'
        exclude module: 'xpp3'
    }
    compile 'com.github.PhilJay:MPAndroidChart:v3.0.2'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'org.apache.commons:commons-io:1.3.2'

    // RX ANDROID
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'

    // KOTLIN
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    // ANKO
    compile "org.jetbrains.anko:anko-common:$anko_version"
    compile "org.jetbrains.anko:anko-sdk15:$anko_version"
    compile "org.jetbrains.anko:anko-support-v4:$anko_version"
    compile "org.jetbrains.anko:anko-appcompat-v7:$anko_version"
}

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

kapt {
    generateStubs = true
}

IMPORTANT: I'm trying that on Elmentary OS (openjdk1.8.0) and the same project can be run on other computer using Ubuntu


来源: stackexchange

问:
Calculate number of weekdays between two dates in Java
Can anyone point me to some Java snippet wherein i can get business (except Sat and Sun) days between two dates.</p>

答:
Solution without loop in 5 lines of code

Days between are defined in the same way as ChronoUnit.DAYS.between(start, end) which means there are 4 days between Monday and Friday. Since we are only interested in weekdays we have to subtract weekends, therefore from Friday until Tuesday there will be 2 weekdays(just compute endDay - startDay and subtract 2 for the weekend). Add 1 to the result if you want an inclusive result, i.e. not days between.

I present two solutions.

First solution (5-liner, short and cryptic):

```<code>import java.time.*;
import java.time.temporal.*;

public static long calcWeekDays1(final LocalDate start, final LocalDate end) {
    final DayOfWeek startW = start.getDayOfWeek();
    final DayOfWeek endW = end.getDayOfWeek();

    final long days = ChronoUnit.DAYS.between(start, end);
    final long daysWithoutWeekends = days - 2 * ((days + startW.getValue())/7);

    //adjust for starting and ending on a Sunday:
    return daysWithoutWeekends + (startW == DayOfWeek.SUNDAY ? 1 : 0) + (endW == DayOfWeek.SUNDAY ? 1 : 0);
}
</code>```

Second solution:

```<code>public static long calcWeekDays2(final LocalDate start, final LocalDate end) {
    final int startW = start.getDayOfWeek().getValue();
    final int endW = end.getDayOfWeek().getValue();

    final long days = ChronoUnit.DAYS.between(start, end);
    long result = days - 2*(days/7); //remove weekends

    if (days % 7 != 0) { //deal with the rest days
        if (startW == 7) {
            result -= 1;
        } else if (endW == 7) {  //they can't both be Sunday, otherwise rest would be zero
            result -= 1;
        } else if (endW < startW) { //another weekend is included
            result -= 2;
        }
    }

    return result;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Solution without loop in 5 lines of code

Days between are defined in the same way as ChronoUnit.DAYS.between(start, end) which means there are 4 days between Monday and Friday. Since we are only interested in weekdays we have to subtract weekends, therefore from Friday until Tuesday there will be 2 weekdays(just compute endDay - startDay and subtract 2 for the weekend). Add 1 to the result if you want an inclusive result, i.e. not days between.

I present two solutions.

First solution (5-liner, short and cryptic):

import java.time.*;
import java.time.temporal.*;

public static long calcWeekDays1(final LocalDate start, final LocalDate end) {
    final DayOfWeek startW = start.getDayOfWeek();
    final DayOfWeek endW = end.getDayOfWeek();

    final long days = ChronoUnit.DAYS.between(start, end);
    final long daysWithoutWeekends = days - 2 * ((days + startW.getValue())/7);

    //adjust for starting and ending on a Sunday:
    return daysWithoutWeekends + (startW == DayOfWeek.SUNDAY ? 1 : 0) + (endW == DayOfWeek.SUNDAY ? 1 : 0);
}

Second solution:

public static long calcWeekDays2(final LocalDate start, final LocalDate end) {
    final int startW = start.getDayOfWeek().getValue();
    final int endW = end.getDayOfWeek().getValue();

    final long days = ChronoUnit.DAYS.between(start, end);
    long result = days - 2*(days/7); //remove weekends

    if (days % 7 != 0) { //deal with the rest days
        if (startW == 7) {
            result -= 1;
        } else if (endW == 7) {  //they can't both be Sunday, otherwise rest would be zero
            result -= 1;
        } else if (endW < startW) { //another weekend is included
            result -= 2;
        }
    }

    return result;
}

ContentLicense: CC BY-SA 4.0


问:
Grouping switch statement cases together?
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

```<code>SELECT CASE Answer
CASE 1, 2, 3, 4
</code>```

Example in C++ (For those that need it):

```<code>#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}
</code>```

答:
No, but you can with an if-else if-else chain which achieves the same result:

```<code>if (answer >= 1 && answer <= 4)
  cout << "You need more cars.";
else if (answer <= 8)
  cout << "Now you need a house.";
else
  cout << "What are you? A peace-loving hippie freak?";
</code>```

You may also want to handle the case of 0 cars and then also the unexpected case of a negative number of cars probably by throwing an exception.

PS: I've renamed Answer to answer as it's considered bad style to start variables with an uppercase letter.

As a side note, scripting languages such as Python allow for the nice if answer in [1, 2, 3, 4] syntax which is a flexible way of achieving what you want.

ContentLicense: CC BY-SA 3.0

Body:
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

SELECT CASE Answer
CASE 1, 2, 3, 4

Example in C++ (For those that need it):

#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}

Body:
No, but you can with an if-else if-else chain which achieves the same result:

if (answer >= 1 && answer <= 4)
  cout << "You need more cars.";
else if (answer <= 8)
  cout << "Now you need a house.";
else
  cout << "What are you? A peace-loving hippie freak?";

You may also want to handle the case of 0 cars and then also the unexpected case of a negative number of cars probably by throwing an exception.

PS: I've renamed Answer to answer as it's considered bad style to start variables with an uppercase letter.

As a side note, scripting languages such as Python allow for the nice if answer in [1, 2, 3, 4] syntax which is a flexible way of achieving what you want.


问:
Combobox Binding with validation rules
I have a problem with my binding on a ComboBox which I don't understand why it does not work:

The following code binds the item on the object and it works perfectly:

```<code><ComboBox Grid.Row="4" Grid.Column="2" Name="comboBoxDefinedBy" Style="{StaticResource ComboBoxStandard}" Margin="0,0,5,0" ItemTemplate="{StaticResource DealerTemplateComboBox}"  SelectedValue="{Binding DefinedBy_Id, Mode=TwoWay}" SelectedValuePath="Id">
</ComboBox>
</code>```

The following does not work, whereby the validation rule works perfectly:

```<code><ComboBox Grid.Row="4" Grid.Column="2" Name="comboBoxDefinedBy" Style="{StaticResource ComboBoxStandard}" Margin="0,0,5,0" ItemTemplate="{StaticResource DealerTemplateComboBox}"  SelectedValuePath ="DefinedBy_Id">
    <ComboBox.SelectedItem>
        <Binding Path="Id" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
            <Binding.ValidationRules>
                <customValidationRules:ComboBoxIsNotEmptyValidationRule></customValidationRules:ComboBoxIsNotEmptyValidationRule>
            </Binding.ValidationRules>
        </Binding>
    </ComboBox.SelectedItem>
</ComboBox>
</code>```

答:
As this article says you've got a few options.

You can bind your SelectedItem to a property and do the validation on that like this

```<code>private MyDataObject _someData;
public MyDataObject SomeData
{
    get
    {
        return _ someData;
    }
    set
    {
        _ someData = value;
        if (value == null || string.IsNullOrEmpty(value.MyProperty))
            throw new ApplicationException("SomeData is required");
    }
}

<ComboBox.SelectedItem>
    <Binding Path="SomeData" ElementName="Window">
        <Binding.ValidationRules>
            <ExceptionValidationRule />
        </Binding.ValidationRules>
    </Binding>
</ComboBox.SelectedItem>
</code>```

Alternatively, you can create your own validation rule and then do it like this

```<code>public class MyCustomValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value is MyDataObject)
        {
            var myDataObj = (MyDataObject)value;
            if (myDataObj.CheckCustomBusinessRules())
                return new ValidationResult(true, null);
        }

        return new ValidationResult(false, "Invalid selection!");
    }
}

<ComboBox.SelectedItem>
    <Binding Path="SomeData" ElementName="Window">
        <Binding.ValidationRules>
            <local:PersonValidation />
        </Binding.ValidationRules>
    </Binding>
</ComboBox.SelectedItem>
</code>```

Taking this a step further another option, as this question suggests, is to replace the ValidationRules with something like IDataErrorInfo. This article gives a nice overview of the different ways validation can be done.

Title: Combobox Binding with validation rules

Body:
I have a problem with my binding on a ComboBox which I don't understand why it does not work:

The following code binds the item on the object and it works perfectly:

<ComboBox Grid.Row="4" Grid.Column="2" Name="comboBoxDefinedBy" Style="{StaticResource ComboBoxStandard}" Margin="0,0,5,0" ItemTemplate="{StaticResource DealerTemplateComboBox}"  SelectedValue="{Binding DefinedBy_Id, Mode=TwoWay}" SelectedValuePath="Id">
</ComboBox>

The following does not work, whereby the validation rule works perfectly:

<ComboBox Grid.Row="4" Grid.Column="2" Name="comboBoxDefinedBy" Style="{StaticResource ComboBoxStandard}" Margin="0,0,5,0" ItemTemplate="{StaticResource DealerTemplateComboBox}"  SelectedValuePath ="DefinedBy_Id">
    <ComboBox.SelectedItem>
        <Binding Path="Id" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
            <Binding.ValidationRules>
                <customValidationRules:ComboBoxIsNotEmptyValidationRule></customValidationRules:ComboBoxIsNotEmptyValidationRule>
            </Binding.ValidationRules>
        </Binding>
    </ComboBox.SelectedItem>
</ComboBox>

Body:
As this article says you've got a few options.

You can bind your SelectedItem to a property and do the validation on that like this

private MyDataObject _someData;
public MyDataObject SomeData
{
    get
    {
        return _ someData;
    }
    set
    {
        _ someData = value;
        if (value == null || string.IsNullOrEmpty(value.MyProperty))
            throw new ApplicationException("SomeData is required");
    }
}

<ComboBox.SelectedItem>
    <Binding Path="SomeData" ElementName="Window">
        <Binding.ValidationRules>
            <ExceptionValidationRule />
        </Binding.ValidationRules>
    </Binding>
</ComboBox.SelectedItem>

Alternatively, you can create your own validation rule and then do it like this

public class MyCustomValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value is MyDataObject)
        {
            var myDataObj = (MyDataObject)value;
            if (myDataObj.CheckCustomBusinessRules())
                return new ValidationResult(true, null);
        }

        return new ValidationResult(false, "Invalid selection!");
    }
}

<ComboBox.SelectedItem>
    <Binding Path="SomeData" ElementName="Window">
        <Binding.ValidationRules>
            <local:PersonValidation />
        </Binding.ValidationRules>
    </Binding>
</ComboBox.SelectedItem>

Taking this a step further another option, as this question suggests, is to replace the ValidationRules with something like IDataErrorInfo. This article gives a nice overview of the different ways validation can be done.


问:
How to use nchar with like operator in SQL Server
I am trying to use like operator with nchar(1) type column, below is my stored procedure:

```<code>Create procedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType like '%'+@DiscountType+'%'
set nocount off
end
</code>```

I have 2 records in table tblCoupons, but I call proc CouponSearch '' it return 0 records. TIA.

I have also tried below line but not working as well.

```<code> Select Couponcode from tblCoupons where DiscountType like N'%'+@DiscountType+'%'
</code>```

答:
You are looking for IIF condition which handles '' as well as NULL

```<code>select * from tblCoupons
where DiscountType = IIF(@DiscountType = '' OR @DiscountType IS NULL,DiscountType,@DiscountType)
</code>```

Hence your procedure becomes :

```<code>Createprocedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType = IIF(@DiscountType = '' OR @DiscountType IS NULL,DiscountType,@DiscountType)
set nocount off
end
</code>```

Body:
I am trying to use like operator with nchar(1) type column, below is my stored procedure:

Create procedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType like '%'+@DiscountType+'%'
set nocount off
end

I have 2 records in table tblCoupons, but I call proc CouponSearch '' it return 0 records. TIA.

I have also tried below line but not working as well.

 Select Couponcode from tblCoupons where DiscountType like N'%'+@DiscountType+'%'

Body:
You are looking for IIF condition which handles '' as well as NULL

select * from tblCoupons
where DiscountType = IIF(@DiscountType = '' OR @DiscountType IS NULL,DiscountType,@DiscountType)

Hence your procedure becomes :

Createprocedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType = IIF(@DiscountType = '' OR @DiscountType IS NULL,DiscountType,@DiscountType)
set nocount off
end


问:
How to return function columns with null values
I have a function with about 40 columns with null values and these columns have never been used for the past 5 years. So I want to write a query that confirms that these fields have null values. I have used a select query below:

```<code>select col1, col2, col3, .....coln
from dbo.fn_functionName(DATEADD(YEAR, -5, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)),'','','','')
</code>```

The problem with this query is that, Its returning over 10 000 records and my clients are not satisfied.

答:
This is exactly what I needed to use:</p>

```<code>  Select [TransactionID] , [ProductID] ,[ReferenceOrderID] ,[ReferenceOrderLineID], [TransactionDate] ,[TransactionType] ,[Quantity],[ActualCost] ,[ModifiedDate]
    from tableName
    where datediff(year,[TransactionDate], GETDATE()) < 5
          and ([ProductID] is not null and [ProductID] != '')
          and ([TransactionType] is not null and [TransactionType] != '')
          and ([Quantity] is not null)
          and [ActualCost] is not null
</code>```

Body:
I have a function with about 40 columns with null values and these columns have never been used for the past 5 years. So I want to write a query that confirms that these fields have null values. I have used a select query below:

select col1, col2, col3, .....coln
from dbo.fn_functionName(DATEADD(YEAR, -5, DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)),'','','','')

The problem with this query is that, Its returning over 10 000 records and my clients are not satisfied.

Body:
This is exactly what I needed to use:

  Select [TransactionID] , [ProductID] ,[ReferenceOrderID] ,[ReferenceOrderLineID], [TransactionDate] ,[TransactionType] ,[Quantity],[ActualCost] ,[ModifiedDate]
    from tableName
    where datediff(year,[TransactionDate], GETDATE()) < 5
          and ([ProductID] is not null and [ProductID] != '')
          and ([TransactionType] is not null and [TransactionType] != '')
          and ([Quantity] is not null)
          and [ActualCost] is not null


问:
How to focus on a secondary window?
I have an app that has two secondary windows.  I have buttons that let you switch between windows, which works fine:

ApplicationViewSwitcher.SwitchAsync(_viewToSwitchToId);

When the user launches our app via the jumplist (under the recent heading when you right click on the app icon in the taskbar), I would like to be able to choose which secondary window to focus on.

I use the same code as above, but it does not work (the same secondary window is automatically chosen regardless of what _viewToSwitchToId I provide).

I'm guessing there's some difference between calling the SwitchAsync() from when my app already has focus (from my button) and when it does not have focus (jumplist).

Any ideas?

Edit

Git repository with repro of SwitchAsync() issue.

答:
I would like to be able to choose which secondary window to focus on

I added the  SwitchAsync() method to OnLaunched for a testing, and when launch the app from the jump list, the application view will switch to the assigned view correctly. For example:

```<code>protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
    ...
    CoreApplicationView newView = CoreApplication.CreateNewView();
    int newViewId = 0;
    await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        Frame frame = new Frame();
        Window.Current.Content = frame;
        Window.Current.Activate();
        newViewId = ApplicationView.GetForCurrentView().Id;
    });
    await ApplicationViewSwitcher.SwitchAsync(newViewId);
    //bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
}
</code>```

If you still have issues please provide a minimal reproduced project for a testing on our side.

Updated:
SwitchAsync(Int32, Int32) method can work well for your scenario. For example:

```<code>// Create 2 secondary views
CoreApplicationView newView = CoreApplication.CreateNewView();
int newViewId = 0;
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    Frame frame = new Frame();
    frame.Navigate(typeof(page1));
    Window.Current.Content = frame;
    Window.Current.Activate();
    ApplicationView appView = ApplicationView.GetForCurrentView();
    newViewId = appView.Id;
    appView.Title = newViewId.ToString();
    _viewIds.Add(newViewId);
});

bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);

CoreApplicationView newView2 = CoreApplication.CreateNewView();
int newViewId2 = 0;
await newView2.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    Frame frame = new Frame();
    frame.Navigate(typeof(page2));
    Window.Current.Content = frame;
    Window.Current.Activate();
    ApplicationView appView = ApplicationView.GetForCurrentView();
    newViewId2 = appView.Id;
    appView.Title = newViewId2.ToString();
    _viewIds.Add(newViewId2);
});

bool viewShown2 = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId2);

// Switch to first secondary view, BUT focuses on last secondary view :/
Debug.WriteLine("Switching to secondary view with id: " + _viewIds[0]);
// bool viewShowntoone = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(_viewIds[0]);
await ApplicationViewSwitcher.SwitchAsync(_viewIds[0], _viewIds[1]);
</code>```

Title: How to focus on a secondary window?

Body:
I would like to be able to choose which secondary window to focus on

I added the  SwitchAsync() method to OnLaunched for a testing, and when launch the app from the jump list, the application view will switch to the assigned view correctly. For example:

protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
    ...
    CoreApplicationView newView = CoreApplication.CreateNewView();
    int newViewId = 0;
    await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        Frame frame = new Frame();
        Window.Current.Content = frame;
        Window.Current.Activate();
        newViewId = ApplicationView.GetForCurrentView().Id;
    });
    await ApplicationViewSwitcher.SwitchAsync(newViewId);
    //bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
}

If you still have issues please provide a minimal reproduced project for a testing on our side.

Updated:
SwitchAsync(Int32, Int32) method can work well for your scenario. For example:

// Create 2 secondary views
CoreApplicationView newView = CoreApplication.CreateNewView();
int newViewId = 0;
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    Frame frame = new Frame();
    frame.Navigate(typeof(page1));
    Window.Current.Content = frame;
    Window.Current.Activate();
    ApplicationView appView = ApplicationView.GetForCurrentView();
    newViewId = appView.Id;
    appView.Title = newViewId.ToString();
    _viewIds.Add(newViewId);
});

bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);

CoreApplicationView newView2 = CoreApplication.CreateNewView();
int newViewId2 = 0;
await newView2.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
    Frame frame = new Frame();
    frame.Navigate(typeof(page2));
    Window.Current.Content = frame;
    Window.Current.Activate();
    ApplicationView appView = ApplicationView.GetForCurrentView();
    newViewId2 = appView.Id;
    appView.Title = newViewId2.ToString();
    _viewIds.Add(newViewId2);
});

bool viewShown2 = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId2);

// Switch to first secondary view, BUT focuses on last secondary view :/
Debug.WriteLine("Switching to secondary view with id: " + _viewIds[0]);
// bool viewShowntoone = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(_viewIds[0]);
await ApplicationViewSwitcher.SwitchAsync(_viewIds[0], _viewIds[1]);


问:
Google finance historical
So I was recently using the yahoo finance api for python in order to get stock data for a project. The .get_historical() function broke, which gives a list of closing prices, opening prices, etc for a particular stock over a duration of time (like closing prices for the last month). I started using google finance, and am wondering if there is anything like that, where I can get an up to date list that has closing prices for the last month. Is this possible? Here is what I have tried for google finance:

```<code>from googlefinance import getQuotes
import json
print json.dumps(getQuotes('AAPL'), indent=2)
[
  {
    "Index": "NASDAQ",
    "LastTradeWithCurrency": "129.09",
    "LastTradeDateTime": "2015-03-02T16:04:29Z",
    "LastTradePrice": "129.09",
    "Yield": "1.46",
    "LastTradeTime": "4:04PM EST",
    "LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
    "Dividend": "0.47",
    "StockSymbol": "AAPL",
    "ID": "22144"
  }
]
</code>```

however this doesn't seem to give historical data of any kind

答:
Use pandas_data reader like:</p>

```<code>    import pandas_datareader.data as wb
    web_df = wb.DataReader(symbols, 'google', date_start, date_end)
</code>```

Title: Google finance historical

Body:
So I was recently using the yahoo finance api for python in order to get stock data for a project. The .get_historical() function broke, which gives a list of closing prices, opening prices, etc for a particular stock over a duration of time (like closing prices for the last month). I started using google finance, and am wondering if there is anything like that, where I can get an up to date list that has closing prices for the last month. Is this possible? Here is what I have tried for google finance:

from googlefinance import getQuotes
import json
print json.dumps(getQuotes('AAPL'), indent=2)
[
  {
    "Index": "NASDAQ",
    "LastTradeWithCurrency": "129.09",
    "LastTradeDateTime": "2015-03-02T16:04:29Z",
    "LastTradePrice": "129.09",
    "Yield": "1.46",
    "LastTradeTime": "4:04PM EST",
    "LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
    "Dividend": "0.47",
    "StockSymbol": "AAPL",
    "ID": "22144"
  }
]

however this doesn't seem to give historical data of any kind

Body:
Use pandas_data reader like:

    import pandas_datareader.data as wb
    web_df = wb.DataReader(symbols, 'google', date_start, date_end)


答:
AFAIK all you can do is omit the returns to make things more compact in C++:

```<code>switch(Answer)
{
    case 1: case 2: case 3: case 4:
        cout << "You need more cars.";
        break;
    ...
}
</code>```

(You could remove the other returns as well, of course.)

Title: Grouping switch statement cases together?

Body:
AFAIK all you can do is omit the returns to make things more compact in C++:

switch(Answer)
{
    case 1: case 2: case 3: case 4:
        cout << "You need more cars.";
        break;
    ...
}

(You could remove the other returns as well, of course.)


问:
Superpowered SDK trying to record and play it at the same time
I am trying to create android app with Superpowered SDK, which would allow me to redirect mic input to headphones with added reverb effect to mic, to simulate huge room effect. I found this repository with code snippets: https://bitbucket.org/snippets/kasurd/Mynnp/nativesuperpoweredrecorder-with, but I can't make it working. This is my current code:

```<code>#include <jni.h>
#include <stdio.h>
#include "SuperpoweredExample.h"
#include <SuperpoweredSimple.h>
#include <SuperpoweredCPU.h>
#include <pthread.h>
#include <malloc.h>

static void playerEventCallback(void *clientData, SuperpoweredAdvancedAudioPlayerEvent event, void * __unused value) {
    if (event == SuperpoweredAdvancedAudioPlayerEvent_LoadSuccess) {
        SuperpoweredAdvancedAudioPlayer *player = *((SuperpoweredAdvancedAudioPlayer **)clientData);
        //player->setBpm(126.0f);
        //player->setFirstBeatMs(353);
        player->setPosition(player->firstBeatMs, false, false);
    }else if (event == SuperpoweredAdvancedAudioPlayerEvent_LoadError) {
    } else if (event == SuperpoweredAdvancedAudioPlayerEvent_EOF) {
    };
}

static bool audioProcessingPlayback(void *clientdata, short int *audioIO, int numberOfSamples, int samplerate) {
    return ((SuperpoweredPlayer *)clientdata)->processPlayback(0, audioIO, numberOfSamples);
}

static bool audioProcessingRecording(void *clientdata, short int *audioIO, int numberOfSamples, int samplerate) {
    return ((SuperpoweredPlayer *)clientdata)->processRecording(audioIO, numberOfSamples);
}

bool SuperpoweredPlayer::process(short int *output, unsigned int numberOfSamples) {
    bool processResult =  player->process(stereoBuffer, false, numberOfSamples);
    SuperpoweredFloatToShortInt(stereoBuffer, output, numberOfSamples);
    return processResult;
}

static bool audioProcessing(void *clientdata, short int *audioIO, int numberOfSamples, int __unused samplerate) {
    return ((SuperpoweredPlayer *)clientdata)->process(audioIO, (unsigned int)numberOfSamples);
}

SuperpoweredPlayer::SuperpoweredPlayer(unsigned int sampleRate, unsigned int bufferSize, const char *path, int fileOffset, int fileLength) {

    stereoBuffer = (float *)memalign(16, (bufferSize + 16) * sizeof(float) * 2);
    stereoBufferRecording = (float *)memalign(16, (bufferSize + 16) * sizeof(float) * 2);

    this->sampleRate = sampleRate;
    this->bufferSize = bufferSize;

    playerA = NULL;
    recorder = NULL;
    audioSystemRecording = new SuperpoweredAndroidAudioIO(sampleRate, bufferSize, true, false, audioProcessingRecording, this, bufferSize * 2);

    initPlayerA(path, fileOffset, fileLength, 0);
}

void SuperpoweredPlayer::initPlayerA(const char *path, int fileOffset, int fileSize, double startOffsetMs) {
    audioSystemA = new SuperpoweredAndroidAudioIO(sampleRate, bufferSize, false, true, audioProcessingPlayback, this, bufferSize * 2);
    playerA = new SuperpoweredAdvancedAudioPlayer(&playerA , playerEventCallback, sampleRate, 0);
    playerA->open(path, fileOffset, fileSize);
    playerA->syncMode = SuperpoweredAdvancedAudioPlayerSyncMode_TempoAndBeat;
}

void SuperpoweredPlayer::playPause(bool play) {
    if (!play) {
        askPlaying = false;
        if (playerA != NULL) {
            playerA->pause();
        }
    } else {
        if (playerA != NULL) {
            playerA->play(false);
        }
        askPlaying = true;
    };
    SuperpoweredCPU::setSustainedPerformanceMode(play);
}

void SuperpoweredPlayer::startRecording(const char *tempPath, const char *destinationPath) {
    recorder = new SuperpoweredRecorder(tempPath, sampleRate);
    askRecording = true;
    recorder->start(destinationPath);
    playPause(true);
}

void SuperpoweredPlayer::stopRecording() {
    if (!askRecording) {
        return;
    }
    askPlaying = false;
    askRecording = false;
    recorder->stop();
    playPause(false);
}

// method to receive playback parts
bool SuperpoweredPlayer::processPlayback(int playerId, short int *output, unsigned int numberOfSamples) {
    pthread_mutex_lock(&mutex);
    if (!askPlaying) {
        pthread_mutex_unlock(&mutex);
        return false;
    }
    playerA->process(stereoBuffer, false, numberOfSamples, 1.0f, 0.0f, -1.0f);

    SuperpoweredFloatToShortInt(stereoBuffer, output, numberOfSamples);

    pthread_mutex_unlock(&mutex);
    return true;
}

// method to receive recording parts
bool SuperpoweredPlayer::processRecording(short int *input, unsigned int numberOfSamples) {
    pthread_mutex_lock(&mutex);
    if (askRecording) {
        unsigned int data = 0;
        SuperpoweredShortIntToFloat(input, stereoBufferRecording, numberOfSamples);
        data = recorder->process(stereoBufferRecording, NULL, numberOfSamples);
        pthread_mutex_unlock(&mutex);
        return true;
    }
    pthread_mutex_unlock(&mutex);
    return false;
}

//void SuperpoweredPlayer::setTempo(double value) {
//    player->setTempo(value, true);
//}

SuperpoweredPlayer::~SuperpoweredPlayer() {
    delete playerA;
    free(stereoBuffer);
    pthread_mutex_destroy(&mutex);
}

static SuperpoweredPlayer *player = NULL;
static const char *path;

extern "C" JNIEXPORT void Java_com_example_pc_superpoweredsdk_SuperPoweredPlayerWrapper_SuperpoweredPlayer(JNIEnv *javaEnvironment, jobject __unused obj, jint sampleRate, jint bufferSize, jstring apkPath, jint fileOffset, jint fileLength) {
    path = javaEnvironment->GetStringUTFChars(apkPath, JNI_FALSE);
    player = new SuperpoweredPlayer((unsigned int)sampleRate, ((unsigned int)bufferSize), path + 'temp.wav', fileOffset, fileLength);
    javaEnvironment->ReleaseStringUTFChars(apkPath, path);
}

extern "C" JNIEXPORT void Java_com_example_pc_superpoweredsdk_SuperPoweredPlayerWrapper_playPause(JNIEnv * __unused javaEnvironment, jobject __unused obj, jboolean play) {
    player->startRecording(path + 'temp.wav', path + 'dest.wav');
}
</code>```

sampleRate is 44100, bufferSize is 512, and path is context.getFilesDir().getAbsolutePath()

I am stuck at the moment, trying to figure out, how should I playback mic input with added reverb filter threw headphones in real time with as little latency as possible.

答:
The code attached is not really relevant here, as it mostly deals with a player.
I recommend to do your own code from scratch. Use SuperpoweredAndroidAudioIO for audio input/output, and use SuperpoweredRecorder to process the incoming audio. Will be no more than a few lines total.</p>

Body:
I am trying to create android app with Superpowered SDK, which would allow me to redirect mic input to headphones with added reverb effect to mic, to simulate huge room effect. I found this repository with code snippets: https://bitbucket.org/snippets/kasurd/Mynnp/nativesuperpoweredrecorder-with, but I can't make it working. This is my current code:

#include <jni.h>
#include <stdio.h>
#include "SuperpoweredExample.h"
#include <SuperpoweredSimple.h>
#include <SuperpoweredCPU.h>
#include <pthread.h>
#include <malloc.h>

static void playerEventCallback(void *clientData, SuperpoweredAdvancedAudioPlayerEvent event, void * __unused value) {
    if (event == SuperpoweredAdvancedAudioPlayerEvent_LoadSuccess) {
        SuperpoweredAdvancedAudioPlayer *player = *((SuperpoweredAdvancedAudioPlayer **)clientData);
        //player->setBpm(126.0f);
        //player->setFirstBeatMs(353);
        player->setPosition(player->firstBeatMs, false, false);
    }else if (event == SuperpoweredAdvancedAudioPlayerEvent_LoadError) {
    } else if (event == SuperpoweredAdvancedAudioPlayerEvent_EOF) {
    };
}

static bool audioProcessingPlayback(void *clientdata, short int *audioIO, int numberOfSamples, int samplerate) {
    return ((SuperpoweredPlayer *)clientdata)->processPlayback(0, audioIO, numberOfSamples);
}

static bool audioProcessingRecording(void *clientdata, short int *audioIO, int numberOfSamples, int samplerate) {
    return ((SuperpoweredPlayer *)clientdata)->processRecording(audioIO, numberOfSamples);
}

bool SuperpoweredPlayer::process(short int *output, unsigned int numberOfSamples) {
    bool processResult =  player->process(stereoBuffer, false, numberOfSamples);
    SuperpoweredFloatToShortInt(stereoBuffer, output, numberOfSamples);
    return processResult;
}

static bool audioProcessing(void *clientdata, short int *audioIO, int numberOfSamples, int __unused samplerate) {
    return ((SuperpoweredPlayer *)clientdata)->process(audioIO, (unsigned int)numberOfSamples);
}

SuperpoweredPlayer::SuperpoweredPlayer(unsigned int sampleRate, unsigned int bufferSize, const char *path, int fileOffset, int fileLength) {

    stereoBuffer = (float *)memalign(16, (bufferSize + 16) * sizeof(float) * 2);
    stereoBufferRecording = (float *)memalign(16, (bufferSize + 16) * sizeof(float) * 2);

    this->sampleRate = sampleRate;
    this->bufferSize = bufferSize;

    playerA = NULL;
    recorder = NULL;
    audioSystemRecording = new SuperpoweredAndroidAudioIO(sampleRate, bufferSize, true, false, audioProcessingRecording, this, bufferSize * 2);

    initPlayerA(path, fileOffset, fileLength, 0);
}

void SuperpoweredPlayer::initPlayerA(const char *path, int fileOffset, int fileSize, double startOffsetMs) {
    audioSystemA = new SuperpoweredAndroidAudioIO(sampleRate, bufferSize, false, true, audioProcessingPlayback, this, bufferSize * 2);
    playerA = new SuperpoweredAdvancedAudioPlayer(&playerA , playerEventCallback, sampleRate, 0);
    playerA->open(path, fileOffset, fileSize);
    playerA->syncMode = SuperpoweredAdvancedAudioPlayerSyncMode_TempoAndBeat;
}

void SuperpoweredPlayer::playPause(bool play) {
    if (!play) {
        askPlaying = false;
        if (playerA != NULL) {
            playerA->pause();
        }
    } else {
        if (playerA != NULL) {
            playerA->play(false);
        }
        askPlaying = true;
    };
    SuperpoweredCPU::setSustainedPerformanceMode(play);
}

void SuperpoweredPlayer::startRecording(const char *tempPath, const char *destinationPath) {
    recorder = new SuperpoweredRecorder(tempPath, sampleRate);
    askRecording = true;
    recorder->start(destinationPath);
    playPause(true);
}

void SuperpoweredPlayer::stopRecording() {
    if (!askRecording) {
        return;
    }
    askPlaying = false;
    askRecording = false;
    recorder->stop();
    playPause(false);
}

// method to receive playback parts
bool SuperpoweredPlayer::processPlayback(int playerId, short int *output, unsigned int numberOfSamples) {
    pthread_mutex_lock(&mutex);
    if (!askPlaying) {
        pthread_mutex_unlock(&mutex);
        return false;
    }
    playerA->process(stereoBuffer, false, numberOfSamples, 1.0f, 0.0f, -1.0f);

    SuperpoweredFloatToShortInt(stereoBuffer, output, numberOfSamples);

    pthread_mutex_unlock(&mutex);
    return true;
}

// method to receive recording parts
bool SuperpoweredPlayer::processRecording(short int *input, unsigned int numberOfSamples) {
    pthread_mutex_lock(&mutex);
    if (askRecording) {
        unsigned int data = 0;
        SuperpoweredShortIntToFloat(input, stereoBufferRecording, numberOfSamples);
        data = recorder->process(stereoBufferRecording, NULL, numberOfSamples);
        pthread_mutex_unlock(&mutex);
        return true;
    }
    pthread_mutex_unlock(&mutex);
    return false;
}

//void SuperpoweredPlayer::setTempo(double value) {
//    player->setTempo(value, true);
//}

SuperpoweredPlayer::~SuperpoweredPlayer() {
    delete playerA;
    free(stereoBuffer);
    pthread_mutex_destroy(&mutex);
}

static SuperpoweredPlayer *player = NULL;
static const char *path;

extern "C" JNIEXPORT void Java_com_example_pc_superpoweredsdk_SuperPoweredPlayerWrapper_SuperpoweredPlayer(JNIEnv *javaEnvironment, jobject __unused obj, jint sampleRate, jint bufferSize, jstring apkPath, jint fileOffset, jint fileLength) {
    path = javaEnvironment->GetStringUTFChars(apkPath, JNI_FALSE);
    player = new SuperpoweredPlayer((unsigned int)sampleRate, ((unsigned int)bufferSize), path + 'temp.wav', fileOffset, fileLength);
    javaEnvironment->ReleaseStringUTFChars(apkPath, path);
}

extern "C" JNIEXPORT void Java_com_example_pc_superpoweredsdk_SuperPoweredPlayerWrapper_playPause(JNIEnv * __unused javaEnvironment, jobject __unused obj, jboolean play) {
    player->startRecording(path + 'temp.wav', path + 'dest.wav');
}

sampleRate is 44100, bufferSize is 512, and path is context.getFilesDir().getAbsolutePath()

I am stuck at the moment, trying to figure out, how should I playback mic input with added reverb filter threw headphones in real time with as little latency as possible.


答:
Or this, For checking null values and Empty String.

Example Source

```<code>        CREATE TABLE TBLCOUPONS
            (
              Couponid INT ,
              Couponcode VARCHAR(10) ,
              DiscountType NCHAR(1) ,
              Discount INT
            )

        INSERT  TBLCOUPONS
                ( Couponid, Couponcode, DiscountType, Discount )
        VALUES  ( 1, 'JT5326', '$', 5 ),
                ( 2, 'CY1990', '%', 9 )

        GO
</code>```

PROCEDURE

```<code>        CREATE PROCEDURE [dbo].[CouponSearch] ( @DiscountType NCHAR(1) )
        AS
            BEGIN

                IF ( @DiscountType = '' )
                    BEGIN
                        SET @DiscountType = NULL
                    END

                SELECT  Couponcode
                FROM    tblCoupons
                WHERE   DiscountType = ISNULL(@DiscountType, DiscountType)
            END
            GO
</code>```

EXECUTION

```<code>    EXEC [CouponSearch] '%'
        GO
        EXEC [CouponSearch] '$'
        GO
        EXEC [CouponSearch] ''
        GO
        EXEC [CouponSearch] NULL
        GO
</code>```

RESULTS

```<code>         ------------------EXEC [CouponSearch] '%'
        Couponcode
        ----------
        CY1990

        (1 row(s) affected)

         ------------------EXEC [CouponSearch] '$'
        Couponcode
        ----------
        JT5326

        (1 row(s) affected)

         -------------------EXEC [CouponSearch] ''
        Couponcode
        ----------
        JT5326
        CY1990

        (2 row(s) affected)

        -------------------EXEC [CouponSearch] NULL
        Couponcode
        ----------
        JT5326
        CY1990

        (2 row(s) affected)
</code>```

Title: How to use nchar with like operator in SQL Server

Body:
Or this, For checking null values and Empty String.

Example Source

        CREATE TABLE TBLCOUPONS
            (
              Couponid INT ,
              Couponcode VARCHAR(10) ,
              DiscountType NCHAR(1) ,
              Discount INT
            )

        INSERT  TBLCOUPONS
                ( Couponid, Couponcode, DiscountType, Discount )
        VALUES  ( 1, 'JT5326', '$', 5 ),
                ( 2, 'CY1990', '%', 9 )

        GO

PROCEDURE

        CREATE PROCEDURE [dbo].[CouponSearch] ( @DiscountType NCHAR(1) )
        AS
            BEGIN

                IF ( @DiscountType = '' )
                    BEGIN
                        SET @DiscountType = NULL
                    END

                SELECT  Couponcode
                FROM    tblCoupons
                WHERE   DiscountType = ISNULL(@DiscountType, DiscountType)
            END
            GO

EXECUTION

    EXEC [CouponSearch] '%'
        GO
        EXEC [CouponSearch] '$'
        GO
        EXEC [CouponSearch] ''
        GO
        EXEC [CouponSearch] NULL
        GO

RESULTS

         ------------------EXEC [CouponSearch] '%'
        Couponcode
        ----------
        CY1990

        (1 row(s) affected)

         ------------------EXEC [CouponSearch] '$'
        Couponcode
        ----------
        JT5326

        (1 row(s) affected)

         -------------------EXEC [CouponSearch] ''
        Couponcode
        ----------
        JT5326
        CY1990

        (2 row(s) affected)

        -------------------EXEC [CouponSearch] NULL
        Couponcode
        ----------
        JT5326
        CY1990

        (2 row(s) affected)


问:
How to add a transition for a slide show?
I wanted to add a transition for the slide show which i am making for one of my page..

Here is the code,

        var index= 1;

        var toggle=0;

        function plusIndex(n){
         index = index + n;
         showImage(n);
        }
        showImage(1);

        function showImage(n){
        var i;
        var x = document.getElementsByClassName("placestovisit");
        if (index > x.length) {index=1};
        if (index < 1) {index= x.length};
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
            x[index-1].style.display= "block";
        }

        autoSlide();
        function autoSlide(){
        if (toggle) {return};
        var i;
        var x = document.getElementsByClassName("placestovisit");
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
        if (index > x.length) {index = 1};
            x[index-1].style.display= "block";
        index++;
        setTimeout(autoSlide, 4000);
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <body style="height:100%;">

<div id="placescontainer">
<div class="placestovisit fade">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Hanumangundi_Falls.jpg/1200px-Hanumangundi_Falls.jpg" alt="" />
      <h1>Hanumanagundi Falls</h1>
      <h2 > Suthanabbe Falls or Hanumanagundi Falls is located in the hilly surroundings of the Kudremukh National Park in the Chikkamagaluru district of Karnataka, India.
Suthanabbe Falls is located between Karkala and Lakya dam in the Kudremukh national park. The water falls from a height of 22 meters creating a scenic surroundings around it.</h2>
</div>

<div class="placestovisit fade">
      <img src="https://upload.wikimedia.org/wikipedia/commons/4/4b/Hampi_virupaksha_temple.jpg" alt="" />
      <h1> Hambi(Hambe) </h1>
          <h2> Hampi (Hampe) is a village and temple town recognised as a UNESCO World Heritage Site, listed as the Group of Monuments at Hampi. in northern Karnataka, India. It was one of the richest and largest cities in the world during its prime. It is located within the ruins of the city of Vijayanagara, the former capital of the Vijayanagara Empire. Predating the city of Vijayanagara, Hampi continues to be an important religious centre, housing the Virupaksha Temple and several other monuments belonging to the old city. According to statistics of 2014, Hampi is the most searched historical place in Karnataka on Google.</h2>
</div>
<div class="placestovisit w3-animate-fading">
      <img src="http://www.thebetterindia.com/wp-content/uploads/2012/09/IMG_0750-Com-800x533.jpg" alt="" />
      <h1> Agumbe </h1>
          <h2> Agumbe is a hill station which can be reached by bikes or cars. The way to this place is a diversion from Parkala (The diversion is just a few kms from DT). The best part of the trip to Agumbe is the ride. Beautiful sceneries on both sides will keep company all along the way. This place is abount 45 km from Manipal. Agumbe is one of the highest peaks of the Western Ghats located about 60kms from Udupi. Situated at a height of 830 metres from sea level, it overlooks the Arabian Sea. Agumbe is part of the Shimoga district which is a neighboring district of Udupi. </h2>
</div>

<div class="placestovisit fade">
      <img src="https://d28dwf34zswvrl.cloudfront.net/wp-content/uploads/2017/01/kerala-carbon-neutral-panchayat.jpg" alt="" />
      <h1> Kerala </h1>
          <h2> The border of Kerala is just 75 km from Manipal. The 300-year-old Bekal Fort, shaped like a giant key-hole, is one of the largest and best-preserved forts in Kerala. Surrounded by a splendid beach, the historic Bekal Fort offers a superb view of the Arabian Sea from its tall observation towers, where a few centuries ago huge cannons used to be placed. Today, it is one of the favourite spots for film-makers because the Bekal Fort and its surroundings with backwaters and hilly destinations make fascinating locales. This fort was made by Tipu Sultan and is built right next to the sea. The popular song 'Tu Hi Re' was picturised with this fort in the backdrop.</h2>
</div>

<div class="placestovisit fade">
      <img src="http://udupitoday.com/udtoday/images/uploads/January/images/jan1431attur1.jpg" alt="" />
      <h1> Attur church </h1>
          <h2> Attur Church situated in the outskirts of Karkala town in Karnataka state — India. It is situated 58 km from Mangalore.
Placed amidst placid greenery, the Attur-Karkala parish has a rich history with its origin tracing back to 1759. Moreover it is known for its miraculous history. Miracle, history, beauty, social activities, all bundled into one.
Unlike others, the church is a place of worship and belief for all, irrespective of caste and creed. An vidence for universal peace and brotherhood. People from all walks of the society come here to offer their prayers to St Lawrence</h2>
</div>
<button class="btn" onclick="plusIndex(-1)" id="btn1"> ❮</button>
<button class="btn"  onclick="plusIndex(1)" id="btn2"> ❯</button>

<button class="play"  onclick="toggle=1-toggle; autoSlide()" id="btn3">  Play/Pause </button>

</div>

    </body></code>```

Fiddle Demo

I am newbie to javascript as well as css.

The above works properly, which out transition offline, I dont know what is the problem in fiddle. I think that there is some small misunderstanding, with that..

Could any one help me in adding a slide transition.

I need something like the link http://www.devtrix.net/sliderman/examples.html

答:
You can use css and make your Slider change images Like Fading, zoom,..

```<code>animate-fading{animation:fading 10s infinite}@keyframes fading{0%{opacity:0}50%{opacity:1}100%{opacity:0}}
animate-zoom {animation:animatezoom 0.6s}@keyframes animatezoom{from{transform:scale(0)} to{transform:scale(1)}}
animate-top{position:relative;animation:animatetop 0.4s}@keyframes animatetop{from{top:-300px;opacity:0} to{top:0;opacity:1}}
</code>```

Check W3Schools Example: here

Also you can use SildeShow Maker softwares like Amazing Slider.
easy download, easy use: download link

See Screeshot from it:

See a jsfiddle example:  jsfiddle

Body:
I wanted to add a transition for the slide show which i am making for one of my page..

Here is the code,

        var index= 1;

        var toggle=0;

        function plusIndex(n){
         index = index + n;
         showImage(n);
        }
        showImage(1);

        function showImage(n){
        var i;
        var x = document.getElementsByClassName("placestovisit");
        if (index > x.length) {index=1};
        if (index < 1) {index= x.length};
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
            x[index-1].style.display= "block";
        }

        autoSlide();
        function autoSlide(){
        if (toggle) {return};
        var i;
        var x = document.getElementsByClassName("placestovisit");
        for (i=0; i<x.length; i++)
        {
          x[i].style.display="none";
        }
        if (index > x.length) {index = 1};
            x[index-1].style.display= "block";
        index++;
        setTimeout(autoSlide, 4000);
        }

Hanumanagundi Falls

 Suthanabbe Falls or Hanumanagundi Falls is located in the hilly surroundings of the Kudremukh National Park in the Chikkamagaluru district of Karnataka, India.
Suthanabbe Falls is located between Karkala and Lakya dam in the Kudremukh national park. The water falls from a height of 22 meters creating a scenic surroundings around it.

 Hambi(Hambe)

 Hampi (Hampe) is a village and temple town recognised as a UNESCO World Heritage Site, listed as the Group of Monuments at Hampi. in northern Karnataka, India. It was one of the richest and largest cities in the world during its prime. It is located within the ruins of the city of Vijayanagara, the former capital of the Vijayanagara Empire. Predating the city of Vijayanagara, Hampi continues to be an important religious centre, housing the Virupaksha Temple and several other monuments belonging to the old city. According to statistics of 2014, Hampi is the most searched historical place in Karnataka on Google.

 Agumbe

 Agumbe is a hill station which can be reached by bikes or cars. The way to this place is a diversion from Parkala (The diversion is just a few kms from DT). The best part of the trip to Agumbe is the ride. Beautiful sceneries on both sides will keep company all along the way. This place is abount 45 km from Manipal. Agumbe is one of the highest peaks of the Western Ghats located about 60kms from Udupi. Situated at a height of 830 metres from sea level, it overlooks the Arabian Sea. Agumbe is part of the Shimoga district which is a neighboring district of Udupi.

 Kerala

 The border of Kerala is just 75 km from Manipal. The 300-year-old Bekal Fort, shaped like a giant key-hole, is one of the largest and best-preserved forts in Kerala. Surrounded by a splendid beach, the historic Bekal Fort offers a superb view of the Arabian Sea from its tall observation towers, where a few centuries ago huge cannons used to be placed. Today, it is one of the favourite spots for film-makers because the Bekal Fort and its surroundings with backwaters and hilly destinations make fascinating locales. This fort was made by Tipu Sultan and is built right next to the sea. The popular song 'Tu Hi Re' was picturised with this fort in the backdrop.

 Attur church

 Attur Church situated in the outskirts of Karkala town in Karnataka state — India. It is situated 58 km from Mangalore.
Placed amidst placid greenery, the Attur-Karkala parish has a rich history with its origin tracing back to 1759. Moreover it is known for its miraculous history. Miracle, history, beauty, social activities, all bundled into one.
Unlike others, the church is a place of worship and belief for all, irrespective of caste and creed. An vidence for universal peace and brotherhood. People from all walks of the society come here to offer their prayers to St Lawrence

<button class="btn" onclick="plusIndex(-1)" id="btn1"> ❮</button>
<button class="btn"  onclick="plusIndex(1)" id="btn2"> ❯</button>

<button class="play"  onclick="toggle=1-toggle; autoSlide()" id="btn3">  Play/Pause </button>

Fiddle Demo

I am newbie to javascript as well as css.

The above works properly, which out transition offline, I dont know what is the problem in fiddle. I think that there is some small misunderstanding, with that..

Could any one help me in adding a slide transition.

I need something like the link http://www.devtrix.net/sliderman/examples.html

Body:
You can use css and make your Slider change images Like Fading, zoom,..

animate-fading{animation:fading 10s infinite}@keyframes fading{0%{opacity:0}50%{opacity:1}100%{opacity:0}}
animate-zoom {animation:animatezoom 0.6s}@keyframes animatezoom{from{transform:scale(0)} to{transform:scale(1)}}
animate-top{position:relative;animation:animatetop 0.4s}@keyframes animatetop{from{top:-300px;opacity:0} to{top:0;opacity:1}}

Check W3Schools Example: here

Also you can use SildeShow Maker softwares like Amazing Slider.
easy download, easy use: download link

See Screeshot from it:

See a jsfiddle example:  jsfiddle


问:
Retrieve Starting and Ending values from a table whose values have gaps
How can I retrieve the values from a table where there are TicketType and TicketNo columns. Each TicketType can have mutiple TicketNos and these TicketNos may have gaps between them. TicketNos are not generated by the system. Not my choice. Here is a sample of the data and the desired output:

```<code>    declare @tickets table ( TicketType varchar(20),
                         TicketNo int )
insert into @tickets( tickettype, ticketno )
select 'AIRCON 1', 1
union all
select 'AIRCON 1', 2
union all
select 'AIRCON 1', 3
union all
select 'AIRCON 1', 6
union all
select 'AIRCON 1', 7
union all
select 'AIRCON 1', 8
union all
select 'AIRCON 1', 9
union all
select 'AIRCON 2', 1
union all
select 'AIRCON 2', 2
union all
select 'AIRCON 2', 3
union all
select 'AIRCON 2', 4
union all
select 'AIRCON 2', 5
union all
select 'AIRCON 3', 1
union all
select 'AIRCON 3', 2
union all
select 'AIRCON 3', 9
union all
select 'AIRCON 3', 10

select * from @tickets

SELECT 'AIRCON 1' TicketType, 1 Starting, 3 Ending
union all
select 'AIRCON 1', 6, 9
union all
select 'AIRCON 2', 1, 5
union all
select 'AIRCON 3', 1, 2
union all
select 'AIRCON 3', 9, 10
</code>```

Sample data:

```<code>+------------------------------------+
|   TicketType           TicketNo    |
+------------------------------------+
| AIRCON 1             1             |
| AIRCON 1             2             |
| AIRCON 1             3             |
| AIRCON 1             6             |
| AIRCON 1             7             |
| AIRCON 1             8             |
| AIRCON 1             9             |
| AIRCON 2             1             |
| AIRCON 2             2             |
| AIRCON 2             3             |
| AIRCON 2             4             |
| AIRCON 2             5             |
| AIRCON 3             1             |
| AIRCON 3             2             |
| AIRCON 3             9             |
| AIRCON 3             10            |
</code>```

Desired Result

```<code>| TicketType Starting    Ending      |
| ---------- ----------- ----------- |
| AIRCON 1   1           3           |
| AIRCON 1   6           9           |
| AIRCON 2   1           5           |
| AIRCON 3   1           2           |
| AIRCON 3   9           10          |
+------------------------------------+
</code>```

答:
You have to calculate the grouping column (root) for islands in your data. Like this:</p>

```<code>;with cteMain as (
    select
        *
        , lag(t.TicketNo, 1, -1) over (order by t.TicketType, t.TicketNo) as TicketNoLag
    from @tickets t
), cteHierarchy as (
    select
        m.TicketType
        , m.TicketNo
        , m.TicketNoLag
        , m.TicketNo as Root
    from cteMain m
    where m.TicketNo - m.TicketNoLag <> 1
    union all
    select
        m.TicketType
        , m.TicketNo
        , m.TicketNoLag
        , h.Root as Root
    from cteMain m
        inner join cteHierarchy h on m.TicketNoLag = h.TicketNo
            and m.TicketType = h.TicketType
            and m.TicketNo - m.TicketNoLag = 1
)
select
    h.TicketType
    , min(h.TicketNo) as Starting
    , max(h.TicketNo) as Ending
from cteHierarchy h
group by h.TicketType, h.Root
order by h.TicketType
</code>```

Body:
How can I retrieve the values from a table where there are TicketType and TicketNo columns. Each TicketType can have mutiple TicketNos and these TicketNos may have gaps between them. TicketNos are not generated by the system. Not my choice. Here is a sample of the data and the desired output:

    declare @tickets table ( TicketType varchar(20),
                         TicketNo int )
insert into @tickets( tickettype, ticketno )
select 'AIRCON 1', 1
union all
select 'AIRCON 1', 2
union all
select 'AIRCON 1', 3
union all
select 'AIRCON 1', 6
union all
select 'AIRCON 1', 7
union all
select 'AIRCON 1', 8
union all
select 'AIRCON 1', 9
union all
select 'AIRCON 2', 1
union all
select 'AIRCON 2', 2
union all
select 'AIRCON 2', 3
union all
select 'AIRCON 2', 4
union all
select 'AIRCON 2', 5
union all
select 'AIRCON 3', 1
union all
select 'AIRCON 3', 2
union all
select 'AIRCON 3', 9
union all
select 'AIRCON 3', 10

select * from @tickets

SELECT 'AIRCON 1' TicketType, 1 Starting, 3 Ending
union all
select 'AIRCON 1', 6, 9
union all
select 'AIRCON 2', 1, 5
union all
select 'AIRCON 3', 1, 2
union all
select 'AIRCON 3', 9, 10

Sample data:

+------------------------------------+
|   TicketType           TicketNo    |
+------------------------------------+
| AIRCON 1             1             |
| AIRCON 1             2             |
| AIRCON 1             3             |
| AIRCON 1             6             |
| AIRCON 1             7             |
| AIRCON 1             8             |
| AIRCON 1             9             |
| AIRCON 2             1             |
| AIRCON 2             2             |
| AIRCON 2             3             |
| AIRCON 2             4             |
| AIRCON 2             5             |
| AIRCON 3             1             |
| AIRCON 3             2             |
| AIRCON 3             9             |
| AIRCON 3             10            |

Desired Result

| TicketType Starting    Ending      |
| ---------- ----------- ----------- |
| AIRCON 1   1           3           |
| AIRCON 1   6           9           |
| AIRCON 2   1           5           |
| AIRCON 3   1           2           |
| AIRCON 3   9           10          |
+------------------------------------+

Body:
You have to calculate the grouping column (root) for islands in your data. Like this:

;with cteMain as (
    select
        *
        , lag(t.TicketNo, 1, -1) over (order by t.TicketType, t.TicketNo) as TicketNoLag
    from @tickets t
), cteHierarchy as (
    select
        m.TicketType
        , m.TicketNo
        , m.TicketNoLag
        , m.TicketNo as Root
    from cteMain m
    where m.TicketNo - m.TicketNoLag <> 1
    union all
    select
        m.TicketType
        , m.TicketNo
        , m.TicketNoLag
        , h.Root as Root
    from cteMain m
        inner join cteHierarchy h on m.TicketNoLag = h.TicketNo
            and m.TicketType = h.TicketType
            and m.TicketNo - m.TicketNoLag = 1
)
select
    h.TicketType
    , min(h.TicketNo) as Starting
    , max(h.TicketNo) as Ending
from cteHierarchy h
group by h.TicketType, h.Root
order by h.TicketType


问:
Android, want to delete the image after selected from the gallery
I'm creating a program that can select image from gallery and after selected, the text next to the image will change to "Delete" for delete the image.
I have worked on select image from gallery, and now I don't know how to make the delete function. Can someone please help!
And here is my code. Where I should put the delete.</p>

```<code>addPhotoText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectNewsFeedImage();
        }
    });

.....else if (items[item].equals("Choose from Gallery")) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(i, "Select File"), RESULT_LOAD_IMAGE);
            }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == RESULT_LOAD_IMAGE && data != null) {
            Bitmap bm = null;
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
            addPhotoIcon.setImageBitmap(bm);......
</code>```

答:
you should have to use URI here it is in the OnActivityResult</p>

```<code> Uri selectedI = data.getData();

 File file = new File(String.valueOf(selectedI));
 file.delete();
</code>```

Body:
I'm creating a program that can select image from gallery and after selected, the text next to the image will change to "Delete" for delete the image.
I have worked on select image from gallery, and now I don't know how to make the delete function. Can someone please help!
And here is my code. Where I should put the delete.

addPhotoText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectNewsFeedImage();
        }
    });

.....else if (items[item].equals("Choose from Gallery")) {
                Intent i = new Intent();
                i.setType("image/*");
                i.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(i, "Select File"), RESULT_LOAD_IMAGE);
            }

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == RESULT_LOAD_IMAGE && data != null) {
            Bitmap bm = null;
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
            addPhotoIcon.setImageBitmap(bm);......

Body:
you should have to use URI here it is in the OnActivityResult

 Uri selectedI = data.getData();

 File file = new File(String.valueOf(selectedI));
 file.delete();


问:
How to make TFS vNext Builds to delete gated-checkin-shelvestes after successful build?
In XAML Builds, the temp-auto-created shelvesets of Gated CheckIn builds, disappear automatically after the checkin. In vNext - they aren't.

Is there way to make them disappear automatically after successful checkin-build?

答:
For vNext builds, the temp-auto-created shelvesets will also disappear automatically after successful checkin-build. I test this at my side, it works correctly.

If the Gated CheckIn builds failed, then the Shelvessets will be remained.
So, please check if the temp-auto-created shelvesets are the ones failed to Gated CheckIn

Please reference below screenshot:


问:
Regex Searching in vim
I'm using vim to do some pattern matching on a text file. I've enabled search highlighting so that I know exactly what is getting matched on each search and am getting confused.

Consider searching for [a-z]* on the following text:```123456789abcdefghijklmnopqrstuvwxyxz987654321ABCDEFGHIJKLMNOPQRSTUVWQXZ```

I expected this search to match zero or more consecutive characters that are in the range [a-z]. Instead, I get a match on the entire line.

Should this be the expected behaviour?

Thanks,

Andrew

答:
It's matching the empty strings that occur after every character. It has no way of highlighting empty ranges, so it looks like everything is highlighted.

Try searching for [a-z]\+ instead.

Title: Regex Searching in vim

Body:
I'm using vim to do some pattern matching on a text file. I've enabled search highlighting so that I know exactly what is getting matched on each search and am getting confused.

Consider searching for [a-z]* on the following text:
123456789abcdefghijklmnopqrstuvwxyxz987654321ABCDEFGHIJKLMNOPQRSTUVWQXZ

I expected this search to match zero or more consecutive characters that are in the range [a-z]. Instead, I get a match on the entire line.

Should this be the expected behaviour?

Thanks,

Andrew


问:
GitPython error when pulling from remote repository
I'm trying to pull from a remote repo in a local one with this code:

```<code>repo = git.Repo('/home/user/repo/')
o = repo.remotes.origin
try:
    o.pull()
except:
    logging.exception("oops:")
</code>```

This fails miserably with the following traceback:

```<code>Traceback (most recent call last):
  File "/home/user/my_site/app/app.py", line 58, in regen_logs
    o.pull()
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/remote.py", line 665, in pull
    proc = self.repo.git.pull(self, refspec, with_extended_output=True, as_process=True, v=True, **kwargs)
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/cmd.py", line 440, in <lambda>
    return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/cmd.py", line 834, in _call_process
    return self.execute(make_call(), **_kwargs)
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/cmd.py", line 576, in execute
    raise GitCommandNotFound(str(err))
GitCommandNotFound: [Errno 2] No such file or directory
</code>```

However, when doing the exact three commands (Repo, set origin, pull()) in an interactive session, it works just fine:

```<code>>>> import git
>>> repo = git.Repo('/home/user/repo')
>>> o = repo.remotes.origin
>>> o.pull()
[<git.remote.FetchInfo object at 0x242d2b8>]
</code>```

I do have Git installed on the system:

```<code>$ rpm -q git
git-1.8.3.1-6.el7.x86_64
</code>```

Any clues what I'm doing wrong here?

答:
You need to set path to git before import git, like this:

import os

os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = '/usr/local/bin/git'

from git import Repo

Body:
I'm trying to pull from a remote repo in a local one with this code:

repo = git.Repo('/home/user/repo/')
o = repo.remotes.origin
try:
    o.pull()
except:
    logging.exception("oops:")

This fails miserably with the following traceback:

Traceback (most recent call last):
  File "/home/user/my_site/app/app.py", line 58, in regen_logs
    o.pull()
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/remote.py", line 665, in pull
    proc = self.repo.git.pull(self, refspec, with_extended_output=True, as_process=True, v=True, **kwargs)
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/cmd.py", line 440, in <lambda>
    return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/cmd.py", line 834, in _call_process
    return self.execute(make_call(), **_kwargs)
  File "/home/user/my_site/venv/lib/python2.7/site-packages/git/cmd.py", line 576, in execute
    raise GitCommandNotFound(str(err))
GitCommandNotFound: [Errno 2] No such file or directory

However, when doing the exact three commands (Repo, set origin, pull()) in an interactive session, it works just fine:

>>> import git
>>> repo = git.Repo('/home/user/repo')
>>> o = repo.remotes.origin
>>> o.pull()
[<git.remote.FetchInfo object at 0x242d2b8>]

I do have Git installed on the system:

$ rpm -q git
git-1.8.3.1-6.el7.x86_64

Any clues what I'm doing wrong here?