问:
Apache RewriteRule Proxy does not follow redirects
I am trying to configure Apache 2.4 with mod_proxy as a reverse proxy and I'm having a problem with redirects not passed from the origin server to the client.

I have the following configuration in the virtual host configuration:

```<code>[...]
ProxyPreserveHost On
# ProxyPass  "/" "http://old.domain.tld/"
ProxyPassReverse  "/" "http://old.domain.tld/"
[...]
</code>```

When using the commented-out ProxyPass directive in the virtual host config, everything works fine. Which means a 30x-redirect from the origin server gets correctly rewritten and forwarded to the client.

When configuring the ProxyPass in .htaccess (which I need because this only should happen under certain conditions), the reverse proxy is working fine except that it does not process any redirects to the client.

I have the following .htaccess:

```<code>RewriteEngine On
RewriteRule ^(.*)$ http://old.domain.tld/$1 [P]
</code>```

Now, I always get a 404 - not found in the client, when the origin server sends a 30x-Redirect.

In the proxy server log, I can see the following traces:

```<code>[...] strip per-dir prefix: /[...]/domain.tld/htdocs/ ->
[...] applying pattern '^(.*)$' to uri ''
[...] rewrite '' -> 'http://old.domain.tld/'
[...] escaped URI in per-dir context for proxy, http://old.domain.tld/ -> http://old.domain.tld/
[...] forcing proxy-throughput with http://old.domain.tld/
[...] go-ahead with proxy request proxy:http://old.domain.tld/ [OK]
</code>```

The client gets the following headers delivered:

```<code>HTTP/1.1 404 Not Found
Date: Fri, 25 Nov 2016 14:04:23 GMT
Server: Apache/2
Content-Length: 1060
Content-Type: text/html; charset=utf-8
Keep-Alive: timeout=5, max=100
Proxy-Connection: Keep-alive
</code>```

I don't understand why Apache or mod_rewrite/mod_proxy is not forwarding the correct redirect when configured in .htaccess.

Is there any solution for that? Or am I doing something wrong?

Thank you.

答:
ProxyPassReverse its spected to handle redirects so origin server wont take the client outside of the proxy.

This directive lets Apache adjust the URL in the Location,
  Content-Location and URI headers on HTTP redirect responses. This is
  essential when Apache is used as a reverse proxy (or gateway) to avoid
  bypassing the reverse proxy because of HTTP redirects on the backend
  servers which stay behind the reverse proxy.

Only the HTTP response headers specifically mentioned above will be
  rewritten. Apache will not rewrite other response headers, nor will it
  rewrite URL references inside HTML pages. This means that if the
  proxied content contains absolute URL references, they will bypass the
  proxy. A third-party module that will look inside the HTML and rewrite
  URL references is Nick Kew's mod_proxy_html.

Body:
I am trying to configure Apache 2.4 with mod_proxy as a reverse proxy and I'm having a problem with redirects not passed from the origin server to the client.

I have the following configuration in the virtual host configuration:

[...]
ProxyPreserveHost On
# ProxyPass  "/" "http://old.domain.tld/"
ProxyPassReverse  "/" "http://old.domain.tld/"
[...]

When using the commented-out ProxyPass directive in the virtual host config, everything works fine. Which means a 30x-redirect from the origin server gets correctly rewritten and forwarded to the client.

When configuring the ProxyPass in .htaccess (which I need because this only should happen under certain conditions), the reverse proxy is working fine except that it does not process any redirects to the client.

I have the following .htaccess:

RewriteEngine On
RewriteRule ^(.*)$ http://old.domain.tld/$1 [P]

Now, I always get a 404 - not found in the client, when the origin server sends a 30x-Redirect.

In the proxy server log, I can see the following traces:

[...] strip per-dir prefix: /[...]/domain.tld/htdocs/ ->
[...] applying pattern '^(.*)$' to uri ''
[...] rewrite '' -> 'http://old.domain.tld/'
[...] escaped URI in per-dir context for proxy, http://old.domain.tld/ -> http://old.domain.tld/
[...] forcing proxy-throughput with http://old.domain.tld/
[...] go-ahead with proxy request proxy:http://old.domain.tld/ [OK]

The client gets the following headers delivered:

HTTP/1.1 404 Not Found
Date: Fri, 25 Nov 2016 14:04:23 GMT
Server: Apache/2
Content-Length: 1060
Content-Type: text/html; charset=utf-8
Keep-Alive: timeout=5, max=100
Proxy-Connection: Keep-alive

I don't understand why Apache or mod_rewrite/mod_proxy is not forwarding the correct redirect when configured in .htaccess.

Is there any solution for that? Or am I doing something wrong?

Thank you.


来源: stackexchange

问:
How to remove the square brackets in output of the list?
```<code>items=['a', 'b', 'c', 'd', 'e']
print("The first 3 items in the list are: ")
for item in items[:3]:
    print(item)

#or
print("The first 3 items in the list are: " + str(items[:3]))

</code>```

Q: How should I make the output of the 'first 3 items' to be horizontal(like the second code) but without the square brackets(like the 1st code)?

答:
You can use str.join(iterable), where str is the separator between the items in the iterable. For example:

```<code>items = ['a', 'b', 'c', 'd', 'e']
print('The first 3 items in the list are: ' + ', '.join(items[:3]))
</code>```

This prints:

```<code>The first 3 items in the list are: a, b, c
</code>```

In this case, ', ' is the separator between the items of the list. You can change it according to your needs. For example, using ' '.join(items[:3]) instead would result in:

```<code>The first 3 items in the list are: a b c
</code>```

ContentLicense: CC BY-SA 4.0

Body:
items=['a', 'b', 'c', 'd', 'e']
print("The first 3 items in the list are: ")
for item in items[:3]:
    print(item)

#or
print("The first 3 items in the list are: " + str(items[:3]))

Q: How should I make the output of the 'first 3 items' to be horizontal(like the second code) but without the square brackets(like the 1st code)?

Body:
You can use str.join(iterable), where str is the separator between the items in the iterable. For example:

items = ['a', 'b', 'c', 'd', 'e']
print('The first 3 items in the list are: ' + ', '.join(items[:3]))

This prints:

The first 3 items in the list are: a, b, c

In this case, ', ' is the separator between the items of the list. You can change it according to your needs. For example, using ' '.join(items[:3]) instead would result in:

The first 3 items in the list are: a b c


问:
Word interop apply style to all the matches
I have written code to find citations in the word file and trying to make all the citations superscript.

```<code>Word.Range rngCitations = doc.Content;
        rngCitations.Find.MatchWildcards = true;
        rngCitations.Find.Text = @"(\[[0-9]{1,}[,0-9]*\])";
        if (rngCitations.Find.Execute())
        {
            rngCitations.Font.Superscript = 1;
            rngCitations.Font.Bold = 1;

         }
</code>```

But, only first match updating to Superscript. How do I change this code to apply styling to all the matches.

答:
To loop you can use the official example:
https://learn.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-loop-through-found-items-in-documents?view=vs-2019

```<code>rng.Find.ClearFormatting();
rng.Find.Forward = true;
rng.Find.Text = "find me";

rng.Find.Execute(
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing);

while (rng.Find.Found)
{
    intFound++;
    rng.Find.Execute(
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);
}
</code>```

In your case change if with while

```<code>while (rngCitations.Find.Execute())
{
      rngCitations.Font.Superscript = 1;
      rngCitations.Font.Bold = 1;
}
</code>```

