问:
Gradle Build fails with an exception for github repo
repo - https://github.com/sbaier1/avro-car-sensor-simulator

I am trying to build this github project but during the build it fails with an exception.

```<code>> Task :compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point  to the according directory.

* 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 ':compileJava'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:117)
        at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:184)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:110)
        at org.gradle.api.internal.tasks.execution.ResolveIncrementalChangesTaskExecuter.execute(ResolveIncrementalChangesTaskExecuter.java:84)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:91)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java: 74)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:109)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.j ava:67)
        at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTask Executer.java:46)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:93)
        at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:45)
        at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:94)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:46)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
        at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:33 6)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:32 2)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured yo ur JAVA_HOME system variable to point to the according directory.
        at org.gradle.api.internal.tasks.compile.JavaHomeBasedJavaCompilerFactory.create(JavaHomeBasedJavaCompilerFactory.java:45)
        at org.gradle.api.internal.tasks.compile.JavaHomeBasedJavaCompilerFactory.create(JavaHomeBasedJavaCompilerFactory.java:27)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.createCompileTask(JdkJavaCompiler.java:59)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:49)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:36)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:100)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:52)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:38)
        at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:51)
        at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:37)
        at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:39)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory$2.execute(IncrementalCompilerFactory.java:110)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory$2.execute(IncrementalCompilerFactory.java:106)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalResultStoringCompiler.execute(IncrementalResultStoringCompiler.java:59)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalResultStoringCompiler.execute(IncrementalResultStoringCompiler.java:43)
        at org.gradle.api.internal.tasks.compile.CompileJavaBuildOperationReportingCompiler$2.call(CompileJavaBuildOperationReportingCompiler.ja va:59)
        at org.gradle.api.internal.tasks.compile.CompileJavaBuildOperationReportingCompiler$2.call(CompileJavaBuildOperationReportingCompiler.ja va:51)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.api.internal.tasks.compile.CompileJavaBuildOperationReportingCompiler.execute(CompileJavaBuildOperationReportingCompiler.j ava:51)
        at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:154)
        at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:122)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:103)
        at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:73)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$4.run(ExecuteActionsTaskExecuter.java:338)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 402)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 394)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:327)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:312)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:75)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:158)
        at org.gradle.internal.execution.impl.steps.ExecuteStep.execute(ExecuteStep.java:46)
        at org.gradle.internal.execution.impl.steps.CancelExecutionStep.execute(CancelExecutionStep.java:34)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:69)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.execute(TimeoutStep.java:49)
        at org.gradle.internal.execution.impl.steps.CatchExceptionStep.execute(CatchExceptionStep.java:34)
        at org.gradle.internal.execution.impl.steps.CreateOutputsStep.execute(CreateOutputsStep.java:49)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:42)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:28)
        at org.gradle.internal.execution.impl.steps.CacheStep.executeWithoutCache(CacheStep.java:133)
        at org.gradle.internal.execution.impl.steps.CacheStep.lambda$execute$5(CacheStep.java:83)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:82)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:37)
        at org.gradle.internal.execution.impl.steps.PrepareCachingStep.execute(PrepareCachingStep.java:33)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:38)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:23)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:95)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:88)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36)
        at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:34)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:109)
        ... 37 more

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

BUILD FAILED in 1s
2 actionable tasks: 1 executed, 1 up-to-date
</code>```

I get the same error when  I run the script build-generator.sh or the following command

```<code>./gradlew build
</code>```

Output when I check gradle version

```<code>$ ./gradlew --version

------------------------------------------------------------
Gradle 5.2.1
------------------------------------------------------------

Build time:   2019-02-08 19:00:10 UTC
Revision:     f02764e074c32ee8851a4e1877dd1fea8ffb7183

Kotlin DSL:   1.1.3
Kotlin:       1.3.20
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          10.0.2 ("Oracle Corporation" 10.0.2+13)
OS:           Windows 10 10.0 amd64
</code>```

I have 0 experience with gradle so I dont know what I am doing wrong.

答:
The error is saying that I should check if I have the jdk and not just the jre.

I already had jdk installed but JAVA_HOME wasn't set. I set it to "C:/Program Files/Java/jdk" and that solved it.

Note - For this specific repo the Docker daemon needs to be running during the build process.

Body:
repo - https://github.com/sbaier1/avro-car-sensor-simulator

I am trying to build this github project but during the build it fails with an exception.

> Task :compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point  to the according directory.

* 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 ':compileJava'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:117)
        at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:184)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:110)
        at org.gradle.api.internal.tasks.execution.ResolveIncrementalChangesTaskExecuter.execute(ResolveIncrementalChangesTaskExecuter.java:84)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:91)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java: 74)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:109)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.j ava:67)
        at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTask Executer.java:46)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:93)
        at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:45)
        at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:94)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:46)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
        at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:33 6)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:32 2)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured yo ur JAVA_HOME system variable to point to the according directory.
        at org.gradle.api.internal.tasks.compile.JavaHomeBasedJavaCompilerFactory.create(JavaHomeBasedJavaCompilerFactory.java:45)
        at org.gradle.api.internal.tasks.compile.JavaHomeBasedJavaCompilerFactory.create(JavaHomeBasedJavaCompilerFactory.java:27)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.createCompileTask(JdkJavaCompiler.java:59)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:49)
        at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:36)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:100)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:52)
        at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:38)
        at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:51)
        at org.gradle.api.internal.tasks.compile.AnnotationProcessorDiscoveringCompiler.execute(AnnotationProcessorDiscoveringCompiler.java:37)
        at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:39)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory$2.execute(IncrementalCompilerFactory.java:110)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory$2.execute(IncrementalCompilerFactory.java:106)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalResultStoringCompiler.execute(IncrementalResultStoringCompiler.java:59)
        at org.gradle.api.internal.tasks.compile.incremental.IncrementalResultStoringCompiler.execute(IncrementalResultStoringCompiler.java:43)
        at org.gradle.api.internal.tasks.compile.CompileJavaBuildOperationReportingCompiler$2.call(CompileJavaBuildOperationReportingCompiler.ja va:59)
        at org.gradle.api.internal.tasks.compile.CompileJavaBuildOperationReportingCompiler$2.call(CompileJavaBuildOperationReportingCompiler.ja va:51)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.api.internal.tasks.compile.CompileJavaBuildOperationReportingCompiler.execute(CompileJavaBuildOperationReportingCompiler.j ava:51)
        at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:154)
        at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:122)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:103)
        at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:73)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$4.run(ExecuteActionsTaskExecuter.java:338)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 402)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java: 394)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:327)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:312)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:75)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:158)
        at org.gradle.internal.execution.impl.steps.ExecuteStep.execute(ExecuteStep.java:46)
        at org.gradle.internal.execution.impl.steps.CancelExecutionStep.execute(CancelExecutionStep.java:34)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:69)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.execute(TimeoutStep.java:49)
        at org.gradle.internal.execution.impl.steps.CatchExceptionStep.execute(CatchExceptionStep.java:34)
        at org.gradle.internal.execution.impl.steps.CreateOutputsStep.execute(CreateOutputsStep.java:49)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:42)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:28)
        at org.gradle.internal.execution.impl.steps.CacheStep.executeWithoutCache(CacheStep.java:133)
        at org.gradle.internal.execution.impl.steps.CacheStep.lambda$execute$5(CacheStep.java:83)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:82)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:37)
        at org.gradle.internal.execution.impl.steps.PrepareCachingStep.execute(PrepareCachingStep.java:33)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:38)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:23)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:95)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:88)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36)
        at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:34)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:109)
        ... 37 more

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

BUILD FAILED in 1s
2 actionable tasks: 1 executed, 1 up-to-date

I get the same error when  I run the script build-generator.sh or the following command

./gradlew build

Output when I check gradle version

$ ./gradlew --version

------------------------------------------------------------
Gradle 5.2.1
------------------------------------------------------------

Build time:   2019-02-08 19:00:10 UTC
Revision:     f02764e074c32ee8851a4e1877dd1fea8ffb7183

Kotlin DSL:   1.1.3
Kotlin:       1.3.20
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          10.0.2 ("Oracle Corporation" 10.0.2+13)
OS:           Windows 10 10.0 amd64

I have 0 experience with gradle so I dont know what I am doing wrong.


来源: stackexchange

问:
How can I activate multiple buttons in one slide gesture with SwiftUI?
I have 25 buttons laid out in a grid for a game like this.

I'm generating these buttons like this:

