问:
np.savetxt not appending even when file is still open
Edit!!!
 In the end I was able to write this with the while loop that I wanted and saved to correct output folder while it being appending.

Solution:

```<code>tempfilename=keyname+'_trimmed.fastq'
TempSavelocation="./fastqs/"+tempfilename
f=open(TempSavelocation,'ab')
icounter=0
while icounter < len(tempid):
    with open(TempSavelocation,'ab') as f:
    # Creating the type of a structure
    structuredArr=np.array([tempid[icounter],tempseq[icounter],"+", tempqc[icounter]])
    np.savetxt(f, structuredArr, fmt=['%s'])
    icounter=icounter+1
f.close()
</code>```

This gave me the correct output, I also tried with the for-loop but a while is what I was most useful for my particular problem.

Problem:

The issue is that when I run npsavetext it is not working correctly, I initially had this as a while loop (which would be the most ideal in my mind, to cycle through a list that has matched list and append them into a single file)

Below is my code:

```<code>atable=['a','b','b','a','b','b']
f=open(tempfilename,'ab')
f.write(b"\n")
with open(tempfilename,'ab') as f:
    for s in atable:
        structuredArr=np.array([s,"+"])
        np.savetxt("./fastqs/"+tempfilename, structuredArr, delimiter=' ', fmt=['%s'])
f.close()
</code>```

Expected result is below:

```<code>a
+
b
+
b
+
a
+
b
+
b
</code>```

Actual result is

```<code>+
b
</code>```

Ideally what I am trying to actually do is
below:

```<code>icounter=0
    f=open(tempfilename,'ab'
    while icounter < len(tempid):
        with open(tempfilename,'ab') as f:
            # Creating the type of a structure
          structuredArr=np.array([tempid[icounter],tempseq[icounter],"+",tempqc[icounter]])
            np.savetxt("./fastqs/"+tempfilename, structuredArr, delimiter=' ', fmt=['%s'])
            f.write("\n")
        icounter=icounter+1
    f.close()
</code>```

I though that the latter probably didn't append because of my while loop.

Any help would be great.

答:
When using with open, do that saving with the indented block.

```<code>In [329]: atable=['a','b','b','a','b','b']
     ...: with open('abtest.csv','ab') as f:
     ...:     for s in atable:
     ...:         structuredArr=np.array([s,"+"])
     ...:         np.savetxt(f, structuredArr, delimiter=' ', fmt=['%s'])
     ...:
In [330]: cat abtest.csv
a
+
b
+
b
+
a
+
b
+
b
+
</code>```

Body:
Edit!!!
 In the end I was able to write this with the while loop that I wanted and saved to correct output folder while it being appending.

Solution:

tempfilename=keyname+'_trimmed.fastq'
TempSavelocation="./fastqs/"+tempfilename
f=open(TempSavelocation,'ab')
icounter=0
while icounter < len(tempid):
    with open(TempSavelocation,'ab') as f:
    # Creating the type of a structure
    structuredArr=np.array([tempid[icounter],tempseq[icounter],"+", tempqc[icounter]])
    np.savetxt(f, structuredArr, fmt=['%s'])
    icounter=icounter+1
f.close()

This gave me the correct output, I also tried with the for-loop but a while is what I was most useful for my particular problem.

Problem:

The issue is that when I run npsavetext it is not working correctly, I initially had this as a while loop (which would be the most ideal in my mind, to cycle through a list that has matched list and append them into a single file)

Below is my code:

atable=['a','b','b','a','b','b']
f=open(tempfilename,'ab')
f.write(b"\n")
with open(tempfilename,'ab') as f:
    for s in atable:
        structuredArr=np.array([s,"+"])
        np.savetxt("./fastqs/"+tempfilename, structuredArr, delimiter=' ', fmt=['%s'])
f.close()

Expected result is below:

a
+
b
+
b
+
a
+
b
+
b

Actual result is

+
b

Ideally what I am trying to actually do is
below:

icounter=0
    f=open(tempfilename,'ab'
    while icounter < len(tempid):
        with open(tempfilename,'ab') as f:
            # Creating the type of a structure
          structuredArr=np.array([tempid[icounter],tempseq[icounter],"+",tempqc[icounter]])
            np.savetxt("./fastqs/"+tempfilename, structuredArr, delimiter=' ', fmt=['%s'])
            f.write("\n")
        icounter=icounter+1
    f.close()

I though that the latter probably didn't append because of my while loop.

Any help would be great.

Body:
When using with open, do that saving with the indented block.

In [329]: atable=['a','b','b','a','b','b']
     ...: with open('abtest.csv','ab') as f:
     ...:     for s in atable:
     ...:         structuredArr=np.array([s,"+"])
     ...:         np.savetxt(f, structuredArr, delimiter=' ', fmt=['%s'])
     ...:
In [330]: cat abtest.csv
a
+
b
+
b
+
a
+
b
+
b
+


来源: stackexchange

问:
Why Method Overriding is runtime bound
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

```<code>//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}
</code>```

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?

答:
```<code>class BaseClass
{
   public virtual void Test(){
      Console.WriteLine("This is test of base class");
   }
}

class DerivedClass : BaseClass
{
   public override void Test(){
      Console.WriteLine("This is test of derived class");
   }
}

class DerivedClass1 : BaseClass
{
   public override void Test(){
      Console.WriteLine("This is test of derived class-1");
   }
}
</code>```

now if you use

```<code>BaseClass b = new DerivedClass();
b.Test(); // This will derived class method
</code>```

Suppose object created by one another method depend on condition but all are derived from BaseClass

```<code>public BaseClass GetObject(int i)
{
    if(i==1) return new DerivedClass();
    if(i==2) return new DerivedClass1();
}

BaseClass b = GetObject(1);
b.Test(); // This will derivedclass method
BaseClass b = GetObject(2);
b.Test(); // This will derivedclass1 method
</code>```

So all thing depend upon value of i that can decided at runtime and at runtime depend upon type of reference b hold as per that Test method call.

ContentLicense: CC BY-SA 3.0

Title: Why Method Overriding is runtime bound

Body:
Overriding is a principle that allows you to change the functionality of a method in a child class.

For Ex.

//Overriding
public class test
{
        public virtual getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}

When we Inherit test class in test2 at that time compiler knows that there is a virtual method in parent class.
Then why Method overring is runtime bound and not compile time bound?

Body:
class BaseClass
{
   public virtual void Test(){
      Console.WriteLine("This is test of base class");
   }
}

class DerivedClass : BaseClass
{
   public override void Test(){
      Console.WriteLine("This is test of derived class");
   }
}

class DerivedClass1 : BaseClass
{
   public override void Test(){
      Console.WriteLine("This is test of derived class-1");
   }
}

now if you use

BaseClass b = new DerivedClass();
b.Test(); // This will derived class method

Suppose object created by one another method depend on condition but all are derived from BaseClass

public BaseClass GetObject(int i)
{
    if(i==1) return new DerivedClass();
    if(i==2) return new DerivedClass1();
}

BaseClass b = GetObject(1);
b.Test(); // This will derivedclass method
BaseClass b = GetObject(2);
b.Test(); // This will derivedclass1 method

So all thing depend upon value of i that can decided at runtime and at runtime depend upon type of reference b hold as per that Test method call.


问:
Android - Kapt Build Fails
I decided to start a project in android and currently I am having this error. I was having another one that was produced by the databinding dependency which had to match the gradle version. After fixing that, I am still receiving this other error when I'm trying to build my project.

This is my gradle scan report.
Gradle Scan

I have already invalidated cache/restart, clean and rebuild but the problem persists.

The task that is failing is:  Task :app:kaptDebugKotlin FAILED

This is the output in the console when I run the command

./gradlew build --stacktrace

```<code>[kapt] An exception occurred: java.lang.OutOfMemoryError: GC overhead limit exceeded

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
    at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:74)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph.execute(DefaultTaskExecutionGraph.java:143)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:40)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:24)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:46)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:49)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:33)
    at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:355)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:219)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:124)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:50)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:44)
    at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:79)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    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:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    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:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
    at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:14)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:120)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:152)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:147)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:87)
    at org.jetbrains.kotlin.gradle.internal.KaptWithKotlincTask.compile(KaptWithKotlincTask.kt:72)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:801)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:768)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
    ... 111 more

* Get more help at https://help.gradle.org

BUILD FAILED in 33s
</code>```

Here is the informations about my dependencies

dependencies.gradle

```<code>ext {
    versions = [
            support         : "28.0.0",
            firebase        : '16.0.6',
            room            : "2.1.0-alpha04",
            constraintLayout: "2.0.0-alpha3",
            moshi           : "1.8.0",
            okHttp          : "3.12.0",
            retrofit        : '2.5.0',
            dagger          : '2.20',
            butterKnife     : '10.0.0',
            rxKotlin        : '2.3.0',
            rxAndroid       : '2.1.0',
            rxPermissions   : '0.9.4@aar',
            sqlbrite        : '1.1.2',
            traceur         : '1.0.1',
            stetho          : '1.5.0',
            timber          : '4.7.1',
            glide           : '4.8.0',
            sherlock        : '1.0.4@aar',
        espresso        : '3.0.2',
        testRunner      : '1.0.2',
        hamcrest        : '2.1',
        restMock        : '0.3.2',
        mockito         : '2.23.4',
        junit           : '4.12',
        robolectric     : '4.1',
        assertj         : '1.2.0',
        powerMock       : '1.6.6',
        leakcanary      : '1.6.2',
        stethOkhttp     : '1.5.0',
        multiDex        : '2.0.1',
        mockitoKotlin   : '1.6.0'
]

mockito = [mockito: "org.mockito:mockito-core:$versions.mockito"]
junit = [junit: "junit:junit:$versions.junit"]
restMock = [restMock: "com.github.andrzejchm.RESTMock:android:$versions.restMock"]

supportDeps = [
        cardView         : "com.android.support:cardview-v7:$versions.support",
        appcompatV7      : "com.android.support:appcompat-v7:$versions.support",
        design           : "com.android.support:design:$versions.support",
        recyclerView     : "com.android.support:recyclerview-v7:$versions.support",
        supportAnnotation: "com.android.support:support-annotations:$versions.support",
        gridLayout       : "com.android.support:gridlayout-v7:$versions.support",
        constraintlayout : "com.android.support.constraint:constraint-layout:$versions.constraintLayout",
        multiDex         : "com.android.support:multidex:$versions.multiDex"
]

room = [
         room: "androidx.room:room-runtime:$versions.room",
         rxjsupp:  "androidx.room:room-rxjava2:$versions.room",
         coroutines: "androidx.room:room-coroutines:$versions.room"
]

rxJava = [
        rxKotlin : "io.reactivex.rxjava2:rxkotlin:$versions.rxKotlin",
        rxAndroid: "io.reactivex.rxjava2:rxandroid:$versions.rxAndroid",
        traceur         : "com.tspoon.traceur:traceur:$versions.traceur",
        rxRermissions   : "com.tbruyelle.rxpermissions:rxpermissions:$versions.rxPermissions"
]

retrofit = [
        retrofit     : "com.squareup.retrofit2:retrofit:$versions.retrofit",
        rxAdapter    : "com.squareup.retrofit2:adapter-rxjava2:$versions.retrofit",
        moshiConverter: "com.squareup.retrofit2:converter-moshi:$versions.retrofit",
        sqlbrite     : "com.squareup.sqlbrite:sqlbrite:$versions.sqlbrite"
]

moshi = [
        moshi: "com.squareup.moshi:moshi-kotlin:$versions.moshi"
]

okHttp = [
        logger: "com.squareup.okhttp3:logging-interceptor:3.12.1",
        okhttp  : "com.squareup.okhttp3:okhttp:$versions.okHttp",
        stetho  : "com.facebook.stetho:stetho-okhttp3:$versions.stetho"
]

googlePlay = [
        maps             : "com.google.android.gms:play-services-maps:16.0.0",
        crash            : "com.google.firebase:firebase-crash:16.2.1",
        firebaseCore     : "com.google.firebase:firebase-core:$versions.firebase",
        firebaseMessaging: "com.google.firebase:firebase-messaging:17.3.4"
]

onlyDebug = [
        chuck   : "com.readystatesoftware.chuck:library:1.1.0"
]

onlyRelease = [
        chuckNoOp       : 'com.readystatesoftware.chuck:library-no-op:1.1.0',
        sherlockNoOp    : 'com.github.ajitsing:sherlock-no-op:1.0.4@aar'
]

unitTest = [
        harcrestCore        : "org.hamcrest:hamcrest-core:$versions.hamcrest",
        harmcrestLib        : "org.hamcrest:hamcrest-library:$versions.hamcrest",
        hamcrestIntegration : "org.hamcrest:hamcrest-integration:1.4-atlassian-1",
        robolectric         : "org.robolectric:robolectric:$versions.robolectric",
        supportAnnotation   : "com.android.support:support-annotations:$versions.support",
        restMock            : "com.github.andrzejchm.RESTMock:android:$versions.restMock",
        assertj             : "com.squareup.assertj:assertj-android:$versions.assertj",
        kotlinTest          : "org.jetbrains.kotlin:kotlin-test:$kotlin_version",
        kotlinJunit         : "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version",
        mockitoKotlin       : "com.nhaarman:mockito-kotlin:$versions.mockitoKotlin",
        room                : "androidx.room:room-testing:$versions.room"

] + junit + mockito + restMock

androidTests = [
        mockitoAndroid      : "org.mockito:mockito-android:$versions.mockito",
        espressoCore        : "com.android.support.test.espresso:espresso-core:$versions.espresso",
        espressoContrib     : "com.android.support.test.espresso:espresso-contrib:$versions.espresso",
        espressoIntents     : "com.android.support.test.espresso:espresso-intents:$versions.espresso",
        espressoAcc         : "com.android.support.test.espresso:espresso-accessibility:$versions.espresso",
        espressoIdle        : "com.android.support.test.espresso:espresso-idling-resource:$versions.espresso",
        espressoConcurrent  : "com.android.support.test.espresso.idling:idling-concurrent:$versions.espresso",
        espressoNetIdle     : "com.android.support.test.espresso.idling:idling-net:$versions.espresso",
        testRunner          : "com.android.support.test:runner:$versions.testRunner",
        testRules           : "com.android.support.test:rules:$versions.testRunner"
] + mockito + restMock

leakCannary = "com.squareup.leakcanary:leakcanary-android:1.6.2"
timber = "com.jakewharton.timber:timber:$versions.timber"
sherlock = "com.github.ajitsing:sherlock:$versions.sherlock"

dagger = "com.google.dagger:dagger:$versions.dagger"
daggerCompiler = "com.google.dagger:dagger-compiler:$versions.dagger"

butterKnife = "com.jakewharton:butterknife:$versions.butterKnife"
butterKnifeCompiler = "com.jakewharton:butterknife-compiler:$versions.butterKnife"

glide = "com.github.bumptech.glide:glide:$versions.glide"
glideCompiler = "com.github.bumptech.glide:compiler:$versions.glide"
glideOkhttp = "com.github.bumptech.glide:okhttp3-integration:$versions.glide"
databindingCompiler = "com.android.databinding:compiler:3.3.0"

roomKapt =  "androidx.room:room-compiler:$versions.room"

googlePlayLibs = googlePlay.values()
supportLibs = supportDeps.values()
networkLibs = retrofit.values() + okHttp.values() + moshi.values()
rxJavaLibs = rxJava.values()
otherLibs = [butterKnife, timber, dagger, glide] + room.values()

debugLibs = onlyDebug.values() + leakCannary
releaseLibs = onlyRelease.values() + leakCannary
annotationProcessorLibs = [butterKnifeCompiler, daggerCompiler, glideCompiler, roomKapt]

unitTestLibs = unitTest.values() + leakCannary
androidTestsLibs = androidTests.values() + supportLibs

 }
</code>```

My app/build.gradle file:
app/build.gradle

My gradle.properties file:
gradle.properties

答:
Room and Kapt plugin issue fix

On the right hand side of your IDE, click on the Gradle bar -> app -> tasks -> build -> assemble.
to assemble the debug.

ContentLicense: CC BY-SA 4.0

Title: Android - Kapt Build Fails

Body:
I decided to start a project in android and currently I am having this error. I was having another one that was produced by the databinding dependency which had to match the gradle version. After fixing that, I am still receiving this other error when I'm trying to build my project.

This is my gradle scan report.
Gradle Scan

I have already invalidated cache/restart, clean and rebuild but the problem persists.

The task that is failing is:  Task :app:kaptDebugKotlin FAILED

This is the output in the console when I run the command

./gradlew build --stacktrace

[kapt] An exception occurred: java.lang.OutOfMemoryError: GC overhead limit exceeded

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptDebugKotlin'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
    at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:277)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:262)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:74)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph.execute(DefaultTaskExecutionGraph.java:143)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:40)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:24)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:46)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:49)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:40)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:33)
    at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:355)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:219)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:124)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
    at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:154)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
    at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
    at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:50)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:45)
    at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:47)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:44)
    at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:79)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:44)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
    at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
    at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
    at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
    at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
    at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
    at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
    at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
    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:122)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    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:122)
    at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:81)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
    at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:14)
    at org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:120)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:152)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:147)
    at org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:87)
    at org.jetbrains.kotlin.gradle.internal.KaptWithKotlincTask.compile(KaptWithKotlincTask.kt:72)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:46)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:801)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:768)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
    ... 111 more