Body:
I have written code to find citations in the word file and trying to make all the citations superscript.

Word.Range rngCitations = doc.Content;
        rngCitations.Find.MatchWildcards = true;
        rngCitations.Find.Text = @"(\[[0-9]{1,}[,0-9]*\])";
        if (rngCitations.Find.Execute())
        {
            rngCitations.Font.Superscript = 1;
            rngCitations.Font.Bold = 1;

         }

But, only first match updating to Superscript. How do I change this code to apply styling to all the matches.

Body:
To loop you can use the official example:
https://learn.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-loop-through-found-items-in-documents?view=vs-2019

rng.Find.ClearFormatting();
rng.Find.Forward = true;
rng.Find.Text = "find me";

rng.Find.Execute(
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, ref missing);

while (rng.Find.Found)
{
    intFound++;
    rng.Find.Execute(
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing);
}

In your case change if with while

while (rngCitations.Find.Execute())
{
      rngCitations.Font.Superscript = 1;
      rngCitations.Font.Bold = 1;
}


问:
The best way to CSS the WP widget to keep style under any theme
I'm going to make WP widget plugin and want to make it theme independent.

What I mean about this is the fact that I need this widget to keep style set in its CSS regardless of theme used. I'm worrying that theme will overwrite its style.

What's the best CSS technique to do this ? Should I use style based on widget ID(#) or its  Class(.)  ?

答:
when the wp_head() function is fired, use that to include a stylesheet to your css file..

```<code>function wp_mywidget_css() {

    $siteurl = get_option('siteurl');
    $url = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/styles.css';

    echo "\n\n<!-- your plugin css styles -->\n";
    echo "<link rel='stylesheet' type='text/css' href='$url'>\n";
    echo "<!-- /your plugin css styles -->\n\n";
}
add_action('wp_head', 'wp_mywidget_css');
</code>```

place a file called 'styles.css' your plugin folder, which would include the code from the post above, this should stop any theme messing with your styles, just name your widget styles something unique...

ContentLicense: CC BY-SA 3.0

Body:
when the wp_head() function is fired, use that to include a stylesheet to your css file..

function wp_mywidget_css() {

    $siteurl = get_option('siteurl');
    $url = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/styles.css';

    echo "\n\n<!-- your plugin css styles -->\n";
    echo "<link rel='stylesheet' type='text/css' href='$url'>\n";
    echo "<!-- /your plugin css styles -->\n\n";
}
add_action('wp_head', 'wp_mywidget_css');

place a file called 'styles.css' your plugin folder, which would include the code from the post above, this should stop any theme messing with your styles, just name your widget styles something unique...


问:
Could not find fragment.jar (androidx.fragment:fragment:1.0.0)
When I try to compile the project I get this error:

Could not find fragment.jar (androidx.fragment:fragment:1.0.0).

what is the problem?

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.example.apps"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

//        externalNativeBuild {
//            cmake {
//                cppFlags ""
//            }
//        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
//    externalNativeBuild {
//        cmake {
//            path "src/main/cpp/CMakeLists.txt"
//            version "3.10.2"
//        }
//    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'android.arch.persistence.room:runtime:1.1.1'
    annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
    kapt "android.arch.persistence.room:compiler:1.1.1"
    implementation 'com.google.android.material:material:1.2.0-alpha04'

    implementation 'com.google.dagger:dagger-android:2.17'
    implementation 'com.google.dagger:dagger-android-support:2.17'
    kapt 'com.google.dagger:dagger-android-processor:2.17'

    /* Dagger2 - default dependency */
    kapt 'com.google.dagger:dagger-compiler:2.17'
}

</code>```

build errors:

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:38)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:kapt'.
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.rethrowFailure(DefaultConfiguration.java:1195)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.access$2100(DefaultConfiguration.java:138)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getFiles(DefaultConfiguration.java:1170)
    at org.gradle.api.internal.file.AbstractFileCollection.iterator(AbstractFileCollection.java:72)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.iterator(DefaultConfiguration.java:467)
    at org.gradle.api.internal.file.CompositeFileCollection.iterator(CompositeFileCollection.java:64)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt$withWrappedKaptOptions$1.apply(subpluginUtils.kt:100)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt$withWrappedKaptOptions$1.apply(subpluginUtils.kt)
    at java.util.HashMap.compute(HashMap.java:1197)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt.withWrappedKaptOptions(subpluginUtils.kt:56)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt.withWrappedKaptOptions$default(subpluginUtils.kt:51)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask.setupCompilerArgs(KaptGenerateStubsTask.kt:85)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask.setupCompilerArgs(KaptGenerateStubsTask.kt:36)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware$DefaultImpls.setupCompilerArgs$default(CompilerArgumentAware.kt:40)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareKt.prepareCompilerArguments(CompilerArgumentAware.kt:44)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareKt.prepareCompilerArguments$default(CompilerArgumentAware.kt:43)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware$DefaultImpls.getFilteredArgumentsMap(CompilerArgumentAware.kt:37)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareWithInput$DefaultImpls.getFilteredArgumentsMap(CompilerArgumentAware.kt:61)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompileTool.getFilteredArgumentsMap(Tasks.kt:52)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask_Decorated.getFilteredArgumentsMap(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue$1$1.create(AbstractNestedRuntimeBeanNode.java:75)
    at org.gradle.util.SingleMessageLogger.whileDisabled(SingleMessageLogger.java:341)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue$1.get(AbstractNestedRuntimeBeanNode.java:72)
    at com.google.common.base.Suppliers$NonSerializableMemoizingSupplier.get(Suppliers.java:167)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue.call(AbstractNestedRuntimeBeanNode.java:119)
    at org.gradle.api.internal.tasks.properties.AbstractValidatingProperty.validate(AbstractValidatingProperty.java:37)
    at org.gradle.api.internal.tasks.properties.DefaultTaskProperties.validate(DefaultTaskProperties.java:184)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    ... 27 more
Caused by: org.gradle.internal.resolve.ArtifactNotFoundException: Could not find fragment.jar (androidx.fragment:fragment:1.0.0).
Searched in the following locations:
    https://dl.google.com/dl/android/maven2/androidx/fragment/fragment/1.0.0/fragment-1.0.0.jar
    at org.gradle.internal.resolve.result.DefaultBuildableArtifactResolveResult.notFound(DefaultBuildableArtifactResolveResult.java:27)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$LocateInCacheRepositoryAccess.resolveArtifactFromCache(CachingModuleComponentRepository.java:335)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$LocateInCacheRepositoryAccess.resolveArtifact(CachingModuleComponentRepository.java:290)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.lambda$resolveArtifact$15(ErrorHandlingModuleComponentRepository.java:185)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.tryResolveAndMaybeBlacklist(ErrorHandlingModuleComponentRepository.java:241)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.performOperationWithRetries(ErrorHandlingModuleComponentRepository.java:207)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.resolveArtifact(ErrorHandlingModuleComponentRepository.java:183)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainArtifactResolver.resolveArtifact(RepositoryChainArtifactResolver.java:98)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.DefaultArtifactSet$LazyArtifactSource.create(DefaultArtifactSet.java:183)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.DefaultArtifactSet$LazyArtifactSource.create(DefaultArtifactSet.java:170)
    at org.gradle.api.internal.artifacts.DefaultResolvedArtifact.getFile(DefaultResolvedArtifact.java:173)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$InitialTransformationNode$1.transform(TransformationNode.java:150)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$ArtifactTransformationStepBuildOperation.call(TransformationNode.java:229)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$ArtifactTransformationStepBuildOperation.call(TransformationNode.java:212)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$InitialTransformationNode.execute(TransformationNode.java:145)
    at org.gradle.api.internal.artifacts.transform.TransformationNodeExecutor.execute(TransformationNodeExecutor.java:37)
    ... 15 more

</code>```