```<code>VStack {
  ForEach(1..<6) {_ in
    HStack {
      ForEach(1..<6) {_ in
        Button(action: {
          // Button clicked
          doButton()
        }) {
          Rectangle()
            .frame(width: 50, height: 50)
            .border(Color.black, lineWidth: 1)
        }
      }
    }
  }
}
</code>```

How can I make it so if the user drags their finger across multiple buttons, each one of the buttons are clicked, and doButton() is executed?

I tried using a DragGesture() but couldn't get it to work...

答:
Swift 5.1, iOS 13.

I don't have a 100% solution for you, but I do have something to get you off the ground hopefully. These are not buttons, but simply squares. As I click/drag across them they^ll signal I passed by.

It isn't perfect, but should give you some thing more to work with.
I read a tutorial on medium on doing something similar with drag and drop. This one.

Can help but think you'll need to do something with drag here and the Geometry reader ultimately, detecting where they are and responding to that.

```<code>import SwiftUI

struct ContentView: View {
var body: some View {
 return VStack {
  ForEach(1..<6) {colY in
    HStack {
      ForEach(1..<6) {rowX in
          boxView(row: rowX, col: colY)
        }
      }
    }
  }
}
}

struct boxView: View {
 @State var row: Int
 @State var col: Int
 var body: some View {
 let dragGesture = DragGesture(minimumDistance: 0, coordinateSpace: CoordinateSpace.global)
  .onChanged { (value) in
    print("trigger ",self.row,self.col)
  }
 return Rectangle()
    .stroke(Color.black)
    .frame(width: 50, height: 50)
    .gesture(dragGesture)
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 25 buttons laid out in a grid for a game like this.

I'm generating these buttons like this:

VStack {
  ForEach(1..<6) {_ in
    HStack {
      ForEach(1..<6) {_ in
        Button(action: {
          // Button clicked
          doButton()
        }) {
          Rectangle()
            .frame(width: 50, height: 50)
            .border(Color.black, lineWidth: 1)
        }
      }
    }
  }
}

How can I make it so if the user drags their finger across multiple buttons, each one of the buttons are clicked, and doButton() is executed?

I tried using a DragGesture() but couldn't get it to work...

Body:
Swift 5.1, iOS 13.

I don't have a 100% solution for you, but I do have something to get you off the ground hopefully. These are not buttons, but simply squares. As I click/drag across them they^ll signal I passed by.

It isn't perfect, but should give you some thing more to work with.
I read a tutorial on medium on doing something similar with drag and drop. This one.

Can help but think you'll need to do something with drag here and the Geometry reader ultimately, detecting where they are and responding to that.

import SwiftUI

struct ContentView: View {
var body: some View {
 return VStack {
  ForEach(1..<6) {colY in
    HStack {
      ForEach(1..<6) {rowX in
          boxView(row: rowX, col: colY)
        }
      }
    }
  }
}
}

struct boxView: View {
 @State var row: Int
 @State var col: Int
 var body: some View {
 let dragGesture = DragGesture(minimumDistance: 0, coordinateSpace: CoordinateSpace.global)
  .onChanged { (value) in
    print("trigger ",self.row,self.col)
  }
 return Rectangle()
    .stroke(Color.black)
    .frame(width: 50, height: 50)
    .gesture(dragGesture)
  }
}


问:
Reading several datasets
I need to read 8 datasets:

```<code>df01, df02, df03, df04, df05, df06, df07, df08
</code>```

This is my current approach:

```<code>#Set up file paths

filepath_2_df01= "folderX/df01.csv"
filepath_2_df02= "folderX//df02.csv"
filepath_2_df03= "folderX//df03.csv"
filepath_2_df04= "folderX//df04.csv"

filepath_2_df05= "folderY/df05.csv"
filepath_2_df06= "folderY/df06.csv"
filepath_2_df07= "folderY/df07.csv"
filepath_2_df08= "folderY/df08.csv"

#Read files

df01= pd.read_csv(filepath_2_df01)
df02= pd.read_csv(filepath_2_df02)
df03= pd.read_csv(filepath_2_df03)
df04= pd.read_csv(filepath_2_df04)

df05= pd.read_csv(filepath_2_df05)
df06= pd.read_csv(filepath_2_df06)
df07= pd.read_csv(filepath_2_df07)
df08= pd.read_csv(filepath_2_df08)
</code>```

Is there a more concise way of doing that?

答:
use glob</p>

```<code>from glob import glob

filenames = glob('/**/df*.csv') #get list of filenames, starting with df, in a specific folder. ** will search for subfolders as well(folderX and folderY, in your case)

dataframes = [pd.read_csv(f) for f in filenames] # using list comprehension, get a list of dataframes.
master_df = pd.concat(dataframes) #Concatenate list of dataframes to get a master dataframe
</code>```

Title: Reading several datasets

Body:
I need to read 8 datasets:

df01, df02, df03, df04, df05, df06, df07, df08

This is my current approach:

#Set up file paths

filepath_2_df01= "folderX/df01.csv"
filepath_2_df02= "folderX//df02.csv"
filepath_2_df03= "folderX//df03.csv"
filepath_2_df04= "folderX//df04.csv"

filepath_2_df05= "folderY/df05.csv"
filepath_2_df06= "folderY/df06.csv"
filepath_2_df07= "folderY/df07.csv"
filepath_2_df08= "folderY/df08.csv"

#Read files

df01= pd.read_csv(filepath_2_df01)
df02= pd.read_csv(filepath_2_df02)
df03= pd.read_csv(filepath_2_df03)
df04= pd.read_csv(filepath_2_df04)

df05= pd.read_csv(filepath_2_df05)
df06= pd.read_csv(filepath_2_df06)
df07= pd.read_csv(filepath_2_df07)
df08= pd.read_csv(filepath_2_df08)

Is there a more concise way of doing that?

Body:
use glob

from glob import glob

filenames = glob('/**/df*.csv') #get list of filenames, starting with df, in a specific folder. ** will search for subfolders as well(folderX and folderY, in your case)

dataframes = [pd.read_csv(f) for f in filenames] # using list comprehension, get a list of dataframes.
master_df = pd.concat(dataframes) #Concatenate list of dataframes to get a master dataframe


问:
LocalDateTime format with time zone and milliseconds
I'm trying to write a DateTimeFormatter to parse the following format:

```<code>2020-05-29T07:51:33.106-07:00
</code>```

I have looked at ISO_OFFSET_DATE_TIME, but the problem is it does not contain milliseconds. So I decided to write on my own.

It is easy to do so without timezone:

```<code>public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106", formatter)
    );
}
</code>```

It works just fine

But when I tried to add a timezone in the format as

```<code>public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106-07:00", formatter)
    );
}
</code>```

It now fails with an exception that the timezone is unable to be parsed.

```<code>Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-05-29T07:51:33.106-07:00' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Ideone.main(Main.java:16)
</code>```

How to parse a timezone in such a format?

答:
tl;dr

No need to define a formatter.

```<code>OffsetDateTime.parse( "2020-05-29T07:51:33.106-07:00" )
</code>```

Details

The Answer by Jim Garrison is correct. In addition, you are using the wrong class.

The LocalDateTime class represents only a date with a time-of-day, nothing more. This class purposely lacks any concept of time zone or offset-from-UTC. As such, this class cannot represent a moment, is not a point on the timeline.

So, parsing a string with an offset, the -07:00 on the end, as a LocalDateTime does not make sense. The valuable information of offset will be ignored, discarded.

Instead, parse as an OffsetDateTime.

Bonus: Your entire formatter issue becomes moot. Your input string complies with the standard ISO 8601 format used by default in the OffsetDateTime class when parsing/generating strings. No need for you to define any custom formatting pattern at all.

```<code>OffsetDateTime.parse( "2020-05-29T07:51:33.106-07:00" )
</code>```

…and:

```<code>myOffsetDateTime.toString()
</code>```

You said:

But when I tried to add a timezone

No, you added an offset-from-UTC, not a time zone, with your string -07:00.

An offset is merely a number of hours-minutes-seconds ahead or behind the prime meridian.

A time zone is much more. A time zone has a name such as
America/Edmonton. A time zone has a history of the past, present,
and future changes to the offset in the wall-clock time used by the
people of a particular region.

Body:
I'm trying to write a DateTimeFormatter to parse the following format:

2020-05-29T07:51:33.106-07:00

I have looked at ISO_OFFSET_DATE_TIME, but the problem is it does not contain milliseconds. So I decided to write on my own.

It is easy to do so without timezone:

public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106", formatter)
    );
}

It works just fine

But when I tried to add a timezone in the format as

public static void main (String[] args) throws java.lang.Exception {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    System.out.println(
        LocalDateTime.parse("2020-05-29T07:51:33.106-07:00", formatter)
    );
}

It now fails with an exception that the timezone is unable to be parsed.

Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-05-29T07:51:33.106-07:00' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Ideone.main(Main.java:16)

How to parse a timezone in such a format?

Body:
tl;dr

No need to define a formatter.

OffsetDateTime.parse( "2020-05-29T07:51:33.106-07:00" )

Details

The Answer by Jim Garrison is correct. In addition, you are using the wrong class.

The LocalDateTime class represents only a date with a time-of-day, nothing more. This class purposely lacks any concept of time zone or offset-from-UTC. As such, this class cannot represent a moment, is not a point on the timeline.

So, parsing a string with an offset, the -07:00 on the end, as a LocalDateTime does not make sense. The valuable information of offset will be ignored, discarded.

Instead, parse as an OffsetDateTime.

Bonus: Your entire formatter issue becomes moot. Your input string complies with the standard ISO 8601 format used by default in the OffsetDateTime class when parsing/generating strings. No need for you to define any custom formatting pattern at all.

OffsetDateTime.parse( "2020-05-29T07:51:33.106-07:00" )

…and:

myOffsetDateTime.toString()

You said:

But when I tried to add a timezone

No, you added an offset-from-UTC, not a time zone, with your string -07:00.

An offset is merely a number of hours-minutes-seconds ahead or behind the prime meridian.

A time zone is much more. A time zone has a name such as
America/Edmonton. A time zone has a history of the past, present,
and future changes to the offset in the wall-clock time used by the
people of a particular region.


问:
how to get the image inserted from the tinymce editor?
I am trying to use the tinymce text editor, but am not being able to get the contents of the editor using jQuery , and also if I use the simple post method to get the value I get the text, but am not getting the image?

The code I tried using jQuery was:

```<code>$(document).ready(function()
{
    $("#save").click(function()
    {
        $.post("test_skin_dump.php",{
            data_info:$("#elm2").html;
        } ,function(data) {
            if(data)
            {
                $("#show_result").html(data);
            }
        });
    });
});

