问:
SonarQube analysis with MSBuild: Line is out of range in file
So, we have a TeamCity project building a C# webapi project using .NET 4.5 which includes a SonarQube analysis.

At the end of the analysis, we receive the following exception:

```<code>[13:41:13][Step 14/16] ERROR: Error during SonarQube Scanner execution
[13:41:13][Step 14/16] java.lang.IllegalStateException: Line 65 is out of range in the file App_Start/UnityConfig.cs (lines: 64)
</code>```

What did I already check:

UPDATE: Further analysis proves that the error is caused due to dotCover code coverage analysis

File Encoding: UTF-8 (verified with Notepad++, is UTF-8 without BOM), using CRLF line feeds (checked with hexdump and files end with 0x0D 0x0A)

Encoding used by SonarQube

```<code>[16:17:37][Step 14/16] INFO: Default locale: "en_US", source code encoding: "windows-1252" (analysis is platform dependent)
[16:17:37][Step 14/16] INFO: Process project properties
[16:17:37][Step 14/16] bla bla
[16:17:59][Step 14/16] INFO: Source encoding: UTF-8, default locale: en_US
</code>```

Using the following stack:

SonarQube 6.4 (just updated)

SonarC# 5.11 (build 1761)

dotCover included in TeamCity 9.1.6

Microsoft (R) Build Engine version 14.0.24720.0

Java(TM) SE Runtime Environment (build 1.8.0_111-b14)

We do the following steps (related to SonarQube) in our build process:

start Analysis

```<code>E:\SonarQube\sonar-scanner-msbuild-2.3.2\SonarQube.Scanner.MSBuild.exe begin /k:"CoBen" /n:"CoBen" /v:"%build.number%" /d:sonar.cs.nunit.reportsPaths="TestResult-*.xml" /d:sonar.cs.dotcover.reportsPaths="DotCover-*.html"
</code>```

Build project

```<code>MSBuild.exe /p:Configuration=Release;Targets=Rebuild
</code>```

Run unit tests with dotCover

```<code>C:\TeamCity\buildAgent\tools\dotCover\dotCover.exe analyse /TargetExecutable="%system.teamcity.build.workingDir%\packages\NUnit.ConsoleRunner.3.6.1\tools\nunit3-console.exe" /TargetArguments="--teamcity --agents=1 --result=%system.teamcity.build.workingDir%\TestResult-unit.xml;format=nunit2 --where \"cat != WebApiTests\" %system.teamcity.build.workingDir%\TestDlls.nunit" /Output="DotCover-unit.html" /ReportType="HTML"
</code>```

Run Integration tests with dotCover

```<code>C:\TeamCity\buildAgent\tools\dotCover\dotCover.exe analyse /TargetExecutable="%system.teamcity.build.workingDir%\packages\NUnit.ConsoleRunner.3.6.1\tools\nunit3-console.exe" /TargetArguments="--teamcity --agents=1 --result=%system.teamcity.build.workingDir%\TestResult-webapi.xml;format=nunit2 --where \"cat == WebApiTests\" %system.teamcity.build.workingDir%\TestDlls.nunit" /Output="DotCover-webapi.html" /ReportType="HTML"
</code>```

End sonar analysis

```<code>E:\SonarQube\sonar-scanner-msbuild-2.3.2\SonarQube.Scanner.MSBuild.exe end
</code>```

The exact error:

```<code>[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\996.html
[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\997.html
[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\998.html
[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\999.html
[23:25:19][Step 14/16] INFO: Adding this code coverage report to the cache for later reuse: E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi.html
[23:25:19][Step 14/16] INFO: ------------------------------------------------------------------------
[23:25:19][Step 14/16] INFO: EXECUTION FAILURE
[23:25:19][Step 14/16] INFO: ------------------------------------------------------------------------
[23:25:19][Step 14/16] INFO: Total time: 12:17.339s
[23:25:20][Step 14/16] ERROR: Error during SonarQube Scanner execution
[23:25:20][Step 14/16] INFO: Final Memory: 52M/392M
[23:25:20][Step 14/16] INFO: ------------------------------------------------------------------------
[23:25:20][Step 14/16] java.lang.IllegalStateException: Line 65 is out of range in the file App_Start/UnityConfig.cs (lines: 64)
[23:25:20][Step 14/16]  at org.sonar.api.internal.google.common.base.Preconditions.checkState(Preconditions.java:197)
[23:25:20][Step 14/16]  at org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage.validateLine(DefaultCoverage.java:90)
[23:25:20][Step 14/16]  at org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage.lineHits(DefaultCoverage.java:78)
[23:25:20][Step 14/16]  at org.sonar.plugins.dotnet.tests.CoverageReportImportSensor.analyze(CoverageReportImportSensor.java:94)
[23:25:20][Step 14/16]  at org.sonar.plugins.dotnet.tests.CoverageReportImportSensor.execute(CoverageReportImportSensor.java:69)
[23:25:20][Step 14/16]  at org.sonar.scanner.sensor.SensorWrapper.analyse(SensorWrapper.java:53)
[23:25:20][Step 14/16]  at org.sonar.scanner.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:57)
[23:25:20][Step 14/16]  at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:49)
[23:25:20][Step 14/16]  at org.sonar.scanner.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:78)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:175)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.scan(ProjectScanContainer.java:262)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:257)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:255)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:247)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
[23:25:20][Step 14/16]  at org.sonar.scanner.task.ScanTask.execute(ScanTask.java:47)
[23:25:20][Step 14/16]  at org.sonar.scanner.task.TaskContainer.doAfterStart(TaskContainer.java:86)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
[23:25:20][Step 14/16]  at org.sonar.scanner.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:118)
[23:25:20][Step 14/16]  at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:117)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:63)
[23:25:20][Step 14/16]  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[23:25:20][Step 14/16]  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[23:25:20][Step 14/16]  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[23:25:20][Step 14/16]  at java.lang.reflect.Method.invoke(Method.java:498)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
[23:25:20][Step 14/16]  at com.sun.proxy.$Proxy0.execute(Unknown Source)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis(EmbeddedScanner.java:151)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.cli.Main.runAnalysis(Main.java:123)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.cli.Main.execute(Main.java:77)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.cli.Main.main(Main.java:61)
[23:25:20][Step 14/16] ERROR:
[23:25:20][Step 14/16] ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.
[23:25:21][Step 14/16] The SonarQube Scanner did not complete successfully
</code>```

Any idea's what else we could do?

答: Solved! I switched from dotCover to OpenCover and now all is running well.</p>

Body:
So, we have a TeamCity project building a C# webapi project using .NET 4.5 which includes a SonarQube analysis.

At the end of the analysis, we receive the following exception:

[13:41:13][Step 14/16] ERROR: Error during SonarQube Scanner execution
[13:41:13][Step 14/16] java.lang.IllegalStateException: Line 65 is out of range in the file App_Start/UnityConfig.cs (lines: 64)

What did I already check:

UPDATE: Further analysis proves that the error is caused due to dotCover code coverage analysis

File Encoding: UTF-8 (verified with Notepad++, is UTF-8 without BOM), using CRLF line feeds (checked with hexdump and files end with 0x0D 0x0A)