答:
I have copied your Gradle update the buildToolsVersion to "29.0.3" and check with my environment. It is working fine and build successfully.

your Gradle file should look like

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.daggerdemo"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

//        externalNativeBuild {
//            cmake {
//                cppFlags ""
//            }
//        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
//    externalNativeBuild {
//        cmake {
//            path "src/main/cpp/CMakeLists.txt"
//            version "3.10.2"
//        }
//    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'android.arch.persistence.room:runtime:1.1.1'
    annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
    kapt "android.arch.persistence.room:compiler:1.1.1"
    implementation 'com.google.android.material:material:1.2.0-alpha04'

    implementation 'com.google.dagger:dagger-android:2.17'
    implementation 'com.google.dagger:dagger-android-support:2.17'
    kapt 'com.google.dagger:dagger-android-processor:2.17'

    /* Dagger2 - default dependency */
    kapt 'com.google.dagger:dagger-compiler:2.17'
}
</code>```

and make sure your project-level Gradle works file and SDK components are updated.

here is my project level Gradle file:

```<code>buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        jcenter()
        google()

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

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

allprojects {
    repositories {
        jcenter()
        google()

    }
}

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

Body:
When I try to compile the project I get this error:

Could not find fragment.jar (androidx.fragment:fragment:1.0.0).

what is the problem?

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.example.apps"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

//        externalNativeBuild {
//            cmake {
//                cppFlags ""
//            }
//        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
//    externalNativeBuild {
//        cmake {
//            path "src/main/cpp/CMakeLists.txt"
//            version "3.10.2"
//        }
//    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'android.arch.persistence.room:runtime:1.1.1'
    annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
    kapt "android.arch.persistence.room:compiler:1.1.1"
    implementation 'com.google.android.material:material:1.2.0-alpha04'

    implementation 'com.google.dagger:dagger-android:2.17'
    implementation 'com.google.dagger:dagger-android-support:2.17'
    kapt 'com.google.dagger:dagger-android-processor:2.17'

    /* Dagger2 - default dependency */
    kapt 'com.google.dagger:dagger-compiler:2.17'
}

build errors:

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:38)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:kapt'.
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.rethrowFailure(DefaultConfiguration.java:1195)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.access$2100(DefaultConfiguration.java:138)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getFiles(DefaultConfiguration.java:1170)
    at org.gradle.api.internal.file.AbstractFileCollection.iterator(AbstractFileCollection.java:72)
    at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.iterator(DefaultConfiguration.java:467)
    at org.gradle.api.internal.file.CompositeFileCollection.iterator(CompositeFileCollection.java:64)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt$withWrappedKaptOptions$1.apply(subpluginUtils.kt:100)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt$withWrappedKaptOptions$1.apply(subpluginUtils.kt)
    at java.util.HashMap.compute(HashMap.java:1197)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt.withWrappedKaptOptions(subpluginUtils.kt:56)
    at org.jetbrains.kotlin.gradle.internal.SubpluginUtilsKt.withWrappedKaptOptions$default(subpluginUtils.kt:51)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask.setupCompilerArgs(KaptGenerateStubsTask.kt:85)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask.setupCompilerArgs(KaptGenerateStubsTask.kt:36)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware$DefaultImpls.setupCompilerArgs$default(CompilerArgumentAware.kt:40)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareKt.prepareCompilerArguments(CompilerArgumentAware.kt:44)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareKt.prepareCompilerArguments$default(CompilerArgumentAware.kt:43)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAware$DefaultImpls.getFilteredArgumentsMap(CompilerArgumentAware.kt:37)
    at org.jetbrains.kotlin.gradle.internal.CompilerArgumentAwareWithInput$DefaultImpls.getFilteredArgumentsMap(CompilerArgumentAware.kt:61)
    at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompileTool.getFilteredArgumentsMap(Tasks.kt:52)
    at org.jetbrains.kotlin.gradle.internal.KaptGenerateStubsTask_Decorated.getFilteredArgumentsMap(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue$1$1.create(AbstractNestedRuntimeBeanNode.java:75)
    at org.gradle.util.SingleMessageLogger.whileDisabled(SingleMessageLogger.java:341)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue$1.get(AbstractNestedRuntimeBeanNode.java:72)
    at com.google.common.base.Suppliers$NonSerializableMemoizingSupplier.get(Suppliers.java:167)
    at org.gradle.api.internal.tasks.properties.bean.AbstractNestedRuntimeBeanNode$BeanPropertyValue.call(AbstractNestedRuntimeBeanNode.java:119)
    at org.gradle.api.internal.tasks.properties.AbstractValidatingProperty.validate(AbstractValidatingProperty.java:37)
    at org.gradle.api.internal.tasks.properties.DefaultTaskProperties.validate(DefaultTaskProperties.java:184)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    ... 27 more
Caused by: org.gradle.internal.resolve.ArtifactNotFoundException: Could not find fragment.jar (androidx.fragment:fragment:1.0.0).
Searched in the following locations:
    https://dl.google.com/dl/android/maven2/androidx/fragment/fragment/1.0.0/fragment-1.0.0.jar
    at org.gradle.internal.resolve.result.DefaultBuildableArtifactResolveResult.notFound(DefaultBuildableArtifactResolveResult.java:27)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$LocateInCacheRepositoryAccess.resolveArtifactFromCache(CachingModuleComponentRepository.java:335)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$LocateInCacheRepositoryAccess.resolveArtifact(CachingModuleComponentRepository.java:290)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.lambda$resolveArtifact$15(ErrorHandlingModuleComponentRepository.java:185)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.tryResolveAndMaybeBlacklist(ErrorHandlingModuleComponentRepository.java:241)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.performOperationWithRetries(ErrorHandlingModuleComponentRepository.java:207)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.resolveArtifact(ErrorHandlingModuleComponentRepository.java:183)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainArtifactResolver.resolveArtifact(RepositoryChainArtifactResolver.java:98)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.DefaultArtifactSet$LazyArtifactSource.create(DefaultArtifactSet.java:183)
    at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.DefaultArtifactSet$LazyArtifactSource.create(DefaultArtifactSet.java:170)
    at org.gradle.api.internal.artifacts.DefaultResolvedArtifact.getFile(DefaultResolvedArtifact.java:173)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$InitialTransformationNode$1.transform(TransformationNode.java:150)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$ArtifactTransformationStepBuildOperation.call(TransformationNode.java:229)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$ArtifactTransformationStepBuildOperation.call(TransformationNode.java:212)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.artifacts.transform.TransformationNode$InitialTransformationNode.execute(TransformationNode.java:145)
    at org.gradle.api.internal.artifacts.transform.TransformationNodeExecutor.execute(TransformationNodeExecutor.java:37)
    ... 15 more

Body:
I have copied your Gradle update the buildToolsVersion to "29.0.3" and check with my environment. It is working fine and build successfully.

your Gradle file should look like

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.daggerdemo"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

//        externalNativeBuild {
//            cmake {
//                cppFlags ""
//            }
//        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
//    externalNativeBuild {
//        cmake {
//            path "src/main/cpp/CMakeLists.txt"
//            version "3.10.2"
//        }
//    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'android.arch.persistence.room:runtime:1.1.1'
    annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
    kapt "android.arch.persistence.room:compiler:1.1.1"
    implementation 'com.google.android.material:material:1.2.0-alpha04'

    implementation 'com.google.dagger:dagger-android:2.17'
    implementation 'com.google.dagger:dagger-android-support:2.17'
    kapt 'com.google.dagger:dagger-android-processor:2.17'

    /* Dagger2 - default dependency */
    kapt 'com.google.dagger:dagger-compiler:2.17'
}

