问:
[ERROR]TransactionBuilder. - The transaction currently built is missing an attachment for :classnet/corda/core/contracts/CommandData
When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.

MetalContract

```<code>
import com.template.states.MetalState;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.contracts.ContractState;
import net.corda.core.identity.Party;
import net.corda.core.transactions.LedgerTransaction;
import org.jetbrains.annotations.NotNull;

import java.security.PublicKey;
import java.util.List;

// ************
// * Contract *
// ************
public class MetalContract implements Contract {
    // This is used to identify our contract when building a transaction.
    public static final String CID = "com.template.contracts.MetalContract";

    // A transaction is valid if the verify() function of the contract of all the transaction's input and output states
    // does not throw an exception.
    @Override
    public void verify(@NotNull LedgerTransaction tx) throws IllegalArgumentException{

        if (tx.getCommands().size() != 1)
            throw new IllegalArgumentException("Transaction must have one Command.");

        Command command = tx.getCommand(0);
        CommandData commandType = command.getValue();

        List<PublicKey> requiredSigners = command.getSigners();

        // -------------------------------- Issue Command Contract Rules ------------------------------------------

     if (commandType instanceof Issue) {
         // Issue transaction logic

         // Shape Rules

         if (tx.getInputs().size() != 0)
             throw new IllegalArgumentException("Issue cannot have inputs");

         if (tx.getOutputs().size() != 1)
             throw new IllegalArgumentException("Issue can only have one output");

         // Content Rules

         ContractState outputState = tx.getOutput(0);

         if (!(outputState instanceof MetalState))
             throw new IllegalArgumentException("Output must be a metal State");

         MetalState metalState = (MetalState) outputState;

         if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
             throw new IllegalArgumentException("Metal is not Gold or Silver");
         }

         // Signer Rules

         Party issuer = metalState.getIssuer();
         PublicKey issuersKey = issuer.getOwningKey();

         if (!(requiredSigners.contains(issuersKey)))
             throw new IllegalArgumentException("Issuer has to sign the issuance");

     }

        // -------------------------------- Transfer Command Contract Rules ------------------------------------------

       else if (commandType instanceof Transfer) {
            // Transfer transaction logic

            // Shape Rules

            if (tx.getInputs().size() != 1)
                throw new IllegalArgumentException("Transfer needs to have one input");

            if (tx.getOutputs().size() != 1)
                throw new IllegalArgumentException("Transfer can only have one output");

            // Content Rules

            ContractState inputState = tx.getInput(0);
            ContractState outputState = tx.getOutput(0);

            if (!(outputState instanceof MetalState))
                throw new IllegalArgumentException("Output must be a metal State");

            MetalState metalState = (MetalState) inputState;

            if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
                throw new IllegalArgumentException("Metal is not Gold or Silver");
            }

            // Signer Rules

            Party owner = metalState.getOwner();
            PublicKey ownersKey = owner.getOwningKey();

            if (!(requiredSigners.contains(ownersKey)))
                throw new IllegalArgumentException("Owner has to sign the transfer");

        }

       else  throw new IllegalArgumentException("Unrecognised command.");

    }

    // Used to indicate the transaction's intent.
    public static class Issue implements CommandData {}
    public static class Transfer implements CommandData {}
}
</code>```
```<code>package com.template.contracts;

import com.template.states.MetalState;
import com.template.contracts.MetalContract;
import net.corda.core.contracts.Contract;
import net.corda.core.identity.CordaX500Name;
import net.corda.testing.contracts.DummyState;
import net.corda.testing.core.DummyCommandData;
import net.corda.testing.core.TestIdentity;
import net.corda.testing.node.MockServices;
import org.junit.Test;

import static net.corda.testing.node.NodeTestUtils.transaction;

public class ContractTests {

    private final TestIdentity Mint = new TestIdentity (new CordaX500Name ("mint", "", "GB"));
    private final TestIdentity TraderA = new TestIdentity (new CordaX500Name ("traderA", "", "GB"));
    private final TestIdentity TraderB = new TestIdentity (new CordaX500Name ("traderB", "", "GB"));

    private final MockServices ledgerServices = new MockServices();

    private MetalState metalState = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateInput = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateOutput = new MetalState("Gold", 10, Mint.getParty(), TraderB.getParty());

    @Test
    public void metalContractImplementsContract() {
        assert (new MetalContract() instanceof Contract);
    }
    @Test
    public void MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction() {

        transaction(ledgerServices, tx -> {
            // Issuer is not a required signer, will fail
            tx.output(MetalContract.CID, metalState);
            tx.command(TraderA.getPublicKey(), new MetalContract.Issue());
            tx.fails();
            return null;
        });

        transaction(ledgerServices, tx -> {
            // Issuer is a required, will verify
            tx.output(MetalContract.CID, metalState);
            tx.command(Mint.getPublicKey(), new MetalContract.Issue());
            tx.verifies();
            return null;
        });
    }
    }
</code>```

The Error is as following .

```<code>[ERROR] 12:35:10,086 [main] transactions.TransactionBuilder. - The transaction currently built is missing an attachment for class: net/corda/core/contracts/CommandData.
                        Attempted to find a suitable attachment but could not find any in the storage.
                        Please contact the developer of the CorDapp for further instructions.

java.lang.NoClassDefFoundError: net/corda/core/contracts/CommandData

    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at net.corda.serialization.internal.model.TypeIdentifier$Unparameterised.getLocalType(TypeIdentifier.kt:151)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:25)
    at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:25)
    at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:149)
    at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:109)
    at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:133)
    at kotlin.collections.MapsKt__MapsKt.putAll(Maps.kt:339)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:504)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:498)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader.load(TypeLoader.kt:45)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.reflect(RemoteSerializerFactory.kt:129)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.access$reflect(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:71)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultDescriptorBasedSerializerRegistry.getOrBuild(DescriptorBasedSerializerRegistry.kt:28)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.get(RemoteSerializerFactory.kt:66)
    at net.corda.serialization.internal.amqp.ComposedSerializerFactory.get(SerializerFactory.kt)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObject(DeserializationInput.kt:172)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObjectOrNull(DeserializationInput.kt:147)
    at net.corda.serialization.internal.amqp.DeserializationInput$deserialize$1.invoke(DeserializationInput.kt:124)
    at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:99)
    at net.corda.serialization.internal.amqp.DeserializationInput.deserialize(DeserializationInput.kt:119)
    at net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme.deserialize(AMQPSerializationScheme.kt:145)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1$1.invoke(SerializationScheme.kt:105)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:105)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:73)
    at net.corda.core.serialization.SerializationFactory.asCurrent(SerializationAPI.kt:85)
    at net.corda.serialization.internal.SerializationFactoryImpl.deserialize(SerializationScheme.kt:105)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:78)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at java.util.AbstractList$Itr.next(AbstractList.java:358)
    at net.corda.core.transactions.LedgerTransaction.createLtxForVerification(LedgerTransaction.kt:668)
    at net.corda.core.transactions.LedgerTransaction.access$createLtxForVerification(LedgerTransaction.kt:44)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:154)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:44)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder$withAttachmentsClassloaderContext$1.invoke(AttachmentsClassLoader.kt:345)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext(AttachmentsClassLoader.kt:344)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext$default(AttachmentsClassLoader.kt:319)
    at net.corda.core.transactions.LedgerTransaction.internalPrepareVerify$core(LedgerTransaction.kt:146)
    at net.corda.core.transactions.LedgerTransaction.verify(LedgerTransaction.kt:136)
    at net.corda.core.transactions.TransactionBuilder.addMissingDependency(TransactionBuilder.kt:185)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core(TransactionBuilder.kt:165)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core$default(TransactionBuilder.kt:133)
    at net.corda.core.transactions.TransactionBuilder.toWireTransaction(TransactionBuilder.kt:130)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.toWireTransaction$test_utils(TestDSL.kt:131)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.verifies(TestDSL.kt:175)
    at net.corda.testing.dsl.Verifies$DefaultImpls.failsWith(LedgerDSLInterpreter.kt:45)
    at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.failsWith(TransactionDSLInterpreter.kt)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.failsWith(TestDSL.kt:74)
    at net.corda.testing.dsl.Verifies$DefaultImpls.fails(LedgerDSLInterpreter.kt:75)
    at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.fails(TransactionDSLInterpreter.kt)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.fails(TestDSL.kt:74)
    at net.corda.testing.dsl.TransactionDSL.fails(TransactionDSLInterpreter.kt)
    at com.template.contracts.ContractTests.lambda$MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction$8(ContractTests.java:134)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt:54)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt:39)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt:231)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt)
    at net.corda.testing.common.internal.CommonSerializationTestHelpersKt.asContextEnv(CommonSerializationTestHelpers.kt:11)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv(InternalSerializationTestHelpers.kt:33)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv$default(InternalSerializationTestHelpers.kt:31)
    at net.corda.testing.internal.InternalTestUtilsKt.withTestSerializationEnvIfNotSet(InternalTestUtils.kt:231)
    at net.corda.testing.node.NodeTestUtils.ledger(NodeTestUtils.kt:36)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt:53)
    at net.corda.testing.node.NodeTestUtils.transaction$default(NodeTestUtils.kt:51)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt)
    at com.template.contracts.ContractTests.MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction(ContractTests.java:130)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
Caused by: java.lang.ClassNotFoundException: net.corda.core.contracts.CommandData
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at net.corda.core.serialization.internal.AttachmentsClassLoader.loadClass(AttachmentsClassLoader.kt:289)
    ... 115 more
</code>```