* Get more help at https://help.gradle.org

BUILD FAILED in 33s

Here is the informations about my dependencies

dependencies.gradle

ext {
    versions = [
            support         : "28.0.0",
            firebase        : '16.0.6',
            room            : "2.1.0-alpha04",
            constraintLayout: "2.0.0-alpha3",
            moshi           : "1.8.0",
            okHttp          : "3.12.0",
            retrofit        : '2.5.0',
            dagger          : '2.20',
            butterKnife     : '10.0.0',
            rxKotlin        : '2.3.0',
            rxAndroid       : '2.1.0',
            rxPermissions   : '0.9.4@aar',
            sqlbrite        : '1.1.2',
            traceur         : '1.0.1',
            stetho          : '1.5.0',
            timber          : '4.7.1',
            glide           : '4.8.0',
            sherlock        : '1.0.4@aar',
        espresso        : '3.0.2',
        testRunner      : '1.0.2',
        hamcrest        : '2.1',
        restMock        : '0.3.2',
        mockito         : '2.23.4',
        junit           : '4.12',
        robolectric     : '4.1',
        assertj         : '1.2.0',
        powerMock       : '1.6.6',
        leakcanary      : '1.6.2',
        stethOkhttp     : '1.5.0',
        multiDex        : '2.0.1',
        mockitoKotlin   : '1.6.0'
]

mockito = [mockito: "org.mockito:mockito-core:$versions.mockito"]
junit = [junit: "junit:junit:$versions.junit"]
restMock = [restMock: "com.github.andrzejchm.RESTMock:android:$versions.restMock"]

supportDeps = [
        cardView         : "com.android.support:cardview-v7:$versions.support",
        appcompatV7      : "com.android.support:appcompat-v7:$versions.support",
        design           : "com.android.support:design:$versions.support",
        recyclerView     : "com.android.support:recyclerview-v7:$versions.support",
        supportAnnotation: "com.android.support:support-annotations:$versions.support",
        gridLayout       : "com.android.support:gridlayout-v7:$versions.support",
        constraintlayout : "com.android.support.constraint:constraint-layout:$versions.constraintLayout",
        multiDex         : "com.android.support:multidex:$versions.multiDex"
]

room = [
         room: "androidx.room:room-runtime:$versions.room",
         rxjsupp:  "androidx.room:room-rxjava2:$versions.room",
         coroutines: "androidx.room:room-coroutines:$versions.room"
]

rxJava = [
        rxKotlin : "io.reactivex.rxjava2:rxkotlin:$versions.rxKotlin",
        rxAndroid: "io.reactivex.rxjava2:rxandroid:$versions.rxAndroid",
        traceur         : "com.tspoon.traceur:traceur:$versions.traceur",
        rxRermissions   : "com.tbruyelle.rxpermissions:rxpermissions:$versions.rxPermissions"
]

retrofit = [
        retrofit     : "com.squareup.retrofit2:retrofit:$versions.retrofit",
        rxAdapter    : "com.squareup.retrofit2:adapter-rxjava2:$versions.retrofit",
        moshiConverter: "com.squareup.retrofit2:converter-moshi:$versions.retrofit",
        sqlbrite     : "com.squareup.sqlbrite:sqlbrite:$versions.sqlbrite"
]

moshi = [
        moshi: "com.squareup.moshi:moshi-kotlin:$versions.moshi"
]

okHttp = [
        logger: "com.squareup.okhttp3:logging-interceptor:3.12.1",
        okhttp  : "com.squareup.okhttp3:okhttp:$versions.okHttp",
        stetho  : "com.facebook.stetho:stetho-okhttp3:$versions.stetho"
]

googlePlay = [
        maps             : "com.google.android.gms:play-services-maps:16.0.0",
        crash            : "com.google.firebase:firebase-crash:16.2.1",
        firebaseCore     : "com.google.firebase:firebase-core:$versions.firebase",
        firebaseMessaging: "com.google.firebase:firebase-messaging:17.3.4"
]

onlyDebug = [
        chuck   : "com.readystatesoftware.chuck:library:1.1.0"
]

onlyRelease = [
        chuckNoOp       : 'com.readystatesoftware.chuck:library-no-op:1.1.0',
        sherlockNoOp    : 'com.github.ajitsing:sherlock-no-op:1.0.4@aar'
]

unitTest = [
        harcrestCore        : "org.hamcrest:hamcrest-core:$versions.hamcrest",
        harmcrestLib        : "org.hamcrest:hamcrest-library:$versions.hamcrest",
        hamcrestIntegration : "org.hamcrest:hamcrest-integration:1.4-atlassian-1",
        robolectric         : "org.robolectric:robolectric:$versions.robolectric",
        supportAnnotation   : "com.android.support:support-annotations:$versions.support",
        restMock            : "com.github.andrzejchm.RESTMock:android:$versions.restMock",
        assertj             : "com.squareup.assertj:assertj-android:$versions.assertj",
        kotlinTest          : "org.jetbrains.kotlin:kotlin-test:$kotlin_version",
        kotlinJunit         : "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version",
        mockitoKotlin       : "com.nhaarman:mockito-kotlin:$versions.mockitoKotlin",
        room                : "androidx.room:room-testing:$versions.room"

] + junit + mockito + restMock

androidTests = [
        mockitoAndroid      : "org.mockito:mockito-android:$versions.mockito",
        espressoCore        : "com.android.support.test.espresso:espresso-core:$versions.espresso",
        espressoContrib     : "com.android.support.test.espresso:espresso-contrib:$versions.espresso",
        espressoIntents     : "com.android.support.test.espresso:espresso-intents:$versions.espresso",
        espressoAcc         : "com.android.support.test.espresso:espresso-accessibility:$versions.espresso",
        espressoIdle        : "com.android.support.test.espresso:espresso-idling-resource:$versions.espresso",
        espressoConcurrent  : "com.android.support.test.espresso.idling:idling-concurrent:$versions.espresso",
        espressoNetIdle     : "com.android.support.test.espresso.idling:idling-net:$versions.espresso",
        testRunner          : "com.android.support.test:runner:$versions.testRunner",
        testRules           : "com.android.support.test:rules:$versions.testRunner"
] + mockito + restMock

leakCannary = "com.squareup.leakcanary:leakcanary-android:1.6.2"
timber = "com.jakewharton.timber:timber:$versions.timber"
sherlock = "com.github.ajitsing:sherlock:$versions.sherlock"

dagger = "com.google.dagger:dagger:$versions.dagger"
daggerCompiler = "com.google.dagger:dagger-compiler:$versions.dagger"

butterKnife = "com.jakewharton:butterknife:$versions.butterKnife"
butterKnifeCompiler = "com.jakewharton:butterknife-compiler:$versions.butterKnife"

glide = "com.github.bumptech.glide:glide:$versions.glide"
glideCompiler = "com.github.bumptech.glide:compiler:$versions.glide"
glideOkhttp = "com.github.bumptech.glide:okhttp3-integration:$versions.glide"
databindingCompiler = "com.android.databinding:compiler:3.3.0"

roomKapt =  "androidx.room:room-compiler:$versions.room"

googlePlayLibs = googlePlay.values()
supportLibs = supportDeps.values()
networkLibs = retrofit.values() + okHttp.values() + moshi.values()
rxJavaLibs = rxJava.values()
otherLibs = [butterKnife, timber, dagger, glide] + room.values()

debugLibs = onlyDebug.values() + leakCannary
releaseLibs = onlyRelease.values() + leakCannary
annotationProcessorLibs = [butterKnifeCompiler, daggerCompiler, glideCompiler, roomKapt]

unitTestLibs = unitTest.values() + leakCannary
androidTestsLibs = androidTests.values() + supportLibs

 }

