问:
Eclipse gives "Conversion to Dalvik format failed" while ant works
I recently updated my SDK Tools and the ADT Plugin to the latest version (got Android 2.3 as well). This required a few changes in my config (mainly I added proguard.config=procfg.txt to default.properties so that I could use the built-in support for proguard), and removed the old proguard config from build.xml. Now, my problem is that Eclipse gives a pretty lengthy error (which I'll embed at the end of the question) The problem is that I did not recently add any libraries. And again, compiling using ant works as expected:

```<code>$ ant debug
Buildfile: /home/felix/workspace/XXX/build.xml
    [setup] Android SDK Tools Revision 8
    [setup] Project Target: Android 2.3
    [setup] API level: 9
    [setup]
    [setup] ------------------
    [setup] Resolving library dependencies:
    [setup] No library dependencies.
    [setup]
    [setup] ------------------
    [setup]
    [setup] WARNING: Attribute minSdkVersion in AndroidManifest.xml (4) is lower than the project target API level (9)
    [setup]
    [setup] Importing rules file: tools/ant/main_rules.xml

-debug-obfuscation-check:

-set-debug-mode:

-compile-tested-if-test:

-dirs:
     [echo] Creating output directories if needed...

-pre-build:

-resource-src:
     [echo] Generating R.java / Manifest.java from the resources...

-aidl:
     [echo] Compiling aidl files into Java classes...

-pre-compile:

compile:
    [javac] /opt/android-sdk/tools/ant/main_rules.xml:361: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 1 source file to /home/felix/workspace/XXX/bin/classes

-post-compile:

-obfuscate:

-dex:
     [echo] Converting compiled files and external libraries into /home/felix/workspace/XXX/bin/classes.dex...

-package-resources:
     [echo] Packaging resources
     [aapt] Creating full resource package...

-package-debug-sign:
[apkbuilder] Creating XXX-debug-unaligned.apk and signing it with a debug key...

debug:
     [echo] Running zip align on final apk...
     [echo] Debug Package: /home/felix/workspace/XXX/bin/XXX-debug.apk

BUILD SUCCESSFUL
Total time: 6 seconds
</code>```

However, Eclipse is whining about repeated classes or something:

```<code>[2010-12-08 15:06:43 - XXX]: Dx
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lcom/android/vending/licensing/AESObfuscator;
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.DexFile.add(DexFile.java:143)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processClass(Main.java:338)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processFileBytes(Main.java:315)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.access$100(Main.java:56)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:266)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:244)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:130)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:108)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processOne(Main.java:284)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processAllFiles(Main.java:220)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.run(Main.java:176)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[2010-12-08 15:06:43 - XXX]: Dx at java.lang.reflect.Method.invoke(Method.java:597)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.DexWrapper.run(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.BuildHelper.executeDx(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder.build(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:627)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:170)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:253)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:256)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:309)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:341)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:140)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:238)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
[2010-12-08 15:06:43 - XXX]: Dx
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lcom/android/vending/licensing/AESObfuscator;
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.DexFile.add(DexFile.java:143)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processClass(Main.java:338)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processFileBytes(Main.java:315)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.access$100(Main.java:56)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:266)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:244)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:130)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:108)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processOne(Main.java:284)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processAllFiles(Main.java:220)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.run(Main.java:176)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[2010-12-08 15:06:43 - XXX]: Dx at java.lang.reflect.Method.invoke(Method.java:597)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.DexWrapper.run(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.BuildHelper.executeDx(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder.build(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:627)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:170)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:253)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:256)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:309)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:341)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:140)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:238)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
[2010-12-08 15:06:43 - XXX]: Dx
trouble processing:
[2010-12-08 15:06:44 - XXX]: Dxclass name (com/android/vending/licensing/LicenseCheckerCallback) does not match path (classes/com/android/vending/licensing/LicenseCheckerCallback.class)
...while parsing classes/com/android/vending/licensing/LicenseCheckerCallback.class
...while processing classes/com/android/vending/licensing/LicenseCheckerCallback.class
[2010-12-08 15:06:44 - XXX]: Dx
trouble processing:
[2010-12-08 15:06:44 - XXX]: Dxclass name (com/android/vending/licensing/NullDeviceLimiter) does not match path (classes/com/android/vending/licensing/NullDeviceLimiter.class)
...while parsing classes/com/android/vending/licensing/NullDeviceLimiter.class
...while processing classes/com/android/vending/licensing/NullDeviceLimiter.class
[2010-12-08 15:06:44 - XXX]: Dx
trouble processing:
[2010-12-08 15:06:44 - XXX]: Dxclass name (com/android/vending/licensing/PreferenceObfuscator) does not match path (classes/com/android/vending/licensing/PreferenceObfuscator.class)
...while parsing classes/com/android/vending/licensing/PreferenceObfuscator.class
...while processing classes/com/android/vending/licensing/PreferenceObfuscator.class
[2010-12-08 15:06:44 - XXX]: Dx
... --------------------------------------- ...
... and so on for every class in my project ...
... --------------------------------------- ...
[2010-12-08 15:06:44 - XXX]: Dx229 warnings
[2010-12-08 15:06:44 - XXX]: Dx2 errors; aborting
[2010-12-08 15:06:44 - XXX] Conversion to Dalvik format failed with error 1
</code>```

Why is this happening? Why is it looking in classes/, which doesn't exist?

The project worked without any problems until yesterday, and it still works if compiled via ant.

Edit: The usual Fix project properties and Clean project don't work.

Edit 2: The errors keep coming and going. I do not have any .jars. Also, I'm using ProGuard. At some point ant stopped working as well (can't remember the errors), I did a

```<code>touch `find .`
</code>```

and things started working again (both Eclipse and ant), for a while. Now Eclipse spews errors again. What's going on!?

Edit 3: It would seem the problem lies with the ProGuard integration. Whenever I comment out the proguard.config directive from default.properties and to a project refresh + clean, it works. This is pretty weird because, when building in debug mode, Eclipse shouldn't obfuscate / optimize the code via ProGuard anyway. Also, my ProGuard configuration works just fine via Ant.

Edit 4: Eclipse + Ant + ProGuard = not getting along together. If I close Eclipse, uncomment my proguard.config directive, build with Ant, comment my proguard.config directive, open Eclipse, Eclipse starts spewing errors. It would seem like Ant is leaving something behind. If I do a clean project it works just fine.

答:
FYI I managed to get the same error message when building one of my applications using ant. however in my case I'd left 2 versions of a jar file in the libs folder. Both jar files were included by my modified ant script (based on recommendations from Can't build and run an android test project created using "ant create test-project" when tested project has jars in libs directory ) which caused the issue. My eclipse project only had one of the 2 libraries specified so didn't encounter the problem.

My solution was simple and worked, I renamed one of the 2 jar files to another extension .jazz and I was able to build the project successfully using ant.