build.gradle from Contract module

```<code>apply plugin: 'net.corda.plugins.cordapp'
apply plugin: 'net.corda.plugins.cordformation'

cordapp {
    targetPlatformVersion corda_platform_version
    minimumPlatformVersion corda_platform_version
    contract {
        name "Template CorDapp"
        vendor "Corda Open Source"
        licence "Apache License, Version 2.0"
        versionId 1
    }
}

sourceSets {
    main{
        java {
            srcDir 'src/main/java'
            java.outputDir = file('bin/main')
        }
    }
    test{
        java{
            srcDir 'src/test/java'
            java.outputDir = file('bin/test')
        }
    }
}

dependencies {
    // Corda dependencies.
    cordaCompile "$corda_release_group:corda-core:$corda_release_version"
    cordaRuntime "$corda_release_group:corda:$corda_release_version"
    testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
}
</code>```

答:
It looks like something wrong with your project structure since it is a NoClassDefFoundError of a core package.

Try closing the project and also removing the project from your recent project list.
And open the project folder then follow the prompt to import Gradle project.

Body:
When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.

MetalContract

import com.template.states.MetalState;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.contracts.ContractState;
import net.corda.core.identity.Party;
import net.corda.core.transactions.LedgerTransaction;
import org.jetbrains.annotations.NotNull;

import java.security.PublicKey;
import java.util.List;

// ************
// * Contract *
// ************
public class MetalContract implements Contract {
    // This is used to identify our contract when building a transaction.
    public static final String CID = "com.template.contracts.MetalContract";

    // A transaction is valid if the verify() function of the contract of all the transaction's input and output states
    // does not throw an exception.
    @Override
    public void verify(@NotNull LedgerTransaction tx) throws IllegalArgumentException{

        if (tx.getCommands().size() != 1)
            throw new IllegalArgumentException("Transaction must have one Command.");

        Command command = tx.getCommand(0);
        CommandData commandType = command.getValue();

        List<PublicKey> requiredSigners = command.getSigners();

        // -------------------------------- Issue Command Contract Rules ------------------------------------------

     if (commandType instanceof Issue) {
         // Issue transaction logic

         // Shape Rules

         if (tx.getInputs().size() != 0)
             throw new IllegalArgumentException("Issue cannot have inputs");

         if (tx.getOutputs().size() != 1)
             throw new IllegalArgumentException("Issue can only have one output");

         // Content Rules

         ContractState outputState = tx.getOutput(0);

         if (!(outputState instanceof MetalState))
             throw new IllegalArgumentException("Output must be a metal State");

         MetalState metalState = (MetalState) outputState;

         if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
             throw new IllegalArgumentException("Metal is not Gold or Silver");
         }

         // Signer Rules

         Party issuer = metalState.getIssuer();
         PublicKey issuersKey = issuer.getOwningKey();

         if (!(requiredSigners.contains(issuersKey)))
             throw new IllegalArgumentException("Issuer has to sign the issuance");

     }

        // -------------------------------- Transfer Command Contract Rules ------------------------------------------

       else if (commandType instanceof Transfer) {
            // Transfer transaction logic

            // Shape Rules

            if (tx.getInputs().size() != 1)
                throw new IllegalArgumentException("Transfer needs to have one input");

            if (tx.getOutputs().size() != 1)
                throw new IllegalArgumentException("Transfer can only have one output");

            // Content Rules

            ContractState inputState = tx.getInput(0);
            ContractState outputState = tx.getOutput(0);

            if (!(outputState instanceof MetalState))
                throw new IllegalArgumentException("Output must be a metal State");

            MetalState metalState = (MetalState) inputState;

            if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
                throw new IllegalArgumentException("Metal is not Gold or Silver");
            }

            // Signer Rules

            Party owner = metalState.getOwner();
            PublicKey ownersKey = owner.getOwningKey();

            if (!(requiredSigners.contains(ownersKey)))
                throw new IllegalArgumentException("Owner has to sign the transfer");

        }

       else  throw new IllegalArgumentException("Unrecognised command.");

    }

    // Used to indicate the transaction's intent.
    public static class Issue implements CommandData {}
    public static class Transfer implements CommandData {}
}

package com.template.contracts;

import com.template.states.MetalState;
import com.template.contracts.MetalContract;
import net.corda.core.contracts.Contract;
import net.corda.core.identity.CordaX500Name;
import net.corda.testing.contracts.DummyState;
import net.corda.testing.core.DummyCommandData;
import net.corda.testing.core.TestIdentity;
import net.corda.testing.node.MockServices;
import org.junit.Test;

import static net.corda.testing.node.NodeTestUtils.transaction;

public class ContractTests {

    private final TestIdentity Mint = new TestIdentity (new CordaX500Name ("mint", "", "GB"));
    private final TestIdentity TraderA = new TestIdentity (new CordaX500Name ("traderA", "", "GB"));
    private final TestIdentity TraderB = new TestIdentity (new CordaX500Name ("traderB", "", "GB"));

    private final MockServices ledgerServices = new MockServices();

    private MetalState metalState = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateInput = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
    private MetalState metalStateOutput = new MetalState("Gold", 10, Mint.getParty(), TraderB.getParty());

    @Test
    public void metalContractImplementsContract() {
        assert (new MetalContract() instanceof Contract);
    }
    @Test
    public void MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction() {

        transaction(ledgerServices, tx -> {
            // Issuer is not a required signer, will fail
            tx.output(MetalContract.CID, metalState);
            tx.command(TraderA.getPublicKey(), new MetalContract.Issue());
            tx.fails();
            return null;
        });

        transaction(ledgerServices, tx -> {
            // Issuer is a required, will verify
            tx.output(MetalContract.CID, metalState);
            tx.command(Mint.getPublicKey(), new MetalContract.Issue());
            tx.verifies();
            return null;
        });
    }
    }

