问:
Unable to fix "Plugin with id 'com.android.application' not found"

Plugin with id 'com.android.application' not found

That's the error I get each time I sync the project.

Project level build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'io.realm:realm-gradle-plugin:2.3.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

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

app Level gradle file

```<code>apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'realm-android'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "com.example.appname"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

//    packagingOptions {
//        exclude 'META-INF/INDEX.LIST'
//        exclude 'META-INF/DEPENDENCIES'
//        exclude 'META-INF/LICENSE'
//        exclude 'META-INF/spring.handlers'
//        exclude 'META-INF/spring.schemas'
//        exclude 'META-INF/cxf/bus-extensions.txt'
//    }

    android {
        lintOptions {
            abortOnError false
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    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.1.1'
    compile 'com.android.support:design:25.1.1'
    compile 'com.android.support:support-v4:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    compile 'jp.wasabeef:recyclerview-animators:2.2.4'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'commons-io:commons-io:2.5'
    compile 'io.reactivex:rxjava:1.2.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'io.realm:android-adapters:1.4.1'
    compile 'com.squareup.okhttp:okhttp:2.7.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'junit:junit:4.12'
    apt 'com.jakewharton:butterknife-compiler:8.5.1'
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile project(':poishadow-all')
}
</code>```

Effects made to fix it

Tried this popular answer

Tried File > Invalidate Caches / Restart

Copied another projects app and project levels build.gradle files

Observations

If I remove apply plugin: 'com.android.application and sync the error becomes

Plugin with id 'android-apt' not found

and If I also remove Plugin with id 'android-apt' not found the error becomes

'Plugin with id realm-android' not found.

EDIT
I ran ./gradlew build --stacktrace and I got this:

```<code>* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'app'.
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:176)
        at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:181)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
        at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:70)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$000(LifecycleProjectEvaluator.java:33)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:53)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:50)
        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.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:628)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:129)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
        at org.gradle.initialization.DefaultGradleLauncher$1.execute(DefaultGradleLauncher.java:161)
        at org.gradle.initialization.DefaultGradleLauncher$1.execute(DefaultGradleLauncher.java:158)
        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:158)
        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)
Caused by: org.gradle.api.plugins.UnknownPluginException: Plugin with id 'com.android.application' not found.
        at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:110)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:113)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:136)
        at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:44)
        at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
        at org.gradle.api.Script$apply.callCurrent(Unknown Source)
        at build_adp866r1t6j1hlthh3am8fjsj.run(/home/ozuf/Android/Projects/appname/app/build.gradle:1)
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
        ... 62 more

BUILD FAILED

Total time: 2.29 secs
</code>```

答: I have seen this happen when I accidently removed build.gradle.</p>

Body:
Plugin with id 'com.android.application' not found

That's the error I get each time I sync the project.

Project level build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'io.realm:realm-gradle-plugin:2.3.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

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

app Level gradle file

apply plugin: 'com.android.application'
apply plugin: 'android-apt'
apply plugin: 'realm-android'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "com.example.appname"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

//    packagingOptions {
//        exclude 'META-INF/INDEX.LIST'
//        exclude 'META-INF/DEPENDENCIES'
//        exclude 'META-INF/LICENSE'
//        exclude 'META-INF/spring.handlers'
//        exclude 'META-INF/spring.schemas'
//        exclude 'META-INF/cxf/bus-extensions.txt'
//    }

    android {
        lintOptions {
            abortOnError false
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    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.1.1'
    compile 'com.android.support:design:25.1.1'
    compile 'com.android.support:support-v4:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    compile 'jp.wasabeef:recyclerview-animators:2.2.4'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'commons-io:commons-io:2.5'
    compile 'io.reactivex:rxjava:1.2.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'io.realm:android-adapters:1.4.1'
    compile 'com.squareup.okhttp:okhttp:2.7.5'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testCompile 'junit:junit:4.12'
    apt 'com.jakewharton:butterknife-compiler:8.5.1'
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    compile project(':poishadow-all')
}

Effects made to fix it

Tried this popular answer

Tried File > Invalidate Caches / Restart

Copied another projects app and project levels build.gradle files

Observations

If I remove apply plugin: 'com.android.application and sync the error becomes

Plugin with id 'android-apt' not found

and If I also remove Plugin with id 'android-apt' not found the error becomes

'Plugin with id realm-android' not found.

EDIT
I ran ./gradlew build --stacktrace and I got this:

* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating root project 'app'.
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:92)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl$2.run(DefaultScriptPluginFactory.java:176)
        at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:77)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:181)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
        at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:70)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.access$000(LifecycleProjectEvaluator.java:33)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:53)
        at org.gradle.configuration.project.LifecycleProjectEvaluator$1.execute(LifecycleProjectEvaluator.java:50)
        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.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:50)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:628)
        at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:129)
        at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:35)
        at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:60)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:38)
        at org.gradle.initialization.DefaultGradleLauncher$1.execute(DefaultGradleLauncher.java:161)
        at org.gradle.initialization.DefaultGradleLauncher$1.execute(DefaultGradleLauncher.java:158)
        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:158)
        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)
Caused by: org.gradle.api.plugins.UnknownPluginException: Plugin with id 'com.android.application' not found.
        at org.gradle.api.internal.plugins.DefaultPluginManager.apply(DefaultPluginManager.java:110)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyType(DefaultObjectConfigurationAction.java:113)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:136)
        at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:44)
        at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.java:34)
        at org.gradle.api.Script$apply.callCurrent(Unknown Source)
        at build_adp866r1t6j1hlthh3am8fjsj.run(/home/ozuf/Android/Projects/appname/app/build.gradle:1)
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:90)
        ... 62 more

BUILD FAILED

Total time: 2.29 secs


来源: stackexchange

问:
rendering an additional pop up dialog on button click React
I am having issues with rendering a pop up loading screen. So assume i have a imported component called ( LoadingDialog ) and i want it to render when the state property, loading is true. When the user clicks a button on the current component, it triggers an api call which also changes the loading state to true, thus rendering the loading dialog.

I understand I can use conditional rendering to achive this, eg:

```<code> if(this.state.loading){
      return (
        <div>
        <LoadingDialog />
        </div>

      )
    }
    else{
      return(
      <div> OTHER UI ELEMENTS </div>
     )

</code>```

but now i have a problem because, when my loadingDialog is rendered, my other ui (text area, background card, button ) all disappear, which is the opposite of what im trying to achieve. With this approach, i can only display my actual ui elements or the loading dialog.

I've tried separating the other ui elements into a separate container but it doesn't help as i need to call the api on click of an button and the entire problem i'm having now occurs in that child container.

I've also tried the above approach with passing a parent on click method as a prop and calling that when the button is clicked but somehow ended up with a recursive loop of the parent/child component

Heres my actual code:

```<code> if(this.state.loading){
      return (
        <div>
        <LoadingDialog />
        </div>

      )
    }
    else{
      return (
        <div>
          <Card className="center card">
            <div className="row">
              <div class="column" >
                <TextField
                  id="outlined-name"
                  name="searchContent"
                  onChange={this.handleChange}
                  value={this.state.searchContent}
                  label="Name"
                  variant="outlined"
                />
              </div>
              <div className="column">
                <Button
                  variant="outlined"
                  color="primary"
                  onClick={this.handleClick}
                >
                  Search
                </Button>
              </div>
            </div>
          </Card>
        </div>
      );
    }
</code>```

and this is my handle click function:

```<code>
  handleClick = (event, name) => {
    this.setState({loading : true})
    fetch(uri)
      .then(res => res.json())
      .then(data => {
        console.log(data);
        this.setState({loading : false})
      });
  };
</code>```

As i said before, I tried separating the UI bit on the else block to a different component but the problem still persisted. To summarise it again,
I can only render my actual ui or a popup box but not both at any given time.
I want to be able to render both at the same time, if needed.

I am very new to react and staying away from the likes of redux, hooks etc.

答:
SOLVED Thanks to Chris G

So the issue was easily fixed by using a logical and operator to check if loading is true or false, like so {this.state.loading && <LoadingDialog />}

eg.