Body:
I recently updated my SDK Tools and the ADT Plugin to the latest version (got Android 2.3 as well). This required a few changes in my config (mainly I added proguard.config=procfg.txt to default.properties so that I could use the built-in support for proguard), and removed the old proguard config from build.xml. Now, my problem is that Eclipse gives a pretty lengthy error (which I'll embed at the end of the question) The problem is that I did not recently add any libraries. And again, compiling using ant works as expected:

$ ant debug
Buildfile: /home/felix/workspace/XXX/build.xml
    [setup] Android SDK Tools Revision 8
    [setup] Project Target: Android 2.3
    [setup] API level: 9
    [setup]
    [setup] ------------------
    [setup] Resolving library dependencies:
    [setup] No library dependencies.
    [setup]
    [setup] ------------------
    [setup]
    [setup] WARNING: Attribute minSdkVersion in AndroidManifest.xml (4) is lower than the project target API level (9)
    [setup]
    [setup] Importing rules file: tools/ant/main_rules.xml

-debug-obfuscation-check:

-set-debug-mode:

-compile-tested-if-test:

-dirs:
     [echo] Creating output directories if needed...

-pre-build:

-resource-src:
     [echo] Generating R.java / Manifest.java from the resources...

-aidl:
     [echo] Compiling aidl files into Java classes...

-pre-compile:

compile:
    [javac] /opt/android-sdk/tools/ant/main_rules.xml:361: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 1 source file to /home/felix/workspace/XXX/bin/classes

-post-compile:

-obfuscate:

-dex:
     [echo] Converting compiled files and external libraries into /home/felix/workspace/XXX/bin/classes.dex...

-package-resources:
     [echo] Packaging resources
     [aapt] Creating full resource package...

-package-debug-sign:
[apkbuilder] Creating XXX-debug-unaligned.apk and signing it with a debug key...

debug:
     [echo] Running zip align on final apk...
     [echo] Debug Package: /home/felix/workspace/XXX/bin/XXX-debug.apk

BUILD SUCCESSFUL
Total time: 6 seconds

However, Eclipse is whining about repeated classes or something:

[2010-12-08 15:06:43 - XXX]: Dx
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lcom/android/vending/licensing/AESObfuscator;
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.DexFile.add(DexFile.java:143)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processClass(Main.java:338)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processFileBytes(Main.java:315)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.access$100(Main.java:56)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:266)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:244)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:130)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:108)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processOne(Main.java:284)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processAllFiles(Main.java:220)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.run(Main.java:176)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[2010-12-08 15:06:43 - XXX]: Dx at java.lang.reflect.Method.invoke(Method.java:597)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.DexWrapper.run(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.BuildHelper.executeDx(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder.build(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:627)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:170)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:253)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:256)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:309)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:341)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:140)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:238)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
[2010-12-08 15:06:43 - XXX]: Dx
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.IllegalArgumentException: already added: Lcom/android/vending/licensing/AESObfuscator;
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.dex.file.DexFile.add(DexFile.java:143)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processClass(Main.java:338)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processFileBytes(Main.java:315)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.access$100(Main.java:56)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:266)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:244)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:130)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:190)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:122)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:108)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processOne(Main.java:284)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.processAllFiles(Main.java:220)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.dx.command.dexer.Main.run(Main.java:176)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[2010-12-08 15:06:43 - XXX]: Dx at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[2010-12-08 15:06:43 - XXX]: Dx at java.lang.reflect.Method.invoke(Method.java:597)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.DexWrapper.run(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.BuildHelper.executeDx(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder.build(Unknown Source)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:627)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:170)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:253)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:256)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:309)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:341)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:140)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:238)
[2010-12-08 15:06:43 - XXX]: Dx at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
[2010-12-08 15:06:43 - XXX]: Dx
trouble processing:
[2010-12-08 15:06:44 - XXX]: Dxclass name (com/android/vending/licensing/LicenseCheckerCallback) does not match path (classes/com/android/vending/licensing/LicenseCheckerCallback.class)
...while parsing classes/com/android/vending/licensing/LicenseCheckerCallback.class
...while processing classes/com/android/vending/licensing/LicenseCheckerCallback.class
[2010-12-08 15:06:44 - XXX]: Dx
trouble processing:
[2010-12-08 15:06:44 - XXX]: Dxclass name (com/android/vending/licensing/NullDeviceLimiter) does not match path (classes/com/android/vending/licensing/NullDeviceLimiter.class)
...while parsing classes/com/android/vending/licensing/NullDeviceLimiter.class
...while processing classes/com/android/vending/licensing/NullDeviceLimiter.class
[2010-12-08 15:06:44 - XXX]: Dx
trouble processing:
[2010-12-08 15:06:44 - XXX]: Dxclass name (com/android/vending/licensing/PreferenceObfuscator) does not match path (classes/com/android/vending/licensing/PreferenceObfuscator.class)
...while parsing classes/com/android/vending/licensing/PreferenceObfuscator.class
...while processing classes/com/android/vending/licensing/PreferenceObfuscator.class
[2010-12-08 15:06:44 - XXX]: Dx
... --------------------------------------- ...
... and so on for every class in my project ...
... --------------------------------------- ...
[2010-12-08 15:06:44 - XXX]: Dx229 warnings
[2010-12-08 15:06:44 - XXX]: Dx2 errors; aborting
[2010-12-08 15:06:44 - XXX] Conversion to Dalvik format failed with error 1

Why is this happening? Why is it looking in classes/, which doesn't exist?

The project worked without any problems until yesterday, and it still works if compiled via ant.

Edit: The usual Fix project properties and Clean project don't work.

Edit 2: The errors keep coming and going. I do not have any .jars. Also, I'm using ProGuard. At some point ant stopped working as well (can't remember the errors), I did a

touch `find .`

and things started working again (both Eclipse and ant), for a while. Now Eclipse spews errors again. What's going on!?

Edit 3: It would seem the problem lies with the ProGuard integration. Whenever I comment out the proguard.config directive from default.properties and to a project refresh + clean, it works. This is pretty weird because, when building in debug mode, Eclipse shouldn't obfuscate / optimize the code via ProGuard anyway. Also, my ProGuard configuration works just fine via Ant.

Edit 4: Eclipse + Ant + ProGuard = not getting along together. If I close Eclipse, uncomment my proguard.config directive, build with Ant, comment my proguard.config directive, open Eclipse, Eclipse starts spewing errors. It would seem like Ant is leaving something behind. If I do a clean project it works just fine.


来源: stackexchange

答:
```<code>window(timeColumn, windowDuration, slideDuration=None, startTime=None)
</code>```

First, window function will create a time templet which mean:

```<code>zero = 1970-01-01 00:00:00 UTC

[zero + startTime + slideDuration * n, zero + startTime + slideDuration * n + windowDuration)
</code>```

For example:

```<code>window('ts', '5 seconds', '3 seconds', '2 seconds')
# is equal to :
['1970-01-01 00:00:02', '1970-01-01 00:00:07'),
['1970-01-01 00:00:05', '1970-01-01 00:00:10'),
['1970-01-01 00:00:08', '1970-01-01 00:00:13'),
['1970-01-01 00:00:11', '1970-01-01 00:00:16'),
...
</code>```