Encoding used by SonarQube

[16:17:37][Step 14/16] INFO: Default locale: "en_US", source code encoding: "windows-1252" (analysis is platform dependent)
[16:17:37][Step 14/16] INFO: Process project properties
[16:17:37][Step 14/16] bla bla
[16:17:59][Step 14/16] INFO: Source encoding: UTF-8, default locale: en_US

Using the following stack:

SonarQube 6.4 (just updated)

SonarC# 5.11 (build 1761)

dotCover included in TeamCity 9.1.6

Microsoft (R) Build Engine version 14.0.24720.0

Java(TM) SE Runtime Environment (build 1.8.0_111-b14)

We do the following steps (related to SonarQube) in our build process:

start Analysis

E:\SonarQube\sonar-scanner-msbuild-2.3.2\SonarQube.Scanner.MSBuild.exe begin /k:"CoBen" /n:"CoBen" /v:"%build.number%" /d:sonar.cs.nunit.reportsPaths="TestResult-*.xml" /d:sonar.cs.dotcover.reportsPaths="DotCover-*.html"

Build project

MSBuild.exe /p:Configuration=Release;Targets=Rebuild

Run unit tests with dotCover

C:\TeamCity\buildAgent\tools\dotCover\dotCover.exe analyse /TargetExecutable="%system.teamcity.build.workingDir%\packages\NUnit.ConsoleRunner.3.6.1\tools\nunit3-console.exe" /TargetArguments="--teamcity --agents=1 --result=%system.teamcity.build.workingDir%\TestResult-unit.xml;format=nunit2 --where \"cat != WebApiTests\" %system.teamcity.build.workingDir%\TestDlls.nunit" /Output="DotCover-unit.html" /ReportType="HTML"

Run Integration tests with dotCover

C:\TeamCity\buildAgent\tools\dotCover\dotCover.exe analyse /TargetExecutable="%system.teamcity.build.workingDir%\packages\NUnit.ConsoleRunner.3.6.1\tools\nunit3-console.exe" /TargetArguments="--teamcity --agents=1 --result=%system.teamcity.build.workingDir%\TestResult-webapi.xml;format=nunit2 --where \"cat == WebApiTests\" %system.teamcity.build.workingDir%\TestDlls.nunit" /Output="DotCover-webapi.html" /ReportType="HTML"

End sonar analysis

E:\SonarQube\sonar-scanner-msbuild-2.3.2\SonarQube.Scanner.MSBuild.exe end

The exact error:

[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\996.html
[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\997.html
[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\998.html
[23:25:19][Step 14/16] INFO: Parsing the dotCover report E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi\src\999.html
[23:25:19][Step 14/16] INFO: Adding this code coverage report to the cache for later reuse: E:\TeamCity\buildAgent\work\5728a1531387749f\.\DotCover-webapi.html
[23:25:19][Step 14/16] INFO: ------------------------------------------------------------------------
[23:25:19][Step 14/16] INFO: EXECUTION FAILURE
[23:25:19][Step 14/16] INFO: ------------------------------------------------------------------------
[23:25:19][Step 14/16] INFO: Total time: 12:17.339s
[23:25:20][Step 14/16] ERROR: Error during SonarQube Scanner execution
[23:25:20][Step 14/16] INFO: Final Memory: 52M/392M
[23:25:20][Step 14/16] INFO: ------------------------------------------------------------------------
[23:25:20][Step 14/16] java.lang.IllegalStateException: Line 65 is out of range in the file App_Start/UnityConfig.cs (lines: 64)
[23:25:20][Step 14/16]  at org.sonar.api.internal.google.common.base.Preconditions.checkState(Preconditions.java:197)
[23:25:20][Step 14/16]  at org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage.validateLine(DefaultCoverage.java:90)
[23:25:20][Step 14/16]  at org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage.lineHits(DefaultCoverage.java:78)
[23:25:20][Step 14/16]  at org.sonar.plugins.dotnet.tests.CoverageReportImportSensor.analyze(CoverageReportImportSensor.java:94)
[23:25:20][Step 14/16]  at org.sonar.plugins.dotnet.tests.CoverageReportImportSensor.execute(CoverageReportImportSensor.java:69)
[23:25:20][Step 14/16]  at org.sonar.scanner.sensor.SensorWrapper.analyse(SensorWrapper.java:53)
[23:25:20][Step 14/16]  at org.sonar.scanner.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:57)
[23:25:20][Step 14/16]  at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:49)
[23:25:20][Step 14/16]  at org.sonar.scanner.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:78)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:175)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.scan(ProjectScanContainer.java:262)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:257)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:255)
[23:25:20][Step 14/16]  at org.sonar.scanner.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:247)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
[23:25:20][Step 14/16]  at org.sonar.scanner.task.ScanTask.execute(ScanTask.java:47)
[23:25:20][Step 14/16]  at org.sonar.scanner.task.TaskContainer.doAfterStart(TaskContainer.java:86)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:143)
[23:25:20][Step 14/16]  at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:128)
[23:25:20][Step 14/16]  at org.sonar.scanner.bootstrap.GlobalContainer.executeTask(GlobalContainer.java:118)
[23:25:20][Step 14/16]  at org.sonar.batch.bootstrapper.Batch.executeTask(Batch.java:117)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:63)
[23:25:20][Step 14/16]  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[23:25:20][Step 14/16]  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[23:25:20][Step 14/16]  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[23:25:20][Step 14/16]  at java.lang.reflect.Method.invoke(Method.java:498)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:60)
[23:25:20][Step 14/16]  at com.sun.proxy.$Proxy0.execute(Unknown Source)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.EmbeddedScanner.doExecute(EmbeddedScanner.java:233)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.api.EmbeddedScanner.runAnalysis(EmbeddedScanner.java:151)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.cli.Main.runAnalysis(Main.java:123)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.cli.Main.execute(Main.java:77)
[23:25:20][Step 14/16]  at org.sonarsource.scanner.cli.Main.main(Main.java:61)
[23:25:20][Step 14/16] ERROR:
[23:25:20][Step 14/16] ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.
[23:25:21][Step 14/16] The SonarQube Scanner did not complete successfully

Any idea's what else we could do?


来源: stackexchange

问:
Eclipse/Ant Making a jar in version 1.9, even though everything seems to be set for 1.8
I have a project I build using ant and eclipse which I'd like to have be compatible with Java 8.

When I try running the jar using Java 8, I get the following error:

```<code>$ /usr/lib/jvm/java-8-openjdk-amd64/bin/java -jar hypnos.jar
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError:
org/joshuad/musicplayer/MusicPlayerUI has been compiled by a more recent version of
the Java Runtime (class file version 53.0), this version of the Java Runtime only
recognizes class file versions up to 52.0
</code>```

So it appears that it's compiling using Oracle's Java 9 (which is installed on my system) but I can't find the place in eclipse where this is designated. Everything I see seems to suggest that we're using java 8 (screenshots below).

I feel like I must be missing something, but I can't figure out where. What do I have to do to get this jar to be compatible with Java 8 / class file version 52.0?