<textarea id="elm2" name="elm2" rows="15" cols="80" style="width: 80%">
</textarea>
</code>```

What am I doing wrong could anybody correct me, please?

答:
Use the following Command to Inset the Code into your editor:

```<code>tinyMCE.execCommand('mceInsertContent',false,'<img src="mypic.png" />');
</code>```

Hope this Helps :)

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use the tinymce text editor, but am not being able to get the contents of the editor using jQuery , and also if I use the simple post method to get the value I get the text, but am not getting the image?

The code I tried using jQuery was:

$(document).ready(function()
{
    $("#save").click(function()
    {
        $.post("test_skin_dump.php",{
            data_info:$("#elm2").html;
        } ,function(data) {
            if(data)
            {
                $("#show_result").html(data);
            }
        });
    });
});

<textarea id="elm2" name="elm2" rows="15" cols="80" style="width: 80%">
</textarea>

What am I doing wrong could anybody correct me, please?

Body:
Use the following Command to Inset the Code into your editor:

tinyMCE.execCommand('mceInsertContent',false,'<img src="mypic.png" />');

Hope this Helps :)

ContentLicense: CC BY-SA 3.0


问:
Extracting fields from a url in scala-js
Suppose I've a url like :

```<code>https://example.com/myproject/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
</code>```

or it may be a webpage on localhost like :

```<code>localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
</code>```

and I've to extract query fields (appearing after '?') from these urls in 2-D array as following :

```<code>_ijt    |    hsdlgh8h5g8hh489sajoej
a       |    102
b       |    a m
c       |    45
d       |    all
e       |    all
</code>```

Please do note that in 'b' field, I've replaced '%20' with a space. These fields like _ijt,a,b,c,d,e etc can vary in number and their names eg 'a' can be 'city'.
So far I've used regular expression to extract out the part after '?' and then use split("&") method to split the string into multiple strings.
Code -

```<code>val url=localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
val pattern="""(http|htpps)([A-Za-z0-9\:\/\%\-\.]*)\?""".r
val temp_url=pattern.replaceFirstIn(url,"")
val fields=temp_url.split("&")
println(fields.foreach(println))
</code>```

and the output is :

```<code>_ijt=hsdlgh8h5g8hh489sajoej
a=102
b=a%20m
c=45
d=all
e=all
</code>```

But it doesn't seem to be the correct way to do this. Any help ?

答:
Use this scala / scalajs library:
https://github.com/lemonlabsuk/scala-uri</p>

```<code>import io.lemonlabs.uri.Url

val uri = Url.parse("http://example.com/path?a=b&a=c&d=e")
uri.query.paramMap // This is: Map("a" -> Vector("b", "c"), "d" -> Vector("e"))
</code>```

Body:
Suppose I've a url like :

https://example.com/myproject/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all

or it may be a webpage on localhost like :

localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all

and I've to extract query fields (appearing after '?') from these urls in 2-D array as following :

_ijt    |    hsdlgh8h5g8hh489sajoej
a       |    102
b       |    a m
c       |    45
d       |    all
e       |    all

Please do note that in 'b' field, I've replaced '%20' with a space. These fields like _ijt,a,b,c,d,e etc can vary in number and their names eg 'a' can be 'city'.
So far I've used regular expression to extract out the part after '?' and then use split("&") method to split the string into multiple strings.
Code -

val url=localhost:63342/my project/index-dev.html?_ijt=hsdlgh8h5g8hh489sajoej&a=102&b=a%20m&c=45&d=all&e=all
val pattern="""(http|htpps)([A-Za-z0-9\:\/\%\-\.]*)\?""".r
val temp_url=pattern.replaceFirstIn(url,"")
val fields=temp_url.split("&")
println(fields.foreach(println))

and the output is :

_ijt=hsdlgh8h5g8hh489sajoej
a=102
b=a%20m
c=45
d=all
e=all

But it doesn't seem to be the correct way to do this. Any help ?

Body:
Use this scala / scalajs library:
https://github.com/lemonlabsuk/scala-uri

import io.lemonlabs.uri.Url

val uri = Url.parse("http://example.com/path?a=b&a=c&d=e")
uri.query.paramMap // This is: Map("a" -> Vector("b", "c"), "d" -> Vector("e"))


问:
Macro to ensure all cells in a table row are filled in
I have a table in Excel and I want to make sure that if a user fills in at least one cell in a row, that they must fill in all the other cells in the row as well.

I've tried to create VBA Code for it below. Basically, it is saying, that if any field in row 7 of my table has something filled in, then check if the first cell in the table has a blank. I will copy/paste the code so it checks if the other cells in the row are filled in as well.

When I try to run this, it says "Object Doesn't Support this Property or Method". Can someone help me please?

```<code>Sub blank()
If Range("H7:Q7").CountA >= 1 Then
    If Cells(7, 8).Value = "" Then
MsgBox "Condition Type cannot be blank"
'I will repeat for the other columns in the row as well.
    End If
End If
End Sub
</code>```

Table

答:
You have the right idea; here is the correct syntax:</p>

```<code>If Application.WorksheetFunction.CountA(Range("H7:Q7")) > 0 Then
    MsgBox "something is there"
End If
</code>```

Body:
I have a table in Excel and I want to make sure that if a user fills in at least one cell in a row, that they must fill in all the other cells in the row as well.

I've tried to create VBA Code for it below. Basically, it is saying, that if any field in row 7 of my table has something filled in, then check if the first cell in the table has a blank. I will copy/paste the code so it checks if the other cells in the row are filled in as well.

When I try to run this, it says "Object Doesn't Support this Property or Method". Can someone help me please?

Sub blank()
If Range("H7:Q7").CountA >= 1 Then
    If Cells(7, 8).Value = "" Then
MsgBox "Condition Type cannot be blank"
'I will repeat for the other columns in the row as well.
    End If
End If
End Sub

Table

Body:
You have the right idea; here is the correct syntax:

If Application.WorksheetFunction.CountA(Range("H7:Q7")) > 0 Then
    MsgBox "something is there"
End If


问:
Compiled c# file not opening when double clicked
I compile my .cs file to .exe in cmd and it works fine and i can run it.
But when i open it by double clicking it opens cmd for a split second then closes, how can i make it actually work?
I tried to find solutions but didnt find any</p>

答:
Your application closes when it reaches it's end.
Let's take this as an example:

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");
    }
}
</code>```

After printing Hello world! there is nothing left to execute so it closes. It work's from cmd because after the program closes, it exits back to cmd and you can still see what your program did. If you want keep your program open you have to stop it from reaching the end of Main (in this case). You can do this by waiting for the user to press enter with Console.ReadLine(), this way the application will only exit after the user pressed enter.

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");
        Console.ReadLine();
    }
}
</code>```

If you want to keep it open until it's closed you can try freezing the main thread with Thread.Sleep(-1)

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");
        Thread.Sleep(-1);
    }
}
</code>```