The Error is as following .

[ERROR] 12:35:10,086 [main] transactions.TransactionBuilder. - The transaction currently built is missing an attachment for class: net/corda/core/contracts/CommandData.
                        Attempted to find a suitable attachment but could not find any in the storage.
                        Please contact the developer of the CorDapp for further instructions.

java.lang.NoClassDefFoundError: net/corda/core/contracts/CommandData

    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at net.corda.serialization.internal.model.TypeIdentifier$Unparameterised.getLocalType(TypeIdentifier.kt:151)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:25)
    at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:38)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:25)
    at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:149)
    at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:109)
    at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:133)
    at kotlin.collections.MapsKt__MapsKt.putAll(Maps.kt:339)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:504)
    at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:498)
    at net.corda.serialization.internal.model.ClassCarpentingTypeLoader.load(TypeLoader.kt:45)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.reflect(RemoteSerializerFactory.kt:129)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.access$reflect(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:71)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:47)
    at net.corda.serialization.internal.amqp.DefaultDescriptorBasedSerializerRegistry.getOrBuild(DescriptorBasedSerializerRegistry.kt:28)
    at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.get(RemoteSerializerFactory.kt:66)
    at net.corda.serialization.internal.amqp.ComposedSerializerFactory.get(SerializerFactory.kt)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObject(DeserializationInput.kt:172)
    at net.corda.serialization.internal.amqp.DeserializationInput.readObjectOrNull(DeserializationInput.kt:147)
    at net.corda.serialization.internal.amqp.DeserializationInput$deserialize$1.invoke(DeserializationInput.kt:124)
    at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:99)
    at net.corda.serialization.internal.amqp.DeserializationInput.deserialize(DeserializationInput.kt:119)
    at net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme.deserialize(AMQPSerializationScheme.kt:145)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1$1.invoke(SerializationScheme.kt:105)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:105)
    at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:73)
    at net.corda.core.serialization.SerializationFactory.asCurrent(SerializationAPI.kt:85)
    at net.corda.serialization.internal.SerializationFactoryImpl.deserialize(SerializationScheme.kt:105)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:78)
    at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
    at java.util.AbstractList$Itr.next(AbstractList.java:358)
    at net.corda.core.transactions.LedgerTransaction.createLtxForVerification(LedgerTransaction.kt:668)
    at net.corda.core.transactions.LedgerTransaction.access$createLtxForVerification(LedgerTransaction.kt:44)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:154)
    at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:44)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder$withAttachmentsClassloaderContext$1.invoke(AttachmentsClassLoader.kt:345)
    at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext(AttachmentsClassLoader.kt:344)
    at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext$default(AttachmentsClassLoader.kt:319)
    at net.corda.core.transactions.LedgerTransaction.internalPrepareVerify$core(LedgerTransaction.kt:146)
    at net.corda.core.transactions.LedgerTransaction.verify(LedgerTransaction.kt:136)
    at net.corda.core.transactions.TransactionBuilder.addMissingDependency(TransactionBuilder.kt:185)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core(TransactionBuilder.kt:165)
    at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core$default(TransactionBuilder.kt:133)
    at net.corda.core.transactions.TransactionBuilder.toWireTransaction(TransactionBuilder.kt:130)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.toWireTransaction$test_utils(TestDSL.kt:131)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.verifies(TestDSL.kt:175)
    at net.corda.testing.dsl.Verifies$DefaultImpls.failsWith(LedgerDSLInterpreter.kt:45)
    at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.failsWith(TransactionDSLInterpreter.kt)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.failsWith(TestDSL.kt:74)
    at net.corda.testing.dsl.Verifies$DefaultImpls.fails(LedgerDSLInterpreter.kt:75)
    at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.fails(TransactionDSLInterpreter.kt)
    at net.corda.testing.dsl.TestTransactionDSLInterpreter.fails(TestDSL.kt:74)
    at net.corda.testing.dsl.TransactionDSL.fails(TransactionDSLInterpreter.kt)
    at com.template.contracts.ContractTests.lambda$MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction$8(ContractTests.java:134)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt:54)
    at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt:39)
    at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt:231)
    at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt)
    at net.corda.testing.common.internal.CommonSerializationTestHelpersKt.asContextEnv(CommonSerializationTestHelpers.kt:11)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv(InternalSerializationTestHelpers.kt:33)
    at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv$default(InternalSerializationTestHelpers.kt:31)
    at net.corda.testing.internal.InternalTestUtilsKt.withTestSerializationEnvIfNotSet(InternalTestUtils.kt:231)
    at net.corda.testing.node.NodeTestUtils.ledger(NodeTestUtils.kt:36)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt:53)
    at net.corda.testing.node.NodeTestUtils.transaction$default(NodeTestUtils.kt:51)
    at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt)
    at com.template.contracts.ContractTests.MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction(ContractTests.java:130)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
Caused by: java.lang.ClassNotFoundException: net.corda.core.contracts.CommandData
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at net.corda.core.serialization.internal.AttachmentsClassLoader.loadClass(AttachmentsClassLoader.kt:289)
    ... 115 more

build.gradle from Contract module

apply plugin: 'net.corda.plugins.cordapp'
apply plugin: 'net.corda.plugins.cordformation'

cordapp {
    targetPlatformVersion corda_platform_version
    minimumPlatformVersion corda_platform_version
    contract {
        name "Template CorDapp"
        vendor "Corda Open Source"
        licence "Apache License, Version 2.0"
        versionId 1
    }
}

sourceSets {
    main{
        java {
            srcDir 'src/main/java'
            java.outputDir = file('bin/main')
        }
    }
    test{
        java{
            srcDir 'src/test/java'
            java.outputDir = file('bin/test')
        }
    }
}

dependencies {
    // Corda dependencies.
    cordaCompile "$corda_release_group:corda-core:$corda_release_version"
    cordaRuntime "$corda_release_group:corda:$corda_release_version"
    testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
}


来源: stackexchange

问:
Join table with null in all group
im new in stack. I cant found problem like this.

I have two tables.

One table x with transactions

```<code>Hour (approximation to full hour)   id_seler     expenses
1:00                                    1             3,04
2:00                                    2             4,04
3:00                                    3             5,03
4:00                                    4             6,04
3:00                                    4             7,04
</code>```

Second table y with limit seler id:

```<code>seler_id
   1
   2
   4
   5
</code>```

I try to join table y to table x to get score like this

```<code>id_seler      hour            sum expensex
   1        1:00              3,04
   1        2:00              null
   1        3:00              null
   1        4:00              null
   2        1:00              null
   2        2:00              4,04
   2        3:00              null
   2        4:00              null
   4        1:00              null
   4        2:00              null
   4       3:00               7,04
   4        4:00              6,04
   5        1:00              null
   5        2:00              null
   5       3:00               null
   5       4:00               null
</code>```

I want that query back me all id_seler for all hours with expenses.

I tried to use left join

```<code>from y left join x on x.id_seller=y.id_seller
group by hour
</code>```

but it back me null only for this id_seler which is dosent exist in table x next of last hour - In this exaple for id_seler=5

答:
In order to have all of the Hour values in your final result, you have to CROSS JOIN table y with a full list of Hour values.