and make sure your project-level Gradle works file and SDK components are updated.

here is my project level Gradle file:

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        jcenter()
        google()

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

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

allprojects {
    repositories {
        jcenter()
        google()

    }
}

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


问:
A pattern to pause/resume an async task?
I have a mostly IO-bound continuous task (a background spellchecker talking to a spellcheck server). Sometimes, this task needs to be put on hold and resumed later, depending on the user activity.

While suspend/resume is essentially what async/await does, I've found little information on how to implement the actual pause/play logic for an asynchronous method. Is there a recommended pattern for this?

I've also looked at using Stephen Toub's AsyncManualResetEvent for this, but thought it might be an overkill.

答:
All the other answers seem either complicated or missing the mark when it comes to async/await programming by holding the thread which is CPU expensive and can lead to deadlocks.  After lots of trial, error and many deadlocks, this finally worked for my high usage test. </p>

```<code>var isWaiting = true;
while (isWaiting)
{
    try
    {
        //A long delay is key here to prevent the task system from holding the thread.
        //The cancellation token allows the work to resume with a notification
        //from the CancellationTokenSource.
        await Task.Delay(10000, cancellationToken);
    }
    catch (TaskCanceledException)
    {
        //Catch the cancellation and it turns into continuation
        isWaiting = false;
    }
}
</code>```

Body:
All the other answers seem either complicated or missing the mark when it comes to async/await programming by holding the thread which is CPU expensive and can lead to deadlocks.  After lots of trial, error and many deadlocks, this finally worked for my high usage test.

var isWaiting = true;
while (isWaiting)
{
    try
    {
        //A long delay is key here to prevent the task system from holding the thread.
        //The cancellation token allows the work to resume with a notification
        //from the CancellationTokenSource.
        await Task.Delay(10000, cancellationToken);
    }
    catch (TaskCanceledException)
    {
        //Catch the cancellation and it turns into continuation
        isWaiting = false;
    }
}


问:
Windows Mobile - Disable USB (Compact Framework - C#)
I need to disable USB on Windows Mobile. How to disable USB on Windows Mobile using Compact Framework 2.0 (C#)? I am using OpenNETCF too. If it has some class to disable USB, I can use it too.</p>

答:
A bit of advice, you have to implement both operations to lock / unlock the usb device. Because if you can't unlock it you must perform a clean boot.

You should provision the device with this specific policies

```<code><!-- DenyRAPI.xml !-->
<wap-provisioningdoc>
    <characteristic type="SecurityPolicy">
        <parm name="4097" value="0"/>
    </characteristic>
</wap-provisioningdoc>

<!-- AllowRAPI.xml !-->
<wap-provisioningdoc>
    <characteristic type="SecurityPolicy">
        <parm name="4097" value="2"/>
    </characteristic>
</wap-provisioningdoc>
</code>```

I provide a link to the original post in which is suggested that you create the cabs.
Original Post

I have used another approach to read the XML configuration and then using the following method I execute the provisioning

```<code>Microsoft.WindowsMobile.Configuration.ConfigurationManager.ProcessConfiguration(XmlDocument,boolean);
</code>```

Another option is to use builds the cabs and install them by using wceload.exe

Body:
A bit of advice, you have to implement both operations to lock / unlock the usb device. Because if you can't unlock it you must perform a clean boot.

You should provision the device with this specific policies

<!-- DenyRAPI.xml !-->
<wap-provisioningdoc>
    <characteristic type="SecurityPolicy">
        <parm name="4097" value="0"/>
    </characteristic>
</wap-provisioningdoc>

<!-- AllowRAPI.xml !-->
<wap-provisioningdoc>
    <characteristic type="SecurityPolicy">
        <parm name="4097" value="2"/>
    </characteristic>
</wap-provisioningdoc>

I provide a link to the original post in which is suggested that you create the cabs.
Original Post

I have used another approach to read the XML configuration and then using the following method I execute the provisioning

Microsoft.WindowsMobile.Configuration.ConfigurationManager.ProcessConfiguration(XmlDocument,boolean);

Another option is to use builds the cabs and install them by using wceload.exe


答:
There are several ways. The appropriate here (IMO) is to use

```<code>print("items are: " + ', '.join(items[:3]))
</code>```

Which (depending on your python version) can be simplified to:

```<code>print(f'items are: {", ".join(items[:3])}')
</code>```

or without the comma

Another way is to tell the print to not print linebreaks:

```<code>for item in items[:3]:
    print(item, end='')
</code>```

Title: How to remove the square brackets in output of the list?

Body:
There are several ways. The appropriate here (IMO) is to use

print("items are: " + ', '.join(items[:3]))

Which (depending on your python version) can be simplified to:

print(f'items are: {", ".join(items[:3])}')

or without the comma

Another way is to tell the print to not print linebreaks:

for item in items[:3]:
    print(item, end='')


问:
Info.plist Utility Error: "Info.plist couldn't be opened because there is no such file"
I'm running into what seems to be common error, in that Xcode can't seem to find my 'Info.plist' file.

I've checked the answers to these two StackOverflow questions (Could not read from Info.plist and Objective C/Xcode error: The file “Info.plist” couldn’t be opened because there is no such file)...I am using a relative path, and the plist file is in the correct absolute location. The type and location are correct as shown in the image below:

My biggest concern is that this is now happening on multiple projects, including one I ran successfully just a few hours ago! Does anyone know how to solve this???

EDIT I've also tried reinstalling XCODE and replacing the plist file. Xcode still can't find 'info.plist'.

NOTE I wanted to add that this was for Xcode 6.2.X (I can't remember which version number exactly, but it was pre-Xcode 6.3.X).

答:
if you change info.plist location from project to a folder inside the app then you will get this error i was facing same error and error resolved by this way

```<code> Select your app and from Targets yourApp > Build Settings > Packaging >
 Info.Plist and change that path
</code>```

Body:
if you change info.plist location from project to a folder inside the app then you will get this error i was facing same error and error resolved by this way

 Select your app and from Targets yourApp > Build Settings > Packaging >
 Info.Plist and change that path


问:
Zabbix frontend Error connecting to database
I am having a problem at zabbix web interface, it won't connect to the database as I receive this error: Error connecting to database.
Here are two screenshots from both files:
/etc/zabbix/zabbix_server.conf

/usr/share/zabbix/conf/zabbix.conf.php.example

Any help?
Thanks!

答: In your case, the password should be in quotation marks: DBPassword="zabbix"


问:
Queue creation for MDBs in Wildfly
I have such MDB in my application

```<code>@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "java:jboss/exported/jms/queue/TestQueue"),
        @ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "source = 'client'")})
public class JmsReceiver implements MessageListener {

    @Override
    public void onMessage(Message message) {
        // .......
    }

}
</code>```

The question is the way of queue creation. I remember that with Wildfly 16 it was enough simply to deploy application with MDB and the queue was available remotely with JNDI name jms/queue/TestQueue but with Wildfly 18 it starts to work only after I create the queue with proper name in server console.

How exactly the queue creation works in Wildfly and ActiveMQ?

答: I would recommend that you add a jms destination definition xml file to your deployment. See https://docs.jboss.org/author/display/WFLY10/Messaging+configuration for an example</p>

Title: Queue creation for MDBs in Wildfly

Body:
I have such MDB in my application

@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "java:jboss/exported/jms/queue/TestQueue"),
        @ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "source = 'client'")})