```<code>render(){
   return(
     <div>
       {this.state.loading && <LoadingDialog />}
     <div>
        //REST OF THE STUFF THAT SHOULD BE RENDERED REGARDLESS
     </div>
    </div>
    )
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having issues with rendering a pop up loading screen. So assume i have a imported component called ( LoadingDialog ) and i want it to render when the state property, loading is true. When the user clicks a button on the current component, it triggers an api call which also changes the loading state to true, thus rendering the loading dialog.

I understand I can use conditional rendering to achive this, eg:

 if(this.state.loading){
      return (

        <LoadingDialog />

      )
    }
    else{
      return(

 OTHER UI ELEMENTS

     )

but now i have a problem because, when my loadingDialog is rendered, my other ui (text area, background card, button ) all disappear, which is the opposite of what im trying to achieve. With this approach, i can only display my actual ui elements or the loading dialog.

I've tried separating the other ui elements into a separate container but it doesn't help as i need to call the api on click of an button and the entire problem i'm having now occurs in that child container.

I've also tried the above approach with passing a parent on click method as a prop and calling that when the button is clicked but somehow ended up with a recursive loop of the parent/child component

Heres my actual code:

 if(this.state.loading){
      return (

        <LoadingDialog />

      )
    }
    else{
      return (

          <Card className="center card">

                <TextField
                  id="outlined-name"
                  name="searchContent"
                  onChange={this.handleChange}
                  value={this.state.searchContent}
                  label="Name"
                  variant="outlined"
                />

                <Button
                  variant="outlined"
                  color="primary"
                  onClick={this.handleClick}
                >
                  Search
                </Button>

          </Card>

      );
    }

and this is my handle click function:

  handleClick = (event, name) => {
    this.setState({loading : true})
    fetch(uri)
      .then(res => res.json())
      .then(data => {
        console.log(data);
        this.setState({loading : false})
      });
  };

As i said before, I tried separating the UI bit on the else block to a different component but the problem still persisted. To summarise it again,
I can only render my actual ui or a popup box but not both at any given time.
I want to be able to render both at the same time, if needed.

I am very new to react and staying away from the likes of redux, hooks etc.

Body:
SOLVED Thanks to Chris G

So the issue was easily fixed by using a logical and operator to check if loading is true or false, like so {this.state.loading && <LoadingDialog />}

eg.

render(){
   return(
     <div>
       {this.state.loading && <LoadingDialog />}
     <div>
        //REST OF THE STUFF THAT SHOULD BE RENDERED REGARDLESS
     </div>
    </div>
    )
}


问:
How to insert a third party API result into Wordpress page/content?
I have a CURL method that we use for calling the third party API via GitBash:

```<code>curl -u "xxx@dxwxcxrp.com:hPhO4IXXXXXYM2zXXXXX" -X GET -H "Content-Type: application/json" "https://dxwxcxrp.atlassian.net/rest/api/3/search?jql=created>=startOfMonth()&key=DCHC01&startAt=1&maxResults=1&fields=id,key"
</code>```

The result will be like this:

```<code>{
   "expand":"names,schema",
   "startAt":1,
   "maxResults":1,
   "total":31,
   "issues":[
      {
         "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
         "id":"28648",
         "self":"https://dxwxcxrp.atlassian.net/rest/api/3/issue/28648",
         "key":"DCHC01-7059"
      }
   ]
}
</code>```

How do we display this on Wordpress website? Do we need to create a plugin for this? Or is there any other method that is simple to implement?

答:
Depends where you want to display it, and (sometimes) how your site is built.  You could use shortcodes, which would only require a function (and register callback) in functions.php, or you could build a small plugin.  If you want it to run on every page load and you're not worried about API rate limits, the shortcode solution would probably be easiest to implement.

Modification of the sample linked to above:

function startOfMonth()
{
    return 1;
}

// [dcpartners_json]
function dcpartners_json($atts)
{
    $ch = curl_init();
    $startOfMonth = startOfMonth();
    $auth = "xxx@dxwxcxrp.com:hPhO4IXXXXXYM2zXXXXX";

    curl_setopt($ch, CURLOPT_URL, "https://dxwxcxrp.atlassian.net/rest/api/3/search?jql=created>=$startOfMonth&key=DCHC01&startAt=1&maxResults=1&fields=id,key");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: application/json']);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $json = curl_exec($ch);
    curl_close();

    return $json;
}

add_shortcode('dcpartners_json', 'dcpartners_json');
```

That would just spit out a JSON string, not HTML.

Body:
I have a CURL method that we use for calling the third party API via GitBash:

curl -u "xxx@dxwxcxrp.com:hPhO4IXXXXXYM2zXXXXX" -X GET -H "Content-Type: application/json" "https://dxwxcxrp.atlassian.net/rest/api/3/search?jql=created>=startOfMonth()&key=DCHC01&startAt=1&maxResults=1&fields=id,key"

The result will be like this:

{
   "expand":"names,schema",
   "startAt":1,
   "maxResults":1,
   "total":31,
   "issues":[
      {
         "expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields",
         "id":"28648",
         "self":"https://dxwxcxrp.atlassian.net/rest/api/3/issue/28648",
         "key":"DCHC01-7059"
      }
   ]
}

How do we display this on Wordpress website? Do we need to create a plugin for this? Or is there any other method that is simple to implement?

Body:
Depends where you want to display it, and (sometimes) how your site is built.  You could use shortcodes, which would only require a function (and register callback) in functions.php, or you could build a small plugin.  If you want it to run on every page load and you're not worried about API rate limits, the shortcode solution would probably be easiest to implement.

Modification of the sample linked to above:

function startOfMonth()
{
    return 1;
}

// [dcpartners_json]
function dcpartners_json($atts)
{
    $ch = curl_init();
    $startOfMonth = startOfMonth();
    $auth = "xxx@dxwxcxrp.com:hPhO4IXXXXXYM2zXXXXX";

    curl_setopt($ch, CURLOPT_URL, "https://dxwxcxrp.atlassian.net/rest/api/3/search?jql=created>=$startOfMonth&key=DCHC01&startAt=1&maxResults=1&fields=id,key");
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: application/json']);
    curl_setopt($ch, CURLOPT_USERPWD, $auth);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $json = curl_exec($ch);
    curl_close();

    return $json;
}

add_shortcode('dcpartners_json', 'dcpartners_json');

That would just spit out a JSON string, not HTML.