Then, each row in your DataFrame will "fall into" time templet, according to timeColumn.
One row can belong to many time templet cells.

Finally, drop all empty time templet cells and do agg.

ContentLicense: CC BY-SA 3.0

Title: How to understand the result of the spark sql window function

Body:
I have the following code to try the spark sql window function:

test("spark sql time window 2") {
    val spark = SparkSession.builder().master("local").appName("SparkSQLWindowTest").getOrCreate()
    import spark.implicits._
    import org.apache.spark.sql.functions._
    val ds = Seq(
      SaleRecord("2017-10-11 09:01:12", 1),
      SaleRecord("2017-10-11 09:01:18", 6),
      SaleRecord("2017-10-11 10:11:12", 2),
      SaleRecord("2017-10-11 10:18:13", 5),
      SaleRecord("2017-10-11 10:22:13", 3),
      SaleRecord("2017-10-11 10:22:22", 6),
      SaleRecord("2017-10-11 10:34:56", 2),
      SaleRecord("2017-10-11 10:48:22", 6),
      SaleRecord("2017-10-11 11:52:23", 4),
      SaleRecord("2017-10-11 12:56:24", 2)).toDS

    val ds2 = ds.groupBy(window($"Time", "20 minutes", "9 minutes")).agg(sum("revenue")).orderBy("window.start")
    ds2.show(truncate = false)

    /*
+---------------------------------------------+------------+
|window                                       |sum(revenue)|
+---------------------------------------------+------------+
|[2017-10-11 08:45:00.0,2017-10-11 09:05:00.0]|7.0         |
|[2017-10-11 08:54:00.0,2017-10-11 09:14:00.0]|7.0         |
|[2017-10-11 09:57:00.0,2017-10-11 10:17:00.0]|2.0         |
|[2017-10-11 10:06:00.0,2017-10-11 10:26:00.0]|16.0        |
|[2017-10-11 10:15:00.0,2017-10-11 10:35:00.0]|16.0        |
|[2017-10-11 10:24:00.0,2017-10-11 10:44:00.0]|2.0         |
|[2017-10-11 10:33:00.0,2017-10-11 10:53:00.0]|8.0         |
|[2017-10-11 10:42:00.0,2017-10-11 11:02:00.0]|6.0         |
|[2017-10-11 11:36:00.0,2017-10-11 11:56:00.0]|4.0         |
|[2017-10-11 11:45:00.0,2017-10-11 12:05:00.0]|4.0         |
|[2017-10-11 12:39:00.0,2017-10-11 12:59:00.0]|2.0         |
|[2017-10-11 12:48:00.0,2017-10-11 13:08:00.0]|2.0         |
+---------------------------------------------+------------+

     */
  }

The definition of the SaleRecord is a simple case class:

case class SaleRecord(time: String, revenue: Double)

I could not understand how the first three rows is generated in the result?

Why the first window is
[2017-10-11 08:45:00.0,2017-10-11 09:05:00.0]

Body:
window(timeColumn, windowDuration, slideDuration=None, startTime=None)

First, window function will create a time templet which mean:

zero = 1970-01-01 00:00:00 UTC

[zero + startTime + slideDuration * n, zero + startTime + slideDuration * n + windowDuration)

For example:

window('ts', '5 seconds', '3 seconds', '2 seconds')
# is equal to :
['1970-01-01 00:00:02', '1970-01-01 00:00:07'),
['1970-01-01 00:00:05', '1970-01-01 00:00:10'),
['1970-01-01 00:00:08', '1970-01-01 00:00:13'),
['1970-01-01 00:00:11', '1970-01-01 00:00:16'),
...

Then, each row in your DataFrame will "fall into" time templet, according to timeColumn.
One row can belong to many time templet cells.

Finally, drop all empty time templet cells and do agg.


问:
using the function erase in std::vector
I Have this function, its purpose is to delete a pointer of class BaseFile
from a vector called children

```<code> //children is vector of type vector<BaseFile*>
void Directory::removeFile(BaseFile* file)
{
   for(int i = 0 ; (unsigned)i < children.size() ; i++)
    {
        if ((children[i]->getName()).compare(file->getName()) == 0)
        {
            BaseFile* a = children[i];
            children.erase(children.begin()+i);
            if(a != nullptr)
            {
                delete a;//err in this line : double free or corruption
            }
        }
    }
}
</code>```

first question is why I AM getting an error in the line (delete a;) ?
dose the method erase removes the pointer an delete it?
if yes how can i remove the pointer from the vector without deleting it's content in Heap/Stack?

答:
What you need to do is to use std::remove_if to obtain the vector without the matching element.

However, once you have performed the call to std::remove_if you have no way to delete the matching items as the documentation states (emphasis mine):

Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the physical size of the container is unchanged. Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values (as per MoveAssignable post-condition).

Therefore we'll handle the deletion directly in the predicate. Note that we must also take care not to double free anything so we'll keep track of the deleted item through the use of an std::unordered_set

```<code>void Directory::removeFile(BaseFile *file) {
     std::unordered_set<BaseFile*> deleted_set { file }; // Just to avoid deleting the input argument if it's stored in children as well...
     auto match_it = std::remove_if(begin(children), end(children),
          [&](BaseFile *current_file) -> bool {
              bool result = current_file->getName().compare(file->getName()) == 0;
              if (result && end(deleted_set) == deleted_set.find(current_file)) {
                  delete current_file;
                  deleted_set.insert(current_file);
              }
              return result;
          });
     children.erase(match_it, end(children));
}
</code>```

Finally, I hope that the pointer you give as the file argument isn't a member of children as well and if it is, that you don't end up delete-ing it!

Note: Wouldn't it be possible to use smart pointers in your case? It seems that the Directory object has ownership on the BaseFile objects stored in children... So maybe std::unique_ptr would help...

Title: using the function erase in std::vector

Body:
I Have this function, its purpose is to delete a pointer of class BaseFile
from a vector called children

 //children is vector of type vector<BaseFile*>
void Directory::removeFile(BaseFile* file)
{
   for(int i = 0 ; (unsigned)i < children.size() ; i++)
    {
        if ((children[i]->getName()).compare(file->getName()) == 0)
        {
            BaseFile* a = children[i];
            children.erase(children.begin()+i);
            if(a != nullptr)
            {
                delete a;//err in this line : double free or corruption
            }
        }
    }
}

first question is why I AM getting an error in the line (delete a;) ?
dose the method erase removes the pointer an delete it?
if yes how can i remove the pointer from the vector without deleting it's content in Heap/Stack?

Body:
What you need to do is to use std::remove_if to obtain the vector without the matching element.

However, once you have performed the call to std::remove_if you have no way to delete the matching items as the documentation states (emphasis mine):

Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the physical size of the container is unchanged. Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values (as per MoveAssignable post-condition).

Therefore we'll handle the deletion directly in the predicate. Note that we must also take care not to double free anything so we'll keep track of the deleted item through the use of an std::unordered_set