The best solution would be to build a table with all of the Hour values that you need in it. If you can't build a table, you can use a sub-query, or you might be able to derive the Hours values from table x.

Sub-Query

```<code>SELECT
  h.Hour,
  y.Seler_ID
FROM
  (
    SELECT v.Hour
    FROM (VALUES ('0:00'),
                 ('1:00'),
                 ('2:00'),
                 ('3:00')
                 -- Keep adding values here.
          ) v(Hour)
  ) AS h
  CROSS JOIN
  y;
</code>```

From Table x

```<code>SELECT
  h.Hour,
  y.Seler_ID
FROM
  (
    SELECT DISTINCT
      Hour
    FROM x
  ) AS h
  CROSS JOIN
  y;
</code>```

Either way, the results (short version):

```<code>  0:00   1
  1:00   1
  2:00   1
  3:00   1
  0:00   2
  1:00   2
  2:00   2
  3:00   2
  0:00   4
  1:00   4
  2:00   4
  3:00   4
  0:00   5
  1:00   5
  2:00   5
  3:00   5
</code>```

Now that you have all of the Hour and seler_id values, LEFT JOIN to your x table to get the expenses.

```<code>SELECT
  h.Hour,
  y.Seler_ID,
  x.expenses
FROM
  (
    SELECT DISTINCT
      Hour
    FROM x
  ) AS h
  CROSS JOIN
  y
  LEFT JOIN
  x
    ON x.Hour = h.Hour
    ANS x.seler_id = y.seler_id
</code>```

ContentLicense: CC BY-SA 4.0

Title: Join table with null in all group

Body:
im new in stack. I cant found problem like this.

I have two tables.

One table x with transactions

Hour (approximation to full hour)   id_seler     expenses
1:00                                    1             3,04
2:00                                    2             4,04
3:00                                    3             5,03
4:00                                    4             6,04
3:00                                    4             7,04

Second table y with limit seler id:

seler_id
   1
   2
   4
   5

I try to join table y to table x to get score like this

id_seler      hour            sum expensex
   1        1:00              3,04
   1        2:00              null
   1        3:00              null
   1        4:00              null
   2        1:00              null
   2        2:00              4,04
   2        3:00              null
   2        4:00              null
   4        1:00              null
   4        2:00              null
   4       3:00               7,04
   4        4:00              6,04
   5        1:00              null
   5        2:00              null
   5       3:00               null
   5       4:00               null

I want that query back me all id_seler for all hours with expenses.

I tried to use left join

from y left join x on x.id_seller=y.id_seller
group by hour

but it back me null only for this id_seler which is dosent exist in table x next of last hour - In this exaple for id_seler=5

Body:
In order to have all of the Hour values in your final result, you have to CROSS JOIN table y with a full list of Hour values.

The best solution would be to build a table with all of the Hour values that you need in it. If you can't build a table, you can use a sub-query, or you might be able to derive the Hours values from table x.

Sub-Query

SELECT
  h.Hour,
  y.Seler_ID
FROM
  (
    SELECT v.Hour
    FROM (VALUES ('0:00'),
                 ('1:00'),
                 ('2:00'),
                 ('3:00')
                 -- Keep adding values here.
          ) v(Hour)
  ) AS h
  CROSS JOIN
  y;

From Table x

SELECT
  h.Hour,
  y.Seler_ID
FROM
  (
    SELECT DISTINCT
      Hour
    FROM x
  ) AS h
  CROSS JOIN
  y;

Either way, the results (short version):

  0:00   1
  1:00   1
  2:00   1
  3:00   1
  0:00   2
  1:00   2
  2:00   2
  3:00   2
  0:00   4
  1:00   4
  2:00   4
  3:00   4
  0:00   5
  1:00   5
  2:00   5
  3:00   5

Now that you have all of the Hour and seler_id values, LEFT JOIN to your x table to get the expenses.

SELECT
  h.Hour,
  y.Seler_ID,
  x.expenses
FROM
  (
    SELECT DISTINCT
      Hour
    FROM x
  ) AS h
  CROSS JOIN
  y
  LEFT JOIN
  x
    ON x.Hour = h.Hour
    ANS x.seler_id = y.seler_id


问:
openCL kernel returns trash value despite no errors
I've been following these openCL examples. OpenCL isn't giving me any errors even when checking error codes with cl_int err, or from the kernel. But when I output the results of landmap_flags[i], It shows I'm only getting garbage values back from the GPU. I could get the above example to work but when I included my data it started to break down. I'm also unsure if the landmap_flags array is too large for the kernel to handle? (96 * 96 * 96 elements of uchar).

Kernel Code:

```<code>// CL noise lib
.
.
.
kernel void terrain_gen(global uchar* landmap_flags, global float3* pos, int LOD, int chunkSize) {
    const uint n = get_global_id(0);
    const uint x = n%(chunkSize+(2 * LOD));
    const uint y = (n/(chunkSize+(2 * LOD)))%(chunkSize+(2 * LOD));
    const uint z = n/((chunkSize+(2 * LOD))*(chunkSize+(2 * LOD)));
    enum BLOCK { STONE, DIRT, SNOW, GRASS, SAND, GRAVEL, GAETAN, BEDROCK, AIR };
    const float frequency = 500;
    const float noise_1 = (_slang_library_noise2(x+(chunkSize * pos[n].x),z+(chunkSize * pos[n].z))) / frequency;
    landmap_flags[n] = (noise_1*noise_1*40.0f+6.0f>(y+(chunkSize * pos[n].y))) ? DIRT : AIR;
}
</code>```

The kernel is building fine and isn't returning any errors but I figured I could have an error with how I handle the data.

And my code for setting up buffers:

```<code>// set up devices, platform, etc.
.
.
.
    cl::Buffer buffer_landmap(context, CL_MEM_READ_WRITE, sizeof(cl_uchar) * 96 * 96 * 96);
    cl::Buffer buffer_pos(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, sizeof(cl_float3));
    cl::Buffer buffer_LOD(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, sizeof(cl_int));
    cl::Buffer buffer_chunkSize(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, sizeof(cl_int));

    queue.enqueueWriteBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);
    queue.enqueueWriteBuffer(buffer_pos, CL_TRUE, 0, sizeof(cl_float3), pos);
    queue.enqueueWriteBuffer(buffer_LOD, CL_TRUE, 0, sizeof(cl_int), LOD);
    queue.enqueueWriteBuffer(buffer_chunkSize, CL_TRUE, 0, sizeof(cl_int), chunkSize);

    cl::Kernel get_noise(program, "terrain_gen");
    get_noise.setArg(0, buffer_landmap);
    get_noise.setArg(1, buffer_pos);
    get_noise.setArg(2, buffer_LOD);
    get_noise.setArg(3, buffer_chunkSize);

    queue.enqueueNDRangeKernel(get_noise, cl::NullRange, cl::NDRange(1024));

    queue.enqueueReadBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);

    queue.finish();
</code>```

The way I intend for this code to work is to pass three buffers (pos, LOD and chunkSize) as scalar values, and only need to return the landmap_flags to the CPU. Could it be that I'm using incorrect arguments for enqueueNDRangeKernel? A possibility could be that my work group size is too large, or I have too many work groups.

EDIT: I edited my code, scalars no longer passed as buffers, the only thing being written and read is the landmap_flags, kernel has been edited for this as well to treat pos as a scalar value.