My app/build.gradle file:
app/build.gradle

My gradle.properties file:
gradle.properties


问:
Unable to get the documents after creating a query index
Code:

```<code>var querySnapshot = await Firestore //
    .instance
    .collection('collection')
    .where('name', isEqualTo: ['foo'])
    .orderBy('time')
    .limit(1)
    .getDocuments();

print('${querySnapshot.documents}'); // prints []
</code>```

It returns empty List.

Database structure:

Index built

答:
Indexing isn't an issue here.  Given the query and document you're showing, I'd always expect it to return no results.  You're using an array-contains type query on a field that isn't an array.  Your name field is a string, and strings can't be matched by array-contains queries.

If you intended for name to be an array, you'll need to modify the document so that it is actually an array with the string "foo" in it.

Body:
Code:

var querySnapshot = await Firestore //
    .instance
    .collection('collection')
    .where('name', isEqualTo: ['foo'])
    .orderBy('time')
    .limit(1)
    .getDocuments();

print('${querySnapshot.documents}'); // prints []

It returns empty List.

Database structure:

Index built


问:
How to feed the x and y values of a Plotly bar chart from a Pandas data frame
I have the following toy data set:

```<code>df = pd.DataFrame({'Make':['Ford', 'Ford', 'Ford', 'BMW', 'BMW', 'BMW', Mercedes', 'Mercedes', 'Mercedes'],
                          'Score':['88.6', '76.6', '100', '79.1', '86.8', '96.4', '97.3', '98.7', '98.5'],
                          'Dimension':['Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling'],
                          'Month':['Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19']})
</code>```

I'm using Plotly and the Dash framework to build an interactive web-based dashboard.  The code is as follows:

```<code>import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import dash_table
import pandas as pd

app = dash.Dash()

app.layout = html.Div([
dcc.Upload(
        id='upload-data',
        children=html.Div([
        'Drag and Drop or ',
        html.A('Select Files')
        ]),
        style={
        'width': '100%',
        'height': '60px',
        'lineHeight': '60px',
        'borderWidth': '1px',
        'borderStyle': 'dashed',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '10px'
         },
        # Allow multiple files to be uploaded
        multiple=True
),

html.Div(id='output-data-upload'),
])

def parse_contents(contents, filename, date):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
        # Assume that the user uploaded a CSV file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
        # Assume that the user uploaded an excel file
            df = pd.read_excel(io.BytesIO(decoded))
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),

        dash_table.DataTable(
            data=df.to_dict('records'),
            columns=[{'name': i, 'id': i} for i in df.columns]
        ),

        html.Hr(),  # horizontal line

        #### How to get the x and y values DYNAMICALLY from the data frame to pass into the Bar() function? ####

        dcc.Graph(
            figure = go.Figure(data=[
            go.Bar(name=df.columns.values[0], x=pd.unique(df['Make']), y=[88.6, 76.6, 100], text=[88.6, 76.6, 100], textposition='auto'),
            go.Bar(name=df.columns.values[1], x=pd.unique(df['Make']), y=[92.5, 93.6, 93.4], text=[92.5, 93.6, 93.4], textposition='auto'),
            go.Bar(name=df.columns.values[2], x=pd.unique(df['Make']), y=[99.1, 99.2, 95.9], text=[99.1, 99.2, 95.9], textposition='auto'),
            ])
            ),

        html.Hr(),

        # For debugging, display the raw contents provided by the web browser
        html.Div('Raw Content'),
        html.Pre(contents[0:200] + '...', style={
            'whiteSpace': 'pre-wrap',
            'wordBreak': 'break-all'
        })
    ])

@app.callback(Output('output-data-upload', 'children'),
              [Input('upload-data', 'contents')],
              [State('upload-data', 'filename'),
               State('upload-data', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)]
        return children

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

In summary, the user uploads a .csv file and a Pandas data frame is created.  A bar plot is then rendered based on the data in the data frame.

As you can see, the go.Bar() function has x and y values that come from the df dataframe.  The number of x values can fluctuate (in this case, it's 3, but it could be 2 or 10 or anywhere in between).  I have the x values hard-coded in a very inelegant way as indexed values from the column names.

Questions:

1) What's the most Pythonic way to read in the x values dynamically, such that the code accepts a variable number of x values?

2) What is the best way to read in the associated y values dynamically from the df data frame? (I have them completely hard-coded in for the purposes of this example)

Thanks in advance?

答:
did you try it in this way?</p>

```<code>    dcc.Graph(
        figure = go.Figure(data=[
        go.Bar(name=df.columns.values[0], x=pd.unique(df['Make']), y=df['Score'], text=df['Score'], textposition='auto'),
        go.Bar(name=df.columns.values[1], x=pd.unique(df['Make']), y=df['Score'], text=df['Score'], textposition='auto'),
        go.Bar(name=df.columns.values[2], x=pd.unique(df['Make']), y=df['Score'], text=df['Score'], textposition='auto'),
        ])
        ),