For this you need to have using System.Threading; at the top.

Body:
Your application closes when it reaches it's end.
Let's take this as an example:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");
    }
}

After printing Hello world! there is nothing left to execute so it closes. It work's from cmd because after the program closes, it exits back to cmd and you can still see what your program did. If you want keep your program open you have to stop it from reaching the end of Main (in this case). You can do this by waiting for the user to press enter with Console.ReadLine(), this way the application will only exit after the user pressed enter.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");
        Console.ReadLine();
    }
}

If you want to keep it open until it's closed you can try freezing the main thread with Thread.Sleep(-1)

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello world!");
        Thread.Sleep(-1);
    }
}

For this you need to have using System.Threading; at the top.


问:
Share website URL with image and description preview on LinkedIn
I'm trying to share URL on LinkedIn, but it doesn't picking my website description, title and image .

I have tried these methods for sharing but none of these are working.

Share Method 1

Share Method 2

Second seems work for me but it does not pick image. What am I doing wrong here?

Js Fiddle

答:
LinkedIn only supports one URL format...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Sharing Documentation.

But if you want to populate things like title and image in the preview of the share page, then you need to use og: tags.  Insert these into the  block your HTML...

<meta property="og:title" content="Title of the article"/>

<meta property="og:image" content="//media.example.com/ 1234567.jpg"/>

<meta property="og:description" content="Description that will show in the preview"/>

<meta property="og:url" content="//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

If you're not sure, then you can always consult the LinkedIn Post Inspector.

Body:
LinkedIn only supports one URL format...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Sharing Documentation.

But if you want to populate things like title and image in the preview of the share page, then you need to use og: tags.  Insert these into the <head> block your HTML...

<meta property="og:title" content="Title of the article"/>

<meta property="og:image" content="//media.example.com/ 1234567.jpg"/>

<meta property="og:description" content="Description that will show in the preview"/>

<meta property="og:url" content="//www.example.com/URL of the article" />

Source: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

If you're not sure, then you can always consult the LinkedIn Post Inspector.


问:
Can't get text values using XPATH in python
I'm trying to parse currencies from this bank website. In code:

```<code>import requests
import time
import logging
from retrying import retry
from lxml import html

logging.basicConfig(filename='info.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

@retry(wait_fixed=5000)
def fetch_data_from_nb_ved_ru():
try:
    page = requests.get('http://www.nbu.com/exchange_rates')
    #print page.text
    tree = (html.fromstring(page.text))
    #fetched_ved_usd_buy = tree.xpath('//div[@class="exchangeRates"]/table/tbody/tr[5]/td[5]')
    fetched_ved_usd_buy = tree.xpath('/html/body/div[1]/div//div[7]/div/div/div[1]//text()')
    print fetched_ved_usd_buy
    fetched_ved_usd_sell = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[6]/td[6]/text()')).strip()
    fetched_ved_eur_buy = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[7]/td[5]/text()')).strip()
    fetched_ved_eur_sell = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[7]/td[6]/text()')).strip()
    fetched_cb_eur = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[7]/td[4]/text()')).strip()
    fetched_cb_rub = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[18]/td[4]/text()')).strip()
    fetched_cb_usd = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[6]/td[4]/text()')).strip()
except:
    logging.warning("NB VED UZ fetch failed")
    raise IOError("NB VED UZ  fetch failed")
return fetched_ved_usd_buy, fetched_ved_usd_sell, fetched_cb_usd, fetched_ved_eur_buy, fetched_ved_eur_sell,\
    fetched_cb_eur, fetched_cb_rub

while True:
    f = open('values_uzb.txt', 'w')
    ved_usd_buy, ved_usd_sell, cb_usd, ved_eur_buy, ed_eur_sell, cb_eur, cb_rub = fetch_data_from_nb_ved_ru()
               f.write(str(ved_usd_buy)+'\n'+str(ved_usd_sell)+'\n'+str(cb_usd)+'\n'+str(ved_eur_buy)+'\n'+str(ed_eur_sell)+'\n'
        + str(cb_eur)+'\n'+str(cb_rub))

    f.close()
    time.sleep(120)
</code>```

But it always returns empty string, however if I do print page.text, i can see that the values are on their's places.
I got that xpath from firebug. Chrome gives the same xpath.
Tried to construct own xpath
//div[@class="exchangeRates"]/table/tbody/tr[5]/td[5]
but it happens to be not valid to.

Any suggestions?
Thanks.

答:
I use the following statement, which runs perfectly fine for me.</p>
```<code>ActualValue = driver.find_element_by_xpath("//div/div[2]/div").text
</code>```

Body:
I'm trying to parse currencies from this bank website. In code:

import requests
import time
import logging
from retrying import retry
from lxml import html