```<code>        kernel void terrain_gen(global uchar* landmap_flags, float3 pos, int LOD, int chunkSize) {
            const uint n = get_global_id(0);
            const uint x = n%(chunkSize+(2 * LOD));
            const uint y = (n/(chunkSize+(2 * LOD)))%(chunkSize+(2 * LOD));
            const uint z = n/((chunkSize+(2 * LOD))*(chunkSize+(2 * LOD)));
            enum BLOCK { STONE, DIRT, SNOW, GRASS, SAND, GRAVEL, GAETAN, BEDROCK, AIR };
            const float frequency = 500;
            const float noise_1 = (_slang_library_noise2(x+(chunkSize * pos.x),z+(chunkSize * pos.z))) / frequency;
            landmap_flags[n] = (noise_1*noise_1*40.0f+6.0f>(y+(chunkSize * pos.y))) ? DIRT : AIR;
        }
</code>```

```<code>    cl::Buffer buffer_landmap(context, CL_MEM_READ_WRITE, sizeof(cl_uchar) * 96 * 96 * 96);
    cl::CommandQueue queue(context, default_device);
    queue.enqueueWriteBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);

    cl::Kernel get_noise(program, "terrain_gen");
    get_noise.setArg(0, buffer_landmap);
    get_noise.setArg(1, pos);
    get_noise.setArg(2, LOD);
    get_noise.setArg(3, chunkSize);

    queue.enqueueNDRangeKernel(get_noise, cl::NullRange, cl::NDRange(96 * 96 * 96));

    queue.enqueueReadBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);

    queue.finish();
</code>```

答:
@doqtor's observations in the comments are spot on, those are very serious issues.

Additionally, I've noticed the following:

Your pos buffer is created using CL_MEM_HOST_NO_ACCESS but then you call enqueueWriteBuffer() on it. (Though according to the text of your question, you actually want this to be a scalar, not a buffer? And then your kernel code treats it as a long vector as pointed out in the comments…)

You're using CL_MEM_COPY_HOST_PTR to create buffers without passing the host pointer.

You seem to be submitting a work size of 1024 items, but your result buffer is for 96 * 96 * 96 = 884736 items and that's how much data you're reading from the buffer too. (This buffer size is fine, you should not be getting anywhere near VRAM size with that.)

Furthermore, you say that

OpenCL isn't giving me any errors even when checking error codes with cl_int err, or from the kernel.

Given the misuse of flags when creating buffers, this seems… unlikely? Three of your four buffer creations should be failing with CL_INVALID_HOST_PTR due to issue 2 above. I suggest you take another look at your error handling code. (you've not posted it, so I can't comment on specifics)

Body:
I've been following these openCL examples. OpenCL isn't giving me any errors even when checking error codes with cl_int err, or from the kernel. But when I output the results of landmap_flags[i], It shows I'm only getting garbage values back from the GPU. I could get the above example to work but when I included my data it started to break down. I'm also unsure if the landmap_flags array is too large for the kernel to handle? (96 * 96 * 96 elements of uchar).

Kernel Code:

// CL noise lib
.
.
.
kernel void terrain_gen(global uchar* landmap_flags, global float3* pos, int LOD, int chunkSize) {
    const uint n = get_global_id(0);
    const uint x = n%(chunkSize+(2 * LOD));
    const uint y = (n/(chunkSize+(2 * LOD)))%(chunkSize+(2 * LOD));
    const uint z = n/((chunkSize+(2 * LOD))*(chunkSize+(2 * LOD)));
    enum BLOCK { STONE, DIRT, SNOW, GRASS, SAND, GRAVEL, GAETAN, BEDROCK, AIR };
    const float frequency = 500;
    const float noise_1 = (_slang_library_noise2(x+(chunkSize * pos[n].x),z+(chunkSize * pos[n].z))) / frequency;
    landmap_flags[n] = (noise_1*noise_1*40.0f+6.0f>(y+(chunkSize * pos[n].y))) ? DIRT : AIR;
}

The kernel is building fine and isn't returning any errors but I figured I could have an error with how I handle the data.

And my code for setting up buffers:

// set up devices, platform, etc.
.
.
.
    cl::Buffer buffer_landmap(context, CL_MEM_READ_WRITE, sizeof(cl_uchar) * 96 * 96 * 96);
    cl::Buffer buffer_pos(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, sizeof(cl_float3));
    cl::Buffer buffer_LOD(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, sizeof(cl_int));
    cl::Buffer buffer_chunkSize(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, sizeof(cl_int));

    queue.enqueueWriteBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);
    queue.enqueueWriteBuffer(buffer_pos, CL_TRUE, 0, sizeof(cl_float3), pos);
    queue.enqueueWriteBuffer(buffer_LOD, CL_TRUE, 0, sizeof(cl_int), LOD);
    queue.enqueueWriteBuffer(buffer_chunkSize, CL_TRUE, 0, sizeof(cl_int), chunkSize);

    cl::Kernel get_noise(program, "terrain_gen");
    get_noise.setArg(0, buffer_landmap);
    get_noise.setArg(1, buffer_pos);
    get_noise.setArg(2, buffer_LOD);
    get_noise.setArg(3, buffer_chunkSize);

    queue.enqueueNDRangeKernel(get_noise, cl::NullRange, cl::NDRange(1024));

    queue.enqueueReadBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);

    queue.finish();

The way I intend for this code to work is to pass three buffers (pos, LOD and chunkSize) as scalar values, and only need to return the landmap_flags to the CPU. Could it be that I'm using incorrect arguments for enqueueNDRangeKernel? A possibility could be that my work group size is too large, or I have too many work groups.

EDIT: I edited my code, scalars no longer passed as buffers, the only thing being written and read is the landmap_flags, kernel has been edited for this as well to treat pos as a scalar value.

        kernel void terrain_gen(global uchar* landmap_flags, float3 pos, int LOD, int chunkSize) {
            const uint n = get_global_id(0);
            const uint x = n%(chunkSize+(2 * LOD));
            const uint y = (n/(chunkSize+(2 * LOD)))%(chunkSize+(2 * LOD));
            const uint z = n/((chunkSize+(2 * LOD))*(chunkSize+(2 * LOD)));
            enum BLOCK { STONE, DIRT, SNOW, GRASS, SAND, GRAVEL, GAETAN, BEDROCK, AIR };
            const float frequency = 500;
            const float noise_1 = (_slang_library_noise2(x+(chunkSize * pos.x),z+(chunkSize * pos.z))) / frequency;
            landmap_flags[n] = (noise_1*noise_1*40.0f+6.0f>(y+(chunkSize * pos.y))) ? DIRT : AIR;
        }

    cl::Buffer buffer_landmap(context, CL_MEM_READ_WRITE, sizeof(cl_uchar) * 96 * 96 * 96);
    cl::CommandQueue queue(context, default_device);
    queue.enqueueWriteBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);

    cl::Kernel get_noise(program, "terrain_gen");
    get_noise.setArg(0, buffer_landmap);
    get_noise.setArg(1, pos);
    get_noise.setArg(2, LOD);
    get_noise.setArg(3, chunkSize);

    queue.enqueueNDRangeKernel(get_noise, cl::NullRange, cl::NDRange(96 * 96 * 96));

    queue.enqueueReadBuffer(buffer_landmap, CL_TRUE, 0, sizeof(cl_uchar) * 96 * 96 * 96, landmap_flags);

    queue.finish();


问:
How to add two numbers without using ++ or + or another arithmetic operator
How do I add two numbers without using ++ or + or any other arithmetic operator?

It was a question asked a long time ago in some campus interview. Anyway, today someone asked a question regarding some bit-manipulations, and in answers a beautiful quide Stanford bit twiddling was referred. I spend some time studying it and thought that there actually might be an answer to the question. I don't know, I could not find one. Does an answer exist?