void Directory::removeFile(BaseFile *file) {
     std::unordered_set<BaseFile*> deleted_set { file }; // Just to avoid deleting the input argument if it's stored in children as well...
     auto match_it = std::remove_if(begin(children), end(children),
          [&](BaseFile *current_file) -> bool {
              bool result = current_file->getName().compare(file->getName()) == 0;
              if (result && end(deleted_set) == deleted_set.find(current_file)) {
                  delete current_file;
                  deleted_set.insert(current_file);
              }
              return result;
          });
     children.erase(match_it, end(children));
}

Finally, I hope that the pointer you give as the file argument isn't a member of children as well and if it is, that you don't end up delete-ing it!

Note: Wouldn't it be possible to use smart pointers in your case? It seems that the Directory object has ownership on the BaseFile objects stored in children... So maybe std::unique_ptr would help...


问:
How to make our customised dashboard as default dashboard on kibana
I have modified my dashboard and tried saving it as home and I get the below message

Home Set This page has been set as your default Kibana dashboard

Still I am not able to load the modified dashboard as default dashboard, please suggest me on how to do it.

答:
I have found the solution to show default dashboard in kibana :-

Steps :-

Copy id of the dashboard. For that go to your dashboard which you want to show as a default. At top right corner - click on SHARE after that you will see a link url something like :- http://localhost:5601/app/kibana#/dashboard/b55f44a0-4a78-11e7-8976-bcua7acbj?_g=()
From the url copy id after dashboard/ like in this url id is :- b55f44a0-4a78-11e7-8976-bcua7acbj

Go to kibana/config/kibana.yml file and change  :-
kibana.defaultAppId: "discover"  to
kibana.defaultAppId: "dashboard/b55f44a0-4a78-11e7-8976-bcua7acbj"

Now restart kibana.service :- "sudo systemctl restart kibana.service"

And it is done :)


问:
react-router vs react-router-dom, when to use one or the other?
Both have Route, Link, etc. When to use one or the other? I'm really confused on where to use each one. Server side? Client side?

https://reacttraining.com/react-router/

In some examples you need to pass the history, in others not. What to do?

```<code><Router history={browserHistory}>
</code>```

vs

```<code><Router>
</code>```

It's really confusing on when to use one or the other, any help appreciated.

答:
In v4, react-router exports the core components and functions.
react-router-dom exports DOM-aware components, like <Link> ( which
renders ) and  (which interacts with the browser's
window.history ).

react-router-dom re-exports all of react-router's exports, so you
only need to import from react-router-dom in your project.

(Source: GitHub)

Body:
Both have Route, Link, etc. When to use one or the other? I'm really confused on where to use each one. Server side? Client side?

https://reacttraining.com/react-router/

In some examples you need to pass the history, in others not. What to do?

<Router history={browserHistory}>

vs

<Router>

It's really confusing on when to use one or the other, any help appreciated.

Body:
In v4, react-router exports the core components and functions.
react-router-dom exports DOM-aware components, like <Link> ( which
renders <a>) and  (which interacts with the browser's
window.history ).

react-router-dom re-exports all of react-router's exports, so you
only need to import from react-router-dom in your project.

(Source: GitHub)

ContentLicense: CC BY-SA 4.0


问:
Link-time optimization (lto) for mixed C++/C programs
I wonder if it would be possible to effectively use link-time optimization (lto) for programms consisting of a TU with C++ code calling some function in a TU with C code. So, is there a way to get the C function inlined into the resulting program?

The real use case is a microcontroller firmware written in C++. But there are pieces of code that have to written in C because of C semantics (e.g. access to the non-active union member).

(This has nothing to do with manual marking functions as inline)

答:
This should not be a problem at all. In both GCC and Clang link-time optimization operates on intermediate representation of the code. That is, by using -flto you create object files with additional LTO information (gcc) or LLVM bytecode (Clang), at which point the source language stops to matter.

Some go as far as to mix even less related C++ and D yet still use LTO: http://johanengelen.github.io/ldc/2016/11/10/Link-Time-Optimization-LDC.html


问:
what's the intuition of opencv Top Hat and Black Hat
I recently started study opencv. I only have a bachelor's degree on engineering. I am having a hard time of understanding these 2 morphological transformation: Black Hat, Top Hat. the official documents is here

Can some one give some advice of what is the intuition of these operation and what is it for?

答:
Hopefully you understand ”morphological opening”. If so, the (white) Top Hat tells you the pixels that would be removed by ”opening”.

Likewise, the Black Hat tells you the pixels that would be added by ”morphological closing”.


问:
How to compute 'DynamoDB read throughput ratio' while setting up DataPipeline to export DynamoDB data to S3
I have a DynamoDB with ~16M records where each record is of size 4k. The table is configured for autoscaling Target utilization: 70%, Minimum provisioned capacity for Reads: 250 and Maximum provisioned capacity for Writes: 3000.

I am trying to setup data pipeline to backup DynamoDB to S3. The pipeline configuration asks for Read Throughput Ratio which is 0.25 by default.

So the question is how to compute Read Throughput Ratio to back up the table in ~1 Hours. I understand the read capacity units. How is the Read Throughput Ratio related to Read Capacity Units and Auto Scaling Configuration?

答:
Theoretically an RCU is 4KB so if you divide your data volume by 4KB you will get total RCU required for reading the complete data for the given second. So if you divide this value by 60*60 ( Minutes*Seconds) for 1 hour you will get the required RCU configuration but take into account the time required to setup EMR cluster.
But I am confused on how this will behave if auto scaling is configured to the particular table. </p>


问:
Update a struct in Arduino
I have one structure like below in Arduino, I want to update it

```<code>struct record
{
   int bookId;
   int qtyInStock;

};

typedef struct record Record;

Record aRec;
aRec.bookId = 100;
aRec.qtyInStock = 12;

aRec.bookId = 101;
aRec.qtyInStock = 10;

aRec.bookId = 102;
aRec.qtyInStock = 100;
</code>```

If bookId 101 is sold then how can I update qtyInStock? So, qtyInStock for bookId 101 should be 9 now.

Thanks

答:
I would keep all records in a linked list, and iterate over them, find the book id, decrease it's available count.

You know that you are editing a single record (aRec) in your example code right? You will need some sort of container for that:

```<code>struct node {
   Record* value;
   Node* next;
}

sruct recordList {
    Node* head;
}
/* ... */
</code>```

Title: Update a struct in Arduino

Body:
I have one structure like below in Arduino, I want to update it

struct record
{
   int bookId;
   int qtyInStock;

};

typedef struct record Record;

Record aRec;
aRec.bookId = 100;
aRec.qtyInStock = 12;

aRec.bookId = 101;
aRec.qtyInStock = 10;

aRec.bookId = 102;
aRec.qtyInStock = 100;

If bookId 101 is sold then how can I update qtyInStock? So, qtyInStock for bookId 101 should be 9 now.

Thanks

Body:
I would keep all records in a linked list, and iterate over them, find the book id, decrease it's available count.