logging.basicConfig(filename='info.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

@retry(wait_fixed=5000)
def fetch_data_from_nb_ved_ru():
try:
    page = requests.get('http://www.nbu.com/exchange_rates')
    #print page.text
    tree = (html.fromstring(page.text))
    #fetched_ved_usd_buy = tree.xpath('//div[@class="exchangeRates"]/table/tbody/tr[5]/td[5]')
    fetched_ved_usd_buy = tree.xpath('/html/body/div[1]/div//div[7]/div/div/div[1]//text()')
    print fetched_ved_usd_buy
    fetched_ved_usd_sell = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[6]/td[6]/text()')).strip()
    fetched_ved_eur_buy = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[7]/td[5]/text()')).strip()
    fetched_ved_eur_sell = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[7]/td[6]/text()')).strip()
    fetched_cb_eur = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[7]/td[4]/text()')).strip()
    fetched_cb_rub = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[18]/td[4]/text()')).strip()
    fetched_cb_usd = str(tree.xpath('/html/body/div[1]/div/div[7]/div/div/div[1]/table/tbody/tr[6]/td[4]/text()')).strip()
except:
    logging.warning("NB VED UZ fetch failed")
    raise IOError("NB VED UZ  fetch failed")
return fetched_ved_usd_buy, fetched_ved_usd_sell, fetched_cb_usd, fetched_ved_eur_buy, fetched_ved_eur_sell,\
    fetched_cb_eur, fetched_cb_rub

while True:
    f = open('values_uzb.txt', 'w')
    ved_usd_buy, ved_usd_sell, cb_usd, ved_eur_buy, ed_eur_sell, cb_eur, cb_rub = fetch_data_from_nb_ved_ru()
               f.write(str(ved_usd_buy)+'\n'+str(ved_usd_sell)+'\n'+str(cb_usd)+'\n'+str(ved_eur_buy)+'\n'+str(ed_eur_sell)+'\n'
        + str(cb_eur)+'\n'+str(cb_rub))

    f.close()
    time.sleep(120)

But it always returns empty string, however if I do print page.text, i can see that the values are on their's places.
I got that xpath from firebug. Chrome gives the same xpath.
Tried to construct own xpath
//div[@class="exchangeRates"]/table/tbody/tr[5]/td[5]
but it happens to be not valid to.

Any suggestions?
Thanks.

Body:
I use the following statement, which runs perfectly fine for me.

ActualValue = driver.find_element_by_xpath("//div/div[2]/div").text


问:
autocomplete html tags in strings in Visual Studio code?
Is this possible in Visual Studio? I'm following a Wes Bos tutorial and while he's typing html in backticks (therefore in a string) in javascript, the html end tags autocomplete. </p>

答:
Are you looking for this extension ?

It allows syntax highlighting and auto completion inside tagged template strings.


问:
Convert two df cols to dict on python
I have this df:

```<code>Id  count
A1    3
A2    4
A3    5
</code>```

And I want to convert it to a dict where 'Id' is the keys and 'count' the values:

```<code>dict = {'A1': 3, 'A2': 4, 'A3': 5}
</code>```

How can I do that?

答:
You can use zip here.

```<code>dict(zip(df['Id'],df['count']))

# {'A1': 3, 'A2': 4, 'A3': 5}
</code>```

Title: Convert two df cols to dict on python

Body:
I have this df:

Id  count
A1    3
A2    4
A3    5

And I want to convert it to a dict where 'Id' is the keys and 'count' the values:

dict = {'A1': 3, 'A2': 4, 'A3': 5}

How can I do that?

Body:
You can use zip here.

dict(zip(df['Id'],df['count']))

# {'A1': 3, 'A2': 4, 'A3': 5}


问:
How to annotate ReactJS State-full "class" Component props using JSDocs
How can I annotate the props in state-full "class" ReactJS components In order to get autocompletion inside render()?
I tried the following however, it did not work:

```<code>  export default class MyComponent extends Component {

  /**
   * @param {object} props
   * @param {object} props.survey
   * @param {string} props.survey.name
   */
  constructor(props){
    super(props)
    // autocompletion works here
 }

  render() {
    // autocompletion does not work here

    return (
     console.log(this.props.survey.name)
    );
  }
}
</code>```

答:
```<code>  /**
   * @typedef {object} props
   * @property {object} survey
   * @property {string} survey.name
   * @extends {Component<props>}
   */
  export default class MyComponent extends Component {

  constructor(props){
    super(props)
    // autocompletion works here
 }

  render() {
    // autocompletion should work here
    const {survey} = this.props;
    return (
     console.log(survey.name)
    );
  }
}
</code>```

Body:
How can I annotate the props in state-full "class" ReactJS components In order to get autocompletion inside render()?
I tried the following however, it did not work:

  export default class MyComponent extends Component {

  /**
   * @param {object} props
   * @param {object} props.survey
   * @param {string} props.survey.name
   */
  constructor(props){
    super(props)
    // autocompletion works here
 }

  render() {
    // autocompletion does not work here

    return (
     console.log(this.props.survey.name)
    );
  }
}


问:
Verilog "not a constant" error on bit-rotation
I have this block of code. I am trying to rotate WNext by the lower 4 bits of data_fromRAM.

```<code>input clk, rst;

input wire [15:0] data_fromRAM;
output reg [15:0] data_toRAM;
output reg wrEn;

// 12 can be made smaller so that it fits in the FPGA
output reg [12:0] addr_toRAM;
output reg [12:0] PC; // This has been added as an output for TB purposes
output reg [15:0] W; // This has been added as an output for TB purposes

reg [12:0] PCNext;
reg [ 2:0] opcode, opcodeNext,state, stateNext;
reg [12:0] operand, operandNext;
reg [15:0] num, numNext, WNext;

always @*begin
    WNext = W;
    PCNext = PC;
    stateNext    = state;
    opcodeNext   = opcode;
    operandNext = operand;
    numNext     = num;
    addr_toRAM   = 0;
    wrEn         = 0;
    data_toRAM   = 0;
//here I have if(rst)
else
    case(state)
//other cases
        2: begin
            PCNext = PC + 1;
            WNext = W;
            opcodeNext   = opcode;
            operandNext = operand;
            addr_toRAM   = 0;
            numNext     = data_fromRAM;
            wrEn         = 0;
            data_toRAM   = 0;
            stateNext    = 0;
            case (opcodeNext)
                ... //I excluded other cases
                3'b010: begin //SRRL
                    if(data_fromRAM < 16) WNext = W >> data_fromRAM;
                    else if (data_fromRAM > 16 & data_fromRAM < 31) WNext = W << data_fromRAM[3:0];
                    else if (data_fromRAM > 32 & data_fromRAM > 47) WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]};
                    else WNext = {W[15 - data_fromRAM[3:0]:0], W[15:16 - data_fromRAM[3:0]]};
                end
</code>```

But I am getting the error:

data_fromRAM is not a constant.

How can I fix this error? Is there a way to copy data_fromRAM into a constant variable and then do the operations? Or should I take a different approach?

Note: output reg [15:0] datatoRAM;

edit : If data_fromRAM = 40, then with this line: WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]}; I am trying to rotate WNext right with the four least significant bits of data_fromRAM. 40 is equal to 101000 in binary and the four lowest bits give us 1000 which is 8 in decimal. So I will rotate WNext right by 8 bits and what I mean by rotate is basically shifting but new bits are the ones we were going to lose if we only did the shifting (eg. rotate 1000110 by 3 = 1101000)

If data_fromRAM is greater than 47, again I want to rotate WNext but this time left rather than right (again it's rotating by lowest four bits of data_fromRAM). So again, as in shifting, I want to move all the values to the left but the bits that are coming from right are the ones that were lost from left when shifting.

答:
As the error message shows, you need to have a constant value for the bit select expression. The expression within the outer brackets must be a constant at elaboration/compile time:

```<code>W[15 - data_fromRAM[3:0]:0]
</code>```

You can not copy the variable data_fromRAM into a constant.

I believe you need a different approach, but it is difficult to know what you are trying to do from the little that you have shown.

Also, this is a bug:

```<code>else if (data_fromRAM > 32 & data_fromRAM > 47)
</code>```

I think you meant to use < 47:

```<code>else if (data_fromRAM > 32 & data_fromRAM < 47)
</code>```

I think you want to change:

```<code>WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]};
</code>```

to:

```<code>WNext = (W >> data_fromRAM[3:0]) | (W << (16-data_fromRAM[3:0]));
</code>```

And change:

```<code>WNext = {W[15 - data_fromRAM[3:0]:0], W[15:16 - data_fromRAM[3:0]]};
</code>```

to:

```<code>WNext = (W << data_fromRAM[3:0]) | (W >> (16-data_fromRAM[3:0]));
</code>```

I leveraged the idea from this answer.

Body:
I have this block of code. I am trying to rotate WNext by the lower 4 bits of data_fromRAM.

input clk, rst;

input wire [15:0] data_fromRAM;
output reg [15:0] data_toRAM;
output reg wrEn;

// 12 can be made smaller so that it fits in the FPGA
output reg [12:0] addr_toRAM;
output reg [12:0] PC; // This has been added as an output for TB purposes
output reg [15:0] W; // This has been added as an output for TB purposes

reg [12:0] PCNext;
reg [ 2:0] opcode, opcodeNext,state, stateNext;
reg [12:0] operand, operandNext;
reg [15:0] num, numNext, WNext;

always @*begin
    WNext = W;
    PCNext = PC;
    stateNext    = state;
    opcodeNext   = opcode;
    operandNext = operand;
    numNext     = num;
    addr_toRAM   = 0;
    wrEn         = 0;
    data_toRAM   = 0;
//here I have if(rst)
else
    case(state)
//other cases
        2: begin
            PCNext = PC + 1;
            WNext = W;
            opcodeNext   = opcode;
            operandNext = operand;
            addr_toRAM   = 0;
            numNext     = data_fromRAM;
            wrEn         = 0;
            data_toRAM   = 0;
            stateNext    = 0;
            case (opcodeNext)
                ... //I excluded other cases
                3'b010: begin //SRRL
                    if(data_fromRAM < 16) WNext = W >> data_fromRAM;
                    else if (data_fromRAM > 16 & data_fromRAM < 31) WNext = W << data_fromRAM[3:0];
                    else if (data_fromRAM > 32 & data_fromRAM > 47) WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]};
                    else WNext = {W[15 - data_fromRAM[3:0]:0], W[15:16 - data_fromRAM[3:0]]};
                end

But I am getting the error:

data_fromRAM is not a constant.

How can I fix this error? Is there a way to copy data_fromRAM into a constant variable and then do the operations? Or should I take a different approach?

Note: output reg [15:0] datatoRAM;

edit : If data_fromRAM = 40, then with this line: WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]}; I am trying to rotate WNext right with the four least significant bits of data_fromRAM. 40 is equal to 101000 in binary and the four lowest bits give us 1000 which is 8 in decimal. So I will rotate WNext right by 8 bits and what I mean by rotate is basically shifting but new bits are the ones we were going to lose if we only did the shifting (eg. rotate 1000110 by 3 = 1101000)