答:
You can use double negetive to add two integers for example:</p>

```<code>int sum2(int a, int b){
    return -(-a-b);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use double negetive to add two integers for example:

int sum2(int a, int b){
    return -(-a-b);
}


问:
Django sweetify
I already read the documentation about https://github.com/Atrox/sweetify-django but I don't understand clearly, I already download and import requirement of sweetify in Django. I just want that if the record is updated the popup message (sweetify) will appear.

```<code>def studentrecords(request):
   if request.method == 'POST':
      id = request.POST.get("id")
      update = StudentsEnrollmentRecord.objects.get(id=id)
      update.Section = s
      update.save()
      sweetify.success(request, 'You did it', text='Your Form has been Updated',persistent='Hell yeah')
      return render(request, 'Homepage/selectrecord.html')
</code>```

this is my html

```<code>{% load sweetify %}
{% sweetify %}
 <form  method="post" action="/studentrecords/" enctype="multipart/form-data">{% csrf_token %}
<table>
    {% for student in myrecord %}
    <tr>
        <td>Control #</td>
        <td><input type="text" name="id" value="{{student.id}}"></td>
        <td><input type="submit"></td>
    </tr>
    <tr>
        <td>Name: </td>
        <td><input type="text" value="{{student.Student_Users.Firstname}} {{student.Student_Users.Lastname}} {{student.Student_Users.Middle_Initial}}"></td>
        <td>Course/Track</td>
        <td><input type="text" value="{{student.Courses}}"></td>
    </tr>
    <tr>
        <td>Education Level: </td>
        <td><input type="text" value="{{student.Education_Levels}}"></td>
        <td>Strand: </td>
        <td><input type="text" value="{{student.strands}}"></td>
    </tr>
    <tr>
        <td>Section: </td>
        <td>
            <select name="section">
                <option value="{{student.Section.id}}">{{student.Section}}</option>
                {% for sections in section %}
                <option value="{{sections.id}}">{{sections.Description}}</option>
                {% endfor %}
            </select>
        </td>
        <td>Payment Type: </td>
        <td><input type="text" value="{{student.Payment_Type}}" class="myform"></td>
    </tr>
    {% endfor %}
</table>
 </form>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script>
    Swal.fire(
  'Good job!',
   'Data Updated!',
  'success'
)
</script>
</code>```

my settings.py

```<code>INSTALLED_APPS = [
    #my apps
    ….
    'sweetify'
]
SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2'
</code>```

I didn't receive any error , but no popup message appear  (sweetify)

答:
First off, if you'd like to get a notification on any record update, I'd suggest using Signals rather than detecting the request method. It's a way more central and robust solution. Just add this to your models.py:

```<code>from django.db.models.signals import post_save

@receiver(models.signals.post_save, sender=StudentsEnrollmentRecord)
def update_enrollment_record_handler(sender, updated_instance, **kwargs):
    """This method is called after every call of StudentsEnrollmentRecord.save"""
    sweetify.success(request, 'You did it', text='Your Form has been Updated',persistent='Hell yeah')
</code>```

Second - POST is meant to create an object through a RestAPI, you should switch to UPDATE (includes all objects fields) or PUT (updates some of the objects fields).

Third - what happens when you add a print statement above the sweetify line? Does that print run? If not, then your whole setup doesn't even call the studentrecords method and you'll need to share more info so we can replicate the situation and/or advise further.

Title: Django sweetify

Body:
I already read the documentation about https://github.com/Atrox/sweetify-django but I don't understand clearly, I already download and import requirement of sweetify in Django. I just want that if the record is updated the popup message (sweetify) will appear.

def studentrecords(request):
   if request.method == 'POST':
      id = request.POST.get("id")
      update = StudentsEnrollmentRecord.objects.get(id=id)
      update.Section = s
      update.save()
      sweetify.success(request, 'You did it', text='Your Form has been Updated',persistent='Hell yeah')
      return render(request, 'Homepage/selectrecord.html')

this is my html

{% load sweetify %}
{% sweetify %}
 <form  method="post" action="/studentrecords/" enctype="multipart/form-data">{% csrf_token %}

    {% for student in myrecord %}

        Control #
        <input type="text" name="id" value="{{student.id}}">
        <input type="submit">

        Name:
        <input type="text" value="{{student.Student_Users.Firstname}} {{student.Student_Users.Lastname}} {{student.Student_Users.Middle_Initial}}">
        Course/Track
        <input type="text" value="{{student.Courses}}">

        Education Level:
        <input type="text" value="{{student.Education_Levels}}">
        Strand:
        <input type="text" value="{{student.strands}}">

        Section:

            <select name="section">
                <option value="{{student.Section.id}}">{{student.Section}}</option>
                {% for sections in section %}
                <option value="{{sections.id}}">{{sections.Description}}</option>
                {% endfor %}
            </select>

        Payment Type:
        <input type="text" value="{{student.Payment_Type}}" class="myform">

    {% endfor %}

 </form>

my settings.py

INSTALLED_APPS = [
    #my apps
    ….
    'sweetify'
]
SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2'

I didn't receive any error , but no popup message appear  (sweetify)

Body:
First off, if you'd like to get a notification on any record update, I'd suggest using Signals rather than detecting the request method. It's a way more central and robust solution. Just add this to your models.py:

from django.db.models.signals import post_save

@receiver(models.signals.post_save, sender=StudentsEnrollmentRecord)
def update_enrollment_record_handler(sender, updated_instance, **kwargs):
    """This method is called after every call of StudentsEnrollmentRecord.save"""
    sweetify.success(request, 'You did it', text='Your Form has been Updated',persistent='Hell yeah')

Second - POST is meant to create an object through a RestAPI, you should switch to UPDATE (includes all objects fields) or PUT (updates some of the objects fields).

Third - what happens when you add a print statement above the sweetify line? Does that print run? If not, then your whole setup doesn't even call the studentrecords method and you'll need to share more info so we can replicate the situation and/or advise further.


问:
MongoDB Pagination with two values
Let's say my MongoDB records look like this:

{category: A , sub_category : 1}

{category: A , sub_category : 2}

{category: A , sub_category : 3}

{category: B , sub_category : 1}

{category: B , sub_category : 2}

{category: B , sub_category : 3}

{category: C , sub_category : 1}

{category: C , sub_category : 2}

{category: C , sub_category : 3}

I am trying to achieve pagination with these values. So, I created a compound index with both of these fields (both in ascending order).

Let's say my page limit is 2.

So my first query looks like this -> db.record.find().sort({category: 1, sub_category: 1}); -> And the first two records are returned.

My second query looks like this -> db.record.find({category : {$gte: A}, sub_category: {$gt : 2}}).sort({category: 1, sub_category: 1}).

I was expecting record 3 and 4 to return. But I got record 3 and record 6.

I understood that my way of querying is not right. I couldn't find another solution. Please help me with this issue.

P.S. I am not using skip and limit technique, because I am following bucket pattern.

答:
When querying in Mongo if the query can be satisfied by an index then Mongo will traverse the index trees (B-tree's) and will not perform collection scan.

So the expected documents order is basically just a "perceived order". the documents "index order" is different and heavily relies on what fields were indexed, document insertion order and more.

So what can you do? you can force your perceived order by using sort:

```<code>db.record.find({category : {$gte: A}, sub_category: {$gt : 2}}).sort({category: 1, sub_category: 1});
</code>```

Title: MongoDB Pagination with two values

Body:
When querying in Mongo if the query can be satisfied by an index then Mongo will traverse the index trees (B-tree's) and will not perform collection scan.

So the expected documents order is basically just a "perceived order". the documents "index order" is different and heavily relies on what fields were indexed, document insertion order and more.

So what can you do? you can force your perceived order by using sort:

db.record.find({category : {$gte: A}, sub_category: {$gt : 2}}).sort({category: 1, sub_category: 1});


问:
docker postgres pgadmin local connection
I have created an ubuntu image with nginx, php and postgres.

I want to connect the postgres database in my current image with pgadmin located on my local machine.

I have tried using docker inspector to try to use the image ip to make a connection with my local pgadmin but without much success. I've also tried configuring some ports on local to make connection work.

答:
If you verified that PostgreSQL is running and you can connect there with local copy of PgAdmin...

The answer is simple: use host.docker.internal istead of localhost for the PgAdmin running inside the Docker

<img src="https://i.stack.imgur.com/98Asv.png" alt="use host.docker.internal istead of localhost">


问:
Change casing of JSON properties between api versions using Microsoft's ASP.NET API Versioning for Web API 2 and ODATA?
I am introducing API versioning to an existing API.  The existing JSON uses Pascal casing for its property names e.g. "FooBar": "foo".  For v2 of the API, I would like to use the common camel casing, "fooBar": "foo".  I need to keep v1 Pascal casing so that it does not impact any client that is already pulling that version of the API.

My project is

ASP.NET MVC 5.2.7

ASP.NET WEB API 5.2.7

ASP.NET ODATA 7.4.0

ASP.NET WEB API Versioning 4.0.0

My configuration is as follows

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.AddApiVersioning(options => options.ReportApiVersions = true);

        var modelBuilder = new VersionedODataModelBuilder(configuration);

        AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(x => x.GetTypes())
            .Where(x => typeof(IModelConfiguration).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
            .ForEach(t => modelBuilder.ModelConfigurations.Add((IModelConfiguration)Activator.CreateInstance(t)));

        var models = modelBuilder.GetEdmModels();

        configuration.MapVersionedODataRoutes("odata-bypath", "api/v{apiVersion}", models, builder =>
        {
            builder.AddService<IODataPathHandler>(Singleton, sp => new DefaultODataPathHandler { UrlKeyDelimiter = Parentheses });
            builder.AddService<ODataUriResolver>(Singleton, sp => new UnqualifiedCallAndEnumPrefixFreeResolver { EnableCaseInsensitive = true });
        });

        configuration.Count().Filter().OrderBy().Expand().Select().MaxTop(null);

        configuration.MapHttpAttributeRoutes();
    }
}
</code>```