public class JmsReceiver implements MessageListener {

    @Override
    public void onMessage(Message message) {
        // .......
    }

}

The question is the way of queue creation. I remember that with Wildfly 16 it was enough simply to deploy application with MDB and the queue was available remotely with JNDI name jms/queue/TestQueue but with Wildfly 18 it starts to work only after I create the queue with proper name in server console.

How exactly the queue creation works in Wildfly and ActiveMQ?


问:
Angular production build can't load - Loading module was blocked because of a disallowed MIME type (“text/html”)
I built my application running ng build --configuration=production and uploaded it (manually via FTP) to a server (I tried two different ones). Accessing the root like myurl.com works fine, but whenever I want to directly access a subpage, for example, myurl.com/subpage the page is blank and I get the following error:
Loading module from “https://myurl.com/runtime-es2015.js” was blocked because of a disallowed MIME type (“text/html”). Same error for also for polyfills-es2015.js, main-es2015.js

If I access the root and navigate to the subpage everything works fine.

Until now I tried to:

set <base href="."> in index.html

set "target": "es5" in tsconfig.json

manually change the type of the scripts from type="module" to type="text/javascript"
like here:

答:
I had a similar problem with an Angular app I deployed to https://host.my/app.  As mentioned in other SO answer changing the

<base href="/">

to

<base href="./">

solved it for me.  Just setting it to <base href="."> did not.

HTH


问:
Rust Gtk set GtkImage from pixbuf using glade file
I'm trying to load an image from a scaled pixbuf to an existing GtkImage widget from Glade with Rust. I've read all the Gtk-rs documentations regarding this topic, and it should work based on that. However there is always a problem when trying to load from pixbuf. Here's my code to reproduce the error:

```<code>extern crate gtk;
extern crate gio;
extern crate gdk_pixbuf;

use gtk::prelude::*;
use gio::prelude::*;

use gtk::{Builder, MessageDialog, Window, ButtonsType, DialogFlags, MessageType, ResponseType, Image, ImageExt};
use gdk_pixbuf::{Pixbuf};

use std::env::args;

fn build_ui(application: &gtk::Application) {
    let glade_src = include_str!("test.glade");
    let builder = Builder::new_from_string(glade_src);

    let window: Window = builder.get_object("main").expect("Couldn't get main");
    let img2: Image = builder.get_object("img2").expect("Cangt get img2");
    window.set_application(Some(application));
    window.set_title("HLearn - 2020 - Tatyó");

    window.connect_delete_event(move |_, _| {
        println!("Hey");
        let window2: Window = builder.get_object("main").expect("Cant get 2nd");
        let dialog = MessageDialog::new(Some(&window2),
            DialogFlags::MODAL,
            MessageType::Question,
            ButtonsType::YesNo,
            "Are you sure to exit");
        dialog.set_title("Attention!");
        dialog.set_position(gtk::WindowPosition::__Unknown(0));
        let res = dialog.run();
        if res == ResponseType::Yes {
            println!("Yes");
            dialog.destroy();
            Inhibit(false)
        } else {
            println!("No");
            dialog.destroy();
            Inhibit(true)
        }
    });

    let builder2 = Builder::new_from_string(glade_src);
    let window3: Window = builder2.get_object("main").expect("Cant get 3rd");
    let (sx, sy) = window3.get_size();
    let pixbuf = Pixbuf::new_from_file_at_scale(
        "/home/daniel/RUST/test/src/test.gif",
        600,
        700,
        false);
    img2.set_from_pixbuf(Some(&pixbuf));

    window.show_all();
}

fn main() {
    let application = gtk::Application::new(
        Some("com.github.swanux.hlearn"),
        Default::default(),
    )
    .expect("Initialization failed...");

    application.connect_activate(|app| {
        build_ui(app);
    });

    application.run(&args().collect::<Vec<_>>());
}
</code>```

And here's the glade file test.glade

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

<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="main">
    <property name="can_focus">False</property>
    <child>
      <placeholder/>
    </child>
    <child>
      <object class="GtkImage" id="img2">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <property name="hexpand">True</property>
        <property name="vexpand">True</property>
        <property name="stock">gtk-missing-image</property>
      </object>
    </child>
  </object>
</interface>
```

When I try to load image from pixbuf, I always get this error message: expected struct gdk_pixbuf::Pixbuf, found enum std::result::Result. I'm using Linux with the newest Rust installed.

答:
Here's the solution. Change this part :

```<code>let pixbuf = Pixbuf::new_from_file_at_scale(
        "/home/daniel/RUST/test/src/test.gif",
        600,
        700,
        false);
</code>```

To

```<code>let pixbuf = Pixbuf::new_from_file_at_scale(
        "/home/daniel/RUST/test/src/test.gif",
        600,
        700,
        false).expect("Can't get pixbuf");