If data_fromRAM is greater than 47, again I want to rotate WNext but this time left rather than right (again it's rotating by lowest four bits of data_fromRAM). So again, as in shifting, I want to move all the values to the left but the bits that are coming from right are the ones that were lost from left when shifting.

Body:
As the error message shows, you need to have a constant value for the bit select expression. The expression within the outer brackets must be a constant at elaboration/compile time:

W[15 - data_fromRAM[3:0]:0]

You can not copy the variable data_fromRAM into a constant.

I believe you need a different approach, but it is difficult to know what you are trying to do from the little that you have shown.

Also, this is a bug:

else if (data_fromRAM > 32 & data_fromRAM > 47)

I think you meant to use < 47:

else if (data_fromRAM > 32 & data_fromRAM < 47)

I think you want to change:

WNext = {W[data_fromRAM[3:0] - 1:0], W[15:data_fromRAM[3:0]]};

to:

WNext = (W >> data_fromRAM[3:0]) | (W << (16-data_fromRAM[3:0]));

And change:

WNext = {W[15 - data_fromRAM[3:0]:0], W[15:16 - data_fromRAM[3:0]]};

to:

WNext = (W << data_fromRAM[3:0]) | (W >> (16-data_fromRAM[3:0]));

I leveraged the idea from this answer.


问:
HDFS File Compaction with continuous ingestion
We have few tables in HDFS which are getting approx. 40k new files per day. We need to compact these tables every two weeks and for that we need to stop ingestion.

We have spark ingestion getting data from kafka and adding to HDFS (Hive external tables) every 30 mins. The data is queried as soon as it is ingested, our SLA is less than an hour so we can not increase the batch interval.

The tables are partition on two fields, we get older data constantly so most of the partitions are updated during each injection batch

eg:
/user/head/warehouse/main_table/state=CA/store=macys/part-00000-017258f8-aaa-bbb-ccc-wefdsds.c000.snappy.parquet

We are looking into ways to reduce number of file creations but even with that we will have to do compaction every 3/4 weeks if not two.

As most of the partitions are updated constantly, we need to stop the injection (~ 1 day) before starting compaction which is impacting our users.

I am looking for ways to compact automatically with out stopping the ingestion?

答:
Thank you Facha for your suggestions, really appreciate it.

I am pretty new to HDFS concept so please dont mind basic questions,

What would be the impact on running queries which are accessing these specific files while doing swapping of uncompacted files with compacted files (alter table ... partition ... set location). I believe that the queries might fail. Who can we minimize the impact?

Copy a partition's hdfs directory to a different location

As we have two partitions in one table, state and store, will I have to iterate through each sub partition?

/tableName/state=CA/store=macys/file1.parquet
/tableName/state=CA/store=macys/file2.parquet

/tableName/state=CA/store=JCP/file2.parquet
/tableName/state=CA/store=JCP/file2.parquet

/tableName/state=NY/store=macys/file1.parquet
/tableName/state=NY/store=macys/file2.parquet

/tableName/state=NY/store=JCP/file2.parquet
/tableName/state=NY/store=JCP/file2.parquet

```<code>For each state
    for each store
        get list of files in this dir to replace later
        compact
            /tableName/state=$STATE/store=$STORE (SPARK JOb?)
        replace uncompacted files with compacted files
        alter table ... partition ... set location
</code>```

I would prefer your other suggestion in step 5 " just as well replace the "small" files in the original partition location with their compacted version"

How would I go ahead with implementing it, will it be best done with scripting or scala or some other programing language. I have basic knowledge of scripting, good experiencs in java and new to scala but can learn in couple of days.

Regards,
P

Body:
Thank you Facha for your suggestions, really appreciate it.

I am pretty new to HDFS concept so please dont mind basic questions,

What would be the impact on running queries which are accessing these specific files while doing swapping of uncompacted files with compacted files (alter table ... partition ... set location). I believe that the queries might fail. Who can we minimize the impact?

Copy a partition's hdfs directory to a different location

As we have two partitions in one table, state and store, will I have to iterate through each sub partition?

/tableName/state=CA/store=macys/file1.parquet
/tableName/state=CA/store=macys/file2.parquet

/tableName/state=CA/store=JCP/file2.parquet
/tableName/state=CA/store=JCP/file2.parquet

/tableName/state=NY/store=macys/file1.parquet
/tableName/state=NY/store=macys/file2.parquet

/tableName/state=NY/store=JCP/file2.parquet
/tableName/state=NY/store=JCP/file2.parquet

For each state
    for each store
        get list of files in this dir to replace later
        compact
            /tableName/state=$STATE/store=$STORE (SPARK JOb?)
        replace uncompacted files with compacted files
        alter table ... partition ... set location

I would prefer your other suggestion in step 5 " just as well replace the "small" files in the original partition location with their compacted version"

How would I go ahead with implementing it, will it be best done with scripting or scala or some other programing language. I have basic knowledge of scripting, good experiencs in java and new to scala but can learn in couple of days.

Regards,
P


答:
I think it's</p>

```<code>result = dict(zip(df['Id'], df['count']))
</code>```

Title: Convert two df cols to dict on python

Body:
I think it's

result = dict(zip(df['Id'], df['count']))


问:
How can I get/install Source Insight in Ubuntu
I use Source Insight in Windows, but now I use Ubuntu and I can't find a version of Source Insight for Linux.

What can I do?

I use Source Insight to look the Linux core source code.  It is a good IDE.

答: Source Insight works perfect under wine on x86/64_x86 Linux.</p>


问:
Remove unstaged files from merge
i have two branches, one more updated than other one and I want to merge into the outdated one the updated but only the commits that don't cause conflicts.
When I do the merge and try to checkout the unstaged files it says 'warning: path "my file" is unmerged' and i want to merge anyways, how can i do that?</p>

答:
Let's call your branches outdated and updated. I'm assuming you want to do the merge of updated into outdated without merging the conflicted files but somehow keeping your updated branch's version of them. So:

Get on outdated. Attempt the merge of updated.

Git emits a list of conflicting files.

Write down their pathnames.

Abort the merge.

Get back on updated. Copy the conflicting files to a place of greater safety (outside this worktree).

Checkout, from outdated, the conflicting files, thus overwriting the conflicting files in updated with versions of those files that do not conflict because they are identical.

Get back on outdated and do the merge.

Get back on updated and copy the conflicting files back into the worktree.

Title: Remove unstaged files from merge


问:
click, getElementByClassName etc with for() not working
I am a Javascript beginner and am trying to solve a problem here. I don't find the mistake.

I try that the ID and the class variants work. The click and the message does not work.

java script

let click = document.querySelectorAll('.trigger');

let messageAllClass = document.querySelectorAll('.messageAllClass');
let messageClass = document.getElementByClassName('messageClass');
let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";
let i;
let cls = clicks.length;

//messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
//messageClass.innerHTML = messageClass.textContent + messageTxtClass;
messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;

for(let i = 0; i < messageAllClass.length; i++) {
    messageAllClass[i].innerHTML = document.querySelectorAll('.messageAllClass');
}

for(let i = 0; i < messageClass.length; i++) {
    messageClass[i].innerHTML = document.getElementByClassName('messageClass');
}

for (let i = 0; i < cls; i++) {
  click[i].onclick = function () {
    messageAllClass.innerHTML = "null";
    messageClass.innerHTML = "null";
    messeageIDuniq.innerHTML = deleted;
    alert("all messages deleted!");
  }
}
```

<p><strong>html</strong></p>

<pre class="lang-html prettyprint-override"><code><h1>On one side</h1>

<div class="main">
  <h3>Message:</h3>
  <div class="messageAllClass"></div>
  <div class="messageClass"></div>
  <div id="messageID"></div>
</div>

<div class="panel">
  <h3>Panel:</h3>
  <div class="messageAllClass"></div>
  <div class="messageClass"></div>
</div>

<button type="button" class="trigger">Delete all messages</button>

</code>```

saved on jsfiddle

答:
The names you used for your variables are a bit confusing because they are all very similar but I believe I got what you were hoping to achieve: </p>

```<code>let click = document.querySelectorAll('.trigger');
let messageAllClass = document.querySelectorAll('.messageAllClass');

// as previously mention in the comments it's Elements and not Element as this get's a collection of classes
let messageClass = document.getElementsByClassName('messageClass');

let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";
let i;

let cls = click.length;

//messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
//messageClass.innerHTML = messageClass.textContent + messageTxtClass;
messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;

for(let i = 0; i < messageAllClass.length; i++) {
  console.log(messageAllClass[i])
    // you want to add the inner html of that collection
    messageAllClass[i].innerHTML = document.querySelectorAll('.messageAllClass')[0].innerHTML;

}

for(let i = 0; i < messageClass.length; i++) {
    // you want to add the inner html of that collection
    messageClass[i].innerHTML = document.getElementsByClassName('messageClass')[0].innerHTML;

}

for (let i = 0; i < cls; i++) {
  click[i].onclick = function () {
    messageAllClass.innerHTML = "null";
    messageClass.innerHTML = "null";
    messeageIDuniq.innerHTML = deleted;
    alert("all messages deleted!");
  }
}
</code>```

Body:
I am a Javascript beginner and am trying to solve a problem here. I don't find the mistake.

I try that the ID and the class variants work. The click and the message does not work.

java script

let click = document.querySelectorAll('.trigger');

let messageAllClass = document.querySelectorAll('.messageAllClass');
let messageClass = document.getElementByClassName('messageClass');
let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";
let i;
let cls = clicks.length;

//messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
//messageClass.innerHTML = messageClass.textContent + messageTxtClass;
messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;

for(let i = 0; i < messageAllClass.length; i++) {
    messageAllClass[i].innerHTML = document.querySelectorAll('.messageAllClass');
}

for(let i = 0; i < messageClass.length; i++) {
    messageClass[i].innerHTML = document.getElementByClassName('messageClass');
}

for (let i = 0; i < cls; i++) {
  click[i].onclick = function () {
    messageAllClass.innerHTML = "null";
    messageClass.innerHTML = "null";
    messeageIDuniq.innerHTML = deleted;
    alert("all messages deleted!");
  }
}

html

On one side

Message:

Panel:

<button type="button" class="trigger">Delete all messages</button>

saved on jsfiddle

Body:
The names you used for your variables are a bit confusing because they are all very similar but I believe I got what you were hoping to achieve:

let click = document.querySelectorAll('.trigger');
let messageAllClass = document.querySelectorAll('.messageAllClass');

// as previously mention in the comments it's Elements and not Element as this get's a collection of classes
let messageClass = document.getElementsByClassName('messageClass');

let messeageIDuniq = document.getElementById('messageID');

let messageTxtAllClass = "hallo from AllClass";
let messageTxtClass = "hallo from Class";
let messageTxtIDuniq = "hallo from ID, i am unique :-)";

let deleted = "deleted";
let i;

let cls = click.length;

//messageAllClass.innerHTML = messAllClass.textContent + messageTxtAllClass;
//messageClass.innerHTML = messageClass.textContent + messageTxtClass;
messeageIDuniq.innerHTML = messeageIDuniq.textContent + messageTxtIDuniq;

for(let i = 0; i < messageAllClass.length; i++) {
  console.log(messageAllClass[i])
    // you want to add the inner html of that collection
    messageAllClass[i].innerHTML = document.querySelectorAll('.messageAllClass')[0].innerHTML;

}

for(let i = 0; i < messageClass.length; i++) {
    // you want to add the inner html of that collection
    messageClass[i].innerHTML = document.getElementsByClassName('messageClass')[0].innerHTML;

}

for (let i = 0; i < cls; i++) {
  click[i].onclick = function () {
    messageAllClass.innerHTML = "null";
    messageClass.innerHTML = "null";
    messeageIDuniq.innerHTML = deleted;
    alert("all messages deleted!");
  }
}


问:
How can I read uitextview text line by line iOS?
I have uitextview with text. I want to read it line by line. I want to it for up to iOS 5 and without - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; delegate method. How can I do that?

答:
Expanding on @santhu's answer, here is a Swift 4 answer:

```<code>textView.text = "this is some long text, that is one continuous string but is on different lines."

textView.layoutManager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: text.count)) { (rect, usedRect, textContainer, glyphRange, stop) in

    let characterRange = textView.layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
    let line = (textView.text as NSString).substring(with: characterRange)
    print(line)
    print("----------------------------------------------")
}

print("----------------------------------------------")
print("----------------------------------------------")
</code>```

Output:

```<code>this is some long text, t
----------------------------------------------
hat is one continuous str
----------------------------------------------
ing but is on different lin
----------------------------------------------
es.
----------------------------------------------
----------------------------------------------
----------------------------------------------
</code>```

Body:
Expanding on @santhu's answer, here is a Swift 4 answer:

textView.text = "this is some long text, that is one continuous string but is on different lines."

textView.layoutManager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: text.count)) { (rect, usedRect, textContainer, glyphRange, stop) in

    let characterRange = textView.layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
    let line = (textView.text as NSString).substring(with: characterRange)
    print(line)
    print("----------------------------------------------")
}