Project > Properties > Java Build Path

Project > Properties > Java Compiler

Window > Preferences > Compiler

Right Click Ant Build File > Run As > External Tools Configuration

Ant Build File

```<code><project name="Hypnos Music Player" default="compile" basedir=".">
    <property name="src" location="src"/>
    <property name="build" location="build"/>
    <property name="jarFile" location="hypnos.jar"/>

    <path id="class.path">
        <fileset dir="lib">
            <include name="**/*.jar" />
        </fileset>
        <pathelement location="${jarFile}" />
    </path>

    <target name="init">
        <tstamp/>
        <mkdir dir="${build}"/>
    </target>

    <target name="compile" depends="init" description="compile the source">
        <javac fork="yes" includeantruntime="false" srcdir="${src}" destdir="${build}">
            <classpath refid="class.path" />
        </javac>
    </target>

    <target name="jar" depends="compile" description="Create a jar.">
        <jar destfile="${jarFile}" basedir="${build}">
            <manifest>
                <attribute name="Main-Class" value="org.joshuad.musicplayer.MusicPlayerUI" />
                <attribute name="Class-Path" value="lib/commons-cli-1.4.jar lib/jaad-0.8.4-nospi.jar
                                                    lib/jaudiotagger-2.2.6-SNAPSHOT.jar lib/jflac-1.2.jar
                                                    lib/jl1.0.1.jar lib/jogg-0.0.7.jar lib/jorbis-0.0.15.jar
                                                    lib/vorbisspi1.0.3.jar" />
            </manifest>
        </jar>
    </target>
</project>
</code>```

答:
What is your $JAVA_HOME environment variable?

I recently had a similar problem and it turns out that Ant seems to ignore many settings provided by Eclipse and only uses $JAVA_HOME. I discovered this by placing the following in build.xml:

```<code><target name="jdk_version_validation">
    <echo message="Java Version: ${java.version}" />
    <echo message="Java home: ${java.home}" />
    <echo message="JAVA_HOME: ${env.JAVA_HOME}" />
    <echo message="JAVACMD: ${env.JAVACMD}" />
</target>
</code>```

Which got me this:

```<code>jdk_version_validation:
     [echo] Java Version: 1.7.0_80
     [echo] Java home: C:\Program Files\Java\jre7
     [echo] JAVA_HOME: C:\Program Files\Java\jdk1.8.0_131\
     [echo] JAVACMD: C:\Program Files\Java\jdk1.7.0_80\bin
</code>```

I found that the only sure way to predict which version Ant will produce is by brute-forcing the following in build.xml:

```<code><property name="ant.build.javac.source" value="1.7"/>
<property name="ant.build.javac.target" value="1.7"/>
</code>```

So, my recommendation to you: Try placing in your build.xml the following:

```<code><property name="ant.build.javac.source" value="1.8"/>
<property name="ant.build.javac.target" value="1.8"/>
</code>```

Update, for the benefit of those with a variation of the problem described in the OP, to eliminate any possibility of "Eclipse fooling Ant":

Go to Window > Preferences > Java > Installed JREs and try leaving only the target JRE, making sure it is the one inside the JDK folder (not the sibling one directly under the Java folder).

Go to Project > Properties > Java Compiler and check Enable project specific settings, making sure that the Compiler compliance level is set to the target JRE java version.

ContentLicense: CC BY-SA 3.0

Body:
I have a project I build using ant and eclipse which I'd like to have be compatible with Java 8.

When I try running the jar using Java 8, I get the following error:

$ /usr/lib/jvm/java-8-openjdk-amd64/bin/java -jar hypnos.jar
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError:
org/joshuad/musicplayer/MusicPlayerUI has been compiled by a more recent version of
the Java Runtime (class file version 53.0), this version of the Java Runtime only
recognizes class file versions up to 52.0

So it appears that it's compiling using Oracle's Java 9 (which is installed on my system) but I can't find the place in eclipse where this is designated. Everything I see seems to suggest that we're using java 8 (screenshots below).

I feel like I must be missing something, but I can't figure out where. What do I have to do to get this jar to be compatible with Java 8 / class file version 52.0?

Project > Properties > Java Build Path

Project > Properties > Java Compiler

Window > Preferences > Compiler

Right Click Ant Build File > Run As > External Tools Configuration

Ant Build File

<project name="Hypnos Music Player" default="compile" basedir=".">
    <property name="src" location="src"/>
    <property name="build" location="build"/>
    <property name="jarFile" location="hypnos.jar"/>

    <path id="class.path">
        <fileset dir="lib">
            <include name="**/*.jar" />
        </fileset>
        <pathelement location="${jarFile}" />
    </path>

    <target name="init">
        <tstamp/>
        <mkdir dir="${build}"/>
    </target>

    <target name="compile" depends="init" description="compile the source">
        <javac fork="yes" includeantruntime="false" srcdir="${src}" destdir="${build}">
            <classpath refid="class.path" />
        </javac>
    </target>

    <target name="jar" depends="compile" description="Create a jar.">
        <jar destfile="${jarFile}" basedir="${build}">
            <manifest>
                <attribute name="Main-Class" value="org.joshuad.musicplayer.MusicPlayerUI" />
                <attribute name="Class-Path" value="lib/commons-cli-1.4.jar lib/jaad-0.8.4-nospi.jar
                                                    lib/jaudiotagger-2.2.6-SNAPSHOT.jar lib/jflac-1.2.jar
                                                    lib/jl1.0.1.jar lib/jogg-0.0.7.jar lib/jorbis-0.0.15.jar
                                                    lib/vorbisspi1.0.3.jar" />
            </manifest>
        </jar>
    </target>
</project>

Body:
What is your $JAVA_HOME environment variable?

I recently had a similar problem and it turns out that Ant seems to ignore many settings provided by Eclipse and only uses $JAVA_HOME. I discovered this by placing the following in build.xml:

<target name="jdk_version_validation">
    <echo message="Java Version: ${java.version}" />
    <echo message="Java home: ${java.home}" />
    <echo message="JAVA_HOME: ${env.JAVA_HOME}" />
    <echo message="JAVACMD: ${env.JAVACMD}" />
</target>

Which got me this:

jdk_version_validation:
     [echo] Java Version: 1.7.0_80
     [echo] Java home: C:\Program Files\Java\jre7
     [echo] JAVA_HOME: C:\Program Files\Java\jdk1.8.0_131\
     [echo] JAVACMD: C:\Program Files\Java\jdk1.7.0_80\bin

I found that the only sure way to predict which version Ant will produce is by brute-forcing the following in build.xml:

<property name="ant.build.javac.source" value="1.7"/>
<property name="ant.build.javac.target" value="1.7"/>

So, my recommendation to you: Try placing in your build.xml the following:

<property name="ant.build.javac.source" value="1.8"/>
<property name="ant.build.javac.target" value="1.8"/>

Update, for the benefit of those with a variation of the problem described in the OP, to eliminate any possibility of "Eclipse fooling Ant":

Go to Window > Preferences > Java > Installed JREs and try leaving only the target JRE, making sure it is the one inside the JDK folder (not the sibling one directly under the Java folder).