</code>```

Body:
I have the following toy data set:

df = pd.DataFrame({'Make':['Ford', 'Ford', 'Ford', 'BMW', 'BMW', 'BMW', Mercedes', 'Mercedes', 'Mercedes'],
                          'Score':['88.6', '76.6', '100', '79.1', '86.8', '96.4', '97.3', '98.7', '98.5'],
                          'Dimension':['Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling'],
                          'Month':['Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19']})

I'm using Plotly and the Dash framework to build an interactive web-based dashboard.  The code is as follows:

import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
import dash_table
import pandas as pd

app = dash.Dash()

app.layout = html.Div([
dcc.Upload(
        id='upload-data',
        children=html.Div([
        'Drag and Drop or ',
        html.A('Select Files')
        ]),
        style={
        'width': '100%',
        'height': '60px',
        'lineHeight': '60px',
        'borderWidth': '1px',
        'borderStyle': 'dashed',
        'borderRadius': '5px',
        'textAlign': 'center',
        'margin': '10px'
         },
        # Allow multiple files to be uploaded
        multiple=True
),

html.Div(id='output-data-upload'),
])

def parse_contents(contents, filename, date):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
        # Assume that the user uploaded a CSV file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
        # Assume that the user uploaded an excel file
            df = pd.read_excel(io.BytesIO(decoded))
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    return html.Div([
        html.H5(filename),
        html.H6(datetime.datetime.fromtimestamp(date)),

        dash_table.DataTable(
            data=df.to_dict('records'),
            columns=[{'name': i, 'id': i} for i in df.columns]
        ),

        html.Hr(),  # horizontal line

        #### How to get the x and y values DYNAMICALLY from the data frame to pass into the Bar() function? ####

        dcc.Graph(
            figure = go.Figure(data=[
            go.Bar(name=df.columns.values[0], x=pd.unique(df['Make']), y=[88.6, 76.6, 100], text=[88.6, 76.6, 100], textposition='auto'),
            go.Bar(name=df.columns.values[1], x=pd.unique(df['Make']), y=[92.5, 93.6, 93.4], text=[92.5, 93.6, 93.4], textposition='auto'),
            go.Bar(name=df.columns.values[2], x=pd.unique(df['Make']), y=[99.1, 99.2, 95.9], text=[99.1, 99.2, 95.9], textposition='auto'),
            ])
            ),

        html.Hr(),

        # For debugging, display the raw contents provided by the web browser
        html.Div('Raw Content'),
        html.Pre(contents[0:200] + '...', style={
            'whiteSpace': 'pre-wrap',
            'wordBreak': 'break-all'
        })
    ])

@app.callback(Output('output-data-upload', 'children'),
              [Input('upload-data', 'contents')],
              [State('upload-data', 'filename'),
               State('upload-data', 'last_modified')])
def update_output(list_of_contents, list_of_names, list_of_dates):
    if list_of_contents is not None:
        children = [
            parse_contents(c, n, d) for c, n, d in
            zip(list_of_contents, list_of_names, list_of_dates)]
        return children

if __name__ == '__main__':
    app.run_server(debug=True)

In summary, the user uploads a .csv file and a Pandas data frame is created.  A bar plot is then rendered based on the data in the data frame.

As you can see, the go.Bar() function has x and y values that come from the df dataframe.  The number of x values can fluctuate (in this case, it's 3, but it could be 2 or 10 or anywhere in between).  I have the x values hard-coded in a very inelegant way as indexed values from the column names.

Questions:

1) What's the most Pythonic way to read in the x values dynamically, such that the code accepts a variable number of x values?

2) What is the best way to read in the associated y values dynamically from the df data frame? (I have them completely hard-coded in for the purposes of this example)

Thanks in advance?

Body:
did you try it in this way?

    dcc.Graph(
        figure = go.Figure(data=[
        go.Bar(name=df.columns.values[0], x=pd.unique(df['Make']), y=df['Score'], text=df['Score'], textposition='auto'),
        go.Bar(name=df.columns.values[1], x=pd.unique(df['Make']), y=df['Score'], text=df['Score'], textposition='auto'),
        go.Bar(name=df.columns.values[2], x=pd.unique(df['Make']), y=df['Score'], text=df['Score'], textposition='auto'),
        ])
        ),


问:
code in the kernel space for swapping the contents of two non-overlapping 4KB arrays
The below code in the kernel space is for swapping the contents of two non-overlapping 4KB arrays, does it have any bugs:

```<code>1: void swap4kb(void* a, void* b) {
2:   char tmp[4096];
3:   assert(a != NULL);
4:   assert(b != NULL);
5:   memcpy(tmp, a, 4096);
6:   memcpy(a, b, 4096);
7:   memcpy(b, tmp, 4096);
8: }
</code>```

答:
Does it have any bugs?

It doesn't have bugs; assuming that it doesn't need to be done "atomically", and assuming that you have enough space on the stack for the char tmp[4096]; array.

However, a lot of kernels use a "one kernel stack per task" model, which means there's an incentive to use small kernel stacks. For example, if there's 100 processes that have an average of 10 threads each; then 1 MiB kernel stacks would add up to almost 1 GiB of RAM consumed by kernel stacks alone. Using 4 KiB kernel stacks makes some sense (due to 4 KiB being the size of a page in most systems), and in that case your code will overflow the stack and can be considered buggy for that reason.

In any case; the mistake is assuming this code makes sense in the first place. Typically you'd have "pointers to arrays" and swap the pointers instead, which avoids the overhead of copying the data itself.

Body:
The below code in the kernel space is for swapping the contents of two non-overlapping 4KB arrays, does it have any bugs:

1: void swap4kb(void* a, void* b) {
2:   char tmp[4096];
3:   assert(a != NULL);
4:   assert(b != NULL);
5:   memcpy(tmp, a, 4096);
6:   memcpy(a, b, 4096);
7:   memcpy(b, tmp, 4096);
8: }


问:
Optimization of CodeWars Python 3.6 code: Integers: Recreation One
I need help optimizing my python 3.6 code for the CodeWars Integers: Recreation One Kata.

We are given a range of numbers and we have to return the number and the sum of the divisors squared that is a square itself.

"Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!

Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number."

My code works for individual tests, but it times out when submitting:

```<code>def list_squared(m, n):
    sqsq = []
    for i in range(m, n):
        divisors = [j**2 for j in range(1, i+1) if i % j == 0]
        sq_divs = sum(divisors)
        sq = sq_divs ** (1/2)
        if int(sq) ** 2 == sq_divs:
            sqsq.append([i, sq_divs])

    return sqsq
</code>```

答:
You can reduce complexity of loop in list comprehension from O(N) to O(Log((N)) by setting the max range to sqrt(num)+1 instead of num.

By looping from 1 to sqrt(num)+1, we can conclude that if i (current item in the loop) is a factor of num then num divided by i must be another one.

Eg: 2 is a factor of 10, so is 5 (10/2)

The following code passes all the tests:

```<code>import math

def list_squared(m, n):
    result = []
    for num in range(m, n + 1):
        divisors = set()
        for i in range(1, int(math.sqrt(num)+1)):
            if num % i == 0:
                divisors.add(i**2)
                divisors.add(int(num/i)**2)
        total = sum(divisors)
        sr = math.sqrt(total)
        if sr - math.floor(sr) == 0:
            result.append([num, total])
    return result