</code>```

Body:
I'm trying to load an image from a scaled pixbuf to an existing GtkImage widget from Glade with Rust. I've read all the Gtk-rs documentations regarding this topic, and it should work based on that. However there is always a problem when trying to load from pixbuf. Here's my code to reproduce the error:

extern crate gtk;
extern crate gio;
extern crate gdk_pixbuf;

use gtk::prelude::*;
use gio::prelude::*;

use gtk::{Builder, MessageDialog, Window, ButtonsType, DialogFlags, MessageType, ResponseType, Image, ImageExt};
use gdk_pixbuf::{Pixbuf};

use std::env::args;

fn build_ui(application: &gtk::Application) {
    let glade_src = include_str!("test.glade");
    let builder = Builder::new_from_string(glade_src);

    let window: Window = builder.get_object("main").expect("Couldn't get main");
    let img2: Image = builder.get_object("img2").expect("Cangt get img2");
    window.set_application(Some(application));
    window.set_title("HLearn - 2020 - Tatyó");

    window.connect_delete_event(move |_, _| {
        println!("Hey");
        let window2: Window = builder.get_object("main").expect("Cant get 2nd");
        let dialog = MessageDialog::new(Some(&window2),
            DialogFlags::MODAL,
            MessageType::Question,
            ButtonsType::YesNo,
            "Are you sure to exit");
        dialog.set_title("Attention!");
        dialog.set_position(gtk::WindowPosition::__Unknown(0));
        let res = dialog.run();
        if res == ResponseType::Yes {
            println!("Yes");
            dialog.destroy();
            Inhibit(false)
        } else {
            println!("No");
            dialog.destroy();
            Inhibit(true)
        }
    });

    let builder2 = Builder::new_from_string(glade_src);
    let window3: Window = builder2.get_object("main").expect("Cant get 3rd");
    let (sx, sy) = window3.get_size();
    let pixbuf = Pixbuf::new_from_file_at_scale(
        "/home/daniel/RUST/test/src/test.gif",
        600,
        700,
        false);
    img2.set_from_pixbuf(Some(&pixbuf));

    window.show_all();
}

fn main() {
    let application = gtk::Application::new(
        Some("com.github.swanux.hlearn"),
        Default::default(),
    )
    .expect("Initialization failed...");

    application.connect_activate(|app| {
        build_ui(app);
    });

    application.run(&args().collect::<Vec<_>>());
}

And here's the glade file test.glade

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

<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="main">
    <property name="can_focus">False</property>
    <child>
      <placeholder/>
    </child>
    <child>
      <object class="GtkImage" id="img2">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <property name="hexpand">True</property>
        <property name="vexpand">True</property>
        <property name="stock">gtk-missing-image</property>
      </object>
    </child>
  </object>
</interface>

When I try to load image from pixbuf, I always get this error message: expected struct gdk_pixbuf::Pixbuf, found enum std::result::Result. I'm using Linux with the newest Rust installed.

Body:
Here's the solution. Change this part :

let pixbuf = Pixbuf::new_from_file_at_scale(
        "/home/daniel/RUST/test/src/test.gif",
        600,
        700,
        false);

To

let pixbuf = Pixbuf::new_from_file_at_scale(
        "/home/daniel/RUST/test/src/test.gif",
        600,
        700,
        false).expect("Can't get pixbuf");


问:
How to attach ACR from different Subscription to AKS?
can anyone know how to attach ACR from different subscriptions to AKS in Azure?

I am looking for any info about that, alas I've found only a topic https://github.com/Azure/AKS/issues/243 where someone said that this is fixed but unfortunately there's no info how to achieve that?

答: in this case the answer was to provide the proper input (typo in the ACR ID).</p>


问:
Oracle GoldenGate adapter for Kafka - JSON message contents
In My golden gate big data for kafka. when i try to update the record  am getting only updated column and primary key column in after part in json file

```<code>{"table":"MYSCHEMATOPIC.PASSPORTS","op_type":"U","op_ts":"2018-03-17 13:57:50.000000","current_ts":"2018-03-17T13:57:53.901000","pos":"00000000030000010627","before":{"PASSPORT_ID":71541893,"PPS_ID":71541892,"PASSPORT_NO":"1234567","PASSPORT_NO_NUMERIC":241742,"PASSPORT_TYPE_ID":7,"ISSUE_DATE":null,"EXPIRY_DATE":"0060-12-21 00:00:00","ISSUE_PLACE_EN":"UN-DEFINED","ISSUE_PLACE_AR":"?????? ????????","ISSUE_COUNTRY_ID":203,"ISSUE_GOV_COUNTRY_ID":203,"IS_ACTIVE":1,"PREV_PASSPORT_ID":null,"CREATED_DATE":"2003-06-08 00:00:00","CREATED_BY":-9,"MODIFIED_DATE":null,"MODIFIED_BY":null,"IS_SETTLED":0,"MAIN_PASSPORT_PERSON_INFO_ID":34834317,"NATIONALITY_ID":590},
"after":{"PASSPORT_ID":71541893,"NATIONALITY_ID":589}}
</code>```

In After part  in my json out i want to show all columns

How to get all columns in after part?

```<code>gg.handlerlist = kafkahandler
gg.handler.kafkahandler.type=kafka gg.handler.kafkahandler.KafkaProducerConfigFile=custom_kafka_producer.properties
    #The following resolves the topic name using the short table name
    gg.handler.kafkahandler.topicMappingTemplate=passports

    gg.handler.kafkahandler.format=json
    gg.handler.kafkahandler.BlockingSend =false
    gg.handler.kafkahandler.includeTokens=false
    gg.handler.kafkahandler.mode=op
    #gg.handler.kafkahandler.format.insertOpKey=I
    #gg.handler.kafkahandler.format.updateOpKey=U
    #gg.handler.kafkahandler.format.deleteOpKey=D
    #gg.handler.kafkahandler.format.truncateOpKey=T
    #gg.handler.kafkahandler.format.includeColumnNames=TRUE
    goldengate.userexit.timestamp=utc
    goldengate.userexit.writers=javawriter
    javawriter.stats.display=TRUE
    javawriter.stats.full=TRUE
    gg.log=log4j
    gg.log.level=info
  gg.report.time=30sec
</code>```

答:
Hi This issue is fixed by added below change in golden gate side

ADD TRANDATA table_name ALLCOLS

Body:
In My golden gate big data for kafka. when i try to update the record  am getting only updated column and primary key column in after part in json file

{"table":"MYSCHEMATOPIC.PASSPORTS","op_type":"U","op_ts":"2018-03-17 13:57:50.000000","current_ts":"2018-03-17T13:57:53.901000","pos":"00000000030000010627","before":{"PASSPORT_ID":71541893,"PPS_ID":71541892,"PASSPORT_NO":"1234567","PASSPORT_NO_NUMERIC":241742,"PASSPORT_TYPE_ID":7,"ISSUE_DATE":null,"EXPIRY_DATE":"0060-12-21 00:00:00","ISSUE_PLACE_EN":"UN-DEFINED","ISSUE_PLACE_AR":"?????? ????????","ISSUE_COUNTRY_ID":203,"ISSUE_GOV_COUNTRY_ID":203,"IS_ACTIVE":1,"PREV_PASSPORT_ID":null,"CREATED_DATE":"2003-06-08 00:00:00","CREATED_BY":-9,"MODIFIED_DATE":null,"MODIFIED_BY":null,"IS_SETTLED":0,"MAIN_PASSPORT_PERSON_INFO_ID":34834317,"NATIONALITY_ID":590},
"after":{"PASSPORT_ID":71541893,"NATIONALITY_ID":589}}

In After part  in my json out i want to show all columns

How to get all columns in after part?

gg.handlerlist = kafkahandler
gg.handler.kafkahandler.type=kafka gg.handler.kafkahandler.KafkaProducerConfigFile=custom_kafka_producer.properties
    #The following resolves the topic name using the short table name
    gg.handler.kafkahandler.topicMappingTemplate=passports

    gg.handler.kafkahandler.format=json
    gg.handler.kafkahandler.BlockingSend =false
    gg.handler.kafkahandler.includeTokens=false
    gg.handler.kafkahandler.mode=op
    #gg.handler.kafkahandler.format.insertOpKey=I
    #gg.handler.kafkahandler.format.updateOpKey=U
    #gg.handler.kafkahandler.format.deleteOpKey=D
    #gg.handler.kafkahandler.format.truncateOpKey=T
    #gg.handler.kafkahandler.format.includeColumnNames=TRUE
    goldengate.userexit.timestamp=utc
    goldengate.userexit.writers=javawriter
    javawriter.stats.display=TRUE
    javawriter.stats.full=TRUE
    gg.log=log4j
    gg.log.level=info
  gg.report.time=30sec


问:
add horizontal limit line to time series plot in python
I want to add horizontal upper and lower limit line for Temparature timeseries plot. Lets say upper limit line at 30 and lower limit line at 10.

```<code>df3.plot(x="Date", y=["Temp.PM", "Temp.AM"],figsize=(20,8))
</code>```

答:
Here is some code to get started and experimenting:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

dates = pd.date_range('20190822', '20191020', freq='D')
df3 = pd.DataFrame({'Date': dates,
                    'Temp.AM': np.random.normal(22.5, 2, len(dates)),
                    'Temp.PM': np.random.normal(27.5, 2, len(dates))})
df3.plot(x='Date', y=['Temp.PM', 'Temp.AM'], color=['dodgerblue','coral'], figsize=(20, 8))

min_temp = df3['Temp.AM'].min()
max_temp = df3['Temp.PM'].max()
plt.axhline(min_temp, c='coral', ls='--')
plt.axhline(max_temp, c='dodgerblue', ls='--')
plt.text(df3['Date'][0], min_temp, f'\nMin: {min_temp:.1f}°C', ha='left', va='center', c='coral')
plt.text(df3['Date'][0], max_temp, f'Max: {max_temp:.1f}°C\n', ha='left', va='center', c='dodgerblue')
plt.show()
```