问:
Closing a .NET form causes the parent to minimize
I have an issue where the parent form will minimize to the task tray (but I don't think it is losing focus because the next form that shows, the Studio IDE, has focus) when I close a dialog/form that was shown by calling ShowDialog(owner).

The weird thing is that this doesn't happen every time. I don't see how the owner/parent parameter is getting cleared so I don't know why the parent would go away.

答:
in MdiParent...... all the child forms are automatically loaded with
{Maximize}{Minimize}{CLose} buttons...

You just need to use those buttons,,,,,, like in normal window.....

the forms will get rminimized and still will be shown in MdiParent....

Ref: http://www.itpian.com/Coding/6412-How-to-minimize-Form-which-is-shown-in-parent-Form.aspx

OwnerDisplayName: Eric

ContentLicense: CC BY-SA 3.0


问:
want to implement a rotatation of images list interface using javascript
Actually i have a list 6 div elements and each div contains some images and two buttons.
my question is how can we select the list of images for each instance of div using javascript.
All the div's are having the same class name and all the images are having the same class name.
I tried querySelector but it selects only one instance and the same event doesn't run for the other div's
querySelectorAll selects all the div's so unable to execute the event for a particular image inside the div

I want to get this result, when the right button inside the div is clicked i want to display the next image and for the left it is opposite, and if the image is the last one it should display the first image. Like a rotation of images.

答:
Sounds like a slider, no need to recreate the wheel. Use an array to index where you're at.

https://www.w3schools.com/w3css/w3css_slideshow.asp


问:
login after reload page wordpress
I am using the litespeed cache plugin. page does not refresh when users log in.

page refresh code I use

```<code>                    if ("reload" == response.data.action) {
                        window.location.reload(true);
                    }
</code>```

but not working.

this code does not refresh the page. I think it's about litespeed cache.

答:
You can do this by adding a query string when you are enqueueing your javascript file. something like this,

```<code>my-script.js?ver=21524
</code>```

Then on the WordPress Dashboard, navigate to go to Litespeed Cache > Settings > Cache and scroll down to the Drop Query String setting.

In this box, you can list the strings you want to ignore, one per line

```<code>21524
425358
</code>```

Save Changes button, and you’re done.

Title: login after reload page wordpress

Body:
I am using the litespeed cache plugin. page does not refresh when users log in.

page refresh code I use

                    if ("reload" == response.data.action) {
                        window.location.reload(true);
                    }

but not working.

this code does not refresh the page. I think it's about litespeed cache.

Body:
You can do this by adding a query string when you are enqueueing your javascript file. something like this,

my-script.js?ver=21524

Then on the WordPress Dashboard, navigate to go to Litespeed Cache > Settings > Cache and scroll down to the Drop Query String setting.

In this box, you can list the strings you want to ignore, one per line

21524
425358

Save Changes button, and you’re done.


问:
Materialized view of first rows
Supposing I have a table with columns date | group_id | user_id | text, and I would like to get the first 3 texts (by date) of each group_id/user_id pair.

It seems wasteful to query the whole table say, every 3 hours, as the results are unlikely to change for a given pair once set, so I looked at materialized views, but examples were about single rows, not sets of rows.

Another issue is that the date column does not correspond to the ingestion date, does this mean that I have to add an ingestion date column to be able to use the @run_time in scheduled queries?

Alternatively, would it be more sensible to load the batch on a separate table, compare it with/update the "first/materialized" table, before merging it with the main table? (so instead of having queries on the main table, fill the materialized table one preemptively at every load). This looks hacky/wrong though?

答:
The question links to I want a "materialized view" of the latest records, and mentions that it deals with single rows instead of multiple rows. The question says that it wants the 3 latest rows instead of only one.

For that, look at the inner query in that answer. Instead of doing this:

```<code>  SELECT latest_row.*
  FROM (
    SELECT ARRAY_AGG(a ORDER BY datehour DESC LIMIT 1)[OFFSET(0)] latest_row
    FROM `fh-bigquery.wikipedia_v3.pageviews_2018` a
    WHERE datehour > TIMESTAMP_SUB(@run_time, INTERVAL 1 DAY )
    # change to CURRENT_TIMESTAMP() or let scheduled queries do it
    AND datehour > '2000-01-01' # nag
    AND wiki='en' AND title LIKE 'A%'
    GROUP BY title
  )
</code>```

Do this:

```<code>  SELECT latest_row.*
  FROM (
    SELECT ARRAY_AGG(a ORDER BY datehour DESC LIMIT 3)[OFFSET(0)] latest_row
    FROM `fh-bigquery.wikipedia_v3.pageviews_2018` a
    WHERE datehour > TIMESTAMP_SUB(@run_time, INTERVAL 1 DAY )
    # change to CURRENT_TIMESTAMP() or let scheduled queries do it
    AND datehour > '2000-01-01' # nag
    AND wiki='en' AND title LIKE 'A%'
    GROUP BY title
  )
</code>```

Re @run_time - you can compare it to any column, just make sure to have a column that makes sense to the logic you want to implement.

Title: Materialized view of first rows

Body:
The question links to I want a "materialized view" of the latest records, and mentions that it deals with single rows instead of multiple rows. The question says that it wants the 3 latest rows instead of only one.

For that, look at the inner query in that answer. Instead of doing this:

  SELECT latest_row.*
  FROM (
    SELECT ARRAY_AGG(a ORDER BY datehour DESC LIMIT 1)[OFFSET(0)] latest_row
    FROM `fh-bigquery.wikipedia_v3.pageviews_2018` a
    WHERE datehour > TIMESTAMP_SUB(@run_time, INTERVAL 1 DAY )
    # change to CURRENT_TIMESTAMP() or let scheduled queries do it
    AND datehour > '2000-01-01' # nag
    AND wiki='en' AND title LIKE 'A%'
    GROUP BY title
  )

Do this:

  SELECT latest_row.*
  FROM (
    SELECT ARRAY_AGG(a ORDER BY datehour DESC LIMIT 3)[OFFSET(0)] latest_row
    FROM `fh-bigquery.wikipedia_v3.pageviews_2018` a
    WHERE datehour > TIMESTAMP_SUB(@run_time, INTERVAL 1 DAY )
    # change to CURRENT_TIMESTAMP() or let scheduled queries do it
    AND datehour > '2000-01-01' # nag
    AND wiki='en' AND title LIKE 'A%'
    GROUP BY title
  )

Re @run_time - you can compare it to any column, just make sure to have a column that makes sense to the logic you want to implement.


问:
Store multiple types as values in C++ dictionary?
I want to write a C++ object that behaves almost equivalent to a Python dictionary. C++'s std::map and std::unordered_map accommodate some of the functionalities that Python dictionaries already have, yet lack one of the most important capabilities, namely, being able to add arbitrary objects and types. Even if it isn't possible, how close can you get to achieving the capabilities of Python's dictionary?

A few previous questions (here and here) fail to handle the issue of adding multiple types to the dictionary.

For example, I want to be able to do something like this in C++:

my_dict = {'first': 1,
           'second': "string",
           'third': 3.5,
           'fourth': my_object}
my_dict['fifth'] = list([1, 2, 3])
```

The best solutions that I can think would be like using void pointers to data which get reinterpreted, or perhaps some kind of run-time polymorphism with some type restrictions?

答:
The best solutions that I can think would be like using void pointers to data which get reinterpreted, or perhaps some kind of run-time polymorphism with some type restrictions?

Many void pointers and many reinterpretation of pointers in modern C++ should be a signal of a bad design, in my opinion. I believe that polymorphism would be a way to go.

Also, if you have a fixed number of types you want to use, consider using C++17's std::any or std::variant which is a more modern union.

```<code>#include <iostream>
#include <map>
#include <string>
#include <variant>

typedef std::map<std::variant<int, std::string>, std::variant<int, std::string>> Dict;

int main(){
    Dict d;
    d["key"] = 1;
    d[5] = "woah";
    std::cout << std::get<int>(d["key"]) << std::endl; // prints 1

    // edit: print all the keys in d
    for(auto& k_v: d){
        std::visit(
            [](auto& value){std::cout << value << ' ';},
            k_v.first // k_v.second to print all values in d
        );
    }

}
</code>```

The above example might be useful in some use-cases.

Also check out how json objects are implemented in any C++ json library. It might be helpful.

Edit: I added an example of std::visit that iterates over keys in our dictionary.

Body:
I want to write a C++ object that behaves almost equivalent to a Python dictionary. C++'s std::map and std::unordered_map accommodate some of the functionalities that Python dictionaries already have, yet lack one of the most important capabilities, namely, being able to add arbitrary objects and types. Even if it isn't possible, how close can you get to achieving the capabilities of Python's dictionary?

A few previous questions (here and here) fail to handle the issue of adding multiple types to the dictionary.

For example, I want to be able to do something like this in C++:

my_dict = {'first': 1,
           'second': "string",
           'third': 3.5,
           'fourth': my_object}
my_dict['fifth'] = list([1, 2, 3])

The best solutions that I can think would be like using void pointers to data which get reinterpreted, or perhaps some kind of run-time polymorphism with some type restrictions?

Body:
The best solutions that I can think would be like using void pointers to data which get reinterpreted, or perhaps some kind of run-time polymorphism with some type restrictions?

Many void pointers and many reinterpretation of pointers in modern C++ should be a signal of a bad design, in my opinion. I believe that polymorphism would be a way to go.

Also, if you have a fixed number of types you want to use, consider using C++17's std::any or std::variant which is a more modern union.

#include <iostream>
#include <map>
#include <string>
#include <variant>

typedef std::map<std::variant<int, std::string>, std::variant<int, std::string>> Dict;

int main(){
    Dict d;
    d["key"] = 1;
    d[5] = "woah";
    std::cout << std::get<int>(d["key"]) << std::endl; // prints 1

    // edit: print all the keys in d
    for(auto& k_v: d){
        std::visit(
            [](auto& value){std::cout << value << ' ';},
            k_v.first // k_v.second to print all values in d
        );
    }

}

The above example might be useful in some use-cases.

Also check out how json objects are implemented in any C++ json library. It might be helpful.

Edit: I added an example of std::visit that iterates over keys in our dictionary.


问:
Testing billing with static products returns SERVICE_DISCONNECTED
I am upgrading the in-app billing in my app from Version 3 to newer code.  Version 3 is working fine and it production in my app right now but I've read it will be deprecated eventually.

When I try to test the purchase flow using a static product id (android.test.purchased), the BillingResult result code only returns -1 with a debug message of "Service connection is disconnected".  AFAIK, there is no service connection in the newer library but there was in Version 3.

If I use a real in-app product code it tells me I've already purchased it, which is correct but I need to test the actual purchase flow.

I am testing this on an actual device (Pixel 3 XL), not the emulator. I've tried testing it on a separate device that is logged in with a test account (not developer) but I get the same results.

UPDATE: I setup a real (test) in-app managed product in the Developer Console, then installed my app on a device that is logged in with a test (non-developer) account and I'm still getting the "Service connection is disconnected" error.  I feel it's something outside of the code but not sure what.

UPDATE 2: I created a new project with nothing in it except the billing code and it worked so there's something in my app that is causing it to break.

UPDATE 3: I created a new project and imported the code from the broken app into it and still getting the same error message.  I feel, now, there's something with my package name and Google's servers that's returning the error message.

UPDATE 4: I created a blank project but gave it the same package name as my broken app and the billing worked, so it's not the package name.  Now my guess is there's something from the old AIDL billing code (Version 3) that is interfering.

SOLUTION!!! in the application node in the AndroidManifest.xml I had this: tools:node="replace".  Removed that attribute and billing now works.

```<code>    mBillingClient = BillingClient.newBuilder(this).enablePendingPurchases().setListener(this).build();
    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(BillingResult billingResult) {
            if (billingResult.getResponseCode() == OK) {
                    final Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
                    if (purchasesResult.getResponseCode() == OK) {

                        final List<Purchase> purchases = purchasesResult.getPurchasesList();

                        for (final Purchase purchase : purchases) {
                        }
                    }
            }
        }
        @Override
        public void onBillingServiceDisconnected() {
            CommonUtils.showToast(mActivity, "disconnected");
        }
    });

    mUnlockPremiumButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                final List<String> skuList = new ArrayList<> ();
                skuList.add(getString(R.string.inapp_premium_product_id));

                final SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder()
                    .setSkusList(skuList)
                    .setType(BillingClient.SkuType.INAPP);

                mBillingClient.querySkuDetailsAsync(params.build(),
                        new SkuDetailsResponseListener() {
                            @Override
                            public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {

                                for (SkuDetails skuDetails : skuDetailsList) {
                                    if (getString(R.string.inapp_premium_product_id).equals(skuDetails.getSku())) {

                                        final BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                                                .setSkuDetails(skuDetails)
                                                .build();

                                        final BillingResult result = mBillingClient.launchBillingFlow(mActivity, flowParams);

                                        if (result.getResponseCode() == ITEM_ALREADY_OWNED)
                                        {
                                            CommonUtils.showToast(mActivity, getString(R.string.alert_purchased));
                                        }
                                        else if (result.getResponseCode() != OK)
                                        {
                                            //always returns a getResponseCode of -1 (service disconnected)
                                        }
                                    }
                                }
                            }
                        });
        }
    });