</code>```

Body:
I need help optimizing my python 3.6 code for the CodeWars Integers: Recreation One Kata.

We are given a range of numbers and we have to return the number and the sum of the divisors squared that is a square itself.

"Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!

Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number."

My code works for individual tests, but it times out when submitting:

def list_squared(m, n):
    sqsq = []
    for i in range(m, n):
        divisors = [j**2 for j in range(1, i+1) if i % j == 0]
        sq_divs = sum(divisors)
        sq = sq_divs ** (1/2)
        if int(sq) ** 2 == sq_divs:
            sqsq.append([i, sq_divs])

    return sqsq

Body:
You can reduce complexity of loop in list comprehension from O(N) to O(Log((N)) by setting the max range to sqrt(num)+1 instead of num.

By looping from 1 to sqrt(num)+1, we can conclude that if i (current item in the loop) is a factor of num then num divided by i must be another one.

Eg: 2 is a factor of 10, so is 5 (10/2)

The following code passes all the tests:

import math

def list_squared(m, n):
    result = []
    for num in range(m, n + 1):
        divisors = set()
        for i in range(1, int(math.sqrt(num)+1)):
            if num % i == 0:
                divisors.add(i**2)
                divisors.add(int(num/i)**2)
        total = sum(divisors)
        sr = math.sqrt(total)
        if sr - math.floor(sr) == 0:
            result.append([num, total])
    return result


问:
Module not found: Error: Can't resolve '../aws-exports' (React-Native Expo Web)
I've developed an app which works perfectly when I run it through expo start --tunnel and then the w key for expo web.

In order to deploy it, I have tried to use the Amplify console, which seemed to work. However, while deploying the app, it has halted with the following messages:

```<code>2020-02-10T16:39:57.658Z [WARNING]: <s> [webpack.Progress] 70% building 41/59 modules 18 active /root/.nvm/versions/node/v10.16.0/lib/node_modules/expo-cli/node_modules/babel-loader/lib/index.js??ref--5-oneOf-2!/codebuild/output/src261112836/src/gmpmgr2v/node_modules/expo/build/Notifications/ExponentNotifications.web.js
2020-02-10T16:39:57.661Z [WARNING]: [16:39:57]  web  Failed to compile.
2020-02-10T16:39:57.661Z [WARNING]: [16:39:57]
2020-02-10T16:39:57.662Z [WARNING]: [16:39:57] Module not found: Error: Can't resolve '../aws-exports' in '/codebuild/output/src261112836/src/gmpmgr2v/src/modules'
2020-02-10T16:39:57.662Z [WARNING]: [16:39:57] Set EXPO_DEBUG=true in your env to view the stack trace.
2020-02-10T16:39:57.673Z [ERROR]: !!! Build failed
2020-02-10T16:39:57.674Z [ERROR]: !!! Non-Zero Exit Code detected
2020-02-10T16:39:57.674Z [INFO]: # Starting environment caching...
2020-02-10T16:39:57.674Z [INFO]: # Environment caching completed
</code>```

I don't believe there is an issue with my aws-config file, otherwise I would not be able to run it through the expo start --tunnel command.

I believe it is probably not copying aws-config.js to somewhere it should while creating the build.

Has anyone had this problem as well, or know how to address it?

答: For some reason, in the case of this app, a relative reference to aws-exports file did not work, by using the two dots. Changing to a direct path did the job.</p>

Body:
I've developed an app which works perfectly when I run it through expo start --tunnel and then the w key for expo web.

In order to deploy it, I have tried to use the Amplify console, which seemed to work. However, while deploying the app, it has halted with the following messages:

2020-02-10T16:39:57.658Z [WARNING]: <s> [webpack.Progress] 70% building 41/59 modules 18 active /root/.nvm/versions/node/v10.16.0/lib/node_modules/expo-cli/node_modules/babel-loader/lib/index.js??ref--5-oneOf-2!/codebuild/output/src261112836/src/gmpmgr2v/node_modules/expo/build/Notifications/ExponentNotifications.web.js
2020-02-10T16:39:57.661Z [WARNING]: [16:39:57]  web  Failed to compile.
2020-02-10T16:39:57.661Z [WARNING]: [16:39:57]
2020-02-10T16:39:57.662Z [WARNING]: [16:39:57] Module not found: Error: Can't resolve '../aws-exports' in '/codebuild/output/src261112836/src/gmpmgr2v/src/modules'
2020-02-10T16:39:57.662Z [WARNING]: [16:39:57] Set EXPO_DEBUG=true in your env to view the stack trace.
2020-02-10T16:39:57.673Z [ERROR]: !!! Build failed
2020-02-10T16:39:57.674Z [ERROR]: !!! Non-Zero Exit Code detected
2020-02-10T16:39:57.674Z [INFO]: # Starting environment caching...
2020-02-10T16:39:57.674Z [INFO]: # Environment caching completed

I don't believe there is an issue with my aws-config file, otherwise I would not be able to run it through the expo start --tunnel command.

I believe it is probably not copying aws-config.js to somewhere it should while creating the build.

Has anyone had this problem as well, or know how to address it?


问:
Query is taking so long
I have the following code which takes 25 seconds to show data on screen.

Any ideas on how to make it work with isset instead of in_array ?

I think this could go a lot faster !

```<code>if (!$matches[0]['match_id']) $matches = array();

for ($i=0; $i<count($matches); $i++) {

    if (in_array($matches[$i]['match_id'],$validMatches)) {

    $match_stats = $db->get_by_fields('player_match_stats', array('match_id'=>$matches[$i]['match_id'], 'player_id'=>$pid));
        if($match_stats['points']!='') $ret[0]++;
        $ret[1] = $ret[1] + $match_stats['points'];
        $ret[2] = $ret[2] + $match_stats['threepoints'];
    }
}

if ($ret[0] != 0) {
    $ret[3] = $ret[1] / $ret[0];
    $ret[3] = number_format($ret[3], 1);
}

return $ret;
</code>```

答:
Few notes from me:

Don't use count in for loop. It calculates length every iteration. Use foreach instead if you have array.

Use array_intersect to retrieve all valid matches from matches array before your loop.

Remove your loop outside of query and retrieve all records from database at once using WHERE id IN (12,13,15,16,...,77). Then iterate over your results.

Title: Query is taking so long

Body:
I have the following code which takes 25 seconds to show data on screen.

Any ideas on how to make it work with isset instead of in_array ?

I think this could go a lot faster !

if (!$matches[0]['match_id']) $matches = array();

for ($i=0; $i<count($matches); $i++) {

    if (in_array($matches[$i]['match_id'],$validMatches)) {

    $match_stats = $db->get_by_fields('player_match_stats', array('match_id'=>$matches[$i]['match_id'], 'player_id'=>$pid));
        if($match_stats['points']!='') $ret[0]++;
        $ret[1] = $ret[1] + $match_stats['points'];
        $ret[2] = $ret[2] + $match_stats['threepoints'];
    }
}

if ($ret[0] != 0) {
    $ret[3] = $ret[1] / $ret[0];
    $ret[3] = number_format($ret[3], 1);
}

return $ret;


问:
Where is my.cnf or mysql.conf on Mac OS Catalina?
I would like to change something in the mysql configuration file but I cannot find it in /etc/my.cnf or in /usr/local/mysql.

Do you know where I can find this file?

Note that I installed mysql from the official website by a .pkg file not Homebrew.

Thank you.

答:
As @YvesLeBorg suggested, the my.cnf file can be find at  /etc/my.cnf or /etc/mysql/my.cnf or /usr/local/etc/my.cnf  or ~/.my.cnf

In order to identify where the my.cnf is, permet a cat on each of those links.

Also, remember the different my.cnf file locations can be found by running mysql --help


问:
Handling Dollar Sign in Input numeric text
I'm running into an issue with my Python program.

In fact, I have a sales price input which can contain a dollar sign and must respect the following constraints :

It must be numeric

The sales price must be at least $100, including dollars and cents

The problem I'm facing is : if the user inputs a sales price including a dollar sign, how to "ignore" it in order to determine if the input is numeric ? The same issue applies when it comes to a decimal point.

Also, note that :

If the input is not a numeric entry, I would like it to prompt "price must be numeric".

If the entry is less than $100, I would like it to prompt "Price must be at least $100".

This is what I have so far :

```<code>salesPrice= input("What is the sales price of the new phone? ")