print("----------------------------------------------")
print("----------------------------------------------")

Output:

this is some long text, t
----------------------------------------------
hat is one continuous str
----------------------------------------------
ing but is on different lin
----------------------------------------------
es.
----------------------------------------------
----------------------------------------------
----------------------------------------------


答:
```<code> dict(df.values)
</code>```

will do the job.

Note that this assumes df has 2 "columns" i.e. those other than the index.

Title: Convert two df cols to dict on python

Body:
 dict(df.values)

will do the job.

Note that this assumes df has 2 "columns" i.e. those other than the index.


问:
How do I fix this Java generics wildcard error?
In this question, TofuBeer was having problems creating a genericized IterableEnumeration.

The answer came from jcrossley3 pointing to this link http://www.javaspecialists.eu/archive/Issue107.html which pretty much solved the problem.

There is still one thing I don't get.  The real problem, as effectively pointed out by erickson, was that:

You cannot specify a wildcard when constructing a parameterized type

But removing the wildcard in the declaration didn't work either:

```<code>final IterableEnumeration<ZipEntry> iteratable
                  = new IterableEnumeration<ZipEntry>(zipFile.entries());
</code>```

Results in the following error:

```<code>Main.java:19: cannot find symbol
symbol  : constructor IterableEnumeration(java.util.Enumeration<capture#469 of ? extends java.util.zip.ZipEntry>)
location: class IterableEnumeration<java.util.zip.ZipEntry>
        final IterableEnumeration<ZipEntry> iteratable = new IterableEnumeration<ZipEntry>(  zipFile.entries());
                                                         ^
1 error
</code>```

But the samples in the JavaSpecialist do work:

```<code>  IterableEnumeration<String> ie =
              new IterableEnumeration<String>(sv.elements());
</code>```

The only difference I can spot is that in the JavaSpecialists blog, the Enumeration comes from a Vector whose signature is:

```<code>public Enumeration<E> elements()
</code>```

while the one that fails comes from ZipFile whose signature is:

```<code>public Enumeration<? extends ZipEntry> entries()
</code>```

Finally, all of this is absorbed by the for-each construct and the static make method suggested in the link

```<code>for(final ZipEntry entry : IterableEnumeration.make( zipFile.entries() ))  {
    if(!(entry.isDirectory())) {
        names.add(entry.getName());
    }
}
</code>```

But!! the point in that newsletter was not to solve this problem, but to avoid the need to specify a generic type, just because the syntax looks ugly!!

So.. my questions is:

What is happening?

Why doesn't creating an instance of IterableEnumeration work when the parameter is an Enumeration whose type is <? extends SomeClass> ?  And why does the make for-each construct swallow the problem?!!!

Why does this work:

```<code>for(final ZipEntry entry : IterableEnumeration.make( zipFile.entries() ))  {
</code>```

but this not work?

```<code>final IterableEnumeration<ZipEntry> iteratable
                     = IterableEnumeration.make( zipFile.entries() );
</code>```

Below is a (slightly) modified version of TofuBeer's original code:

```<code>import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.Vector;

public class Main {
    private ZipFile zipFile;

    public Set<String> entries() {

        final Vector<ZipEntry>    vector = new Vector<ZipEntry>();
        // why this works.
        //final IterableEnumeration<ZipEntry> iteratable = new IterableEnumeration<ZipEntry>( vector.elements() );

        // but this do not.
        //final IterableEnumeration<ZipEntry> iteratable = new IterableEnumeration<ZipEntry>( zipFile.entries() );

        // nor this
        final IterableEnumeration<ZipEntry> iteratable = IterableEnumeration.make( zipFile.entries() );

        // And what's with the for-each that doesn't care about the type?
        final Set<String>   names = new HashSet<String>();

        for(final ZipEntry entry : IterableEnumeration.make( zipFile.entries() ))  {
            if(!(entry.isDirectory())) {
                names.add(entry.getName());
            }
        }

        return (names);
    }
}

class IterableEnumeration<T> implements Iterable<T> {
    private final Enumeration<T> enumeration;

    public IterableEnumeration(final Enumeration<T> e) {
        enumeration = e;
    }

    public Iterator<T> iterator() {
        return new Iterator<T>() {
             public boolean hasNext() {
                return (enumeration.hasMoreElements());
            }

            public T next() {
                return (enumeration.nextElement());
            }

            public void remove() {
                throw new UnsupportedOperationException("Cannot remove via an Enumeration");
            }
        };
    }
    // As suggested by http://www.javaspecialists.eu/archive/Issue107.html
    // but doesn't help with: final IterableEnumeration<ZipEntry> iteratable = IterableEnumeration.make( zipFile.entries() );
    public static <T> Iterable<T> make(Enumeration<T> en) {
        return new IterableEnumeration<T>(en);
    }
}
</code>```

I want to understand it!!

答:
I'm not sure what's happening with the foreach loop, but you need to add the wildcard to your declaration of IterableEnumeration to accept the unspecified type returned from ZipFile.entries().

Replace

```<code>    private final Enumeration<T> enumeration;

    public IterableEnumeration(final Enumeration<T> e) {
        enumeration = e;
    }

    public static <T> Iterable<T> make(Enumeration<T> en) {
        return new IterableEnumeration<T>(en);
    }
</code>```