</code>```

答:
This was the application node, in the AndroidManifest, when the billing was breaking:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:node="replace">
    ...
</application>
</code>```

removing tools:node="replace" fixed the billing.  Hopefully this will save someone the days I wasted.

Body:
I am upgrading the in-app billing in my app from Version 3 to newer code.  Version 3 is working fine and it production in my app right now but I've read it will be deprecated eventually.

When I try to test the purchase flow using a static product id (android.test.purchased), the BillingResult result code only returns -1 with a debug message of "Service connection is disconnected".  AFAIK, there is no service connection in the newer library but there was in Version 3.

If I use a real in-app product code it tells me I've already purchased it, which is correct but I need to test the actual purchase flow.

I am testing this on an actual device (Pixel 3 XL), not the emulator. I've tried testing it on a separate device that is logged in with a test account (not developer) but I get the same results.

UPDATE: I setup a real (test) in-app managed product in the Developer Console, then installed my app on a device that is logged in with a test (non-developer) account and I'm still getting the "Service connection is disconnected" error.  I feel it's something outside of the code but not sure what.

UPDATE 2: I created a new project with nothing in it except the billing code and it worked so there's something in my app that is causing it to break.

UPDATE 3: I created a new project and imported the code from the broken app into it and still getting the same error message.  I feel, now, there's something with my package name and Google's servers that's returning the error message.

UPDATE 4: I created a blank project but gave it the same package name as my broken app and the billing worked, so it's not the package name.  Now my guess is there's something from the old AIDL billing code (Version 3) that is interfering.

SOLUTION!!! in the application node in the AndroidManifest.xml I had this: tools:node="replace".  Removed that attribute and billing now works.

    mBillingClient = BillingClient.newBuilder(this).enablePendingPurchases().setListener(this).build();
    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(BillingResult billingResult) {
            if (billingResult.getResponseCode() == OK) {
                    final Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
                    if (purchasesResult.getResponseCode() == OK) {

                        final List<Purchase> purchases = purchasesResult.getPurchasesList();

                        for (final Purchase purchase : purchases) {
                        }
                    }
            }
        }
        @Override
        public void onBillingServiceDisconnected() {
            CommonUtils.showToast(mActivity, "disconnected");
        }
    });

    mUnlockPremiumButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                final List<String> skuList = new ArrayList<> ();
                skuList.add(getString(R.string.inapp_premium_product_id));

                final SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder()
                    .setSkusList(skuList)
                    .setType(BillingClient.SkuType.INAPP);

                mBillingClient.querySkuDetailsAsync(params.build(),
                        new SkuDetailsResponseListener() {
                            @Override
                            public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {

                                for (SkuDetails skuDetails : skuDetailsList) {
                                    if (getString(R.string.inapp_premium_product_id).equals(skuDetails.getSku())) {

                                        final BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                                                .setSkuDetails(skuDetails)
                                                .build();

                                        final BillingResult result = mBillingClient.launchBillingFlow(mActivity, flowParams);

                                        if (result.getResponseCode() == ITEM_ALREADY_OWNED)
                                        {
                                            CommonUtils.showToast(mActivity, getString(R.string.alert_purchased));
                                        }
                                        else if (result.getResponseCode() != OK)
                                        {
                                            //always returns a getResponseCode of -1 (service disconnected)
                                        }
                                    }
                                }
                            }
                        });
        }
    });

Body:
This was the application node, in the AndroidManifest, when the billing was breaking:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:node="replace">
    ...
</application>

removing tools:node="replace" fixed the billing.  Hopefully this will save someone the days I wasted.


问:
Alternative for "component: () => import()" in VueJS routing
I downloaded a template online to better understand VueJS and also create a web app. However I have a problem with routing. There is a function in my router's index.js that imports a path. The import syntax seems to be buggy due to some webpack issues. I tried a lot of different things but couldn't fix the bug so I want to find a workaround for that import syntax

This is my code for router's index.js

```<code>import Vue from 'vue'
import VueAnalytics from 'vue-analytics'
import Router from 'vue-router'
import Meta from 'vue-meta'

// Routes
import paths from './paths'
// import views from './views'

function route (path, view, name) {
  return {
    name: name || view,
    path,
    component: () => import(
      `../views/${view}.vue`
    )
  }
}

Vue.use(Router)

// Create a new router
const router = new Router({
  mode: 'history',
  routes: paths.map(path => route(path.path, path.view, path.name)).concat([
    { path: '*', redirect: '/home' }
  ]),
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    if (to.hash) {
      return { selector: to.hash }
    }
    return { x: 0, y: 0 }
  }
})

Vue.use(Meta)

// Bootstrap Analytics
// Set in .env
// https://github.com/MatteoGabriele/vue-analytics
if (process.env.GOOGLE_ANALYTICS) {
  Vue.use(VueAnalytics, {
    id: process.env.GOOGLE_ANALYTICS,
    router,
    autoTracking: {
      page: process.env.NODE_ENV !== 'development'
    }
  })
}

export default router
</code>```

When i try to build it, I get an error saying:

```<code>ERROR in ./src/router/index.js
Module build failed: SyntaxError: C:/djangoProjects/martin - Copy/martin/src/router/index.js: Unexpected token (15:21)
</code>```

The syntax error is on line (15:21), in the route function on the component: () => import( line and exactly on import. Fixing this issue is a pain so I was wondering if there is a workaround for it without using the import syntax?

答:
If I remember correctly you'll need a plugin for babel that can handle dynamic imports.

Check out:
https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import

Run npm install @babel/plugin-syntax-dynamic-import

Create or open .babelrc

```<code>{
    "plugins": ["@babel/plugin-syntax-dynamic-import"]
}
</code>```

Body:
I downloaded a template online to better understand VueJS and also create a web app. However I have a problem with routing. There is a function in my router's index.js that imports a path. The import syntax seems to be buggy due to some webpack issues. I tried a lot of different things but couldn't fix the bug so I want to find a workaround for that import syntax

This is my code for router's index.js

import Vue from 'vue'
import VueAnalytics from 'vue-analytics'
import Router from 'vue-router'
import Meta from 'vue-meta'

// Routes
import paths from './paths'
// import views from './views'

function route (path, view, name) {
  return {
    name: name || view,
    path,
    component: () => import(
      `../views/${view}.vue`
    )
  }
}

Vue.use(Router)

// Create a new router
const router = new Router({
  mode: 'history',
  routes: paths.map(path => route(path.path, path.view, path.name)).concat([
    { path: '*', redirect: '/home' }
  ]),
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    if (to.hash) {
      return { selector: to.hash }
    }
    return { x: 0, y: 0 }
  }
})

Vue.use(Meta)

// Bootstrap Analytics
// Set in .env
// https://github.com/MatteoGabriele/vue-analytics
if (process.env.GOOGLE_ANALYTICS) {
  Vue.use(VueAnalytics, {
    id: process.env.GOOGLE_ANALYTICS,
    router,
    autoTracking: {
      page: process.env.NODE_ENV !== 'development'
    }
  })
}

export default router

When i try to build it, I get an error saying:

ERROR in ./src/router/index.js
Module build failed: SyntaxError: C:/djangoProjects/martin - Copy/martin/src/router/index.js: Unexpected token (15:21)