if salesPrice[0]=="$":
    val= int(salesPrice[1:])
    if val < 100
        print('Price must be at least $100')
    else:
        price=float(salesPrice[1:])
elif ValueError:
    print('Price must be numeric')
else:
    if salesPrice[0]!= '$':
        if salesPrice[0:]< Min_price:
        print('Price must be at least $100')
        else:
            price=float(salesPrice[0:])
</code>```

答:
I'm assuming you're using Python3 since your use of input() doesn't throw a SyntaxError upon receiving a non-numeric string. Either way, only the input should change. For Python3:

salesPrice = input("What is the sales price of the new phone? ").replace('$', '')
try:
    salesPrice = float(salesPrice)
    if salesPrice < 100.:
        print("Price must be at least $100")
except ValueError:
    print("Price must be numeric")
```

<p>And for Python 2:</p>

<pre class="lang-py prettyprint-override"><code>salesPrice = raw_input("What is the sales price of the new phone? ").replace('$', '')
try:
    salesPrice = float(salesPrice)
    if salesPrice < 100.:
        print("Price must be at least $100")
except ValueError:
    print("Price must be numeric")
</code>```

For both, you can check if a string is a float with a simple try/except.

Body:
I'm running into an issue with my Python program.

In fact, I have a sales price input which can contain a dollar sign and must respect the following constraints :

It must be numeric

The sales price must be at least $100, including dollars and cents

The problem I'm facing is : if the user inputs a sales price including a dollar sign, how to "ignore" it in order to determine if the input is numeric ? The same issue applies when it comes to a decimal point.

Also, note that :

If the input is not a numeric entry, I would like it to prompt "price must be numeric".

If the entry is less than $100, I would like it to prompt "Price must be at least $100".

This is what I have so far :

salesPrice= input("What is the sales price of the new phone? ")

if salesPrice[0]=="$":
    val= int(salesPrice[1:])
    if val < 100
        print('Price must be at least $100')
    else:
        price=float(salesPrice[1:])
elif ValueError:
    print('Price must be numeric')
else:
    if salesPrice[0]!= '$':
        if salesPrice[0:]< Min_price:
        print('Price must be at least $100')
        else:
            price=float(salesPrice[0:])

Body:
I'm assuming you're using Python3 since your use of input() doesn't throw a SyntaxError upon receiving a non-numeric string. Either way, only the input should change. For Python3:

salesPrice = input("What is the sales price of the new phone? ").replace('$', '')
try:
    salesPrice = float(salesPrice)
    if salesPrice < 100.:
        print("Price must be at least $100")
except ValueError:
    print("Price must be numeric")

And for Python 2:

salesPrice = raw_input("What is the sales price of the new phone? ").replace('$', '')
try:
    salesPrice = float(salesPrice)
    if salesPrice < 100.:
        print("Price must be at least $100")
except ValueError:
    print("Price must be numeric")

For both, you can check if a string is a float with a simple try/except.


问:
Does Kubernetes ConfigMap is only for Pods and Deployments?
It's a simple question - is there a way to use ConfigMap key-values in, let's say - Ingress?

I want to have the configuration of such things in one place, to make it easier to clone the whole cluster.

Is it possible?

答: ConfigMap is for usage in a pod to supply configuration at runtime. The recommendation is any deployment yaml including ingress and configMaps should be stored in a version control system. That way you can apply to a new cluster whenever needed. You can go one step further and adopt what is called GitOps.</p>


问:
Flutter: How to increase onSendProgress calls for a fluid progress bar animation while uploading files?
I have the following code to upload a file.

```<code>var client = new dio.Dio();
await client.put(
  url,
  data: formData,
  options: dio.Options(
    headers: headers,
  ),
  onSendProgress: (int sent, int total) {
    final progress = sent / total;
    print('progress: $progress ($sent/$total)');
  },
);
</code>```

Uploading the file works fine. The thing is, I have a view that has a circular progress bar that indicates the upload progress when onSendProgress is triggered. When I upload a ~10MB file the progress bars jumps from 0% to 100% within a second and then waits for a couple of seconds (depending on the file size) before continuing with the rest of the code. This seems weird to me because I expect the progress bar to gradually increase its progress.

Below you can find the print outputs from my example with a ~10MB file.

```<code>flutter: progress: 0.000003035281907563734 (29/9554302)
flutter: progress: 0.000013187776563897604 (126/9554302)
flutter: progress: 0.999996546058519 (9554269/9554302)
flutter: progress: 0.9999967553883057 (9554271/9554302)
flutter: progress: 1.0 (9554302/9554302)
</code>```

This one is with a smaller file, but the same amount of callbacks.

```<code>flutter: progress: 0.00001847214941293598 (29/1569931)
flutter: progress: 0.00008025830434585978 (126/1569931)
flutter: progress: 0.9999789799679094 (1569898/1569931)
flutter: progress: 0.9999802539092483 (1569900/1569931)
flutter: progress: 1.0 (1569931/1569931)
</code>```

As you can see it jumps from 0% to 100%. I can imagine you thinking, that is just fast internet. But I've tried Wifi, 4G, 3G and they all show the same issue. I hit the upload button, it start on 0% it jumps to 100% and then I have to wait some time (depending on the file size) for the upload to finish.

Is there a way to get more amount of onSendProgress callbacks triggered during the upload or somehow to delay the upload so I can get a smooth upload progress?

EDIT:

I've tried the following with the HTTP package

```<code>import 'dart:async';
import 'package:http/http.dart' as http;

class UploadRequest extends http.MultipartRequest {
  final void Function(int bytes, int totalBytes) onProgress;

  UploadRequest(
    String method,
    Uri url, {
    this.onProgress,
  }) : super(method, url);

  http.ByteStream finalize() {
    final byteStream = super.finalize();
    if (onProgress == null) return byteStream;

    final total = this.contentLength;

    final t = StreamTransformer.fromHandlers(
      handleData: (List<int> data, EventSink<List<int>> sink) {
        onProgress(data.length, total);
        sink.add(data);
      },
    );

    final stream = byteStream.transform(t);
    return http.ByteStream(stream);
  }
}
</code>```

Trigger:

```<code>final request = UploadRequest(
  'PUT',
  Uri.parse(url),
  onProgress: (int bytes, int total) {
    print('progress: $progress ($sent/$total)');
  },
);

request.headers.addAll(headers);
request.files.add(
  http.MultipartFile.fromBytes(
    'file',
    attachment.file.buffer.asUint8List(),
    filename: attachment.name,
    contentType: MediaType.parse(attachment.contentType),
  ),
);