Go to Project > Properties > Java Compiler and check Enable project specific settings, making sure that the Compiler compliance level is set to the target JRE java version.


问:
Best way to check for null values in Java?
Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.

What is the best way to go about this? I've considered these methods.

Which one is the best programming practice for Java?

```<code>// Method 1
if (foo != null) {
    if (foo.bar()) {
        etc...
    }
}

// Method 2
if (foo != null ? foo.bar() : false) {
    etc...
}

// Method 3
try {
    if (foo.bar()) {
        etc...
    }
} catch (NullPointerException e) {
}

// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
    etc...
}
</code>```

答:
Simple one line Code to check for null :</p>

```<code>namVar == null ? codTdoForNul() : codTdoForFul();
</code>```

Body:
Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.

What is the best way to go about this? I've considered these methods.

Which one is the best programming practice for Java?

// Method 1
if (foo != null) {
    if (foo.bar()) {
        etc...
    }
}

// Method 2
if (foo != null ? foo.bar() : false) {
    etc...
}

// Method 3
try {
    if (foo.bar()) {
        etc...
    }
} catch (NullPointerException e) {
}

// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
    etc...
}

Body:
Simple one line Code to check for null :

namVar == null ? codTdoForNul() : codTdoForFul();


问:
Join to a table only when column value is true
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

```<code>select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'
</code>```

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

答:
Very similar to what Dave said, although I would put the booleancolumn check into the WHERE so something like this</p>

```<code>SELECT * FROM T1
INNER JOIN T2
  ON T1.Value = T2.Value
WHERE T2.Value2 = 'variable2'
AND T2.Value3 = 'variable3'
AND T1.booleancolumn = 1
</code>```

OwnerDisplayName: Arni Gunnar Ragnarsson

Body:
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

Body:
Very similar to what Dave said, although I would put the booleancolumn check into the WHERE so something like this

SELECT * FROM T1
INNER JOIN T2
  ON T1.Value = T2.Value
WHERE T2.Value2 = 'variable2'
AND T2.Value3 = 'variable3'
AND T1.booleancolumn = 1

OwnerDisplayName: Ryan Lanciaux

ContentLicense: CC BY-SA 2.5


问:
How to target div#specificDiv in jquery?
I want to ask that how can i target a specific division in Jquery code. In the code below we are targeting "everything", Even if we change this to "div", it will target all the divisions in the file.But my question is that how can we target a specific division, As i want to target at the div with class "particles particles2"