The syntax error is on line (15:21), in the route function on the component: () => import( line and exactly on import. Fixing this issue is a pain so I was wondering if there is a workaround for it without using the import syntax?

Body:
If I remember correctly you'll need a plugin for babel that can handle dynamic imports.

Check out:
https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import

Run npm install @babel/plugin-syntax-dynamic-import

Create or open .babelrc

{
    "plugins": ["@babel/plugin-syntax-dynamic-import"]
}


问:
Teradata error 2641 <tablename> was restructured. Resubmit
I have a table that I drop and create an index each day and I have another job that queries this table with an ACCESS lock.
Sometimes these jobs happen at the same time and then I get the following error:

2641 %DBID.%TVMID was restructured. Resubmit.

I have read in the documentation the following:

```<code>Explanation:
A table was changed before a statement that references the table was processed.
(For example, an index may have been added or a field removed.)

Notes:
The statement may not have the intended result because of the change in the table.

Remedy:
Examine the table and resubmit the request.
</code>```

https://docs.teradata.com/reader/8MhLDQBmL52OycrEKPuGqg/Ju5pqm9uRFO6VziQdcmA6w

I guess this is because the CREATE INDEX sentence requests an EXCLUSIVE lock and the SELECT sentence is queued while the index is created, but when the SELECT is poped from the queue the table has a different version number and it fails.

Maybe I am completely wrong but,
Is there anyway to avoid this behaviour?
Something in the way of making the SELECT sentence reevaluate when it gets the chance to get executed.

Thank you!

答: It is up to the application to handle the 2641 and resubmit the request. There is no option to have the database do so automatically.</p>

Body:
I have a table that I drop and create an index each day and I have another job that queries this table with an ACCESS lock.
Sometimes these jobs happen at the same time and then I get the following error:

2641 %DBID.%TVMID was restructured. Resubmit.

I have read in the documentation the following:

Explanation:
A table was changed before a statement that references the table was processed.
(For example, an index may have been added or a field removed.)

Notes:
The statement may not have the intended result because of the change in the table.

Remedy:
Examine the table and resubmit the request.

https://docs.teradata.com/reader/8MhLDQBmL52OycrEKPuGqg/Ju5pqm9uRFO6VziQdcmA6w

I guess this is because the CREATE INDEX sentence requests an EXCLUSIVE lock and the SELECT sentence is queued while the index is created, but when the SELECT is poped from the queue the table has a different version number and it fails.

Maybe I am completely wrong but,
Is there anyway to avoid this behaviour?
Something in the way of making the SELECT sentence reevaluate when it gets the chance to get executed.

Thank you!


问:
Installed Rails but not able to run it?
I'm using asdf as a ruby package manager, I had a bunch of issues with the PATH environments and was able to install everything correctly. However, I'm running into issues with the rails gem.

I think I might still have ownership errors with it.

This is my path:

/Users/carlos.grijalva/.asdf/shims:/Users/carlos.grijalva/.asdf/bin:/Users/carlos.grijalva/.rbenv/bin:/Users/carlos.grijalva/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

This is which ruby:

/Users/carlos.grijalva/.asdf/shims/ruby

And this is ruby -v:

ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]