Body:
I want to add horizontal upper and lower limit line for Temparature timeseries plot. Lets say upper limit line at 30 and lower limit line at 10.

df3.plot(x="Date", y=["Temp.PM", "Temp.AM"],figsize=(20,8))


答: You can write print(item, end=" ") in your loop.


问:
How to understand Objective-C AppDelegate method application:didFInishLauchingWithOptions?
I am new in iOS development, I saw the function

```<code>-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
</code>```

As I know, to declare a function is

```<code>-/+(return type)function_name: (param type)param
</code>```

So what is the function name of the function mentioned above?

答: Here name of the function is application but its mostly called application didFinishLaunchingWithOptions. Its called first when the app is launched.</p>

Body:
I am new in iOS development, I saw the function

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

As I know, to declare a function is

-/+(return type)function_name: (param type)param

So what is the function name of the function mentioned above?


问:
Geofence PendingIntent is always getting as null
I have implemented geofencing in the application. But the issue is whenever I open the application the geofence is added again. Thus it immediately results in triggering an entry alert if we are within a geofencing area.

Current implementation - workflow:

User opens the App

A service called GeoFenceMakerService is started from the main activity.

GeoFenceMakerService invoke an API call and fetches the details of the places (Lat, Long, Place Id, Place Name, Radius, etc) from the server. There can be one or more places.

The place details (API result) will be saved to the local database.

If there are 1 or more places, then it builds the geofence object for each place (initializeGeoFence).

Build the geofencing request and create pending intent. This will be passed to the Geofencing client to add the geofence. (geofencingClient.addGeofences(getGeofencingRequest(), createGeoFencePendingIntent()))

Stop the GeoFenceMakerService after adding the geofences.

Issue:
The createGeoFencePendingIntent() is always creating new Pending intent and may trigger an entry alert if we are within a geofencing area whenever we open the application.

Similar solution found from stack overflow: Was to implement a check using Shared preferences for pending intent. You can see the full solution from here. But am not satisfied with this because, "it is better to check if the pending intent exists instead of writing in the sharedpreferences that we have added the geofences, because when we reboot the phone or change the location accuracy, they are removed and the pending intent does not exist anymore, but the sharedpreferences would not be updated" - (One already mentioned there as comment for the solution mentioned).

Current solution required:
Need to check whether the Geofence is already added or not and add geofence only if none exists.

I am attaching the entire GeoFenceMakerService code for reference.

```<code>package com.****.*****.services;

import android.Manifest;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.****.****.api.Api;
import com.****.****.api.ApiMethods;
import com.****.****.models.Place;
import com.****.****.models.response.PlacesListResponse;
import com.****.****.receiver.GeofenceBroadcastReceiver;
import com.****.****.utils.DatabaseManager;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingClient;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GeoFenceMakerService extends Service {

    public static final String TAG = "GeoFenceMakerService";
    private ArrayList<Place> places = null;
    private GeofencingClient geofencingClient = null;
    private ArrayList<Geofence> geofenceList = null;
    private PendingIntent geoFencePendingIntent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "GeoFenceMakerService Created");
        geofencingClient = LocationServices.getGeofencingClient(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //handleStart(intent, startId);
        Log.d(TAG, "Inside onStartCommand");
        getPlacesList();
        return START_NOT_STICKY;
    }

    private void getPlacesList() {
        Log.i(TAG, "getPlacesList: ");
        ApiMethods apiMethods;
        Call<PlacesListResponse> listResponseCall;
        apiMethods = Api.getInstance(this);
        listResponseCall = apiMethods.getAllPlacesList();
        Log.i(TAG, "Getting places list from API");
        listResponseCall.enqueue(new Callback<PlacesListResponse>() {
            @Override
            public void onResponse(Call<PlacesListResponse> call, Response<PlacesListResponse> response) {
                if (response.code() == Api.STATUS_200) {
                    handlePlacesList(response.body());
                } else {
                    Log.e(TAG, "Get places list api failed with code: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<PlacesListResponse> call, Throwable t) {
                Log.e(TAG, "Get places list api failed" + t.getLocalizedMessage());
            }
        });
    }

    private void handlePlacesList(PlacesListResponse placesListResponse) {
        Log.i(TAG, "handlePlacesList: ");
        DatabaseManager databaseManager = new DatabaseManager(this);

        if (placesListResponse != null) {

            Log.i(TAG, "Got places list response");
            places = placesListResponse.getPlaces();
            databaseManager.savePlacesToDatabase(places);
            if (!(places.size() == 0)) {
                initializeGeoFence();
                addGeoFence2();
            }
           /* initializeGeoFence();
            addGeoFence2();*/
        } else {

            Log.e(TAG, "Places list response is null");

        }
    }

    private void initializeGeoFence() {
        // Toast.makeText(this, "initializing geo fence", Toast.LENGTH_LONG).show();
        Log.i(TAG, "initializing geo fence");
        Geofence geofence;
        geofenceList = new ArrayList<>();
        for (Place place : places) {
            Log.i(TAG, "Adding geofence at " + place.getLatitude() + ", " + place.getLongitude());
            // @TODO Fetch and set the Geofence Radius dynamically
            geofence = new Geofence.Builder()
                    // Set the request ID of the geofence. This is a string to identify this
                    // geofence.
                    .setRequestId(place.getPlaceId() + "")
                    .setCircularRegion(
                            place.getLatitude(),
                            place.getLongitude(),
                            500f)
                    .setExpirationDuration(60 * 60 * 1000)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

            geofenceList.add(geofence);
        }
    }

    private void addGeoFence2() {
        Log.i(TAG, "addGeoFence2: ");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Make sure permission is granted before starting the service. NOTE: Requesting permission from Service is not allowed.
            return;
        }
        geofencingClient.addGeofences(getGeofencingRequest(), createGeoFencePendingIntent())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.i(TAG, "Geo fence added");
                        // Toast.makeText(HomeActivity.this, "Geo fence added", Toast.LENGTH_LONG).show();
                        GeoFenceMakerService.this.stopSelf();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "Geo fence add failed. ");
                        e.printStackTrace();
                        // Toast.makeText(HomeActivity.this, "Geo fence add failed", Toast.LENGTH_LONG).show();
                        GeoFenceMakerService.this.stopSelf();
                    }
                });
    }

    private GeofencingRequest getGeofencingRequest() {

        // Toast.makeText(this, "getGeofencingRequest", Toast.LENGTH_LONG).show();
        Log.i(TAG, "getGeofencingRequest");
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofences(geofenceList);
        return builder.build();
    }

    private PendingIntent createGeoFencePendingIntent() {
        Intent intent;

        Log.d(TAG, "createGeoFencePendingIntent");

        if (geoFencePendingIntent == null) {
            Log.i(TAG, "GeoFence pending intent is null. Creating new instance");

            intent = new Intent(this, GeofenceBroadcastReceiver.class);
            // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
            // calling addGeofences() and removeGeofences().
            geoFencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.
                    FLAG_UPDATE_CURRENT);

        }

        return geoFencePendingIntent;
    }

}
</code>```