With

```<code>    private final Enumeration<? extends T> enumeration;

    public IterableEnumeration(final Enumeration<? extends T> e) {
        enumeration = e;
    }

    public static <T> Iterable<T> make(Enumeration<? extends T> en) {
        return new IterableEnumeration<T>(en);
    }
</code>```

OwnerDisplayName: Oscar Reyes

Body:
In this question, TofuBeer was having problems creating a genericized IterableEnumeration.

The answer came from jcrossley3 pointing to this link http://www.javaspecialists.eu/archive/Issue107.html which pretty much solved the problem.

There is still one thing I don't get.  The real problem, as effectively pointed out by erickson, was that:

You cannot specify a wildcard when constructing a parameterized type

But removing the wildcard in the declaration didn't work either:

final IterableEnumeration<ZipEntry> iteratable
                  = new IterableEnumeration<ZipEntry>(zipFile.entries());

Results in the following error:

Main.java:19: cannot find symbol
symbol  : constructor IterableEnumeration(java.util.Enumeration<capture#469 of ? extends java.util.zip.ZipEntry>)
location: class IterableEnumeration<java.util.zip.ZipEntry>
        final IterableEnumeration<ZipEntry> iteratable = new IterableEnumeration<ZipEntry>(  zipFile.entries());
                                                         ^
1 error

But the samples in the JavaSpecialist do work:

  IterableEnumeration<String> ie =
              new IterableEnumeration<String>(sv.elements());

The only difference I can spot is that in the JavaSpecialists blog, the Enumeration comes from a Vector whose signature is:

public Enumeration<E> elements()

while the one that fails comes from ZipFile whose signature is:

public Enumeration<? extends ZipEntry> entries()

Finally, all of this is absorbed by the for-each construct and the static make method suggested in the link

for(final ZipEntry entry : IterableEnumeration.make( zipFile.entries() ))  {
    if(!(entry.isDirectory())) {
        names.add(entry.getName());
    }
}

But!! the point in that newsletter was not to solve this problem, but to avoid the need to specify a generic type, just because the syntax looks ugly!!

So.. my questions is:

What is happening?

Why doesn't creating an instance of IterableEnumeration work when the parameter is an Enumeration whose type is <? extends SomeClass> ?  And why does the make for-each construct swallow the problem?!!!

Why does this work:

for(final ZipEntry entry : IterableEnumeration.make( zipFile.entries() ))  {

but this not work?

final IterableEnumeration<ZipEntry> iteratable
                     = IterableEnumeration.make( zipFile.entries() );

Below is a (slightly) modified version of TofuBeer's original code:

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.Vector;

public class Main {
    private ZipFile zipFile;

    public Set<String> entries() {

        final Vector<ZipEntry>    vector = new Vector<ZipEntry>();
        // why this works.
        //final IterableEnumeration<ZipEntry> iteratable = new IterableEnumeration<ZipEntry>( vector.elements() );

        // but this do not.
        //final IterableEnumeration<ZipEntry> iteratable = new IterableEnumeration<ZipEntry>( zipFile.entries() );

        // nor this
        final IterableEnumeration<ZipEntry> iteratable = IterableEnumeration.make( zipFile.entries() );

        // And what's with the for-each that doesn't care about the type?
        final Set<String>   names = new HashSet<String>();

        for(final ZipEntry entry : IterableEnumeration.make( zipFile.entries() ))  {
            if(!(entry.isDirectory())) {
                names.add(entry.getName());
            }
        }

        return (names);
    }
}

class IterableEnumeration<T> implements Iterable<T> {
    private final Enumeration<T> enumeration;

    public IterableEnumeration(final Enumeration<T> e) {
        enumeration = e;
    }

    public Iterator<T> iterator() {
        return new Iterator<T>() {
             public boolean hasNext() {
                return (enumeration.hasMoreElements());
            }

            public T next() {
                return (enumeration.nextElement());
            }

            public void remove() {
                throw new UnsupportedOperationException("Cannot remove via an Enumeration");
            }
        };
    }
    // As suggested by http://www.javaspecialists.eu/archive/Issue107.html
    // but doesn't help with: final IterableEnumeration<ZipEntry> iteratable = IterableEnumeration.make( zipFile.entries() );
    public static <T> Iterable<T> make(Enumeration<T> en) {
        return new IterableEnumeration<T>(en);
    }
}

I want to understand it!!

LastEditorDisplayName: Eddie

Body:
I'm not sure what's happening with the foreach loop, but you need to add the wildcard to your declaration of IterableEnumeration to accept the unspecified type returned from ZipFile.entries().

Replace

    private final Enumeration<T> enumeration;

    public IterableEnumeration(final Enumeration<T> e) {
        enumeration = e;
    }

    public static <T> Iterable<T> make(Enumeration<T> en) {
        return new IterableEnumeration<T>(en);
    }

With

    private final Enumeration<? extends T> enumeration;

    public IterableEnumeration(final Enumeration<? extends T> e) {
        enumeration = e;
    }

    public static <T> Iterable<T> make(Enumeration<? extends T> en) {
        return new IterableEnumeration<T>(en);
    }

OwnerDisplayName: Matthew


问:
ArcGIS JS API: make circle not zoom
I have a ArcGIS JavaScript API map. On map click I want to display a circle and highlight all the points within that circle.

However, when I create the circle and zoom in the map, the circle zooms in as well. How can I get the circle to stay the same pixel radius no matter what the zoom level of the map?

```

答:
The circle that you create, using a 500 miles buffer of the click point, is a polygon. So naturally will be the same one no matter what zoom level you have. In other words, represent a geographic area so it can not change based on the zoom level.

On contrary, in the same example you have the points that represent the earthquakes, that are represented with a orange circle. Because it is a symbol that represents a geographic place, it keeps the size in pixels for all zoom levels.

Resuming, you can not make the 500 miles buffer area, represented by the polygon, to change with the zoom levels, because it is an area.

Title: ArcGIS JS API: make circle not zoom


问:
how to print a specific image through onclick
I need to be able to print out specifically just the image class="main" when I click on the img class="print" within the same div class="imgcontainer", so three separate images individually printed.

HTML

```<code>            <div id="printables">
                <div class="imgcontainer">
                    <img class="main" src="assets/printables/Header Ipad.jpg">
                    <img class="print" src="assets/print.png">
                    <a href="assets/printables" download>
                        <img class="download" src="assets/download.png">
                    </a>
                </div>
                <div class="imgcontainer">
                    <img class="main" src="assets/printables/Milestones Chart.jpg">
                    <img class="print" src="assets/print.png">
                    <a href="assets/printables/Milestones Chart.jpg" download>
                        <img class="download" src="assets/download.png">
                    </a>
                </div>
                <div class="imgcontainer">
                    <img class="main" src="assets/printables/FinancialRuler Diagram.jpg">
                    <img class="print" src="assets/print.png">
                    <a href="assets/printables/FinancialRuler Diagram.jpg" download>
                        <img class="download" src="assets/download.png">
                    </a>
                </div>
            </div>
</code>```

答:
You can try the following approach to print the images:

```<code> $("img.print").on("click", function() {
    let mainImage = $(this).prev(".main").attr("src");
    ImagePrint(mainImage);
 });

 function ImageSourcetoPrint(source) {
    return "<html><head><script>function step1(){\n" +
   "setTimeout('step2()', 10);}\n" +
   "function step2(){window.print();window.close()}\n" +
   "</scri" + "pt></head><body onload='step1()'>\n" +
   "<img src='" + source + "' /></body></html>";
 }

 function ImagePrint(source) {
   Pagelink = "about:blank";
   var pwa = window.open(Pagelink, "_new");
   pwa.document.open();
   pwa.document.write(ImageSourcetoPrint(source));
   pwa.document.close();
 }
</code>```

This solution is taken from here.

Body:
You can try the following approach to print the images:

 $("img.print").on("click", function() {
    let mainImage = $(this).prev(".main").attr("src");
    ImagePrint(mainImage);
 });

 function ImageSourcetoPrint(source) {
    return "<html><head><script>function step1(){\n" +
   "setTimeout('step2()', 10);}\n" +
   "function step2(){window.print();window.close()}\n" +
   "</scri" + "pt></head><body onload='step1()'>\n" +
   "<img src='" + source + "' /></body></html>";
 }

 function ImagePrint(source) {
   Pagelink = "about:blank";
   var pwa = window.open(Pagelink, "_new");
   pwa.document.open();
   pwa.document.write(ImageSourcetoPrint(source));
   pwa.document.close();
 }

This solution is taken from here.