And this is my GEM environment

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 2.7.6
  - RUBY VERSION: 2.5.3 (2018-10-18 patchlevel 105) [x86_64-darwin18]
  - INSTALLATION DIRECTORY: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/lib/ruby/gems/2.5.0
  - USER INSTALLATION DIRECTORY: /Users/carlos.grijalva/.gem/ruby/2.5.0
  - RUBY EXECUTABLE: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/bin
  - SPEC CACHE DIRECTORY: /Users/carlos.grijalva/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-18
  - GEM PATHS:
     - /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/lib/ruby/gems/2.5.0
     - /Users/carlos.grijalva/.gem/ruby/2.5.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/bin
     -
     - /Users/carlos.grijalva/.asdf/shims
     - /Users/carlos.grijalva/.asdf/bin
     - /Users/carlos.grijalva/.rbenv/bin
     - /Users/carlos.grijalva/bin
     - /usr/local/bin
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
</code>```

答:
You only want to use one ruby version manager.  Make sure you remove anything related to RBEN if you're not using it as your version manager.

Have a look here for things you may need to do.

You should also check your shell for any PATH definitions you don't need regarding RBENV.

Title: Installed Rails but not able to run it?

Body:
I'm using asdf as a ruby package manager, I had a bunch of issues with the PATH environments and was able to install everything correctly. However, I'm running into issues with the rails gem.

I think I might still have ownership errors with it.

This is my path:

/Users/carlos.grijalva/.asdf/shims:/Users/carlos.grijalva/.asdf/bin:/Users/carlos.grijalva/.rbenv/bin:/Users/carlos.grijalva/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

This is which ruby:

/Users/carlos.grijalva/.asdf/shims/ruby

And this is ruby -v:

ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]

And this is my GEM environment

RubyGems Environment:
  - RUBYGEMS VERSION: 2.7.6
  - RUBY VERSION: 2.5.3 (2018-10-18 patchlevel 105) [x86_64-darwin18]
  - INSTALLATION DIRECTORY: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/lib/ruby/gems/2.5.0
  - USER INSTALLATION DIRECTORY: /Users/carlos.grijalva/.gem/ruby/2.5.0
  - RUBY EXECUTABLE: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/bin
  - SPEC CACHE DIRECTORY: /Users/carlos.grijalva/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-18
  - GEM PATHS:
     - /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/lib/ruby/gems/2.5.0
     - /Users/carlos.grijalva/.gem/ruby/2.5.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /Users/carlos.grijalva/.asdf/installs/ruby/2.5.3/bin
     -
     - /Users/carlos.grijalva/.asdf/shims
     - /Users/carlos.grijalva/.asdf/bin
     - /Users/carlos.grijalva/.rbenv/bin
     - /Users/carlos.grijalva/bin
     - /usr/local/bin
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin


问:
Dynamic query (in stored procedure) based on params provided (SQL Server 2016)
I have an employee table that has over 30 columns. This table is exposed by a web service via a stored procedure that returns all users.

I need to create a new stored procedure that allows you to search on 6 specific columns. I have those columns as input params for the stored procedure, but I am unsure how to create a query that only uses the params that were passed.

For example:

```<code>exec SearchUsers @firstName = 'John', @department = 'Admin'
</code>```

should perform a query only those columns. However, there are 5 available params that can be passed in.

Here are my parameters

```<code>@lastName nvarchar(255) = '',
@firstName nvarchar(255)  = '',
@office nvarchar(50)  = '',
@department nvarchar(50)  = '',
@language nvarchar(255)  = '',
@jobTitle nvarchar(255) = '',
</code>```

I want to build a query that is dynamic enough to only query the values provided.

答:
here a example :</p>

```<code>Create PROCEDURE [dbo].[SearchUsers] (

@lastName Varchar(255) = '',
@firstName Varchar(255)  = '',
@office Varchar(50)  = '',
@department Varchar(50)  = '',
@language Varchar(255)  = '',
@jobTitle Varchar(255) = ''

AS

Set Nocount On

Select lastname,firstname,office,departament,language,jobtitle From Users (Nolock)
Where
lastname Like Case When @lastName <> '' Then @lastName Else lastname End
And firstname Like Case When @firstName <> '' Then @firstName Else firstname End
And office Like Case When @office <> '' Then @office Else office End
And departament Like Case When @department <> '' Then @department Else departament End
And language Like Case When @jobTitle <> '' Then @jobTitle Else jobtitle End

Set Nocount Off

exec SearchUsers @firstName = 'John', @department = 'Admin'
</code>```

Body:
I have an employee table that has over 30 columns. This table is exposed by a web service via a stored procedure that returns all users.

I need to create a new stored procedure that allows you to search on 6 specific columns. I have those columns as input params for the stored procedure, but I am unsure how to create a query that only uses the params that were passed.

For example:

exec SearchUsers @firstName = 'John', @department = 'Admin'

should perform a query only those columns. However, there are 5 available params that can be passed in.

Here are my parameters

@lastName nvarchar(255) = '',
@firstName nvarchar(255)  = '',
@office nvarchar(50)  = '',
@department nvarchar(50)  = '',
@language nvarchar(255)  = '',
@jobTitle nvarchar(255) = '',

I want to build a query that is dynamic enough to only query the values provided.

Body:
here a example :

Create PROCEDURE [dbo].[SearchUsers] (

@lastName Varchar(255) = '',
@firstName Varchar(255)  = '',
@office Varchar(50)  = '',
@department Varchar(50)  = '',
@language Varchar(255)  = '',
@jobTitle Varchar(255) = ''

AS

Set Nocount On

Select lastname,firstname,office,departament,language,jobtitle From Users (Nolock)
Where
lastname Like Case When @lastName <> '' Then @lastName Else lastname End
And firstname Like Case When @firstName <> '' Then @firstName Else firstname End
And office Like Case When @office <> '' Then @office Else office End
And departament Like Case When @department <> '' Then @department Else departament End
And language Like Case When @jobTitle <> '' Then @jobTitle Else jobtitle End

Set Nocount Off

exec SearchUsers @firstName = 'John', @department = 'Admin'


问:
Add "Checked" to radio button, either from cookie, or based on assigned class
I'm including some accessibility tools to a project I'm working on.
I have very little jQuery experience. So far I've followed an excellent guide by James Hibbard, which has brought me quite far. I'm able to change font, size and contrast via radio buttons, and save it to a cookie so the selected choices are remembered.

I'm stuck at getting the radio buttons to show "checked" for the right choice.

Ideally I would load from the cookie, and add "checked" to the appropriate radio button. But alternatively, I could read the class applied to , and use that to determine the checked box.

The script is more or less 1:1 ripped from the guide I followed.

Following the guide, each value is separated by a hyphen ("-"), starting with what it changes plus the actual value, as an example, value="text-sans" for the regular Sans Serif font, and value="text-dyslexic" for the speciality font.

Font selection works wonderfully.

Currently I have no ID for each radio button, I tried to add an ID, and add checked="checked" via jQuery, but I am nowhere near experienced enough to write that from scratch, as evidenced by the past few hour of failing to do so.

```<code>$(document).ready(function() {
    function changeStyles(optValue){
      var property = optValue.split("-")[0];
      removeOldClass(property);
      $("body").addClass(optValue);
      $.cookie('bodyClassList', $("body").attr('class'));
    }

    function removeOldClass(property){
      var classList = $("body").attr('class').split(/\s+/);
      $.each(classList, function(index, item){
        if (item.match(property)){
          $("body").removeClass(item);
        }
      });
    }

    $(".selector").change(function(){
      changeStyles(this.value);
    });

    $(".selector > option").each(function() {
      if(
          $.cookie('bodyClassList') != null &&
          $.cookie('bodyClassList')
           .match($(this).val())
        ){
        $(this).attr("selected","selected");
      }
    });

    $("#reset").click(function(){
      $("body").removeClass();
      $(".selector").each(function(){
        $(this[0]).attr('selected', true);
      })
      $.cookie('bodyClassList', null);
    });

    if($.cookie('bodyClassList') != null) {
      $("body").removeClass();
      $("body").addClass($.cookie('bodyClassList'));
    }
  });
</code>```

No error messages so far, I can echo the contents of the cookie, and seeing as the selection is remembered, I know the cookie bit works, yay!

Any help is most welcome.
Thank you.

答:
OXiGEN had the right idea, changed this bit in code:
Notice the .selector >> input, as we go "two levels" down, because of the  tag.

```<code>$(".selector >> input").each(function() {
  if(
      $.cookie('bodyClassList') != null &&
      $.cookie('bodyClassList')
       .match($(this).val())
    ){
    $(this).attr("checked","checked");
  }
});
</code>```

The HTML for each radio button group now looks like this:

```<code>  <div class="selector">
    <label><input type="radio" name="text" class="selector" value="text-sans">Regular</label><br>
    <label><input type="radio" name="text" class="selector" value="text-dyslexic">Dyslexic</label>
  </div>
</code>```

And it works beautifully!

Thanks!

Body:
I'm including some accessibility tools to a project I'm working on.
I have very little jQuery experience. So far I've followed an excellent guide by James Hibbard, which has brought me quite far. I'm able to change font, size and contrast via radio buttons, and save it to a cookie so the selected choices are remembered.

I'm stuck at getting the radio buttons to show "checked" for the right choice.

Ideally I would load from the cookie, and add "checked" to the appropriate radio button. But alternatively, I could read the class applied to , and use that to determine the checked box.

The script is more or less 1:1 ripped from the guide I followed.

Following the guide, each value is separated by a hyphen ("-"), starting with what it changes plus the actual value, as an example, value="text-sans" for the regular Sans Serif font, and value="text-dyslexic" for the speciality font.

Font selection works wonderfully.

Currently I have no ID for each radio button, I tried to add an ID, and add checked="checked" via jQuery, but I am nowhere near experienced enough to write that from scratch, as evidenced by the past few hour of failing to do so.

$(document).ready(function() {
    function changeStyles(optValue){
      var property = optValue.split("-")[0];
      removeOldClass(property);
      $("body").addClass(optValue);
      $.cookie('bodyClassList', $("body").attr('class'));
    }

    function removeOldClass(property){
      var classList = $("body").attr('class').split(/\s+/);
      $.each(classList, function(index, item){
        if (item.match(property)){
          $("body").removeClass(item);
        }
      });
    }

    $(".selector").change(function(){
      changeStyles(this.value);
    });

    $(".selector > option").each(function() {
      if(
          $.cookie('bodyClassList') != null &&
          $.cookie('bodyClassList')
           .match($(this).val())
        ){
        $(this).attr("selected","selected");
      }
    });

    $("#reset").click(function(){
      $("body").removeClass();
      $(".selector").each(function(){
        $(this[0]).attr('selected', true);
      })
      $.cookie('bodyClassList', null);
    });

    if($.cookie('bodyClassList') != null) {
      $("body").removeClass();
      $("body").addClass($.cookie('bodyClassList'));
    }
  });

No error messages so far, I can echo the contents of the cookie, and seeing as the selection is remembered, I know the cookie bit works, yay!

Any help is most welcome.
Thank you.

Body:
OXiGEN had the right idea, changed this bit in code:
Notice the .selector >> input, as we go "two levels" down, because of the  tag.

$(".selector >> input").each(function() {
  if(
      $.cookie('bodyClassList') != null &&
      $.cookie('bodyClassList')
       .match($(this).val())
    ){
    $(this).attr("checked","checked");
  }
});

The HTML for each radio button group now looks like this:

  <div class="selector">
    <label><input type="radio" name="text" class="selector" value="text-sans">Regular</label><br>
    <label><input type="radio" name="text" class="selector" value="text-dyslexic">Dyslexic</label>
  </div>

And it works beautifully!

Thanks!


问:
Is there a concise way to check if an int variable is equal to a series of ints? | C#
Rather than something like this:

```<code>switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}
</code>```

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

答:
If your goal is to be concise.

```<code>//
(new []{2, 5, 11, 15}).Contains(id)
//
</code>```

If you want to be fast probably stick with the switch.

I think I like the HashSet though.

Body:
Rather than something like this:

switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

Body:
If your goal is to be concise.

//
(new []{2, 5, 11, 15}).Contains(id)
//

If you want to be fast probably stick with the switch.

I think I like the HashSet though.


问:
Variable-Resolution Van der Corput Sequence
I'm seeking to perform a Van der Corput-like sampling of a range, but with a custom resolution.

As an example, consider sampling the range [0, 100], with a resolution of 25. This would entail sampling at [0, 25, 50, 75, 100], and if we follow a Van der Corput-like sequence, something like: [0, 100, 50, 25, 75].

Each "pass" of the Van der Corput algorithm iteratively divides the range into segments 1/2 the size of the previous pass (2 points, then 3, 5, 9, 17, ...). So if my minimum resolution is 24, then I would need 2^n + 1 (in this case, 9) samples, rather than ceil(100/24) = 5 samples in order to achieve the desired resolution.

Are there any approaches that yield the solution I'm looking for?

答:
First of all, I think your sequence has a minor flaw, 100 is never part of that sequence. The Van der Corput sequence should be 0, 50, 25, 75, ....

A Van der Corput sequence shows an interesting pattern if we look at the binary fractions of the number. In essence it boils down to:

```<code>binary    decimal     binary reverse
0.0       0.0           0.0
0.1       0.5           1.0
0.01      0.25         10.0
0.11      0.75         11.0
0.001     0.125       100.0
0.101     0.625       101.0
0.011     0.375       110.0
0.111     0.875       111.0
</code>```

the binary reverse mirrors the number over the "binary point". So here we see that this is actually just a binary counter.

We can use that logic to generate the i-th element of the sequence for a given range with l and u the integral lower and upperbound respectively:

```<code>def vdc_seq(i, l, u):
    v = 0
    p = 0
    d = u - l
    while i:
        v <<= 1
        if i & 1:
            v += d
        i >>= 1
        p += 1
    if p:
        v += (1 << p-1)
    return l + v >> p
</code>```

For example:

```<code>>>> list(map(partial(vdc_seq, l=0, u=100), range(9)))
[0, 50, 25, 75, 13, 63, 38, 88, 6]
</code>```

We can easily use floating points here, by replacing this:

```<code>def vdc_seq(i, l, u):
    v = 0
    p = 1
    d = u - l
    while i:
        v <<= 1
        if i & 1:
            v += d
        i >>= 1
        p <<= 1
    return l + v / p