You know that you are editing a single record (aRec) in your example code right? You will need some sort of container for that:

struct node {
   Record* value;
   Node* next;
}

sruct recordList {
    Node* head;
}
/* ... */


问:
Dynamically instantiate multiple copies of a MC
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

```<code>package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}
</code>```

EDIT:

```<code>package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}
</code>```

答:
Regarding this part of the question:

I then created a class and added it to
  the stage:

... addChild(new PostItNote());

But I wasn't able to (or don't know
  how) to set the x, y position on the
  stage.

The most basic and common way of setting x and y of a new object you add like that would probably be to do something like this:

```<code>var newPostIt:PostItNote = new PostItNote();
newPostIt.x = 100;
newPostIt.y = 200;
addChild(newPostIt);
</code>```

In other words, to keep a reference to the new object you create, instead of doing addChild(new PostItNote()), and set x and y and other properties before (or after) you add it to the stage.

ContentLicense: CC BY-SA 2.5

Body:
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}

EDIT:

package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}

Body:
Regarding this part of the question:

I then created a class and added it to
  the stage:

... addChild(new PostItNote());

But I wasn't able to (or don't know
  how) to set the x, y position on the
  stage.

The most basic and common way of setting x and y of a new object you add like that would probably be to do something like this:

var newPostIt:PostItNote = new PostItNote();
newPostIt.x = 100;
newPostIt.y = 200;
addChild(newPostIt);

In other words, to keep a reference to the new object you create, instead of doing addChild(new PostItNote()), and set x and y and other properties before (or after) you add it to the stage.


问:
How to increase the counter value when clicking the button in java script
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="divInfo">
      <span id="box1" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;"></span>
      <span id="box2" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box3" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box4" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box5" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box6" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box7" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box8" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box9" style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
      <span id="box10"style="border: 1px solid black; background: #CCCCCC; display: none;padding: 2px;height:90px;width:10px;float:left;margin-left:10px;"></span>
     </div>
     <div class="divInfo2">
      <input type="text" id="value" value="0">
     </div>
     <div class="IncDrc">
      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">
     </div>
     <div>
      <p id="demo"></p>
     </div></code>```

答:
You can pass the action as an argument to your function

```<code>var count = 0;
function myFunction(action, div) {
  if(action == 'add') {
    count++;
  else {
    count--;
  }
  // do something else
}
</code>```

then on your html

```<code><button type="button" onclick="myFunction('add', 'box')">+</button>
<button type="button" onclick="myFunction('sub', 'box')">-</button>
</code>```

Body:
I am new to java script i am doing one event that is when i clicking the plus button the css style was printed but value not increase. and same as clicking menus button the last child is not removed...

i want to print the css style and incremented value and same decrease value and delete the last child........

below is my html

    var counter = 0;
    var numBoxes = 10;
    function myFun(showDiv) {
           var ele = document.getElementById(showDiv + counter);
           if(counter>numBoxes) {
                  document.getElementById("incBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
           else {
                  ele.style.display = "block";
           }
           if(counter>0) {
                 ele.style.display = "block";
           }
           else {
                  document.getElementById("decBtn").addEventListener("click", function(){
        document.getElementById("demo").innerHTML = "Limit Is Over";
       });
           }
    }

      <input type="text" id="value" value="0">

      <input id="incBtn" type="button" value="+" onclick="counter++; myFun('box');">
      <input id="decBtn" type="button" value="-" onclick="counter--; myFun('box');">

Body:
You can pass the action as an argument to your function

var count = 0;
function myFunction(action, div) {
  if(action == 'add') {
    count++;
  else {
    count--;
  }
  // do something else
}

then on your html

<button type="button" onclick="myFunction('add', 'box')">+</button>
<button type="button" onclick="myFunction('sub', 'box')">-</button>


问:
Griddle_React default css
I am using griddle-react and have issues with default styling css i.e. 'griddle-cell' or 'griddle-row'. Where do I find/install corresponding css ? Or am I supposed to create myself ?

```<code><Griddle styleConfig={styleConfig}
            data={...}
            plugins={[plugins.LocalPlugin]}
/>
</code>```

and

```<code>const styleConfig = {
    classNames: {
        Cell: 'griddle-cell',
        Row: 'griddle-row', //'row-class',
    }
  }
</code>```

答:
Griddle 1.x does not ship with a default stylesheet, just default class names.

As of around v1.8 (via Griddle#677) it does include an incomplete LegacyStylePlugin that we'd love to align more closely with how Griddle 0.x rendered, if you care to contribute.

Title: Griddle_React default css

Body:
I am using griddle-react and have issues with default styling css i.e. 'griddle-cell' or 'griddle-row'. Where do I find/install corresponding css ? Or am I supposed to create myself ?

<Griddle styleConfig={styleConfig}
            data={...}
            plugins={[plugins.LocalPlugin]}
/>

and

const styleConfig = {
    classNames: {
        Cell: 'griddle-cell',
        Row: 'griddle-row', //'row-class',
    }
  }


问:
Creating voice command synonyms in GRXML
I've created a voice controlled UWP application in C++/CX (for Hololens, if that matters). A very simple one, mostly according to some samples, this is the speech recognition event handler:

```<code>void MyAppMain::HasSpoken(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionResultGeneratedEventArgs ^args)
{
    if (args->Result->Confidence == SpeechRecognitionConfidence::Medium
        || args->Result->Confidence == SpeechRecognitionConfidence::High)
    {
        process_voice_command(args->Result->Text);
    }
}
</code>```

Everything works so far, the recognition result is in args->Result->Text variable. Now, I only need to support a very limited set of voice commands and simply ignore everything else, but within that limited set of commands I want some variability. It seems, the last example on this page is exactly about that. So I made the following grammar file based on that:

```<code><grammar version="1.0" xml:lang="en-US" root="nextCommands" xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="nextCommands">
    <item>
      <one-of>
        <item>next</item>
        <item>go</item>
        <item>advance</item>
      </one-of>
      <tag>out="next";</tag>
    </item>
  </rule>

</grammar>
</code>```

What I want with it is that when I say either "next", "go" or "advance", the recognition engine just returns "next", so it is in the args->Result->Text above. What it actually does for me right now is limiting the set of recognized words to those three, but it simply returns the word I say, without converting it to "next". Looks like it either ignores the <tag> element, or I have to retrieve its content in a different way in my C++/CX program. Or <tag> doesn't work the way I think it does. What shall I change to make it work?

答:
I have found a way to do what I want with SRGS (at least for the very simple case described in the question). So, it seems <tag> doesn't change the recognition result directly (at least, not with tag-format="semantics/1.0", there are other tag-format's, as described, for example, here, they may do something else). Instead, it populates some additional collection of properties. So this is how I changed my code for now:

```<code><grammar version="1.0" xml:lang="en-US"
root="nextCommands" xmlns="http://www.w3.org/2001/06/grammar"
tag-format="semantics/1.0">

  <rule id="nextCommands">
    <item>
      <one-of>
        <item>next</item>
        <item>go</item>
        <item>advance</item>
      </one-of>
      <tag>out.HONEY="bunny";</tag>
    </item>
  </rule>

</grammar>
</code>```

Now, when either "next", "go" or "advance" is recognized, it still goes to args->Result->Text unchanged, but also there's gonna be a new pair in the args->Result->SemanticInterpretation->Properties with the HONEY key and the bunny value. I can check if that was the case with

```<code>args->Result->SemanticInterpretation->Properties->HasKey("HONEY");
</code>```

and, if so, retrieve the value of it with

```<code>args->Result->SemanticInterpretation->Properties->Lookup("HONEY")->GetAt(0); //returns "bunny"
</code>```

Body:
I've created a voice controlled UWP application in C++/CX (for Hololens, if that matters). A very simple one, mostly according to some samples, this is the speech recognition event handler:

void MyAppMain::HasSpoken(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionResultGeneratedEventArgs ^args)
{
    if (args->Result->Confidence == SpeechRecognitionConfidence::Medium
        || args->Result->Confidence == SpeechRecognitionConfidence::High)
    {
        process_voice_command(args->Result->Text);
    }
}

Everything works so far, the recognition result is in args->Result->Text variable. Now, I only need to support a very limited set of voice commands and simply ignore everything else, but within that limited set of commands I want some variability. It seems, the last example on this page is exactly about that. So I made the following grammar file based on that:

<grammar version="1.0" xml:lang="en-US" root="nextCommands" xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="nextCommands">
    <item>
      <one-of>
        <item>next</item>
        <item>go</item>
        <item>advance</item>
      </one-of>
      <tag>out="next";</tag>
    </item>
  </rule>

</grammar>

What I want with it is that when I say either "next", "go" or "advance", the recognition engine just returns "next", so it is in the args->Result->Text above. What it actually does for me right now is limiting the set of recognized words to those three, but it simply returns the word I say, without converting it to "next". Looks like it either ignores the <tag> element, or I have to retrieve its content in a different way in my C++/CX program. Or <tag> doesn't work the way I think it does. What shall I change to make it work?

Body:
I have found a way to do what I want with SRGS (at least for the very simple case described in the question). So, it seems <tag> doesn't change the recognition result directly (at least, not with tag-format="semantics/1.0", there are other tag-format's, as described, for example, here, they may do something else). Instead, it populates some additional collection of properties. So this is how I changed my code for now:

<grammar version="1.0" xml:lang="en-US"
root="nextCommands" xmlns="http://www.w3.org/2001/06/grammar"
tag-format="semantics/1.0">

  <rule id="nextCommands">
    <item>
      <one-of>
        <item>next</item>
        <item>go</item>
        <item>advance</item>
      </one-of>
      <tag>out.HONEY="bunny";</tag>
    </item>
  </rule>

</grammar>

Now, when either "next", "go" or "advance" is recognized, it still goes to args->Result->Text unchanged, but also there's gonna be a new pair in the args->Result->SemanticInterpretation->Properties with the HONEY key and the bunny value. I can check if that was the case with

args->Result->SemanticInterpretation->Properties->HasKey("HONEY");

and, if so, retrieve the value of it with

args->Result->SemanticInterpretation->Properties->Lookup("HONEY")->GetAt(0); //returns "bunny"


问:
Debugging Jquery ajax function
JS code:

```<code>$.ajax({

        type: 'POST',
         url: 'http://localhost/MyServiceDir/Service.asmx/Foo',
         contentType: 'application/json; charset=utf-8',
         data: jsonData,
         success: function (msg) {
             alert("good");
         },
         error: function (xhr, status) {
              switch (status) {
                 case 404:
                     alert('File not found');
                     break;
                 case 500:
                     alert('Server error');
                     break;
                 case 0:
                     alert('Request aborted');
                     break;
                 default:
                     alert('Unknown error ' + status);
             }
         }
     });
</code>```

I get "unknown error error". How do I get to the bottom of this? I would like to know what the error actually is. Thanks!

答:
The "status" parameter only includes why it failed -- timeout, error, etc... To get the status code you need to check the response object: xhr.status

See http://www.w3.org/TR/XMLHttpRequest/#response for details.

If you are getting "500 Internal Server Error" that is all you are going to get from ajax. You will have to check your application or server logs. This could be a syntax error or or library error or something else along those lines.

Title: Debugging Jquery ajax function

Body:
JS code:

$.ajax({

        type: 'POST',
         url: 'http://localhost/MyServiceDir/Service.asmx/Foo',
         contentType: 'application/json; charset=utf-8',
         data: jsonData,
         success: function (msg) {
             alert("good");
         },
         error: function (xhr, status) {
              switch (status) {
                 case 404:
                     alert('File not found');
                     break;
                 case 500:
                     alert('Server error');
                     break;
                 case 0:
                     alert('Request aborted');
                     break;
                 default:
                     alert('Unknown error ' + status);
             }
         }
     });

I get "unknown error error". How do I get to the bottom of this? I would like to know what the error actually is. Thanks!


问:
Django: Distinct Users Filtering
I'm trying to build a messaging app. Here's my model,

```<code>class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
</code>```

This is what I tried in view,

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))
</code>```

In the template,

```<code>{% for abc in data %}
    {{ abc.receiver }} <br/>
{% endfor %}
</code>```

Here i wants to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). How can I do that?