$(document).ready(function() {

  $(document).on('click', function() {
    $('body').jGravity({
      target: 'eveything',
      ignoreClass: 'ignoreMe',
      weight: 25,
      depth: 5,
      drag: true
    });
    // Misc code for demo purposes
    $(this).removeClass('#fountains');

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="template-page"> </div>
<div class="particles particles2 ignoreMe jGravity" id="fountains"></div></code>```

答:
Here a small snippet that will help you understand how selectors work:

$(document).on('click', '.particles', function() {
  // code here that should be executed when particles div is clicked.
  alert("You clicked me!");
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="particles">Click</div></code>```

When you click on the 'click', an alert would be popped up, but if you click anywhere in the document, nothing happens. That's because, in JQuery, we have mentioned that the click event should get fired on the click on ".particles", which is the class of the div.

If you want to use IDs, you need to use '#'. Example:
$("#ID_OF_THE_CONTAINER")

Body:
Here a small snippet that will help you understand how selectors work:

$(document).on('click', '.particles', function() {
  // code here that should be executed when particles div is clicked.
  alert("You clicked me!");
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="particles">Click</div>

When you click on the 'click', an alert would be popped up, but if you click anywhere in the document, nothing happens. That's because, in JQuery, we have mentioned that the click event should get fired on the click on ".particles", which is the class of the div.

If you want to use IDs, you need to use '#'. Example:
$("#ID_OF_THE_CONTAINER")


问:
tidyr::spread() function throws an error
I try to use gather and spread functions in tidyverse package, but it throws an error in spread function

library(caret)

```<code>dataset<-iris

# gather function is to convert wide data to long data

dataset_gather<-dataset %>% tidyr::gather(key=Type,value = Values,1:4)

head(dataset_gather)

# spead is the opposite of gather
</code>```

This code below throws an error like this Error: Duplicate identifiers for rows

```<code>dataset_spead<- dataset_gather%>%tidyr::spread(key = Type,value = Values)
</code>```

答:
Added later: Sorry @alistaire, only saw your comment on the original post after posting this response.

As far as I understand Error: Duplicate identifiers for rows..., it occurs when you have values with the same identifier. For example in the original 'iris' dataset, the first five rows of Species = setosa all have a Petal.Width of 0.2, and three rows of Petal.Length have values of 1.4. Gathering those data isn't an issue, but when you try spread them, the function doesn't know what belongs to what. That is, which 0.2 Petal.Width and 1.4 Petal.Length belongs to which row of setosa.

The (tidyverse) solution I use in those circumstances is to create a unique marker for each row of data at the gather stage so that the function can keep track which duplicate data belong to which rows when you want to spread again. See example below:

# Load packages
library(dplyr)
library(tidyr)

# Get data
dataset <- iris

# View dataset
head(dataset)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa

# Gather data
dataset_gathered <- dataset %>%
    # Create a unique identifier for each row
    mutate(marker = row_number(Species)) %>%
    # Gather the data
    gather(key = Type, value = Values, 1:4)

# View gathered data
head(dataset_gathered)
#>   Species marker         Type Values
#> 1  setosa      1 Sepal.Length    5.1
#> 2  setosa      2 Sepal.Length    4.9
#> 3  setosa      3 Sepal.Length    4.7
#> 4  setosa      4 Sepal.Length    4.6
#> 5  setosa      5 Sepal.Length    5.0
#> 6  setosa      6 Sepal.Length    5.4

# Spread it out again
dataset_spread <- dataset_gathered %>%
    # Group the data by the marker
    group_by(marker) %>%
    # Spread it out again
    spread(key = Type, value = Values) %>%
    # Not essential, but remove marker
    ungroup() %>%
    select(-marker)

# View spread data
head(dataset_spread)
#> # A tibble: 6 x 5
#>   Species Petal.Length Petal.Width Sepal.Length Sepal.Width
#>    <fctr>        <dbl>       <dbl>        <dbl>       <dbl>
#> 1  setosa          1.4         0.2          5.1         3.5
#> 2  setosa          1.4         0.2          4.9         3.0
#> 3  setosa          1.3         0.2          4.7         3.2
#> 4  setosa          1.5         0.2          4.6         3.1
#> 5  setosa          1.4         0.2          5.0         3.6
#> 6  setosa          1.7         0.4          5.4         3.9
```

(and as ever, thanks to Jenny Bryan for the reprex package)

Body:
I try to use gather and spread functions in tidyverse package, but it throws an error in spread function

library(caret)

dataset<-iris

# gather function is to convert wide data to long data

dataset_gather<-dataset %>% tidyr::gather(key=Type,value = Values,1:4)

head(dataset_gather)

# spead is the opposite of gather

This code below throws an error like this Error: Duplicate identifiers for rows

dataset_spead<- dataset_gather%>%tidyr::spread(key = Type,value = Values)

Body:
Added later: Sorry @alistaire, only saw your comment on the original post after posting this response.

As far as I understand Error: Duplicate identifiers for rows..., it occurs when you have values with the same identifier. For example in the original 'iris' dataset, the first five rows of Species = setosa all have a Petal.Width of 0.2, and three rows of Petal.Length have values of 1.4. Gathering those data isn't an issue, but when you try spread them, the function doesn't know what belongs to what. That is, which 0.2 Petal.Width and 1.4 Petal.Length belongs to which row of setosa.

The (tidyverse) solution I use in those circumstances is to create a unique marker for each row of data at the gather stage so that the function can keep track which duplicate data belong to which rows when you want to spread again. See example below:

# Load packages
library(dplyr)
library(tidyr)

# Get data
dataset <- iris

# View dataset
head(dataset)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          5.1         3.5          1.4         0.2  setosa
#> 2          4.9         3.0          1.4         0.2  setosa
#> 3          4.7         3.2          1.3         0.2  setosa
#> 4          4.6         3.1          1.5         0.2  setosa
#> 5          5.0         3.6          1.4         0.2  setosa
#> 6          5.4         3.9          1.7         0.4  setosa

# Gather data
dataset_gathered <- dataset %>%
    # Create a unique identifier for each row
    mutate(marker = row_number(Species)) %>%
    # Gather the data
    gather(key = Type, value = Values, 1:4)

# View gathered data
head(dataset_gathered)
#>   Species marker         Type Values
#> 1  setosa      1 Sepal.Length    5.1
#> 2  setosa      2 Sepal.Length    4.9
#> 3  setosa      3 Sepal.Length    4.7
#> 4  setosa      4 Sepal.Length    4.6
#> 5  setosa      5 Sepal.Length    5.0
#> 6  setosa      6 Sepal.Length    5.4

# Spread it out again
dataset_spread <- dataset_gathered %>%
    # Group the data by the marker
    group_by(marker) %>%
    # Spread it out again
    spread(key = Type, value = Values) %>%
    # Not essential, but remove marker
    ungroup() %>%
    select(-marker)

# View spread data
head(dataset_spread)
#> # A tibble: 6 x 5
#>   Species Petal.Length Petal.Width Sepal.Length Sepal.Width
#>    <fctr>        <dbl>       <dbl>        <dbl>       <dbl>
#> 1  setosa          1.4         0.2          5.1         3.5
#> 2  setosa          1.4         0.2          4.9         3.0
#> 3  setosa          1.3         0.2          4.7         3.2
#> 4  setosa          1.5         0.2          4.6         3.1
#> 5  setosa          1.4         0.2          5.0         3.6
#> 6  setosa          1.7         0.4          5.4         3.9

(and as ever, thanks to Jenny Bryan for the reprex package)


问:
How am I supposed to initialize pthread mutexes?
```<code>#include <pthread.h>

pthread_mutex_t* mut;

int main()
{
        mut = PTHREAD_MUTEX_INITIALIZER;
}
</code>```

The above code spits out error: expected expression before ‘{’ token.

```<code>#include <pthread.h>

pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER;

int main()
{

}
</code>```

The above code spits out warning: braces around scalar initializer

So how am I supposed to initialize a mutex?

答:
Firstly you should declare it as pthread_mutex_t and not as a pointer pthread_mutex_t *. You should also decide if the mutex is global or local to a function.

If it's global you can initialize it using: pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

If it's local you have to call : pthread_mutex_init(&mut,NULL); (you have to check returned value)

Note that PTHREAD_MUTEX_INITIALIZER is a macro and you can't assign it to a pointer.

From pthread_mutex_init() man page :

Only mutex itself may be used for performing synchronization. The
  result of referring to copies of mutex in calls to
  pthread_mutex_lock(), pthread_mutex_trylock(), pthread_mutex_unlock(),
  and pthread_mutex_destroy() is undefined.
  Attempting to initialize an already initialized mutex results in
  undefined behavior.

Usually the method with the function call is used if you want to set attributes to the lock (second argument of the function) such as shareable between processes or recursive.

Body:
#include <pthread.h>

pthread_mutex_t* mut;

int main()
{
        mut = PTHREAD_MUTEX_INITIALIZER;
}

The above code spits out error: expected expression before ‘{’ token.

#include <pthread.h>

pthread_mutex_t* mut = PTHREAD_MUTEX_INITIALIZER;

int main()
{

}

The above code spits out warning: braces around scalar initializer

So how am I supposed to initialize a mutex?


问:
Disabling Java huge-pages system-wide on a RH machine
I know I can disable Java's use of huge-pages for a process by adding

```<code>-XX:-UseLargePages
</code>```

to the process invocation line.

However, I'd like to prevent every java application from using huge-pages, without me having to discover each process running on the machine.

Disabling THP in RH does not do it. Java still, by default, allocate memory from huge-pages even when THP is disabled.

答:
Try to set this in the environment variable JAVA_TOOL_OPTIONS

See http://www.oracle.com/technetwork/java/javase/envvars-138887.html for details

I checked this with my Eclipse installation. Before starting it I set the variable with set JAVA_TOOL_OPTIONS="-Dfoo=123 -Dbar=456" (using export on the command line or setting it in the environment file will do the same trick on Linux).

Checking the JVM with visualvm shows that the new parameters are considered:

On the console or the corresponding logfile you will most likely see an entry like this:

Picked up JAVA_TOOL_OPTIONS: "-Dfoo=123 -Dbar=456"

Body:
I know I can disable Java's use of huge-pages for a process by adding

-XX:-UseLargePages

to the process invocation line.

However, I'd like to prevent every java application from using huge-pages, without me having to discover each process running on the machine.

Disabling THP in RH does not do it. Java still, by default, allocate memory from huge-pages even when THP is disabled.


问:
Is there a way to set global axios config for error response codes
I'm using axios in my react/redux application and when I get errors like 401, 404, etc I currently have to deal with them for each action function when I make the calls to axios. I have a axios_config.js where I've wrapped the axios calls with some common idioms. For example:

```<code>// need to move this to app config
const BASE_URL = 'http://localhost:8080/api/';

function config() {
  return {
    headers: {'X-Token-Auth': localStorage.getItem('token')}
  }
}

export function fetchData(url) {
  return axios.get(`${BASE_URL}${url}`, config());
};
</code>```

Where I'm struggling are the common errors like 401, 404, etc. Currently, I'm doing this:

```<code>export function fetchBrands() {
  return function(dispatch) {
    dispatch({type:FETCHING_BRANDS});

    fetchData('brands')
      .then(response => {
        dispatch({
          type: FETCH_BRANDS_SUCCESS,
          payload: response
        });
      })
      .catch(err => {
        // deal with errors
      });
  }
}
</code>```

But in the catch block, I don't want to have to deal with 401, 404 etc every single time. So I need to be able to deal with those on a more global scale but still have the ability to handle specific errors to the request like server side validation errors for example.

答:
You can use response interceptors as documents in axios documentation.

axios.interceptors.response.use(undefined, function (error) {
    if(error.response.status === 401) {
      ipcRenderer.send('response-unauthenticated');
      return Promise.reject(error);
    }
  });```

other thread with same discussion

Body:
I'm using axios in my react/redux application and when I get errors like 401, 404, etc I currently have to deal with them for each action function when I make the calls to axios. I have a axios_config.js where I've wrapped the axios calls with some common idioms. For example:

// need to move this to app config
const BASE_URL = 'http://localhost:8080/api/';

function config() {
  return {
    headers: {'X-Token-Auth': localStorage.getItem('token')}
  }
}

export function fetchData(url) {
  return axios.get(`${BASE_URL}${url}`, config());
};

Where I'm struggling are the common errors like 401, 404, etc. Currently, I'm doing this:

export function fetchBrands() {
  return function(dispatch) {
    dispatch({type:FETCHING_BRANDS});

    fetchData('brands')
      .then(response => {
        dispatch({
          type: FETCH_BRANDS_SUCCESS,
          payload: response
        });
      })
      .catch(err => {
        // deal with errors
      });
  }
}

But in the catch block, I don't want to have to deal with 401, 404 etc every single time. So I need to be able to deal with those on a more global scale but still have the ability to handle specific errors to the request like server side validation errors for example.

Body:
You can use response interceptors as documents in axios documentation.

axios.interceptors.response.use(undefined, function (error) {
    if(error.response.status === 401) {
      ipcRenderer.send('response-unauthenticated');
      return Promise.reject(error);
    }
  });

other thread with same discussion

ContentLicense: CC BY-SA 4.0


问:
How to get old console logs (javascript)
I want to get a list of logs which are sent to browser's console. Is there any way to do it.</p>

```<code>console.log("lol");
console.log("imao");

list
->["lol", "imao"]
</code>```

答:
You can hijack JavaScript functions</p>

```<code>(function(){
    var oldLog = console.log;
    console.log = function (message) {
        // DO MESSAGE HERE.
        oldLog.apply(console, arguments);
    };
})();
</code>```

Body:
I want to get a list of logs which are sent to browser's console. Is there any way to do it.

console.log("lol");
console.log("imao");

list
->["lol", "imao"]

Body:
You can hijack JavaScript functions

(function(){
    var oldLog = console.log;
    console.log = function (message) {
        // DO MESSAGE HERE.
        oldLog.apply(console, arguments);
    };
})();


问:
How to retain data securely on browser refresh in angularja?
I have authorization data received after calling service. On browser refresh I want retain the data securely and avoid a service call. Please suggest. </p>

答:
You can use:

localStorage.setItem('data', data);

or

$window.localStorage.data = JSON.stringify(data);

It won't get deleted on page refresh. You can see data in local storage.

You can use cookies as well, those are used for authorization mostly, it is secure than local storage as well as they can be expired in some time.


问:
Will a captured __weak variable be copied to heap with the _block_copy() function?
When a Block which captures a __strong variable is copied to the heap,  the variable is also copied to the heap with the _block_copy() function.

But what would happen when using a __weak variable?

```<code>id __weak weakObj = someObj;
someBlock = [^() {
   //using __weak variable
} copy];
</code>```

答:
When a block captures any non-__block variable, the variable is always copied into an independent copy kept with the block when the block is created, not when the block is copied. It is true even if the block is not moved to the heap. This is also true regardless of the type of the variable (whether it is a primitive type, or ARC-managed strong or weak pointer type).

For example, if you run the following example with ARC turned off:

```<code>int foo = 5;
void (^someBlock)(void) = ^{
  NSLog(@"value in block: %d", foo);
};
foo = 6;
NSLog(@"value outside block: %d", foo); // logs "value outside block: 6"
someBlock();                            // logs "value in block: 5"
NSLog(@"block is: %@", someBlock);      // logs "block is: <__NSStackBlock__: 0x7fff523f0ba0>"
</code>```

You will notice that the block was never moved to the heap, as it was a __NSStackBlock__ at the end (I did it with ARC turned off to have control over the copying of blocks because ARC might implicitly move blocks to the heap defensively). You will also notice that the value of the variable inside the block was not affected by an assignment to the variable outside the block after the block was created, proving that the variable was copied before the assignment (i.e. when the block was created). This demonstration was done with a primitive int to show that it works for any type -- it doesn't only apply to ARC-managed pointer types -- but it is still equally true for ARC-managed pointer types, both strong and weak.

Body:
When a Block which captures a __strong variable is copied to the heap,  the variable is also copied to the heap with the _block_copy() function.

But what would happen when using a __weak variable?

id __weak weakObj = someObj;
someBlock = [^() {
   //using __weak variable
} copy];

Body:
When a block captures any non-__block variable, the variable is always copied into an independent copy kept with the block when the block is created, not when the block is copied. It is true even if the block is not moved to the heap. This is also true regardless of the type of the variable (whether it is a primitive type, or ARC-managed strong or weak pointer type).

For example, if you run the following example with ARC turned off:

int foo = 5;
void (^someBlock)(void) = ^{
  NSLog(@"value in block: %d", foo);
};
foo = 6;
NSLog(@"value outside block: %d", foo); // logs "value outside block: 6"
someBlock();                            // logs "value in block: 5"
NSLog(@"block is: %@", someBlock);      // logs "block is: <__NSStackBlock__: 0x7fff523f0ba0>"

You will notice that the block was never moved to the heap, as it was a __NSStackBlock__ at the end (I did it with ARC turned off to have control over the copying of blocks because ARC might implicitly move blocks to the heap defensively). You will also notice that the value of the variable inside the block was not affected by an assignment to the variable outside the block after the block was created, proving that the variable was copied before the assignment (i.e. when the block was created). This demonstration was done with a primitive int to show that it works for any type -- it doesn't only apply to ARC-managed pointer types -- but it is still equally true for ARC-managed pointer types, both strong and weak.


问:
How to install twitter kit using fabric plugin in android studio
I have recently install fabric plugin in Android studio and try to install twitter kit. But i could't find twitter kit in fabric. As I remember previously it was shown in all kits page.

Please guide me how to install twitter kit using fabric.

答:
Twitter sold Fabric to Google. A number of changes will occur in Fabric, because of this. One of them is that they removed Twitterkit from Fabric. You can still install it, however not via Fabric.
Here you can find the Twitter kit documentation

You will also have to update your applications with TwitterKit build in.
It is all explained in this blogpost. They sent an email to the admin of your Fabrics organization account.


问:
Play a 2nd flash video after the first ends
I have a flash object set up in the standard format:

```<code><script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript">
swfobject.embedSWF("swfplayer.swf", "myContent", "300", "120", "9", "expressInstall.swf");
</script>
</code>```

but I want to start playing a second flash video on a different part of the web page the moment the first video ends. Is there a kind of listener of some sort to use?

Thanks

答: Look at Detecting end of Flash movie in javascript</p>

Body:
I have a flash object set up in the standard format:

but I want to start playing a second flash video on a different part of the web page the moment the first video ends. Is there a kind of listener of some sort to use?

Thanks


问:
Access Title Property in ContentPage from XAML - Xamarin.Forms
I've created a Xamarin.Forms project and then I've added a "Forms Xaml Page" called Main.xaml. After that I've tried to choose a Title to the ContentPage. But I cannot find the Title property in ContentPage. Visual Studio 2015 doesn't show this option to me (see picture bellow):

Where's the Title property in ContentPage?

Also, I've put a StackLayout inside the ContentPage, but I cannot put a Button inside this StackLayout. I can put the Button inside the ContentPage, but not inside the StackLayout. Why that happens (see picture bellow)?

Why is not possible to find a Button inside the StackLayout?

I think I can access Title from codebehind, but not from XAML.

答:
This worked for me (answer from jonalza):

"Right click on XAML file -> click on "Open with..." option -> Select "XAML Desinger" in the list -> click on "Set as Default" button"
enter link description here

EDIT: As in your picture your line:  <?xml version="1.0" encoding="utf-8" ?> appears in red and blue, and not only in blue, as usual, also check the answer from Brendan Zagaeski...


问:
Multiple discount in sql query
I have a table like this:

```<code>----------------------------table---------------------------
item     price     discount_1%     discount2_%     quantitiy
------------------------------------------------------------
Crew     5.00      10              20              5
</code>```

I need to calculate the net prices for each row.
Now i use this query:

```<code>SELECT item, SUM((price * quantity) - ((price * quantity) * (discount_1% /100))) AS tot
FROM table.
</code>```

Now this query works pefectly for the first discount but i don't know how to calculate the second one...

The result must be:

```<code>--------------
item     tot
--------------
Crew     18
</code>```

答:
If the second discount is applied to the net price AFTER the first discount has been taken then you need to multiply the effect of the two discounts:-</p>

```<code>select
item,
price * 0.01 * (100 - discount_1%) * 0.01 * (100 - discount_2%) * quantity as total
from table
group by
item
</code>```

Title: Multiple discount in sql query

Body:
I have a table like this:

----------------------------table---------------------------
item     price     discount_1%     discount2_%     quantitiy
------------------------------------------------------------
Crew     5.00      10              20              5

I need to calculate the net prices for each row.
Now i use this query:

SELECT item, SUM((price * quantity) - ((price * quantity) * (discount_1% /100))) AS tot
FROM table.

Now this query works pefectly for the first discount but i don't know how to calculate the second one...

The result must be:

--------------
item     tot
--------------
Crew     18

Body:
If the second discount is applied to the net price AFTER the first discount has been taken then you need to multiply the effect of the two discounts:-

select
item,
price * 0.01 * (100 - discount_1%) * 0.01 * (100 - discount_2%) * quantity as total
from table
group by
item


问:
String returns in finally and try block
I came across this question and I am unable to understand the reason of the output it is giving.

The program is:

```<code>public static String method(){

    String s = new String();
    try
    {
        s = "return value from try block";
        return s;
    }
    catch (Exception e)
    {
        s = s + "return value from catch block";
        return s;
    }
    finally
    {
        s = s + "return value from finally block";
    }

}
</code>```

The output is:

return value from try block

Now, I debugged it and the value of s at return s statement in try block was return value from try block, return value from catch block after it returned from finally block.

Still the output is :

return value from try block

Can any one please explain this behavior?

答:
Avoid return statement in try block if you include finally in your code instead use it at the end of the method. Also, you can't modify the value of the returned variable in finally block.
See https://stackoverflow.com/a/3643047/6286156

Title: String returns in finally and try block

Body:
I came across this question and I am unable to understand the reason of the output it is giving.

The program is:

public static String method(){

    String s = new String();
    try
    {
        s = "return value from try block";
        return s;
    }
    catch (Exception e)
    {
        s = s + "return value from catch block";
        return s;
    }
    finally
    {
        s = s + "return value from finally block";
    }

}

The output is:

return value from try block

Now, I debugged it and the value of s at return s statement in try block was return value from try block, return value from catch block after it returned from finally block.

Still the output is :

return value from try block

Can any one please explain this behavior?


问:
List comprehension for Pythagorean Triples
I am new to Python and would like to learn how to use list comprehension.

I have this code that prints a list of Pythagorean Triples less than the user-input value n:

```<code>n = int(input("Enter the value of n:"))

a = 0
b = 0
c = 0
m = 2
triples = []

while c < n:
    for i in range(1, m, 1):
        a = m*m - i*i
        b = 2*m*i
        c = m*m + i*i
        if c > n:
            break
        triples.append((a, b, c))
    m += 1

print(triples)
</code>```

It kinda works but I want to do the same using list comprehension in Python how can we do that?

For example if I input 17 the output should be [(3,4,5), (8,6,10),(5,12,13), (15,8,17), (9,12,15)] however I am not getting (9,12,15).

答:
Take a look at the official python documentation for list comprehensions it explains how they work really well.

As for your actual question, the following should be an equivalent list comprehension to print the Pythagorean triples up til n:

```<code>n = int(input('Enter the value of n: '))
print([(a, b, c) for a in range(1, n + 1) for b in range(a, n + 1)
       for c in range(b, n + 1) if a**2 + b**2 == c**2])
</code>```

Hopefully, it is clear to you what the issue is in your current code :)

Example Usage:

```<code>Enter the value of n: 17
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15)]
</code>```

Edit: A more efficient version that utilizes Python 3.8's walrus operator:

```<code>import math

n = int(input('Enter the value of n: '))
print([(a, b, int(c)) for a in range(1, n + 1) for b in range(a, n + 1)
       if (c := math.sqrt(a**2 + b**2)) % 1 == 0 and c <= n])
</code>```

Body:
I am new to Python and would like to learn how to use list comprehension.

I have this code that prints a list of Pythagorean Triples less than the user-input value n:

n = int(input("Enter the value of n:"))

a = 0
b = 0
c = 0
m = 2
triples = []

while c < n:
    for i in range(1, m, 1):
        a = m*m - i*i
        b = 2*m*i
        c = m*m + i*i
        if c > n:
            break
        triples.append((a, b, c))
    m += 1

print(triples)

It kinda works but I want to do the same using list comprehension in Python how can we do that?

For example if I input 17 the output should be [(3,4,5), (8,6,10),(5,12,13), (15,8,17), (9,12,15)] however I am not getting (9,12,15).

Body:
Take a look at the official python documentation for list comprehensions it explains how they work really well.

As for your actual question, the following should be an equivalent list comprehension to print the Pythagorean triples up til n:

n = int(input('Enter the value of n: '))
print([(a, b, c) for a in range(1, n + 1) for b in range(a, n + 1)
       for c in range(b, n + 1) if a**2 + b**2 == c**2])

Hopefully, it is clear to you what the issue is in your current code :)

Example Usage:

Enter the value of n: 17
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15)]

Edit: A more efficient version that utilizes Python 3.8's walrus operator:

import math

n = int(input('Enter the value of n: '))
print([(a, b, int(c)) for a in range(1, n + 1) for b in range(a, n + 1)
       if (c := math.sqrt(a**2 + b**2)) % 1 == 0 and c <= n])


问:
Java throws Exception :Selenium 3.4.0,Gecko driver 16.01,FF 53.01
When run,java throws following exception:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{marionette=true, browserName=firefox, version=, platform=A.
Im using gecko driver 16.1.When I use gecko 14.01 its navigating till gmail page and then not able to find element even when I set implicit wait.</p>

```<code>    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.MarionetteDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    public class login {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
    System.setProperty("webdriver.gecko.driver","C:/Users/asdf/Desktop/selenium/gecko32/geckodriver.exe");
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);
    WebDriver driver = new MarionetteDriver(capabilities);
        //WebDriver driver = new FirefoxDriver();
        //  Wait For Page To Load
        // Put a Implicit wait, this means that any search for elements on the page
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        // Navigate to URL
    driver.get("https://mail.google.com/");
    driver.manage().window().maximize();
    //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        // gmail login
    driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    driver.findElement(By.id("next")).click();
    driver.findElement(By.id("Passwd")).sendKeys("password");
</code>```

答: Try to use latest versions of Firefox browser and gecko driver. Hope this helps</p>

Body:
When run,java throws following exception:
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Unable to create new remote session. desired capabilities = Capabilities [{marionette=true, browserName=firefox, version=, platform=A.
Im using gecko driver 16.1.When I use gecko 14.01 its navigating till gmail page and then not able to find element even when I set implicit wait.

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.firefox.MarionetteDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    public class login {
    public static void main(String[] args) {
        // Create a new instance of the Firefox driver
    System.setProperty("webdriver.gecko.driver","C:/Users/asdf/Desktop/selenium/gecko32/geckodriver.exe");
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability("marionette", true);
    WebDriver driver = new MarionetteDriver(capabilities);
        //WebDriver driver = new FirefoxDriver();
        //  Wait For Page To Load
        // Put a Implicit wait, this means that any search for elements on the page
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        // Navigate to URL
    driver.get("https://mail.google.com/");
    driver.manage().window().maximize();
    //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        // gmail login
    driver.findElement(By.xpath("//*[@id='identifierId']")).sendKeys("username");
    driver.findElement(By.id("next")).click();
    driver.findElement(By.id("Passwd")).sendKeys("password");


问:
Validate access to an entity: Customizing authorization validation annotations
There are two entities and two service layers in my Spring boot app: User , Group

The following removeMember method is in the service layer:

```<code>/*Remove member with id userId from group with id groupId, if username is the admin of that group*/
public void removeMember(long groupId, long userId, String username) {
    Group group = loadById(groupId);
    validateAdminAccessToGroup(group, username);
    User user = userService.loadById(userId);
    validateMemberAccessToGroup(group, user.getName());
    if (group.isAdmin(user)) {
        throw new BadRequestException("Group admin cannot delete himself/herself from the group");
    }
    group.removeMember(user);
}

private void validateAdminAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isAdmin(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId() + " as an admin");
    }
}

private void validateMemberAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isMember(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId());
    }
}
</code>```

As you can see, only the admin of a group can remove a member from that group.

validateAdminAccessToGroup validates that user has access admin access to a group, otherwise it throughs an error. validateMemberAccessToGroup validates that user is a member of a group.

Should we do this access check inside the method ? or using @PreAuthorize annotations ? Can we say this is a cross-cutting concern ?

答:
I would suggest you to use spring security's PreAuthorize classes. Here is an small example of the usage. Your code can be called from the PermissionEvaluator implementation, which will be invoked by spring internal classes.

since you need an entity/record based access, you can implement the overriden hasPermission method which takes the following parameters as input authentication(logged in user details), targetId(groupId), targetType(group), permission(delete).

You need to have the below annotation on top of the controller/service method.

@PreAuthorize("hasPermission(#groupId ,'groupd','delete')")

This will move all the authorization logic across all the different services into a single class.

Body:
There are two entities and two service layers in my Spring boot app: User , Group

The following removeMember method is in the service layer:

/*Remove member with id userId from group with id groupId, if username is the admin of that group*/
public void removeMember(long groupId, long userId, String username) {
    Group group = loadById(groupId);
    validateAdminAccessToGroup(group, username);
    User user = userService.loadById(userId);
    validateMemberAccessToGroup(group, user.getName());
    if (group.isAdmin(user)) {
        throw new BadRequestException("Group admin cannot delete himself/herself from the group");
    }
    group.removeMember(user);
}

private void validateAdminAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isAdmin(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId() + " as an admin");
    }
}

private void validateMemberAccessToGroup(Group group, String username) {
    User user = userService.loadByName(username);
    if (!group.isMember(user)) {
        throw new AccessDeniedException("User with id " + user.getId() + " was denied to access group with id " + group.getId());
    }
}

As you can see, only the admin of a group can remove a member from that group.

validateAdminAccessToGroup validates that user has access admin access to a group, otherwise it throughs an error. validateMemberAccessToGroup validates that user is a member of a group.

Should we do this access check inside the method ? or using @PreAuthorize annotations ? Can we say this is a cross-cutting concern ?


问:
user_create.sh Ubuntu shell script
Hi I am writing a shell script for a school assignment but cant seem to get it to work as needed. Bellow is what I have so far. What I am aiming to do is add the account name e.g. Real name to the user account when it is created. Also a Cron tab which records disk usage at 11:59 daily and saves it to storage.log. </p>

```<code>#!/bin/bash

IFS=","

while read f1 f2 f3 f4

do  hostname $f1
    useradd $f2
    passwd $f3
    groupadd $f4

        #echo "Real name      : $f1"

        #echo "Username          : $f2"

        #echo "Default password        : $f3"

        #echo "Group Name      : $f4"

59 11 * * * sudo du >>/home/bond/Desktop/GroupActivities/storage.log
done < /home/bond/Desktop/GroupActivities/data.csv
</code>```

答:
useradd command has a flag that does exactly what you need, from man useradd:

```<code>   -c, --comment COMMENT
       Any text string. It is generally a short description of the login, and is currently used as the field for the user's full name.
</code>```

Title: user_create.sh Ubuntu shell script

Body:
Hi I am writing a shell script for a school assignment but cant seem to get it to work as needed. Bellow is what I have so far. What I am aiming to do is add the account name e.g. Real name to the user account when it is created. Also a Cron tab which records disk usage at 11:59 daily and saves it to storage.log.

#!/bin/bash

IFS=","

while read f1 f2 f3 f4

do  hostname $f1
    useradd $f2
    passwd $f3
    groupadd $f4

        #echo "Real name      : $f1"

        #echo "Username          : $f2"

        #echo "Default password        : $f3"

        #echo "Group Name      : $f4"

59 11 * * * sudo du >>/home/bond/Desktop/GroupActivities/storage.log
done < /home/bond/Desktop/GroupActivities/data.csv

Body:
useradd command has a flag that does exactly what you need, from man useradd:

   -c, --comment COMMENT
       Any text string. It is generally a short description of the login, and is currently used as the field for the user's full name.