</code>```

The "resolution" of the 2k+1-1-th element is 2-k, so for a given minimal resolution m, we can determine when to stop, and generate a list like:

```<code>from functools import partial

def vdc_seq_list_min(l, u, m):
    n = 2 * (u - l + m - 1) // m - 1
    return map(partial(vdc_seq, l=l, u=u), range(n))
</code>```

For example:

```<code>>>> list(vdc_seq_list_min(0, 100, 24))
[0, 50, 25, 75, 13, 63, 38, 88, 6]
>>> list(vdc_seq_list_min(0, 100, 10))
[0, 50, 25, 75, 13, 63, 38, 88, 6, 56, 31, 81, 19, 69, 44, 94, 3, 53, 28, 78]
</code>```

Body:
First of all, I think your sequence has a minor flaw, 100 is never part of that sequence. The Van der Corput sequence should be 0, 50, 25, 75, ....

A Van der Corput sequence shows an interesting pattern if we look at the binary fractions of the number. In essence it boils down to:

binary    decimal     binary reverse
0.0       0.0           0.0
0.1       0.5           1.0
0.01      0.25         10.0
0.11      0.75         11.0
0.001     0.125       100.0
0.101     0.625       101.0
0.011     0.375       110.0
0.111     0.875       111.0

the binary reverse mirrors the number over the "binary point". So here we see that this is actually just a binary counter.

We can use that logic to generate the i-th element of the sequence for a given range with l and u the integral lower and upperbound respectively:

def vdc_seq(i, l, u):
    v = 0
    p = 0
    d = u - l
    while i:
        v <<= 1
        if i & 1:
            v += d
        i >>= 1
        p += 1
    if p:
        v += (1 << p-1)
    return l + v >> p

For example:

>>> list(map(partial(vdc_seq, l=0, u=100), range(9)))
[0, 50, 25, 75, 13, 63, 38, 88, 6]

We can easily use floating points here, by replacing this:

def vdc_seq(i, l, u):
    v = 0
    p = 1
    d = u - l
    while i:
        v <<= 1
        if i & 1:
            v += d
        i >>= 1
        p <<= 1
    return l + v / p

The "resolution" of the 2k+1-1-th element is 2-k, so for a given minimal resolution m, we can determine when to stop, and generate a list like:

from functools import partial

def vdc_seq_list_min(l, u, m):
    n = 2 * (u - l + m - 1) // m - 1
    return map(partial(vdc_seq, l=l, u=u), range(n))

For example:

>>> list(vdc_seq_list_min(0, 100, 24))
[0, 50, 25, 75, 13, 63, 38, 88, 6]
>>> list(vdc_seq_list_min(0, 100, 10))
[0, 50, 25, 75, 13, 63, 38, 88, 6, 56, 31, 81, 19, 69, 44, 94, 3, 53, 28, 78]


问:
How to get character matches in Azure Search index instead of substrings
I created an Azure index for my DocumentDB collection, and it seems to be working fine. The index has properties for a user account like FirstName, LastName, and Username. The problem is the default tokenizer seems to be tokenizing the Username field. While I want token matches for the first two fields, I'd like character matching for the usernames. Is there an easy way to achieve this through the Azure portal? If not, how can I achieve this?

答:
Adding another answer based on your above comments.  So basically in the best case, what you want to do is prefix, suffix and wildcard search.  So if the username was user246392, you could find it by typing "use", "392" or even "er246".  The prefix is easy, because you could search use* and it would find it.

Kendra Little did a really nice blog post on how to leverage RegEx with Azure Search, which can allow you to do the full wildcard part of your ask (i.e. search for "392").

If you wanted to do the suffix search, you can do a trick that is quite efficient where you create a new field that would be a custom analyzer that would index the words in opposite order.  Here is an example of a index schema that would allow this (over suffixName field)

```<code>{
"name":"people",
"fields": [
    { "name":"id", "type":"Edm.String", "key":true, "searchable":false },
    {"name": "suffixName", "type": "Edm.String", "searchable":true, "indexAnalyzer":"suffixIndexingAnalyzer", "searchAnalyzer":"reverseText"}
],
"analyzers": [
    {
        "@odata.type": "#Microsoft.Azure.Search.CustomAnalyzer",
        "name": "suffixIndexingAnalyzer",
        "tokenizer": "keyword_v2",
        "tokenFilters": [
            "asciifolding",
            "lowercase",
            "reverse",
            "my_edgeNGramForSuffix"
        ],
        "charFilters": []
    },
    {
        "@odata.type": "#Microsoft.Azure.Search.CustomAnalyzer",
        "name": "reverseText",
        "tokenizer": "classic",
        "tokenFilters": [
            "lowercase",
            "reverse"
        ],
        "charFilters": []
    }

],
"tokenFilters":[
    {
        "@odata.type": "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2",
        "name": "my_edgeNGramForSuffix",
        "minGram": 2,
        "maxGram": 25,
        "side": "front"
    }
]
</code>```

}

Body:
Adding another answer based on your above comments.  So basically in the best case, what you want to do is prefix, suffix and wildcard search.  So if the username was user246392, you could find it by typing "use", "392" or even "er246".  The prefix is easy, because you could search use* and it would find it.

Kendra Little did a really nice blog post on how to leverage RegEx with Azure Search, which can allow you to do the full wildcard part of your ask (i.e. search for "392").

If you wanted to do the suffix search, you can do a trick that is quite efficient where you create a new field that would be a custom analyzer that would index the words in opposite order.  Here is an example of a index schema that would allow this (over suffixName field)

{
"name":"people",
"fields": [
    { "name":"id", "type":"Edm.String", "key":true, "searchable":false },
    {"name": "suffixName", "type": "Edm.String", "searchable":true, "indexAnalyzer":"suffixIndexingAnalyzer", "searchAnalyzer":"reverseText"}
],
"analyzers": [
    {
        "@odata.type": "#Microsoft.Azure.Search.CustomAnalyzer",
        "name": "suffixIndexingAnalyzer",
        "tokenizer": "keyword_v2",
        "tokenFilters": [
            "asciifolding",
            "lowercase",
            "reverse",
            "my_edgeNGramForSuffix"
        ],
        "charFilters": []
    },
    {
        "@odata.type": "#Microsoft.Azure.Search.CustomAnalyzer",
        "name": "reverseText",
        "tokenizer": "classic",
        "tokenFilters": [
            "lowercase",
            "reverse"
        ],
        "charFilters": []
    }

],
"tokenFilters":[
    {
        "@odata.type": "#Microsoft.Azure.Search.EdgeNGramTokenFilterV2",
        "name": "my_edgeNGramForSuffix",
        "minGram": 2,
        "maxGram": 25,
        "side": "front"
    }
]

}


问:
Need to change date into current work week (1-52), but skip to the next week if the day is Wed - Sat in VBA
I'm having trouble writing code in VBA that would allow me to input any given date then have an output of the current work week.  I need a restriction of if the date is Sunday through Tuesday, it will keep that current work week and year but if the date is Wednesday through Saturday, then the next work week and year will show.  For example, I'm looking to input (5/28/19) and have an output of 201922 or an input of (5/29/19) with an output of 201923 even though its technically the same work week.

Before getting too in depth, I do have a working function that provides the year and work week, but I'm trying to adapt the function or add a separate function that will change in to the next work week according to the given date.

I'm new to VBA but have tried to do a little research over the last few days.  I was thinking that I could somehow have one input of the date then have two outputs where one would be the year and work week then the other would be the number associated with that date (1 for Sunday, 2 for Monday, and so on).  I tried to create an if then statement that says if the number associated with that date is 1, 2, or 3 then the workweek would stay the same.  If it was any other number then 1 would be added to that work week so it would move to the next one.  I'm having trouble with trying to make two outputs and have them connected, if that makes any sense.

This is the code that I tried to create, but continuously failed at making. The function that gives the correct work week (without the adaptation of the work week based on the date weekday) is WWV1

```<code>Function WWV2(WeekdayName As Integer)

Dim WWV1 As Integer

If WeekdayName(Date) = 1 Or 2 Or 3 Then WWV1 = WWV1

Else: WWV1 = WWV1 + 1

End Function
</code>```

This provides the cell with #NUM! when I use the function in that cell, which I assume is because I need to somehow connect the two functions.

答:
how about this:

```<code>=YEAR(A1) & TEXT(WEEKNUM(A1,13),"00")
</code>```

WeekNum returns the weeknumber with 13 saying it starts on Wednesday:

VBA

```<code> wkcd = Year(Range("A1")) & Format(Application.WeekNum(Range("A1")),"00")
</code>```

Body:
I'm having trouble writing code in VBA that would allow me to input any given date then have an output of the current work week.  I need a restriction of if the date is Sunday through Tuesday, it will keep that current work week and year but if the date is Wednesday through Saturday, then the next work week and year will show.  For example, I'm looking to input (5/28/19) and have an output of 201922 or an input of (5/29/19) with an output of 201923 even though its technically the same work week.

Before getting too in depth, I do have a working function that provides the year and work week, but I'm trying to adapt the function or add a separate function that will change in to the next work week according to the given date.

I'm new to VBA but have tried to do a little research over the last few days.  I was thinking that I could somehow have one input of the date then have two outputs where one would be the year and work week then the other would be the number associated with that date (1 for Sunday, 2 for Monday, and so on).  I tried to create an if then statement that says if the number associated with that date is 1, 2, or 3 then the workweek would stay the same.  If it was any other number then 1 would be added to that work week so it would move to the next one.  I'm having trouble with trying to make two outputs and have them connected, if that makes any sense.

This is the code that I tried to create, but continuously failed at making. The function that gives the correct work week (without the adaptation of the work week based on the date weekday) is WWV1

Function WWV2(WeekdayName As Integer)

Dim WWV1 As Integer

If WeekdayName(Date) = 1 Or 2 Or 3 Then WWV1 = WWV1

Else: WWV1 = WWV1 + 1

End Function

This provides the cell with #NUM! when I use the function in that cell, which I assume is because I need to somehow connect the two functions.

Body:
how about this:

=YEAR(A1) & TEXT(WEEKNUM(A1,13),"00")

WeekNum returns the weeknumber with 13 saying it starts on Wednesday:

VBA

 wkcd = Year(Range("A1")) & Format(Application.WeekNum(Range("A1")),"00")


问:
Add a block of text after another with sed
I want to add the following block of text
    //There are more text here
    zone "mysite.com" {
     type master;
     file "mysite.com.fwd";
     allow-update { none; };
     };

just after the block of text shown below

```<code>zone "." IN {
    type hint;
    file "named.ca";
};
</code>```

The file should ultimately look like the following

```<code> //There are more lines up here
 zone "." IN {
        type hint;
        file "named.ca";
    };

  zone "mysite.com" {
       type master;
       file "mysite.com.fwd";
         allow-update { none; };
         };
            //There are more lines below here
</code>```

The difficult here is that \n in the pattern to match don't work with sed.

Thanks for your help in advanced

答:
I couldn't get any of these to work on MacOS.

This works for me:

```<code>sed -i '' "/^\s*};/ a \\
\\
\zone "mysite.com" {\\
\  type master;\\
\  file "mysite.com.fwd";\\
\  allow-update { none; };\\
\};\\
" filename
</code>```

This is tested with the following script. It creates a new file, prints it out, modifies it and prints it again:

```<code>testfile="testsed.txt"
rm ${testfile}
cat <<EOF > ${testfile}
//There are more lines up here
zone "." IN {
  type hint;
  file "named.ca";
};
EOF
cat ${testfile}

sed -i '' "/^\s*};/ a \\
\\
\zone "mysite.com" {\\
\  type master;\\
\  file "mysite.com.fwd";\\
\  allow-update { none; };\\
\};\\
" ${testfile}

echo
echo "==== After Transform ===="
echo
cat ${testfile}
</code>```

Body:
I want to add the following block of text
    //There are more text here
    zone "mysite.com" {
     type master;
     file "mysite.com.fwd";
     allow-update { none; };
     };

just after the block of text shown below

zone "." IN {
    type hint;
    file "named.ca";
};

The file should ultimately look like the following

 //There are more lines up here
 zone "." IN {
        type hint;
        file "named.ca";
    };

  zone "mysite.com" {
       type master;
       file "mysite.com.fwd";
         allow-update { none; };
         };
            //There are more lines below here

The difficult here is that \n in the pattern to match don't work with sed.

Thanks for your help in advanced

Body:
I couldn't get any of these to work on MacOS.

This works for me:

sed -i '' "/^\s*};/ a \\
\\
\zone "mysite.com" {\\
\  type master;\\
\  file "mysite.com.fwd";\\
\  allow-update { none; };\\
\};\\
" filename

This is tested with the following script. It creates a new file, prints it out, modifies it and prints it again:

testfile="testsed.txt"
rm ${testfile}
cat <<EOF > ${testfile}
//There are more lines up here
zone "." IN {
  type hint;
  file "named.ca";
};
EOF
cat ${testfile}

sed -i '' "/^\s*};/ a \\
\\
\zone "mysite.com" {\\
\  type master;\\
\  file "mysite.com.fwd";\\
\  allow-update { none; };\\
\};\\
" ${testfile}

echo
echo "==== After Transform ===="
echo
cat ${testfile}


问:
Is this class Threadsafe?
Hi

Is the class below threadsafe?

```<code>class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}
</code>```

答:
Class itself is thread-safe.

Content of the map contained with the class is not. Client can change the entry after getting it. Does it make the whole class thread-safe depends on the logical relationship between this class and V.

Title: Is this class Threadsafe?

Body:
Hi

Is the class below threadsafe?

class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}


问:
Wordpress notification based on advanced custom fields data
I have posts on my website (custom post type) of which the content is filled from advanced custom fields input. The post also include a date field and an email address field. What I like to do is send automatic notifications to the email address when the date is today. Or even better 3 days before the date of today.

I've read some articles about using Wordpress php mail function but don't know where to start. Any points in the right direction are appreciated.

答:
So you can use the Wordpress wp_mail() function.

https://developer.wordpress.org/reference/functions/wp_mail/

Make sure you are using a SMPT plugin so your email doesn't end up in spam.

https://wordpress.org/plugins/wp-mail-smtp/

That should get you started, not sure how I would set up the job to send the mail, by I would definitely use wp_mail().


问:
Retrieve bitmap from uri
I have included 'share via myApp' option. I inserted following code in the receiving activity class.

```<code>    // Get the intent that started this activity
    Intent intent = getIntent();
    Uri data = intent.getData();

    // Figure out what to do based on the intent type
    if (intent.getType().indexOf("image/") != -1) {
        // Handle intents with image data ...
}
</code>```

What is the next step to retrieve bitmap image.

答:
You can try this. You can call setPic() in onActivityResult method. I have used this in an application to take photos an put it in an ImageView.</p>

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

    //currentPhotoPath contains path of image file.
    //visorFoto is a reference to an ImageView object.
    File file = new File(currentPhotoPath);
    Uri imageUri = Uri.fromFile(file);
    visorFoto.setImageURI(imageUri);

}
</code>```