After reading through the docs and specifically Versioned ODataModelBuilder I have not found a way to change the casing based on which version of the API the model is being built for.  I can get it to be all Pascal casing or all camel casing, but not v1 Pascal casing and v2 camel casing.

Adjusting the above configuration

```<code>var modelBuilder = new VersionedODataModelBuilder( configuration )
{
    ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase()
};
</code>```

would use camel casing (yes I know the explicit call is unnecessary since it is the default).  Then I built my own extension method ODataConventialModelBuilder().EnablePascalCase() that mimicked EnableLowerCamelCase() method to get Pascal casing to work.

```<code>var modelBuilder = new VersionedODataModelBuilder( configuration )
{
    ModelBuilderFactory = () => new ODataConventionModelBuilder().EnablePascalCase()
};
</code>```

However, I could never find a way to know which version of the API I was building the model for.

At one point, I thought I had it using OnModelCreating to add

```<code>((ODataConventionModelBuilder) builder).OnModelCreating += new PascalCaser().ApplyCase;
</code>```

to each of the v1 IModelConfiguration classes, but it didn't work once I was building multiple models.

Is there a way to change the JSON property naming based on which API version the model is for?

答:
Using the OData Model Configurations approach described here
first add a class that derives from IModelConfiguration to your project.

Something like this:

public class VersionedModelConfiguration : IModelConfiguration
{
    private void ConfigureV1(ODataModelBuilder builder)
    {
        builder.EntitySet<Product>("Products");
    }

    private void ConfigureV2(ODataModelBuilder builder)
    {
        if (builder.GetType().Equals(typeof(ODataConventionModelBuilder)))
        {
            ((ODataConventionModelBuilder)builder).EnableLowerCamelCase();
        }
        builder.EntitySet<Product>("Products");
    }

    public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
    {

        switch (apiVersion.MajorVersion)
        {
            case 1:
                ConfigureV1(builder);
                break;
            case 2:
                ConfigureV2(builder);
                break;
            default:
                ConfigureV1(builder);
                break;
        }
    }
}
```

<p>Then in <code>Register</code> method:</p>

<pre class="lang-cs prettyprint-override"><code>// ...
var modelBuilder = new VersionedODataModelBuilder(configuration)
{
    ModelBuilderFactory = () => new ODataConventionModelBuilder(),
    ModelConfigurations = { new VersionedModelConfiguration() }
};

var models = modelBuilder.GetEdmModels();
// ...
</code>```

Don't be tempted to leave out the line ModelBuilderFactory = () => new ODataConventionModelBuilder()

/api/v1/$metadata:

<?xml version="1.0" encoding="UTF-8"?>
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
   <edmx:DataServices>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="NS.Models">
         <EntityType Name="Product">
            <Key>
               <PropertyRef Name="Id" />
            </Key>
            <Property Name="Id" Type="Edm.Int32" Nullable="false" />
            <Property Name="Name" Type="Edm.String" />
         </EntityType>
      </Schema>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Default">
         <EntityContainer Name="Container">
            <EntitySet Name="Products" EntityType="NS.Models.Product" />
         </EntityContainer>
      </Schema>
   </edmx:DataServices>
</edmx:Edmx>
```

<p><code>/api/v2/$metadata</code>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
   <edmx:DataServices>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="NS.Models">
         <EntityType Name="Product">
            <Key>
               <PropertyRef Name="id" />
            </Key>
            <Property Name="id" Type="Edm.Int32" Nullable="false" />
            <Property Name="name" Type="Edm.String" />
         </EntityType>
      </Schema>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Default">
         <EntityContainer Name="Container">
            <EntitySet Name="Products" EntityType="NS.Models.Product" />
         </EntityContainer>
      </Schema>
   </edmx:DataServices>
</edmx:Edmx>
</code>```

Body:
I am introducing API versioning to an existing API.  The existing JSON uses Pascal casing for its property names e.g. "FooBar": "foo".  For v2 of the API, I would like to use the common camel casing, "fooBar": "foo".  I need to keep v1 Pascal casing so that it does not impact any client that is already pulling that version of the API.

My project is

ASP.NET MVC 5.2.7

ASP.NET WEB API 5.2.7

ASP.NET ODATA 7.4.0

ASP.NET WEB API Versioning 4.0.0

My configuration is as follows

public static class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.AddApiVersioning(options => options.ReportApiVersions = true);

        var modelBuilder = new VersionedODataModelBuilder(configuration);

        AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(x => x.GetTypes())
            .Where(x => typeof(IModelConfiguration).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
            .ForEach(t => modelBuilder.ModelConfigurations.Add((IModelConfiguration)Activator.CreateInstance(t)));

        var models = modelBuilder.GetEdmModels();

        configuration.MapVersionedODataRoutes("odata-bypath", "api/v{apiVersion}", models, builder =>
        {
            builder.AddService<IODataPathHandler>(Singleton, sp => new DefaultODataPathHandler { UrlKeyDelimiter = Parentheses });
            builder.AddService<ODataUriResolver>(Singleton, sp => new UnqualifiedCallAndEnumPrefixFreeResolver { EnableCaseInsensitive = true });
        });

        configuration.Count().Filter().OrderBy().Expand().Select().MaxTop(null);

        configuration.MapHttpAttributeRoutes();
    }
}