答:
Add distinct in your query

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('receiver').distinct().order_by()
</code>```

This query will fetch all the distinct recievers from the message objects

Updated answer:-

.distinct([*fields]) will work with postgresql

```<code>data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('receiver','-created_at').distinct('reciever')
</code>```

Title: Django: Distinct Users Filtering

Body:
I'm trying to build a messaging app. Here's my model,

class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in view,

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))

In the template,

{% for abc in data %}
    {{ abc.receiver }}

{% endfor %}

Here i wants to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). How can I do that?

Body:
Add distinct in your query

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('receiver').distinct().order_by()

This query will fetch all the distinct recievers from the message objects

Updated answer:-

.distinct([*fields]) will work with postgresql

data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('receiver','-created_at').distinct('reciever')


问:
Adding className but css is not affecting in ReactJS Components
I have a component called Single Box which will return a div , but i need to have the same class for 6 times , one of the way is i can write Single Box component six times , but thats not a good way.

So i made another component which Multiple Box , here i will loop the Single Box component for six times .

SingleBox

```<code>  render(){
    return(
      <div className="box-content"></div>
    )
  }
</code>```

MultipleBox

```<code> render(){
  let singleBoxArray = [];
   for (var i=0; i<3; i++) {
     if(i< 2){
       singleBoxArray.push(<SingleBox key={i}/>);
     }else {
       singleBoxArray.push(<SingleBox className="box-three"/>)
     }
   }
    return(
      <div>
        {singleBoxArray}
      </div>
    )

    }