答:
An Intent sent from Location Services can trigger various actions in
  your app, but you should not have it start an activity or fragment,
  because components should only become visible in response to a user
  action. In many cases, a BroadcastReceiver is a good way to handle a
  geofence transition. A BroadcastReceiver gets updates when an event
  occurs, such as a transition into or out of a geofence, and can start
  long-running background work.

check here

```<code>private PendingIntent getGeofencePendingIntent() {
    if (geofencePendingIntent != null) {
        return geofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);

    geofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return geofencePendingIntent;
}
</code>```

Body:
I have implemented geofencing in the application. But the issue is whenever I open the application the geofence is added again. Thus it immediately results in triggering an entry alert if we are within a geofencing area.

Current implementation - workflow:

User opens the App

A service called GeoFenceMakerService is started from the main activity.

GeoFenceMakerService invoke an API call and fetches the details of the places (Lat, Long, Place Id, Place Name, Radius, etc) from the server. There can be one or more places.

The place details (API result) will be saved to the local database.

If there are 1 or more places, then it builds the geofence object for each place (initializeGeoFence).

Build the geofencing request and create pending intent. This will be passed to the Geofencing client to add the geofence. (geofencingClient.addGeofences(getGeofencingRequest(), createGeoFencePendingIntent()))

Stop the GeoFenceMakerService after adding the geofences.

Issue:
The createGeoFencePendingIntent() is always creating new Pending intent and may trigger an entry alert if we are within a geofencing area whenever we open the application.

Similar solution found from stack overflow: Was to implement a check using Shared preferences for pending intent. You can see the full solution from here. But am not satisfied with this because, "it is better to check if the pending intent exists instead of writing in the sharedpreferences that we have added the geofences, because when we reboot the phone or change the location accuracy, they are removed and the pending intent does not exist anymore, but the sharedpreferences would not be updated" - (One already mentioned there as comment for the solution mentioned).

Current solution required:
Need to check whether the Geofence is already added or not and add geofence only if none exists.

I am attaching the entire GeoFenceMakerService code for reference.

package com.****.*****.services;

import android.Manifest;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.****.****.api.Api;
import com.****.****.api.ApiMethods;
import com.****.****.models.Place;
import com.****.****.models.response.PlacesListResponse;
import com.****.****.receiver.GeofenceBroadcastReceiver;
import com.****.****.utils.DatabaseManager;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingClient;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GeoFenceMakerService extends Service {

    public static final String TAG = "GeoFenceMakerService";
    private ArrayList<Place> places = null;
    private GeofencingClient geofencingClient = null;
    private ArrayList<Geofence> geofenceList = null;
    private PendingIntent geoFencePendingIntent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "GeoFenceMakerService Created");
        geofencingClient = LocationServices.getGeofencingClient(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //handleStart(intent, startId);
        Log.d(TAG, "Inside onStartCommand");
        getPlacesList();
        return START_NOT_STICKY;
    }

    private void getPlacesList() {
        Log.i(TAG, "getPlacesList: ");
        ApiMethods apiMethods;
        Call<PlacesListResponse> listResponseCall;
        apiMethods = Api.getInstance(this);
        listResponseCall = apiMethods.getAllPlacesList();
        Log.i(TAG, "Getting places list from API");
        listResponseCall.enqueue(new Callback<PlacesListResponse>() {
            @Override
            public void onResponse(Call<PlacesListResponse> call, Response<PlacesListResponse> response) {
                if (response.code() == Api.STATUS_200) {
                    handlePlacesList(response.body());
                } else {
                    Log.e(TAG, "Get places list api failed with code: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<PlacesListResponse> call, Throwable t) {
                Log.e(TAG, "Get places list api failed" + t.getLocalizedMessage());
            }
        });
    }

    private void handlePlacesList(PlacesListResponse placesListResponse) {
        Log.i(TAG, "handlePlacesList: ");
        DatabaseManager databaseManager = new DatabaseManager(this);

        if (placesListResponse != null) {

            Log.i(TAG, "Got places list response");
            places = placesListResponse.getPlaces();
            databaseManager.savePlacesToDatabase(places);
            if (!(places.size() == 0)) {
                initializeGeoFence();
                addGeoFence2();
            }
           /* initializeGeoFence();
            addGeoFence2();*/
        } else {

            Log.e(TAG, "Places list response is null");

        }
    }

    private void initializeGeoFence() {
        // Toast.makeText(this, "initializing geo fence", Toast.LENGTH_LONG).show();
        Log.i(TAG, "initializing geo fence");
        Geofence geofence;
        geofenceList = new ArrayList<>();
        for (Place place : places) {
            Log.i(TAG, "Adding geofence at " + place.getLatitude() + ", " + place.getLongitude());
            // @TODO Fetch and set the Geofence Radius dynamically
            geofence = new Geofence.Builder()
                    // Set the request ID of the geofence. This is a string to identify this
                    // geofence.
                    .setRequestId(place.getPlaceId() + "")
                    .setCircularRegion(
                            place.getLatitude(),
                            place.getLongitude(),
                            500f)
                    .setExpirationDuration(60 * 60 * 1000)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

            geofenceList.add(geofence);
        }
    }

    private void addGeoFence2() {
        Log.i(TAG, "addGeoFence2: ");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Make sure permission is granted before starting the service. NOTE: Requesting permission from Service is not allowed.
            return;
        }
        geofencingClient.addGeofences(getGeofencingRequest(), createGeoFencePendingIntent())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.i(TAG, "Geo fence added");
                        // Toast.makeText(HomeActivity.this, "Geo fence added", Toast.LENGTH_LONG).show();
                        GeoFenceMakerService.this.stopSelf();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "Geo fence add failed. ");
                        e.printStackTrace();
                        // Toast.makeText(HomeActivity.this, "Geo fence add failed", Toast.LENGTH_LONG).show();
                        GeoFenceMakerService.this.stopSelf();
                    }
                });
    }

    private GeofencingRequest getGeofencingRequest() {

        // Toast.makeText(this, "getGeofencingRequest", Toast.LENGTH_LONG).show();
        Log.i(TAG, "getGeofencingRequest");
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofences(geofenceList);
        return builder.build();
    }

    private PendingIntent createGeoFencePendingIntent() {
        Intent intent;

        Log.d(TAG, "createGeoFencePendingIntent");

        if (geoFencePendingIntent == null) {
            Log.i(TAG, "GeoFence pending intent is null. Creating new instance");

            intent = new Intent(this, GeofenceBroadcastReceiver.class);
            // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
            // calling addGeofences() and removeGeofences().
            geoFencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.
                    FLAG_UPDATE_CURRENT);

        }

        return geoFencePendingIntent;
    }

}

Body:
An Intent sent from Location Services can trigger various actions in
  your app, but you should not have it start an activity or fragment,
  because components should only become visible in response to a user
  action. In many cases, a BroadcastReceiver is a good way to handle a
  geofence transition. A BroadcastReceiver gets updates when an event
  occurs, such as a transition into or out of a geofence, and can start
  long-running background work.

check here

private PendingIntent getGeofencePendingIntent() {
    if (geofencePendingIntent != null) {
        return geofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);

    geofencePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return geofencePendingIntent;
}