Title: Retrieve bitmap from uri

Body:
I have included 'share via myApp' option. I inserted following code in the receiving activity class.

    // Get the intent that started this activity
    Intent intent = getIntent();
    Uri data = intent.getData();

    // Figure out what to do based on the intent type
    if (intent.getType().indexOf("image/") != -1) {
        // Handle intents with image data ...
}

What is the next step to retrieve bitmap image.

Body:
You can try this. You can call setPic() in onActivityResult method. I have used this in an application to take photos an put it in an ImageView.

private void setPic() {

    //currentPhotoPath contains path of image file.
    //visorFoto is a reference to an ImageView object.
    File file = new File(currentPhotoPath);
    Uri imageUri = Uri.fromFile(file);
    visorFoto.setImageURI(imageUri);

}


问:
SQL: Dupe check using multiple columns
I have to make a:

```<code>INSERT INTO aaa(DateFrom, DateTo)
SELECT DateFrom, DateTo FROM bbb
</code>```

but sometimes this date interval already exists in aaa

How should I add the WHERE to the SELECT, to not insert in aaa if that date interval already exists

My problem is this: if I add something like:

```<code>WHERE bbb.DateFrom NOT IN aaa.DateFrom AND bbb.DateTo NOT IN aaa.DateTo
</code>```

this will not check for both dates (interval), but either "From" or "To" dates

答:
Looks like all you need to do is change your "AND" to an "OR" and add nested select statements.</p>

```<code>WHERE bbb.DateFrom NOT IN (select aaa.DateFrom from aaa) AND bbb.DateTo NOT IN (select aaa.DateTo from aaa)
</code>```

Title: SQL: Dupe check using multiple columns

Body:
I have to make a:

INSERT INTO aaa(DateFrom, DateTo)
SELECT DateFrom, DateTo FROM bbb

but sometimes this date interval already exists in aaa

How should I add the WHERE to the SELECT, to not insert in aaa if that date interval already exists

My problem is this: if I add something like:

WHERE bbb.DateFrom NOT IN aaa.DateFrom AND bbb.DateTo NOT IN aaa.DateTo

this will not check for both dates (interval), but either "From" or "To" dates

Body:
Looks like all you need to do is change your "AND" to an "OR" and add nested select statements.

WHERE bbb.DateFrom NOT IN (select aaa.DateFrom from aaa) AND bbb.DateTo NOT IN (select aaa.DateTo from aaa)