var response = await request.send();
</code>```

But sadly, this has the same issue. The file uploads fine, but the progress callback is called only a few times. It hits 100% right away, then I have to wait a while (depending on the file size) before getting a 2xx response from the server. So I don't think this is a specific DIO issue.

I think that it looks like it is not actually showing the upload progress, but rather the progress of the file being read into a stream clientside. Then the stream is uploaded to the server and that is what you are waiting on (of course depending on the file size) even though the progress shows 100%.

答:
This appears to be a bug on dio, I can see two ways you can get around this:

Just add a number to your circular progress, it will say 99% (truncate the rest) so the users will know its not done yet, as 100% will only happen when you get 1.0 as a result).

use the http package instead. the http package as a StreamedRequest which would give you finer control over what's being sent, so you can reflect this on your UI.

Body:
I have the following code to upload a file.

var client = new dio.Dio();
await client.put(
  url,
  data: formData,
  options: dio.Options(
    headers: headers,
  ),
  onSendProgress: (int sent, int total) {
    final progress = sent / total;
    print('progress: $progress ($sent/$total)');
  },
);

Uploading the file works fine. The thing is, I have a view that has a circular progress bar that indicates the upload progress when onSendProgress is triggered. When I upload a ~10MB file the progress bars jumps from 0% to 100% within a second and then waits for a couple of seconds (depending on the file size) before continuing with the rest of the code. This seems weird to me because I expect the progress bar to gradually increase its progress.

Below you can find the print outputs from my example with a ~10MB file.

flutter: progress: 0.000003035281907563734 (29/9554302)
flutter: progress: 0.000013187776563897604 (126/9554302)
flutter: progress: 0.999996546058519 (9554269/9554302)
flutter: progress: 0.9999967553883057 (9554271/9554302)
flutter: progress: 1.0 (9554302/9554302)

This one is with a smaller file, but the same amount of callbacks.

flutter: progress: 0.00001847214941293598 (29/1569931)
flutter: progress: 0.00008025830434585978 (126/1569931)
flutter: progress: 0.9999789799679094 (1569898/1569931)
flutter: progress: 0.9999802539092483 (1569900/1569931)
flutter: progress: 1.0 (1569931/1569931)

As you can see it jumps from 0% to 100%. I can imagine you thinking, that is just fast internet. But I've tried Wifi, 4G, 3G and they all show the same issue. I hit the upload button, it start on 0% it jumps to 100% and then I have to wait some time (depending on the file size) for the upload to finish.

Is there a way to get more amount of onSendProgress callbacks triggered during the upload or somehow to delay the upload so I can get a smooth upload progress?

EDIT:

I've tried the following with the HTTP package

import 'dart:async';
import 'package:http/http.dart' as http;

class UploadRequest extends http.MultipartRequest {
  final void Function(int bytes, int totalBytes) onProgress;

  UploadRequest(
    String method,
    Uri url, {
    this.onProgress,
  }) : super(method, url);

  http.ByteStream finalize() {
    final byteStream = super.finalize();
    if (onProgress == null) return byteStream;

    final total = this.contentLength;

    final t = StreamTransformer.fromHandlers(
      handleData: (List<int> data, EventSink<List<int>> sink) {
        onProgress(data.length, total);
        sink.add(data);
      },
    );

    final stream = byteStream.transform(t);
    return http.ByteStream(stream);
  }
}

Trigger:

final request = UploadRequest(
  'PUT',
  Uri.parse(url),
  onProgress: (int bytes, int total) {
    print('progress: $progress ($sent/$total)');
  },
);

request.headers.addAll(headers);
request.files.add(
  http.MultipartFile.fromBytes(
    'file',
    attachment.file.buffer.asUint8List(),
    filename: attachment.name,
    contentType: MediaType.parse(attachment.contentType),
  ),
);

var response = await request.send();

But sadly, this has the same issue. The file uploads fine, but the progress callback is called only a few times. It hits 100% right away, then I have to wait a while (depending on the file size) before getting a 2xx response from the server. So I don't think this is a specific DIO issue.

I think that it looks like it is not actually showing the upload progress, but rather the progress of the file being read into a stream clientside. Then the stream is uploaded to the server and that is what you are waiting on (of course depending on the file size) even though the progress shows 100%.


问:
How to select rows which are evenly distributed on some column?
I have a table tbl with 3 columns imp_col, data1, data2 where imp_col's type is enum('imp1', 'imp2, 'imp3', 'imp4'). Now if I want to select 10 rows randomly I can do like this.
```<code>select imp_col, data1, data2 from tbl where imp_col in ('imp1', 'imp2', 'imp3') limit 10 order by rand();```But in this case all the 10 resulting rows may have imp_col as imp1.
Is there an SQL query which can return 10 rows with imp_col distributed evenly among imp1, imp2, imp3?
Thanks.

答:
You should try with

```<code>imp_col LIKE "imp1"
OR imp_col LIKE "imp2"
OR imp_col LIKE "imp3"
</code>```

I think IN doesn't works for enums

Body:
I have a table tbl with 3 columns imp_col, data1, data2 where imp_col's type is enum('imp1', 'imp2, 'imp3', 'imp4'). Now if I want to select 10 rows randomly I can do like this.

select imp_col, data1, data2 from tbl where imp_col in ('imp1', 'imp2', 'imp3') limit 10 order by rand();
But in this case all the 10 resulting rows may have imp_col as imp1.
Is there an SQL query which can return 10 rows with imp_col distributed evenly among imp1, imp2, imp3?
Thanks.

Body:
You should try with

imp_col LIKE "imp1"
OR imp_col LIKE "imp2"
OR imp_col LIKE "imp3"

I think IN doesn't works for enums


问:
Typescript local file class 'Cannot find module'
Having the below folder structure

```<code>- api
  - routes
    - meeting.ts
- models
  - DynamoService.ts
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": ".build",
    "strict": true,
    "baseUrl": "./",
    "typeRoots": ["node_modules/@types"],
    "types": ["node"],
    "esModuleInterop": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "allowJs": true,
    "moduleResolution": "node",
    "rootDir": "./",
    "removeComments": true,
    "noEmitOnError": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true
  },
  "exclude": ["node_modules"]
}
</code>```

DynamoService.ts

```<code>export class DynamoService {
...
}
</code>```

meeting.ts

```<code>import { DynamoService } from 'models/DynamoService'

const dynamoService = new DynamoService()

// other Express stuff...
</code>```

When testing this I receive the below runtime error

```<code>Error: Cannot find module 'models/DynamoService'
</code>```

Before trying to move the functionality into a class module having some DynamoDB helper methods in meeting.ts was working just fine.
Visual Studio Code doesn't complain about anything, no compile errors.

That should be a simple task but I seem to have trouble!

答:
There are two approaches to solve this problem.

Relative reference

You could simply change the import line like this:

import { DynamoService } from '../../models/DynamoService'
```

<h2>Typescript path alias</h2>

<p>Another convenient way is to leverage this nice TypeScript feature by configuring <code>paths</code> in <code>tsconfig.json</code>:</p>

```
{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
        "models/*": ["models/*"]
    },
}
```

See more in https://www.typescriptlang.org/tsconfig#paths or https://medium.com/slackernoon/use-typescript-aliases-to-clean-up-your-import-statements-7210b7ec2af1.

Body:
Having the below folder structure

- api
  - routes
    - meeting.ts
- models
  - DynamoService.ts

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": ".build",
    "strict": true,
    "baseUrl": "./",
    "typeRoots": ["node_modules/@types"],
    "types": ["node"],
    "esModuleInterop": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "allowJs": true,
    "moduleResolution": "node",
    "rootDir": "./",
    "removeComments": true,
    "noEmitOnError": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true
  },
  "exclude": ["node_modules"]
}

DynamoService.ts

export class DynamoService {
...
}

meeting.ts

import { DynamoService } from 'models/DynamoService'

const dynamoService = new DynamoService()

// other Express stuff...

When testing this I receive the below runtime error

Error: Cannot find module 'models/DynamoService'

Before trying to move the functionality into a class module having some DynamoDB helper methods in meeting.ts was working just fine.
Visual Studio Code doesn't complain about anything, no compile errors.

That should be a simple task but I seem to have trouble!

Body:
There are two approaches to solve this problem.

Relative reference

You could simply change the import line like this:

import { DynamoService } from '../../models/DynamoService'

Typescript path alias

Another convenient way is to leverage this nice TypeScript feature by configuring paths in tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
        "models/*": ["models/*"]
    },
}

See more in https://www.typescriptlang.org/tsconfig#paths or https://medium.com/slackernoon/use-typescript-aliases-to-clean-up-your-import-statements-7210b7ec2af1.