After reading through the docs and specifically Versioned ODataModelBuilder I have not found a way to change the casing based on which version of the API the model is being built for.  I can get it to be all Pascal casing or all camel casing, but not v1 Pascal casing and v2 camel casing.

Adjusting the above configuration

var modelBuilder = new VersionedODataModelBuilder( configuration )
{
    ModelBuilderFactory = () => new ODataConventionModelBuilder().EnableLowerCamelCase()
};

would use camel casing (yes I know the explicit call is unnecessary since it is the default).  Then I built my own extension method ODataConventialModelBuilder().EnablePascalCase() that mimicked EnableLowerCamelCase() method to get Pascal casing to work.

var modelBuilder = new VersionedODataModelBuilder( configuration )
{
    ModelBuilderFactory = () => new ODataConventionModelBuilder().EnablePascalCase()
};

However, I could never find a way to know which version of the API I was building the model for.

At one point, I thought I had it using OnModelCreating to add

((ODataConventionModelBuilder) builder).OnModelCreating += new PascalCaser().ApplyCase;

to each of the v1 IModelConfiguration classes, but it didn't work once I was building multiple models.

Is there a way to change the JSON property naming based on which API version the model is for?

Body:
Using the OData Model Configurations approach described here
first add a class that derives from IModelConfiguration to your project.

Something like this:

public class VersionedModelConfiguration : IModelConfiguration
{
    private void ConfigureV1(ODataModelBuilder builder)
    {
        builder.EntitySet<Product>("Products");
    }

    private void ConfigureV2(ODataModelBuilder builder)
    {
        if (builder.GetType().Equals(typeof(ODataConventionModelBuilder)))
        {
            ((ODataConventionModelBuilder)builder).EnableLowerCamelCase();
        }
        builder.EntitySet<Product>("Products");
    }

    public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
    {

        switch (apiVersion.MajorVersion)
        {
            case 1:
                ConfigureV1(builder);
                break;
            case 2:
                ConfigureV2(builder);
                break;
            default:
                ConfigureV1(builder);
                break;
        }
    }
}

Then in Register method:

// ...
var modelBuilder = new VersionedODataModelBuilder(configuration)
{
    ModelBuilderFactory = () => new ODataConventionModelBuilder(),
    ModelConfigurations = { new VersionedModelConfiguration() }
};

var models = modelBuilder.GetEdmModels();
// ...

Don't be tempted to leave out the line ModelBuilderFactory = () => new ODataConventionModelBuilder()

/api/v1/$metadata:

<?xml version="1.0" encoding="UTF-8"?>
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
   <edmx:DataServices>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="NS.Models">
         <EntityType Name="Product">
            <Key>
               <PropertyRef Name="Id" />
            </Key>
            <Property Name="Id" Type="Edm.Int32" Nullable="false" />
            <Property Name="Name" Type="Edm.String" />
         </EntityType>
      </Schema>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Default">
         <EntityContainer Name="Container">
            <EntitySet Name="Products" EntityType="NS.Models.Product" />
         </EntityContainer>
      </Schema>
   </edmx:DataServices>
</edmx:Edmx>

/api/v2/$metadata:

<?xml version="1.0" encoding="UTF-8"?>
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
   <edmx:DataServices>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="NS.Models">
         <EntityType Name="Product">
            <Key>
               <PropertyRef Name="id" />
            </Key>
            <Property Name="id" Type="Edm.Int32" Nullable="false" />
            <Property Name="name" Type="Edm.String" />
         </EntityType>
      </Schema>
      <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Default">
         <EntityContainer Name="Container">
            <EntitySet Name="Products" EntityType="NS.Models.Product" />
         </EntityContainer>
      </Schema>
   </edmx:DataServices>
</edmx:Edmx>


问:
ASP.NET MVC view needs to pass selected dropdown and Calendar date to model
I'm attempting to pass a model back to the the controller for mass updates via a stored procedure in the controller. Two key values that need passed back to the controller are the selected dropdown and calendar date from the view. There are fields in the model to store the information, but I can't figure out how to populate the values in the model.

This is the current code:

```<code><div>
    <a href="#" id="addNew">Add New</a>
</div>
<p>
        PlantArea: @Html.DropDownList("PlantArea", " ")
        EntryDate: @Html.TextBox("EntryDate", @DateTime.Now.ToShortDateString(), new { id = "Calendar", @class = "datepicker" })
        <input type="submit" value="Load Daily Entries" />
        <br /> <br />
    </p>
    <table id="dataTable" border="0" cellpadding="0" cellspacing="0">
        <tr>
            <th>Employee Id</th>
            <th>Employee Name</th>
            <th>Status Reason</th>
            <th>HR Comment</th>
        </tr>
        @if (Model != null && Model.Count > 0)
            {
                int j = 0;
                foreach (var i in Model)
                {
                <tr style="border:1px solid black">
                    <td>@Html.TextBoxFor(a => a[j].EmployeeId)</td>
                    <td>@Html.TextBoxFor(a => a[j].Preferred_Name)</td>
                    <td>@Html.TextBoxFor(a => a[j].Entry_Code, new { @Value = ViewBag.DefaultAttendanceCode })</td>
                    <td>@Html.TextBoxFor(a => a[j].HR_Comment)</td>
                    <td>>@Html.TextBoxFor(a => a[j].EntryDate, new { @Value = EntryDate})</td>
                    <td>>@Html.TextBoxFor(a => a[j].Entry_Code, new { @Value = PlantArea })</td>
                    <td>
                        @if (j > 0)
                        {
                            <a href="#" class="remove">Remove</a>
                        }
                    </td>
                </tr>
</code>```

答:
You can change model binding to Tightly coupled.
means you can bind that control to a model value
like @Html.TextBoxFor(m=>m.entrydate)
@Html.DropDownListFor(m=>m.plantarea)

where both entrydate and plantarea should be a property in model. and place the control in form element and you can get the value in control on submit.

Otherwise put two hidden textbox in UI and populate the dropdown and date value in those hidden field. then use the hidden field to get the value

Body:
I'm attempting to pass a model back to the the controller for mass updates via a stored procedure in the controller. Two key values that need passed back to the controller are the selected dropdown and calendar date from the view. There are fields in the model to store the information, but I can't figure out how to populate the values in the model.

This is the current code:

    Add New

        PlantArea: @Html.DropDownList("PlantArea", " ")
        EntryDate: @Html.TextBox("EntryDate", @DateTime.Now.ToShortDateString(), new { id = "Calendar", @class = "datepicker" })
        <input type="submit" value="Load Daily Entries" />

            Employee Id
            Employee Name
            Status Reason
            HR Comment

        @if (Model != null && Model.Count > 0)
            {
                int j = 0;
                foreach (var i in Model)
                {

                    @Html.TextBoxFor(a => a[j].EmployeeId)
                    @Html.TextBoxFor(a => a[j].Preferred_Name)
                    @Html.TextBoxFor(a => a[j].Entry_Code, new { @Value = ViewBag.DefaultAttendanceCode })
                    @Html.TextBoxFor(a => a[j].HR_Comment)
                    >@Html.TextBoxFor(a => a[j].EntryDate, new { @Value = EntryDate})
                    >@Html.TextBoxFor(a => a[j].Entry_Code, new { @Value = PlantArea })

                        @if (j > 0)
                        {
                            Remove
                        }