</code>```

Here for the "Third SingleBox" , i need add one more class and it should affect the css. when i make the console.log("array" , singleBoxArray). For the third elememet i am getting the className in this.props, but my css is not changing .

Many Thanks in Advance

答:
first, you don't need the curly braces for className="box-three"
second, what is the variable singleBox that you are returning in render, I can't find its declaration anywhere, maybe you meant to return the singleBoxArray instead

Body:
I have a component called Single Box which will return a div , but i need to have the same class for 6 times , one of the way is i can write Single Box component six times , but thats not a good way.

So i made another component which Multiple Box , here i will loop the Single Box component for six times .

SingleBox

  render(){
    return(

    )
  }

MultipleBox

 render(){
  let singleBoxArray = [];
   for (var i=0; i<3; i++) {
     if(i< 2){
       singleBoxArray.push(<SingleBox key={i}/>);
     }else {
       singleBoxArray.push(<SingleBox className="box-three"/>)
     }
   }
    return(

        {singleBoxArray}

    )

    }

Here for the "Third SingleBox" , i need add one more class and it should affect the css. when i make the console.log("array" , singleBoxArray). For the third elememet i am getting the className in this.props, but my css is not changing .

Many Thanks in Advance


问:
Execute ffmpeg command without waiting for completion
I want to continuously run a ffmpeg command in php and when this process is running other php methods need to execute in their own process without waiting for the ffmpeg command to complete.  How can I do this?</p>

答:
Look into CRON
It lets you schedule tasks you want to run in the background at a specified pattern.</p>


问:
Creating Nested Multidimensional Array with Loop from Database
I have been working at this for days and have nearly pulled my hair out.

I am trying to output JSON from a FOREACH loop so I can use it to template a daily class schedule. I have got most of the way there and things continue to break or come out unexpected.

The below code produced this:

```<code> {
"DAY": "TUESDAY",
"TIME": {
    "530": {
        "CLASSES": [
            {
                "CLASS": {
                    "INSTRUCTOR": "DANA",
                    "CLASS_LEVEL": "JUNIOR",
                    "MAX_STUDENTS": "8"
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Alexandra",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Leivi",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Traivon",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Keira",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Madison",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
</code>```

However, as you can see, I would like the "STUDENTS" nested underneath "CLASS". What am I doing wrong? I cannot figure it out for the life of me. I am starting to hate multidimensional arrays. :-@

```<code>function dailySchedule() {
    global $conn;
    $sql = 'SET DATEFIRST 1

            SELECT [DAY].[DAY] AS [DAY], CLASS.CLASSTIME AS CLASSTIME, CLASSLEVEL.CLASSLEVEL AS CLASSLEVEL, CLASS.MAXSTUDENT AS MAXSTUDENT,
            INSTRUCTOR.FIRSTNAME AS INSTRUCTOR, STUDENT.FIRSTNAME AS STUDENTFIRST, STUDENT.SURNAME AS STUDENTLAST, STUDENT.DOB AS STUDENTDOB

            FROM STUDENT JOIN BOOKING ON STUDENT.ID = BOOKING.STUDENTID JOIN CLASS ON CLASS.ID = BOOKING.CLASSID JOIN CLASSLEVEL ON
            CLASS.CLASSLEVELID = CLASSLEVEL.ID JOIN [DAY] ON CLASS.CLASSDAY = [DAY].ID JOIN INSTRUCTOR ON CLASS.INSTRUCTORID = INSTRUCTOR.ID

            WHERE   [DAY].ID = (DATEPART(dw, GETUTCDATE() AT TIME ZONE \'AUS Eastern Standard Time\'))

            ORDER BY CLASS.CLASSTIME ASC, INSTRUCTOR.FIRSTNAME ASC, CLASSLEVEL.CLASSLEVEL ASC';

    $studentDetails =
    $sqlEx = $conn->query($sql);
    $schedule = array();

    foreach($sqlEx as $rows) {

        if(!isset($day) || $day !== $rows['DAY']) {
            $day = $rows['DAY'];
            $schedule = array('DAY' => $day) + $schedule;
        }
        if(!isset($time) || $time !== $rows['CLASSTIME']) {
            $time = $rows['CLASSTIME'];
        }
        if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
            $instructor = $rows['INSTRUCTOR'];
            $schedule['TIME'][$time]['CLASSES'][]['CLASS'] = [
                'INSTRUCTOR' => $instructor,
                'CLASS_LEVEL' => $rows['CLASSLEVEL'],
                'MAX_STUDENTS' => $rows['MAXSTUDENT'],
            ];
        }

        //if($instructor == $rows['INSTRUCTOR']){
            $schedule['TIME'][$time]['CLASSES'][]['CLASS']['STUDENTS'][]['STUDENT'][] = [
                    'FIRST NAME' => $rows['STUDENTFIRST'],
                    'LAST NAME' => $rows['STUDENTLAST'],
                    'DATE OF BIRTH' => $rows['STUDENTDOB']
                    ];

        //}

    }
    echo json_encode($schedule, JSON_PRETTY_PRINT);
</code>```

}

Thanks in advance everyone.

答:
I'm not sure is it what you want or not but the top of my head I would use a way different approach : </p>

```<code>$schedule = array();

    foreach($sqlEx as $rows) {

       $Day = $rows["DAY"];
       $ClassTime = $rows["CLASSTIME"];
       $ClassLevel = $rows["CLASSLEVEL"];
       $MaxStudents = $rows["MAXSTUDENTS"];
       $Instructor = $rows["INSTRUCTOR"];
       $StudentFirst = $rows["STUDENTFIRST"];
       $StudentLast = $rows["STUDENTLAST"];
       $StudentDOB = $rows["STUDENTDOB"];

       $schedule[$Day][$ClassTime]["CLASS"] = array("INSTRUCTOR" => $Instructor,"CLASS_LEVEL" =>$ClassLevel,"MAX_SUTENTS" => $MaxStudents);
       $schedule[$Day][$ClassTime]["STUDENT"] = array("FIRSTNAME" => $StudentFirst ,"LASTNAME" => $StudentLast, "DATE OF BIRTH" => $StudentDOB);

    }

    echo json_encode($schedule, JSON_PRETTY_PRINT);
</code>```

Body:
I have been working at this for days and have nearly pulled my hair out.

I am trying to output JSON from a FOREACH loop so I can use it to template a daily class schedule. I have got most of the way there and things continue to break or come out unexpected.

The below code produced this:

 {
"DAY": "TUESDAY",
"TIME": {
    "530": {
        "CLASSES": [
            {
                "CLASS": {
                    "INSTRUCTOR": "DANA",
                    "CLASS_LEVEL": "JUNIOR",
                    "MAX_STUDENTS": "8"
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Alexandra",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Leivi",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Traivon",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Keira",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "CLASS": {
                    "STUDENTS": [
                        {
                            "STUDENT": [
                                {
                                    "FIRST NAME": "Madison",
                                    "LAST NAME": "",
                                    "DATE OF BIRTH": ""
                                }
                            ]
                        }
                    ]
                }
            },

However, as you can see, I would like the "STUDENTS" nested underneath "CLASS". What am I doing wrong? I cannot figure it out for the life of me. I am starting to hate multidimensional arrays. :-@

function dailySchedule() {
    global $conn;
    $sql = 'SET DATEFIRST 1

            SELECT [DAY].[DAY] AS [DAY], CLASS.CLASSTIME AS CLASSTIME, CLASSLEVEL.CLASSLEVEL AS CLASSLEVEL, CLASS.MAXSTUDENT AS MAXSTUDENT,
            INSTRUCTOR.FIRSTNAME AS INSTRUCTOR, STUDENT.FIRSTNAME AS STUDENTFIRST, STUDENT.SURNAME AS STUDENTLAST, STUDENT.DOB AS STUDENTDOB

            FROM STUDENT JOIN BOOKING ON STUDENT.ID = BOOKING.STUDENTID JOIN CLASS ON CLASS.ID = BOOKING.CLASSID JOIN CLASSLEVEL ON
            CLASS.CLASSLEVELID = CLASSLEVEL.ID JOIN [DAY] ON CLASS.CLASSDAY = [DAY].ID JOIN INSTRUCTOR ON CLASS.INSTRUCTORID = INSTRUCTOR.ID

            WHERE   [DAY].ID = (DATEPART(dw, GETUTCDATE() AT TIME ZONE \'AUS Eastern Standard Time\'))

            ORDER BY CLASS.CLASSTIME ASC, INSTRUCTOR.FIRSTNAME ASC, CLASSLEVEL.CLASSLEVEL ASC';

    $studentDetails =
    $sqlEx = $conn->query($sql);
    $schedule = array();

    foreach($sqlEx as $rows) {

        if(!isset($day) || $day !== $rows['DAY']) {
            $day = $rows['DAY'];
            $schedule = array('DAY' => $day) + $schedule;
        }
        if(!isset($time) || $time !== $rows['CLASSTIME']) {
            $time = $rows['CLASSTIME'];
        }
        if(!isset($instructor) || $instructor !== $rows['INSTRUCTOR']) {
            $instructor = $rows['INSTRUCTOR'];
            $schedule['TIME'][$time]['CLASSES'][]['CLASS'] = [
                'INSTRUCTOR' => $instructor,
                'CLASS_LEVEL' => $rows['CLASSLEVEL'],
                'MAX_STUDENTS' => $rows['MAXSTUDENT'],
            ];
        }

        //if($instructor == $rows['INSTRUCTOR']){
            $schedule['TIME'][$time]['CLASSES'][]['CLASS']['STUDENTS'][]['STUDENT'][] = [
                    'FIRST NAME' => $rows['STUDENTFIRST'],
                    'LAST NAME' => $rows['STUDENTLAST'],
                    'DATE OF BIRTH' => $rows['STUDENTDOB']
                    ];

        //}

    }
    echo json_encode($schedule, JSON_PRETTY_PRINT);

}

Thanks in advance everyone.

Body:
I'm not sure is it what you want or not but the top of my head I would use a way different approach :

$schedule = array();

    foreach($sqlEx as $rows) {

       $Day = $rows["DAY"];
       $ClassTime = $rows["CLASSTIME"];
       $ClassLevel = $rows["CLASSLEVEL"];
       $MaxStudents = $rows["MAXSTUDENTS"];
       $Instructor = $rows["INSTRUCTOR"];
       $StudentFirst = $rows["STUDENTFIRST"];
       $StudentLast = $rows["STUDENTLAST"];
       $StudentDOB = $rows["STUDENTDOB"];

       $schedule[$Day][$ClassTime]["CLASS"] = array("INSTRUCTOR" => $Instructor,"CLASS_LEVEL" =>$ClassLevel,"MAX_SUTENTS" => $MaxStudents);
       $schedule[$Day][$ClassTime]["STUDENT"] = array("FIRSTNAME" => $StudentFirst ,"LASTNAME" => $StudentLast, "DATE OF BIRTH" => $StudentDOB);

    }

    echo json_encode($schedule, JSON_PRETTY_PRINT);


问:
Which thread async operations take place
Afte reading the asio's documentation, it's clear to me that the completion handlers are called by one of the threads that called the io_service's  io.run() method. However, something that's is not clear to me is which thread the read/write async methods take place. Is it the thread that I call the methods or is it in one of the threads that called the io.run() method? Or, in last case, does the library create another thread behind the scenes and performs the operation?

答:
For instance, you want to send some data to a remote-partner - asynchronous.

```<code>boost::asio::async_write(_socket, boost::asio::buffer(msg.data(), msg.size()),
    std::bind(&Socket::WriteHandlerInternal, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2));
//Where 'this' is the class Socket
</code>```

Before that, you probably have created a thread which called ioService.run(). The async_write function will take the same ioService you have used to create your socket. It puts it into the queue of your ioService to execute the write operation and the handler - on the thread your ioService runs on, as the async_ already suggests.

Body:
For instance, you want to send some data to a remote-partner - asynchronous.

boost::asio::async_write(_socket, boost::asio::buffer(msg.data(), msg.size()),
    std::bind(&Socket::WriteHandlerInternal, this->shared_from_this(), std::placeholders::_1, std::placeholders::_2));
//Where 'this' is the class Socket

Before that, you probably have created a thread which called ioService.run(). The async_write function will take the same ioService you have used to create your socket. It puts it into the queue of your ioService to execute the write operation and the handler - on the thread your ioService runs on, as the async_ already suggests.


问:
NSInvalidArgumentException, reason: 'Invalid type in JSON write (__NSDate)'
I'm getting this exception when I try to JSON encode NSDate object.I believe NSDate is not compatible for JSON encoding. but I must encode the date.Any solutions?</p>

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
</code>```

答:
For our case, we are using Mantle to convert an object to JSON and one of our objects with property NSDate is missing its JSONTransformer

```<code>@property (nonatomic) NSDate *expiryDate;
</code>```

where:

```<code>+ (NSValueTransformer *)expiryDateJSONTransformer {
     return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
        return [self.dateFormatter dateFromString:dateString];
    } reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
        return [self.dateFormatter stringFromDate:date];
    }];
}

+ (NSDateFormatter *)dateFormatter {
    NSDateFormatter *df = [NSDateFormatter new];
    df.dateFormat = @"yyyy-MM-dd";
    return df;
}
</code>```

Body:
I'm getting this exception when I try to JSON encode NSDate object.I believe NSDate is not compatible for JSON encoding. but I must encode the date.Any solutions?

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'

Body:
For our case, we are using Mantle to convert an object to JSON and one of our objects with property NSDate is missing its JSONTransformer

@property (nonatomic) NSDate *expiryDate;

where:

+ (NSValueTransformer *)expiryDateJSONTransformer {
     return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
        return [self.dateFormatter dateFromString:dateString];
    } reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
        return [self.dateFormatter stringFromDate:date];
    }];
}

+ (NSDateFormatter *)dateFormatter {
    NSDateFormatter *df = [NSDateFormatter new];
    df.dateFormat = @"yyyy-MM-dd";
    return df;
}