text:
BOOST_FIXTURE_TEST_SUITE(miner_tests, TestingSetup)

static
struct {
    unsigned char extranonce;
    unsigned int nonce;
} blockinfo[] = {
    {4, 0xa4a3e223}, {2, 0x15c32f9e}, {1, 0x0375b547}, {1, 0x7004a8a5},
    {2, 0xce440296}, {2, 0x52cfe198}, {1, 0x77a72cd0}, {2, 0xbb5d6f84},
    {2, 0x83f30c2c}, {1, 0x48a73d5b}, {1, 0xef7dcd01}, {2, 0x6809c6c4},
    {2, 0x0883ab3c}, {1, 0x087bbbe2}, {2, 0x2104a814}, {2, 0xdffb6daa},
    {1, 0xee8a0a08}, {2, 0xba4237c1}, {1, 0xa70349dc}, {1, 0x344722bb},
    {3, 0xd6294733}, {2, 0xec9f5c94}, {2, 0xca2fbc28}, {1, 0x6ba4f406},
    {2, 0x015d4532}, {1, 0x6e119b7c}, {2, 0x43e8f314}, {2, 0x27962f38},
    {2, 0xb571b51b}, {2, 0xb36bee23}, {2, 0xd17924a8}, {2, 0x6bc212d9},
    {1, 0x630d4948}, {2, 0x9a4c4ebb}, {2, 0x554be537}, {1, 0xd63ddfc7},
    {2, 0xa10acc11}, {1, 0x759a8363}, {2, 0xfb73090d}, {1, 0xe82c6a34},
    {1, 0xe33e92d7}, {3, 0x658ef5cb}, {2, 0xba32ff22}, {5, 0x0227a10c},
    {1, 0xa9a70155}, {5, 0xd096d809}, {1, 0x37176174}, {1, 0x830b8d0f},
    {1, 0xc6e3910e}, {2, 0x823f3ca8}, {1, 0x99850849}, {1, 0x7521fb81},
    {1, 0xaacaabab}, {1, 0xd645a2eb}, {5, 0x7aea1781}, {5, 0x9d6e4b78},
    {1, 0x4ce90fd8}, {1, 0xabdc832d}, {6, 0x4a34f32a}, {2, 0xf2524c1c},
    {2, 0x1bbeb08a}, {1, 0xad47f480}, {1, 0x9f026aeb}, {1, 0x15a95049},
    {2, 0xd1cb95b2}, {2, 0xf84bbda5}, {1, 0x0fa62cd1}, {1, 0xe05f9169},
    {1, 0x78d194a9}, {5, 0x3e38147b}, {5, 0x737ba0d4}, {1, 0x63378e10},
    {1, 0x6d5f91cf}, {2, 0x88612eb8}, {2, 0xe9639484}, {1, 0xb7fabc9d},
    {2, 0x19b01592}, {1, 0x5a90dd31}, {2, 0x5bd7e028}, {2, 0x94d00323},
    {1, 0xa9b9c01a}, {1, 0x3a40de61}, {1, 0x56e7eec7}, {5, 0x859f7ef6},
    {1, 0xfd8e5630}, {1, 0x2b0c9f7f}, {1, 0xba700e26}, {1, 0x7170a408},
    {1, 0x70de86a8}, {1, 0x74d64cd5}, {1, 0x49e738a1}, {2, 0x6910b602},
    {0, 0x643c565f}, {1, 0x54264b3f}, {2, 0x97ea6396}, {2, 0x55174459},
    {2, 0x03e8779a}, {1, 0x98f34d8f}, {1, 0xc07b2b07}, {1, 0xdfe29668},
    {1, 0x3141c7c1}, {1, 0xb3b595f4}, {1, 0x735abf08}, {5, 0x623bfbce},
    {2, 0xd351e722}, {1, 0xf4ca48c9}, {1, 0x5b19c670}, {1, 0xa164bf0e},
    {2, 0xbbbeb305}, {2, 0xfe1c810a},
};

CBlockIndex CreateBlockIndex(int nHeight)
{
    CBlockIndex index;
    index.nHeight = nHeight;
    index.pprev = chainActive.Tip();
    return index;
}

bool TestSequenceLocks(const CTransaction &tx, int flags)
{
    LOCK(mempool.cs);
    return CheckSequenceLocks(tx, flags);
}

// NOTE: These tests rely on CreateNewBlock doing its own self-validation!
BOOST_AUTO_TEST_CASE(CreateNewBlock_validity)
{
    const CChainParams& chainparams = Params(CBaseChainParams::MAIN);
    CScript scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
    CBlockTemplate *pblocktemplate;
    CMutableTransaction tx,tx2;
    CScript script;
    uint256 hash;
    TestMemPoolEntryHelper entry;
    entry.nFee = 11;
    entry.dPriority = 111.0;
    entry.nHeight = 11;
    maxGeneratedBlock = 100000;
    excessiveBlockSize = maxGeneratedBlock;
    LOCK(cs_main);
    fCheckpointsEnabled = false;

    // Simple block creation, nothing special yet:
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));

    // Simple block creation, with coinbase message
    settingsToUserAgentString();
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));

    // Simple block creation, with coinbase message and miner message
    settingsToUserAgentString();
    minerComment = "I am a meat popsicle.";
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));

    minerComment = "flying is throwing yourself against the ground and missing.  This comment is WAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY too long.";
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));

    // We can't make transactions until we have inputs
    // Therefore, load 100 blocks :)
    int baseheight = 0;
    std::vector<CTransaction*>txFirst;
    for (unsigned int i = 0; i < sizeof(blockinfo)/sizeof(*blockinfo); ++i)
    {
        CBlock *pblock = &pblocktemplate->block; // pointer for convenience
        pblock->nVersion = 1;
        pblock->nTime = chainActive.Tip()->GetMedianTimePast()+1;
        CMutableTransaction txCoinbase(pblock->vtx[0]);
        txCoinbase.nVersion = 1;
        txCoinbase.vin[0].scriptSig = CScript();
        txCoinbase.vin[0].scriptSig.push_back(blockinfo[i].extranonce);
        txCoinbase.vin[0].scriptSig.push_back(chainActive.Height());
        txCoinbase.vout[0].scriptPubKey = CScript();
        pblock->vtx[0] = CTransaction(txCoinbase);
        if (txFirst.size() == 0)
            baseheight = chainActive.Height();
        if (txFirst.size() < 4)
            txFirst.push_back(new CTransaction(pblock->vtx[0]));
        pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
        pblock->nNonce = blockinfo[i].nonce;
        CValidationState state;
        BOOST_CHECK(ProcessNewBlock(state, chainparams, NULL, pblock, true, NULL, false));
        BOOST_CHECK(state.IsValid());
        pblock->hashPrevBlock = pblock->GetHash();
    }
    delete pblocktemplate;

    // Just to make sure we can still make simple blocks
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));
    delete pblocktemplate;

    // block sigops > limit: 1000 CHECKMULTISIG + 1
    tx.vin.resize(1);
    // NOTE: OP_NOP is used to force 20 SigOps for the CHECKMULTISIG
    tx.vin[0].scriptSig = CScript() << OP_0 << OP_0 << OP_0 << OP_NOP << OP_CHECKMULTISIG << OP_1;
    tx.vin[0].prevout.hash = txFirst[0]->GetHash();
    tx.vin[0].prevout.n = 0;
    tx.vout.resize(1);
    tx.vout[0].nValue = 5000000000LL;
    for (unsigned int i = 0; i < 1001; ++i)
    {
        tx.vout[0].nValue -= 1000000;
        hash = tx.GetHash();
        bool spendsCoinbase = (i == 0) ? true : false; // only first tx spends coinbase
        // If we don't set the # of sig ops in the CTxMemPoolEntry, template creation fails
        mempool.addUnchecked(hash, entry.Fee(1000000).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
        tx.vin[0].prevout.hash = hash;
    }
    BOOST_CHECK_THROW(CreateNewBlock(chainparams, scriptPubKey), std::runtime_error);
    mempool.clear();

    tx.vin[0].prevout.hash = txFirst[0]->GetHash();
    tx.vout[0].nValue = 5000000000LL;
    for (unsigned int i = 0; i < 1001; ++i)
    {
        tx.vout[0].nValue -= 1000000;
        hash = tx.GetHash();
        bool spendsCoinbase = (i == 0) ? true : false; // only first tx spends coinbase
        // If we do set the # of sig ops in the CTxMemPoolEntry, template creation passes
        mempool.addUnchecked(hash, entry.Fee(1000000).Time(GetTime()).SpendsCoinbase(spendsCoinbase).SigOps(20).FromTx(tx));
        tx.vin[0].prevout.hash = hash;
    }
    pblocktemplate = CreateNewBlock(chainparams, scriptPubKey);
    BOOST_CHECK(pblocktemplate);
    delete pblocktemplate;

    // Now generate lots of full size blocks and verify that none exceed the maxGeneratedBlock value, the mempool has 65k bytes of tx in it so this code will test both saturated and unsaturated blocks.
    for (unsigned int i = 2000; i <= 80000; i+=2000)
    {
      maxGeneratedBlock = i;

      pblocktemplate = CreateNewBlock(chainparams, scriptPubKey);
      BOOST_CHECK(pblocktemplate);
      BOOST_CHECK(pblocktemplate->block.fExcessive == false);
      BOOST_CHECK(pblocktemplate->block.nBlockSize <= maxGeneratedBlock);
      unsigned int blockSize = pblocktemplate->block.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
      BOOST_CHECK(blockSize <= maxGeneratedBlock);
      //printf("%lu %lu <= %lu\n", (long unsigned int) blockSize, (long unsigned int) pblocktemplate->block.nBlockSize, (long unsigned int) maxGeneratedBlock);
      delete pblocktemplate;
    }

    coinbaseReserve.value=0;  // Test no reserve
     // Now generate lots of full size blocks and verify that none exceed the maxGeneratedBlock value
    for (unsigned int i = 2000; i <= 20000; i+=773)
    {
      maxGeneratedBlock = i;

      pblocktemplate = CreateNewBlock(chainparams, scriptPubKey);
      BOOST_CHECK(pblocktemplate);
      BOOST_CHECK(pblocktemplate->block.fExcessive == false);
      BOOST_CHECK(pblocktemplate->block.nBlockSize <= maxGeneratedBlock);
      unsigned int blockSize = pblocktemplate->block.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
      BOOST_CHECK(blockSize <= maxGeneratedBlock);
      //printf("%lu %lu <= %lu\n", (long unsigned int) blockSize, (long unsigned int) pblocktemplate->block.nBlockSize, (long unsigned int) maxGeneratedBlock);
      delete pblocktemplate;
    }

    std::string testMinerComment("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM__________");
     // Now generate lots of full size blocks and verify that none exceed the maxGeneratedBlock value
    //printf("test mining with different sized miner comments");
    for (unsigned int i = 2000; i <= 40000; i+=113)
    {
      maxGeneratedBlock = i;
      if ((i%100) > 0) minerComment = testMinerComment.substr(0,i%100);
      else minerComment = "";
      //minerComment = testMinerComment.substr(0,i%100);
      pblocktemplate = CreateNewBlock(chainparams, scriptPubKey);
      BOOST_CHECK(pblocktemplate);
      BOOST_CHECK(pblocktemplate->block.fExcessive == false);
      BOOST_CHECK(pblocktemplate->block.nBlockSize <= maxGeneratedBlock);
      unsigned int blockSize = pblocktemplate->block.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
      BOOST_CHECK(blockSize <= maxGeneratedBlock);
      //printf("%lu %lu (miner comment is %d) <= %lu\n", (long unsigned int) blockSize, (long unsigned int) pblocktemplate->block.nBlockSize, i%100, (long unsigned int) maxGeneratedBlock);
      delete pblocktemplate;
    }

    mempool.clear();

    // block size > limit
    tx.vin[0].scriptSig = CScript();
    // 18 * (520char + DROP) + OP_1 = 9433 bytes
    std::vector<unsigned char> vchData(520);
    for (unsigned int i = 0; i < 18; ++i)
        tx.vin[0].scriptSig << vchData << OP_DROP;
    tx.vin[0].scriptSig << OP_1;
    tx.vin[0].prevout.hash = txFirst[0]->GetHash();
    tx.vout[0].nValue = 5000000000LL;
    for (unsigned int i = 0; i < 128; ++i)
    {
        tx.vout[0].nValue -= 10000000;
        hash = tx.GetHash();
        bool spendsCoinbase = (i == 0) ? true : false; // only first tx spends coinbase
        mempool.addUnchecked(hash, entry.Fee(1000000).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx));
        tx.vin[0].prevout.hash = hash;
    }
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));
    delete pblocktemplate;
    mempool.clear();

    // orphan in mempool, template creation fails
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(1000000).Time(GetTime()).FromTx(tx));
    BOOST_CHECK_THROW(CreateNewBlock(chainparams, scriptPubKey), std::runtime_error);
    mempool.clear();

    // child with higher priority than parent
    tx.vin[0].scriptSig = CScript() << OP_1;
    tx.vin[0].prevout.hash = txFirst[1]->GetHash();
    tx.vout[0].nValue = 4900000000LL;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(100000000LL).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
    tx.vin[0].prevout.hash = hash;
    tx.vin.resize(2);
    tx.vin[1].scriptSig = CScript() << OP_1;
    tx.vin[1].prevout.hash = txFirst[0]->GetHash();
    tx.vin[1].prevout.n = 0;
    tx.vout[0].nValue = 5900000000LL;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(400000000LL).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));
    delete pblocktemplate;
    mempool.clear();

    // coinbase in mempool, template creation fails
    tx.vin.resize(1);
    tx.vin[0].prevout.SetNull();
    tx.vin[0].scriptSig = CScript() << OP_0 << OP_1;
    tx.vout[0].nValue = 0;
    hash = tx.GetHash();
    // give it a fee so it'll get mined
    mempool.addUnchecked(hash, entry.Fee(100000).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
    BOOST_CHECK_THROW(CreateNewBlock(chainparams, scriptPubKey), std::runtime_error);
    mempool.clear();

    // invalid (pre-p2sh) txn in mempool, template creation fails
    tx.vin[0].prevout.hash = txFirst[0]->GetHash();
    tx.vin[0].prevout.n = 0;
    tx.vin[0].scriptSig = CScript() << OP_1;
    tx.vout[0].nValue = 4900000000LL;
    script = CScript() << OP_0;
    tx.vout[0].scriptPubKey = GetScriptForDestination(CScriptID(script));
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(10000000L).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
    tx.vin[0].prevout.hash = hash;
    tx.vin[0].scriptSig = CScript() << std::vector<unsigned char>(script.begin(), script.end());
    tx.vout[0].nValue -= 1000000;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(1000000).Time(GetTime()).SpendsCoinbase(false).FromTx(tx));
    BOOST_CHECK_THROW(CreateNewBlock(chainparams, scriptPubKey), std::runtime_error);
    mempool.clear();

    // double spend txn pair in mempool, template creation fails
    tx.vin[0].prevout.hash = txFirst[0]->GetHash();
    tx.vin[0].scriptSig = CScript() << OP_1;
    tx.vout[0].nValue = 4900000000LL;
    tx.vout[0].scriptPubKey = CScript() << OP_1;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(100000000L).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
    tx.vout[0].scriptPubKey = CScript() << OP_2;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(100000000L).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
    BOOST_CHECK_THROW(CreateNewBlock(chainparams, scriptPubKey), std::runtime_error);
    mempool.clear();

    // subsidy changing
    int nHeight = chainActive.Height();
    // Create an actual 209999-long block chain (without valid blocks).
    while (chainActive.Tip()->nHeight < 209999) {
        CBlockIndex* prev = chainActive.Tip();
        CBlockIndex* next = new CBlockIndex();
        next->phashBlock = new uint256(GetRandHash());
        pcoinsTip->SetBestBlock(next->GetBlockHash());
        next->pprev = prev;
        next->nHeight = prev->nHeight + 1;
        next->BuildSkip();
        chainActive.SetTip(next);
    }
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));
    delete pblocktemplate;
    // Extend to a 210000-long block chain.
    while (chainActive.Tip()->nHeight < 210000) {
        CBlockIndex* prev = chainActive.Tip();
        CBlockIndex* next = new CBlockIndex();
        next->phashBlock = new uint256(GetRandHash());
        pcoinsTip->SetBestBlock(next->GetBlockHash());
        next->pprev = prev;
        next->nHeight = prev->nHeight + 1;
        next->BuildSkip();
        chainActive.SetTip(next);
    }
    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));
    delete pblocktemplate;
    // Delete the dummy blocks again.
    while (chainActive.Tip()->nHeight > nHeight) {
        CBlockIndex* del = chainActive.Tip();
        chainActive.SetTip(del->pprev);
        pcoinsTip->SetBestBlock(del->pprev->GetBlockHash());
        delete del->phashBlock;
        delete del;
    }

    // non-final txs in mempool
    SetMockTime(chainActive.Tip()->GetMedianTimePast()+1);
    int flags = LOCKTIME_VERIFY_SEQUENCE|LOCKTIME_MEDIAN_TIME_PAST;
    // height map
    std::vector<int> prevheights;

    // relative height locked
    tx.nVersion = 2;
    tx.vin.resize(1);
    prevheights.resize(1);
    tx.vin[0].prevout.hash = txFirst[0]->GetHash(); // only 1 transaction
    tx.vin[0].prevout.n = 0;
    tx.vin[0].scriptSig = CScript() << OP_1;
    tx.vin[0].nSequence = chainActive.Tip()->nHeight + 1; // txFirst[0] is the 2nd block
    prevheights[0] = baseheight + 1;
    tx.vout.resize(1);
    tx.vout[0].nValue = 4900000000LL;
    tx.vout[0].scriptPubKey = CScript() << OP_1;
    tx.nLockTime = 0;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Fee(100000000L).Time(GetTime()).SpendsCoinbase(true).FromTx(tx));
    BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes
    BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail
    BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 2))); // Sequence locks pass on 2nd block

    // relative time locked
    tx.vin[0].prevout.hash = txFirst[1]->GetHash();
    tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | (((chainActive.Tip()->GetMedianTimePast()+1-chainActive[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); // txFirst[1] is the 3rd block
    prevheights[0] = baseheight + 2;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx));
    BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes
    BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail

    for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
        chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast
    BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 1))); // Sequence locks pass 512 seconds later
    for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
        chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime -= 512; //undo tricked MTP

    // absolute height locked
    tx.vin[0].prevout.hash = txFirst[2]->GetHash();
    tx.vin[0].nSequence = CTxIn::SEQUENCE_FINAL - 1;
    prevheights[0] = baseheight + 3;
    tx.nLockTime = chainActive.Tip()->nHeight + 1;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx));
    BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails
    BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
    BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast())); // Locktime passes on 2nd block

    // absolute time locked
    tx.vin[0].prevout.hash = txFirst[3]->GetHash();
    tx.nLockTime = chainActive.Tip()->GetMedianTimePast();
    prevheights.resize(1);
    prevheights[0] = baseheight + 4;
    hash = tx.GetHash();
    mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx));
    BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails
    BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
    BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later

    // mempool-dependent transactions (not added)
    tx.vin[0].prevout.hash = hash;
    prevheights[0] = chainActive.Tip()->nHeight + 1;
    tx.nLockTime = 0;
    tx.vin[0].nSequence = 0;
    BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes
    BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
    tx.vin[0].nSequence = 1;
    BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail
    tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
    BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass
    tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | 1;
    BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail

    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));

    // None of the of the absolute height/time locked tx should have made
    // it into the template because we still check IsFinalTx in CreateNewBlock,
    // but relative locked txs will if inconsistently added to mempool.
    // For now these will still generate a valid template until BIP68 soft fork
    BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3);
    delete pblocktemplate;
    // However if we advance height by 1 and time by 512, all of them should be mined
    for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++)
        chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast
    chainActive.Tip()->nHeight++;
    SetMockTime(chainActive.Tip()->GetMedianTimePast() + 1);

    BOOST_CHECK(pblocktemplate = CreateNewBlock(chainparams, scriptPubKey));
    BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5);
    delete pblocktemplate;

    chainActive.Tip()->nHeight--;
    SetMockTime(0);
    mempool.clear();

    BOOST_FOREACH(CTransaction *tx, txFirst)
        delete tx;

    fCheckpointsEnabled = true;
}

BOOST_AUTO_TEST_SUITE_END()


text:
.test {
  background: #000;
}
.test:hover {
  width: 200px;
  height: 200px;
  transition-delay: 1s, 1s;
  transition-duration: 1s, 1s;
  transition-property: height, width;
  transition-timing-function: ease-in, ease-in;
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Inocybe abjecta

### Remarks
null


text:
'use strict';

const fs = require('fs');
const path = require('path');

const examples = path.join(__dirname, '..', 'examples');
const dist = path.join(__dirname, '..', 'list.json');

let list = fs.readdirSync(examples);

list = list.filter(item => {
  return !~item.indexOf('.');
});

var data = {
  list: list
};

fs.writeFileSync(dist, JSON.stringify(data, null, 2));


text:
namespace rocksdb {

LDBOptions::LDBOptions() {}

void LDBCommandRunner::PrintHelp(const char* exec_name) {
  std::string ret;

  ret.append("ldb - LevelDB Tool");
  ret.append("\n\n");
  ret.append("commands MUST specify --" + LDBCommand::ARG_DB +
             "=<full_path_to_db_directory> when necessary\n");
  ret.append("\n");
  ret.append(
      "The following optional parameters control if keys/values are "
      "input/output as hex or as plain strings:\n");
  ret.append("  --" + LDBCommand::ARG_KEY_HEX +
             " : Keys are input/output as hex\n");
  ret.append("  --" + LDBCommand::ARG_VALUE_HEX +
             " : Values are input/output as hex\n");
  ret.append("  --" + LDBCommand::ARG_HEX +
             " : Both keys and values are input/output as hex\n");
  ret.append("\n");

  ret.append(
      "The following optional parameters control the database "
      "internals:\n");
  ret.append(
      "  --" + LDBCommand::ARG_CF_NAME +
      "=<string> : name of the column family to operate on. default: default "
      "column family\n");
  ret.append("  --" + LDBCommand::ARG_TTL +
             " with 'put','get','scan','dump','query','batchput'"
             " : DB supports ttl and value is internally timestamp-suffixed\n");
  ret.append("  --" + LDBCommand::ARG_BLOOM_BITS + "=<int,e.g.:14>\n");
  ret.append("  --" + LDBCommand::ARG_FIX_PREFIX_LEN + "=<int,e.g.:14>\n");
  ret.append("  --" + LDBCommand::ARG_COMPRESSION_TYPE +
             "=<no|snappy|zlib|bzip2|lz4|lz4hc|xpress|zstd>\n");
  ret.append("  --" + LDBCommand::ARG_COMPRESSION_MAX_DICT_BYTES +
             "=<int,e.g.:16384>\n");
  ret.append("  --" + LDBCommand::ARG_BLOCK_SIZE + "=<block_size_in_bytes>\n");
  ret.append("  --" + LDBCommand::ARG_AUTO_COMPACTION + "=<true|false>\n");
  ret.append("  --" + LDBCommand::ARG_DB_WRITE_BUFFER_SIZE +
             "=<int,e.g.:16777216>\n");
  ret.append("  --" + LDBCommand::ARG_WRITE_BUFFER_SIZE +
             "=<int,e.g.:4194304>\n");
  ret.append("  --" + LDBCommand::ARG_FILE_SIZE + "=<int,e.g.:2097152>\n");

  ret.append("\n\n");
  ret.append("Data Access Commands:\n");
  PutCommand::Help(ret);
  GetCommand::Help(ret);
  BatchPutCommand::Help(ret);
  ScanCommand::Help(ret);
  DeleteCommand::Help(ret);
  DeleteRangeCommand::Help(ret);
  DBQuerierCommand::Help(ret);
  ApproxSizeCommand::Help(ret);
  CheckConsistencyCommand::Help(ret);

  ret.append("\n\n");
  ret.append("Admin Commands:\n");
  WALDumperCommand::Help(ret);
  CompactorCommand::Help(ret);
  ReduceDBLevelsCommand::Help(ret);
  ChangeCompactionStyleCommand::Help(ret);
  DBDumperCommand::Help(ret);
  DBLoaderCommand::Help(ret);
  ManifestDumpCommand::Help(ret);
  ListColumnFamiliesCommand::Help(ret);
  DBFileDumperCommand::Help(ret);
  InternalDumpCommand::Help(ret);
  RepairCommand::Help(ret);
  BackupCommand::Help(ret);
  RestoreCommand::Help(ret);

  fprintf(stderr, "%s\n", ret.c_str());
}

void LDBCommandRunner::RunCommand(
    int argc, char** argv, Options options, const LDBOptions& ldb_options,
    const std::vector<ColumnFamilyDescriptor>* column_families) {
  if (argc <= 2) {
    PrintHelp(argv[0]);
    exit(1);
  }

  LDBCommand* cmdObj = LDBCommand::InitFromCmdLineArgs(
      argc, argv, options, ldb_options, column_families);
  if (cmdObj == nullptr) {
    fprintf(stderr, "Unknown command\n");
    PrintHelp(argv[0]);
    exit(1);
  }

  if (!cmdObj->ValidateCmdLineOptions()) {
    exit(1);
  }

  cmdObj->Run();
  LDBCommandExecuteResult ret = cmdObj->GetExecuteState();
  fprintf(stderr, "%s\n", ret.ToString().c_str());
  delete cmdObj;

  exit(ret.IsFailed());
}

void LDBTool::Run(int argc, char** argv, Options options,
                  const LDBOptions& ldb_options,
                  const std::vector<ColumnFamilyDescriptor>* column_families) {
  LDBCommandRunner::RunCommand(argc, argv, options, ldb_options,
                               column_families);
}
} // namespace rocksdb

#endif  // ROCKSDB_LITE


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Linq;
using Google.Cloud.Spanner.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Microsoft.EntityFrameworkCore.Storage.Internal;

namespace Google.Cloud.EntityFrameworkCore.Spanner.IntegrationTests
{
    public class ConnectionSpecificationTest
    {
        private class StringInOnConfiguringContext : NorthwindContextBase
        {
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                => optionsBuilder.UseSpanner(SpannerTestStore.NorthwindConnectionString, b => b.ApplyConfiguration());
        }

        private class ConnectionInOnConfiguringContext : NorthwindContextBase
        {
            private readonly SpannerConnection _connection;

            public ConnectionInOnConfiguringContext(SpannerConnection connection) => _connection = connection;

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                => optionsBuilder.UseSpanner(_connection, b => b.ApplyConfiguration());

            public override void Dispose()
            {
                _connection.Dispose();
                base.Dispose();
            }
        }

        private class StringInConfigContext : NorthwindContextBase
        {
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                => optionsBuilder.UseSpanner("Database=Crunchie", b => b.ApplyConfiguration());
        }

        private class NoUseSpannerContext : NorthwindContextBase
        {
        }

        private class OptionsContext : NorthwindContextBase
        {
            private readonly SpannerConnection _connection;
            private readonly DbContextOptions<OptionsContext> _options;

            public OptionsContext(DbContextOptions<OptionsContext> options, SpannerConnection connection)
                : base(options)
            {
                _options = options;
                _connection = connection;
            }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                Assert.Same(_options, optionsBuilder.Options);

                optionsBuilder.UseSpanner(_connection, b => b.ApplyConfiguration());

                Assert.NotSame(_options, optionsBuilder.Options);
            }

            public override void Dispose()
            {
                _connection.Dispose();
                base.Dispose();
            }
        }

        private class NonGenericOptionsContext : NorthwindContextBase
        {
            private readonly DbContextOptions _options;

            public NonGenericOptionsContext(DbContextOptions options)
                : base(options) => _options = options;

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                Assert.Same(_options, optionsBuilder.Options);

                optionsBuilder.UseSpanner(SpannerTestStore.NorthwindConnectionString, b => b.ApplyConfiguration());

                Assert.NotSame(_options, optionsBuilder.Options);
            }
        }

        private class NorthwindContextBase : DbContext
        {
            protected NorthwindContextBase()
            {
            }

            protected NorthwindContextBase(DbContextOptions options)
                : base(options)
            {
            }

            public DbSet<Customer> Customers { get; set; }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Customer>(b =>
                {
                    b.HasKey(c => c.CustomerID);
                    b.ToTable("Customers");
                });
            }
        }

        private class Customer
        {
            public string CustomerID { get; set; }
            public string CompanyName { get; set; }
            public string Fax { get; set; }
        }

        [Fact]
        public void Can_depend_on_DbContextOptions()
        {
            var serviceProvider
                = new ServiceCollection()
                    .AddScoped(p => new SpannerConnection(SpannerTestStore.NorthwindConnectionString))
                    .AddDbContext<OptionsContext>()
                    .BuildServiceProvider();

            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context = serviceProvider.GetRequiredService<OptionsContext>())
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Can_depend_on_DbContextOptions_with_default_service_provider()
        {
            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context = new OptionsContext(
                    new DbContextOptions<OptionsContext>(),
                    new SpannerConnection(SpannerTestStore.NorthwindConnectionString)))
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Can_depend_on_non_generic_options_when_only_one_context()
        {
            var serviceProvider
                = new ServiceCollection()
                    .AddDbContext<NonGenericOptionsContext>()
                    .BuildServiceProvider();

            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context = serviceProvider.GetRequiredService<NonGenericOptionsContext>())
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Can_depend_on_non_generic_options_when_only_one_context_with_default_service_provider()
        {
            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context = new NonGenericOptionsContext(new DbContextOptions<DbContext>()))
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Can_specify_connection_in_OnConfiguring()
        {
            var serviceProvider
                = new ServiceCollection()
                    .AddScoped(p => new SpannerConnection(SpannerTestStore.NorthwindConnectionString))
                    .AddDbContext<ConnectionInOnConfiguringContext>().BuildServiceProvider();

            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context = serviceProvider.GetRequiredService<ConnectionInOnConfiguringContext>())
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Can_specify_connection_in_OnConfiguring_and_create_master_connection()
        {
            using (var conn = new SpannerConnection(SpannerTestStore.NorthwindConnectionString))
            {
                conn.Open();

                using (SpannerTestStore.GetNorthwindStore())
                {
                    using (var context = new ConnectionInOnConfiguringContext(conn))
                    {
                        var relationalConn = context.GetService<ISpannerRelationalConnection>();
                        using (var masterConn = relationalConn.CreateMasterConnection())
                        {
                            masterConn.Open();
                        }
                    }
                }
            }
        }

        [Fact]
        public void Can_specify_connection_in_OnConfiguring_with_default_service_provider()
        {
            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context =
                    new ConnectionInOnConfiguringContext(
                        new SpannerConnection(SpannerTestStore.NorthwindConnectionString)))
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Can_specify_connection_string_in_OnConfiguring()
        {
            var serviceProvider
                = new ServiceCollection()
                    .AddDbContext<StringInOnConfiguringContext>()
                    .BuildServiceProvider();

            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context = serviceProvider.GetRequiredService<StringInOnConfiguringContext>())
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Can_specify_connection_string_in_OnConfiguring_with_default_service_provider()
        {
            using (SpannerTestStore.GetNorthwindStore())
            {
                using (var context = new StringInOnConfiguringContext())
                {
                    Assert.True(context.Customers.Any());
                }
            }
        }

        [Fact]
        public void Throws_if_no_config_without_UseSpanner()
        {
            var serviceProvider
                = new ServiceCollection()
                    .AddDbContext<NoUseSpannerContext>().BuildServiceProvider();

            using (var context = serviceProvider.GetRequiredService<NoUseSpannerContext>())
            {
                Assert.Equal(
                    CoreStrings.NoProviderConfigured,
                    Assert.Throws<InvalidOperationException>(() => context.Customers.Any()).Message);
            }
        }

        [Fact]
        public void Throws_if_no_connection_found_in_config_without_UseSpanner()
        {
            var serviceProvider
                = new ServiceCollection()
                    .AddDbContext<NoUseSpannerContext>().BuildServiceProvider();

            using (var context = serviceProvider.GetRequiredService<NoUseSpannerContext>())
            {
                Assert.Equal(
                    CoreStrings.NoProviderConfigured,
                    Assert.Throws<InvalidOperationException>(() => context.Customers.Any()).Message);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<!-- your theme inherits from the material theme -->
	<style name="AppBaseTheme" parent="android:Theme.Material">
		<!-- theme customizations -->
		<item name="android:colorPrimary">#2196F3</item>
		<item name="android:colorPrimaryDark">#1976D2</item>
		<item name="android:navigationBarColor">#2196F3</item>
	</style>

    <style name="Nappi" parent="android:Widget.Material.Button">

        <item name="android:background">#03A9F4</item>
        <item name="android:layout_margin">10dp</item>
    </style>

</resources>


text:
klasses = [ Project, Document, User, Article, Event ]
old_counts = klasses.map(&:count)
should_prompt = old_counts.min > 0

def get_country
  country = File.readlines(Rails.root + 'spec/fixtures/country_codes.txt').sample
  code, name = country.chomp.split('|')
  @country = {country_name: name, country_code: code}
end

if should_prompt
  puts 'Would you like to ' + 'delete'.red.bold + ' all the existing projects and documents from the database?'
end

while true
  if should_prompt
    print 'yes(y)/no(n): '
    response = STDIN.gets.downcase.chomp
  else
    response = 'y'
  end

  if response == 'y' || response == 'yes'
    puts 'Clearing existing projects and documents'
    klasses.each(&:delete_all)

    pw = 'randomrandom'
    u = User.create(first_name: 'Random', last_name: 'Guy', email: 'random@random.com', password: pw)
    puts 'Added default user with email: ' + u.email.bold.blue + ' and password: ' + pw.bold.red

    u.projects.create! :title => 'Autograder',
                       :description => 'Autograder for the EdX CS169.x SaaS course',
                       :status => 'Active',
                       commit_count: 200

    u.projects.create! :title => 'WebsiteOne',
                       :description => 'The AgileVentures site - a platform for online collaboration and crowdsourced project development.',
                       :status => 'Active',
                       commit_count: 190

    u.projects.create! :title => 'LocalSupport',
                       :description => 'The open source project Local Support is a directory of local charity and non-profit organisations for a small geographical area.
Our customer is the non-profit organization Voluntary Action Harrow.
The mission is to support members of the public searching for support groups for things like helping care for an elderly or sick relative; and also to help charities and non-profits find each other and network.',
                       :status => 'Active',
                       commit_count: 100

    u.projects.create! :title => 'EduChat',
                       :description => 'Supporting real time synchronous chat in online classes',
                       :status => 'Inactive',
                       commit_count: 100

    u.projects.create! :title => 'PP Scheduler',
                       :description => "Problem: Lots of people want to pair, but they don't know when each other are available
Solution: is something that requires absolutely minimal effort on their part to use in order to let them pair",
                       :status => 'Active'

    u.projects.create! :title => 'Funniest Computer Ever',
                       :description => "Can YOU write a program to make humans laugh? Get your editors fired up and your coding caps ready because you've arrived at the Funniest Computer Ever competition!",
                       :status => 'Active'

    puts 'Created default projects'
    break
  elsif response == 'n' || response == 'no'
    break
  end
end

u ||= User.last
for i in (1..3)
  p = u.projects.create title: Faker::Lorem.words(3).join(' '), description: Faker::Lorem.paragraph, status: 'active', created_at: 1.month.ago
  for j in (1..3)
    d = p.documents.create title: Faker::Lorem.words(3).join(' '), body: Faker::Lorem.paragraph, created_at: 1.month.ago, user_id: p.user_id
    for k in (1..rand(3))
      d.children.create title: Faker::Lorem.words(3).join(' '), body: Faker::Lorem.paragraph, project_id: p.id, created_at: 1.month.ago, user_id: p.user_id
    end
  end
end

for i in (1..300)
  get_country
  u = User.create first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, password: Faker::Lorem.characters(10), country_name: @country[:country_name], country_code: @country[:country_code]
  Project.all.sample(3).each do |p|
    u.follow p
  end
end

for i in (1..4)
  User.all.sample(3).each do |u|
    u.articles.create!(title: Faker::Lorem.words(3).join(' '), content: Faker::Lorem.paragraphs(3).join('\n'))
  end
end

Event.create!( name: 'Seeded event',
               category: 'Scrum',
               description: 'Seeded content',
               # event_date: 'Mon, 17 Jun 2013',
               # start_time: '2000-01-01 09:00:00 UTC',
               # end_time: '2000-01-01 17:00:00 UTC',
               start_datetime: 'Mon, 17 Jun 2014',
               duration: 600,
               repeats: 'weekly',
               repeats_every_n_weeks: '1',
               repeats_weekly_each_days_of_the_week_mask: '31',
               repeat_ends: 'never',
               repeat_ends_on: 'Mon, 17 Jun 2015',
               time_zone: 'UTC')

Event.create!( name: 'evening event',
               category: 'Scrum',
               description: 'Seeded content',
               # event_date: 'Mon, 17 Jun 2013',
               # start_time: '2000-01-01 09:00:00 UTC',
               # end_time: '2000-01-01 17:00:00 UTC',
               start_datetime: 'Mon, 17 Jun 2014 17:00:00 UTC',
               duration: 600,
               repeats: 'weekly',
               repeats_every_n_weeks: '1',
               repeats_weekly_each_days_of_the_week_mask: '31',
               repeat_ends: 'never',
               repeat_ends_on: 'Mon, 17 Jun 2015',
               time_zone: 'UTC')

if StaticPage.count == 0
  Rake::Task['db:import_pages'].invoke
end

klasses.each_with_index do |klass, i|
  puts "#{klass.name}.count " + old_counts[i].to_s.bold.red + ' -> ' + klass.count.to_s.bold.green
end


text:
/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
 *   USA                                                                   *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef WITH_MP4

#include <tdebug.h>
#include <tstring.h>
#include "mp4atom.h"
#include "mp4tag.h"
#include "id3v1genres.h"

using namespace TagLib;

class MP4::Tag::TagPrivate
{
public:
  TagPrivate() : file(0), atoms(0) {}
  ~TagPrivate() {}
  TagLib::File *file;
  Atoms *atoms;
  ItemListMap items;
};

MP4::Tag::Tag(TagLib::File *file, MP4::Atoms *atoms)
{
  d = new TagPrivate;
  d->file = file;
  d->atoms = atoms;

  MP4::Atom *ilst = atoms->find("moov", "udta", "meta", "ilst");
  if(!ilst) {
    //debug("Atom moov.udta.meta.ilst not found.");
    return;
  }

  for(unsigned int i = 0; i < ilst->children.size(); i++) {
    MP4::Atom *atom = ilst->children[i];
    file->seek(atom->offset + 8);
    if(atom->name == "----") {
      parseFreeForm(atom, file);
    }
    else if(atom->name == "trkn" || atom->name == "disk") {
      parseIntPair(atom, file);
    }
    else if(atom->name == "cpil" || atom->name == "pgap" || atom->name == "pcst") {
      parseBool(atom, file);
    }
    else if(atom->name == "tmpo") {
      parseInt(atom, file);
    }
    else if(atom->name == "gnre") {
      parseGnre(atom, file);
    }
    else if(atom->name == "covr") {
      parseCovr(atom, file);
    }
    else {
      parseText(atom, file);
    }
  }
}

MP4::Tag::~Tag()
{
  delete d;
}

ByteVectorList
MP4::Tag::parseData(MP4::Atom *atom, TagLib::File *file, int expectedFlags, bool freeForm)
{
  ByteVectorList result;
  ByteVector data = file->readBlock(atom->length - 8);
  int i = 0;
  unsigned int pos = 0;
  while(pos < data.size()) {
    int length = data.mid(pos, 4).toUInt();
    ByteVector name = data.mid(pos + 4, 4);
    int flags = data.mid(pos + 8, 4).toUInt();
    if(freeForm && i < 2) {
      if(i == 0 && name != "mean") {
        debug("MP4: Unexpected atom \"" + name + "\", expecting \"mean\"");
        return result;
      }
      else if(i == 1 && name != "name") {
        debug("MP4: Unexpected atom \"" + name + "\", expecting \"name\"");
        return result;
      }
      result.append(data.mid(pos + 12, length - 12));
    }
    else {
      if(name != "data") {
        debug("MP4: Unexpected atom \"" + name + "\", expecting \"data\"");
        return result;
      }
      if(expectedFlags == -1 || flags == expectedFlags) {
        result.append(data.mid(pos + 16, length - 16));
      }
    }
    pos += length;
    i++;
  }
  return result;
}

void
MP4::Tag::parseInt(MP4::Atom *atom, TagLib::File *file)
{
  ByteVectorList data = parseData(atom, file);
  if(data.size()) {
    d->items.insert(atom->name, (int)data[0].toShort());
  }
}

void
MP4::Tag::parseGnre(MP4::Atom *atom, TagLib::File *file)
{
  ByteVectorList data = parseData(atom, file);
  if(data.size()) {
    int idx = (int)data[0].toShort();
    if(!d->items.contains("\251gen") && idx > 0) {
      d->items.insert("\251gen", StringList(ID3v1::genre(idx - 1)));
    }
  }
}

void
MP4::Tag::parseIntPair(MP4::Atom *atom, TagLib::File *file)
{
  ByteVectorList data = parseData(atom, file);
  if(data.size()) {
    int a = data[0].mid(2, 2).toShort();
    int b = data[0].mid(4, 2).toShort();
    d->items.insert(atom->name, MP4::Item(a, b));
  }
}

void
MP4::Tag::parseBool(MP4::Atom *atom, TagLib::File *file)
{
  ByteVectorList data = parseData(atom, file);
  if(data.size()) {
    bool value = data[0].size() ? data[0][0] != '\0' : false;
    d->items.insert(atom->name, value);
  }
}

void
MP4::Tag::parseText(MP4::Atom *atom, TagLib::File *file, int expectedFlags)
{
  ByteVectorList data = parseData(atom, file, expectedFlags);
  if(data.size()) {
    StringList value;
    for(unsigned int i = 0; i < data.size(); i++) {
      value.append(String(data[i], String::UTF8));
    }
    d->items.insert(atom->name, value);
  }
}

void
MP4::Tag::parseFreeForm(MP4::Atom *atom, TagLib::File *file)
{
  ByteVectorList data = parseData(atom, file, 1, true);
  if(data.size() > 2) {
    StringList value;
    for(unsigned int i = 2; i < data.size(); i++) {
      value.append(String(data[i], String::UTF8));
    }
    String name = "----:" + data[0] + ':' + data[1];
    d->items.insert(name, value);
  }
}

void
MP4::Tag::parseCovr(MP4::Atom *atom, TagLib::File *file)
{
  MP4::CoverArtList value;
  ByteVector data = file->readBlock(atom->length - 8);
  unsigned int pos = 0;
  while(pos < data.size()) {
    int length = data.mid(pos, 4).toUInt();
    ByteVector name = data.mid(pos + 4, 4);
    int flags = data.mid(pos + 8, 4).toUInt();
    if(name != "data") {
      debug("MP4: Unexpected atom \"" + name + "\", expecting \"data\"");
      break;
    }
    if(flags == MP4::CoverArt::PNG || flags == MP4::CoverArt::JPEG) {
      value.append(MP4::CoverArt(MP4::CoverArt::Format(flags),
                                 data.mid(pos + 16, length - 16)));
    }
    pos += length;
  }
  if(value.size() > 0)
    d->items.insert(atom->name, value);
}

ByteVector
MP4::Tag::padIlst(const ByteVector &data, int length)
{
  if (length == -1) {
    length = ((data.size() + 1023) & ~1023) - data.size();
  }
  return renderAtom("free", ByteVector(length, '\1'));
}

ByteVector
MP4::Tag::renderAtom(const ByteVector &name, const ByteVector &data)
{
  return ByteVector::fromUInt(data.size() + 8) + name + data;
}

ByteVector
MP4::Tag::renderData(const ByteVector &name, int flags, const ByteVectorList &data)
{
  ByteVector result;
  for(unsigned int i = 0; i < data.size(); i++) {
    result.append(renderAtom("data", ByteVector::fromUInt(flags) + ByteVector(4, '\0') + data[i]));
  }
  return renderAtom(name, result);
}

ByteVector
MP4::Tag::renderBool(const ByteVector &name, MP4::Item &item)
{
  ByteVectorList data;
  data.append(ByteVector(1, item.toBool() ? '\1' : '\0'));
  return renderData(name, 0x15, data);
}

ByteVector
MP4::Tag::renderInt(const ByteVector &name, MP4::Item &item)
{
  ByteVectorList data;
  data.append(ByteVector::fromShort(item.toInt()));
  return renderData(name, 0x15, data);
}

ByteVector
MP4::Tag::renderIntPair(const ByteVector &name, MP4::Item &item)
{
  ByteVectorList data;
  data.append(ByteVector(2, '\0') +
              ByteVector::fromShort(item.toIntPair().first) +
              ByteVector::fromShort(item.toIntPair().second) +
              ByteVector(2, '\0'));
  return renderData(name, 0x00, data);
}

ByteVector
MP4::Tag::renderIntPairNoTrailing(const ByteVector &name, MP4::Item &item)
{
  ByteVectorList data;
  data.append(ByteVector(2, '\0') +
              ByteVector::fromShort(item.toIntPair().first) +
              ByteVector::fromShort(item.toIntPair().second));
  return renderData(name, 0x00, data);
}

ByteVector
MP4::Tag::renderText(const ByteVector &name, MP4::Item &item, int flags)
{
  ByteVectorList data;
  StringList value = item.toStringList();
  for(unsigned int i = 0; i < value.size(); i++) {
    data.append(value[i].data(String::UTF8));
  }
  return renderData(name, flags, data);
}

ByteVector
MP4::Tag::renderCovr(const ByteVector &name, MP4::Item &item)
{
  ByteVector data;
  MP4::CoverArtList value = item.toCoverArtList();
  for(unsigned int i = 0; i < value.size(); i++) {
    data.append(renderAtom("data", ByteVector::fromUInt(value[i].format()) +
                                   ByteVector(4, '\0') + value[i].data()));
  }
  return renderAtom(name, data);
}

ByteVector
MP4::Tag::renderFreeForm(const String &name, MP4::Item &item)
{
  StringList header = StringList::split(name, ":");
  if (header.size() != 3) {
    debug("MP4: Invalid free-form item name \"" + name + "\"");
    return ByteVector::null;
  }
  ByteVector data;
  data.append(renderAtom("mean", ByteVector::fromUInt(0) + header[1].data(String::UTF8)));
  data.append(renderAtom("name", ByteVector::fromUInt(0) + header[2].data(String::UTF8)));
  StringList value = item.toStringList();
  for(unsigned int i = 0; i < value.size(); i++) {
    data.append(renderAtom("data", ByteVector::fromUInt(1) + ByteVector(4, '\0') + value[i].data(String::UTF8)));
  }
  return renderAtom("----", data);
}

bool
MP4::Tag::save()
{
  ByteVector data;
  for(MP4::ItemListMap::Iterator i = d->items.begin(); i != d->items.end(); i++) {
    const String name = i->first;
    if(name.startsWith("----")) {
      data.append(renderFreeForm(name, i->second));
    }
    else if(name == "trkn") {
      data.append(renderIntPair(name.data(String::Latin1), i->second));
    }
    else if(name == "disk") {
      data.append(renderIntPairNoTrailing(name.data(String::Latin1), i->second));
    }
    else if(name == "cpil" || name == "pgap" || name == "pcst") {
      data.append(renderBool(name.data(String::Latin1), i->second));
    }
    else if(name == "tmpo") {
      data.append(renderInt(name.data(String::Latin1), i->second));
    }
    else if(name == "covr") {
      data.append(renderCovr(name.data(String::Latin1), i->second));
    }
    else if(name.size() == 4){
      data.append(renderText(name.data(String::Latin1), i->second));
    }
    else {
      debug("MP4: Unknown item name \"" + name + "\"");
    }
  }
  data = renderAtom("ilst", data);

  AtomList path = d->atoms->path("moov", "udta", "meta", "ilst");
  if(path.size() == 4) {
    saveExisting(data, path);
  }
  else {
    saveNew(data);
  }

  return true;
}

void
MP4::Tag::updateParents(AtomList &path, long delta, int ignore)
{
  for(unsigned int i = 0; i < path.size() - ignore; i++) {
    d->file->seek(path[i]->offset);
    long size = d->file->readBlock(4).toUInt();
    // 64-bit
    if (size == 1) {
      d->file->seek(4, File::Current); // Skip name
      long long longSize = d->file->readBlock(8).toLongLong();
      // Seek the offset of the 64-bit size
      d->file->seek(path[i]->offset + 8);
      d->file->writeBlock(ByteVector::fromLongLong(longSize + delta));
    }
    // 32-bit
    else {
      d->file->seek(path[i]->offset);
      d->file->writeBlock(ByteVector::fromUInt(size + delta));
    }
  }
}

void
MP4::Tag::updateOffsets(long delta, long offset)
{
  MP4::Atom *moov = d->atoms->find("moov");
  if(moov) {
    MP4::AtomList stco = moov->findall("stco", true);
    for(unsigned int i = 0; i < stco.size(); i++) {
      MP4::Atom *atom = stco[i];
      if(atom->offset > offset) {
        atom->offset += delta;
      }
      d->file->seek(atom->offset + 12);
      ByteVector data = d->file->readBlock(atom->length - 12);
      unsigned int count = data.mid(0, 4).toUInt();
      d->file->seek(atom->offset + 16);
      int pos = 4;
      while(count--) {
        long o = data.mid(pos, 4).toUInt();
        if(o > offset) {
          o += delta;
        }
        d->file->writeBlock(ByteVector::fromUInt(o));
        pos += 4;
      }
    }

    MP4::AtomList co64 = moov->findall("co64", true);
    for(unsigned int i = 0; i < co64.size(); i++) {
      MP4::Atom *atom = co64[i];
      if(atom->offset > offset) {
        atom->offset += delta;
      }
      d->file->seek(atom->offset + 12);
      ByteVector data = d->file->readBlock(atom->length - 12);
      unsigned int count = data.mid(0, 4).toUInt();
      d->file->seek(atom->offset + 16);
      int pos = 4;
      while(count--) {
        long long o = data.mid(pos, 8).toLongLong();
        if(o > offset) {
          o += delta;
        }
        d->file->writeBlock(ByteVector::fromLongLong(o));
        pos += 8;
      }
    }
  }

  MP4::Atom *moof = d->atoms->find("moof");
  if(moof) {
    MP4::AtomList tfhd = moof->findall("tfhd", true);
    for(unsigned int i = 0; i < tfhd.size(); i++) {
      MP4::Atom *atom = tfhd[i];
      if(atom->offset > offset) {
        atom->offset += delta;
      }
      d->file->seek(atom->offset + 9);
      ByteVector data = d->file->readBlock(atom->offset - 9);
      unsigned int flags = (ByteVector(1, '\0') + data.mid(0, 3)).toUInt();
      if(flags & 1) {
        long long o = data.mid(7, 8).toLongLong();
        if(o > offset) {
          o += delta;
        }
        d->file->seek(atom->offset + 16);
        d->file->writeBlock(ByteVector::fromLongLong(o));
      }
    }
  }
}

void
MP4::Tag::saveNew(ByteVector &data)
{
  data = renderAtom("meta", TagLib::ByteVector(4, '\0') +
                    renderAtom("hdlr", TagLib::ByteVector(8, '\0') + TagLib::ByteVector("mdirappl") + TagLib::ByteVector(9, '\0')) +
                    data + padIlst(data));

  AtomList path = d->atoms->path("moov", "udta");
  if(path.size() != 2) {
    path = d->atoms->path("moov");
    data = renderAtom("udta", data);
  }

  long offset = path[path.size() - 1]->offset + 8;
  d->file->insert(data, offset, 0);

  updateParents(path, data.size());
  updateOffsets(data.size(), offset);
}

void
MP4::Tag::saveExisting(ByteVector &data, AtomList &path)
{
  MP4::Atom *ilst = path[path.size() - 1];
  long offset = ilst->offset;
  long length = ilst->length;

  MP4::Atom *meta = path[path.size() - 2];
  AtomList::Iterator index = meta->children.find(ilst);

  // check if there is an atom before 'ilst', and possibly use it as padding
  if(index != meta->children.begin()) {
    AtomList::Iterator prevIndex = index;
    prevIndex--;
    MP4::Atom *prev = *prevIndex;
    if(prev->name == "free") {
      offset = prev->offset;
      length += prev->length;
    }
  }
  // check if there is an atom after 'ilst', and possibly use it as padding
  AtomList::Iterator nextIndex = index;
  nextIndex++;
  if(nextIndex != meta->children.end()) {
    MP4::Atom *next = *nextIndex;
    if(next->name == "free") {
      length += next->length;
    }
  }

  long delta = data.size() - length;
  if(delta > 0 || (delta < 0 && delta > -8)) {
    data.append(padIlst(data));
    delta = data.size() - length;
  }
  else if(delta < 0) {
    data.append(padIlst(data, -delta - 8));
    delta = 0;
  }

  d->file->insert(data, offset, length);

  if(delta) {
    updateParents(path, delta, 1);
    updateOffsets(delta, offset);
  }
}

String
MP4::Tag::title() const
{
  if(d->items.contains("\251nam"))
    return d->items["\251nam"].toStringList().toString(", ");
  return String::null;
}

String
MP4::Tag::artist() const
{
  if(d->items.contains("\251ART"))
    return d->items["\251ART"].toStringList().toString(", ");
  return String::null;
}

String
MP4::Tag::album() const
{
  if(d->items.contains("\251alb"))
    return d->items["\251alb"].toStringList().toString(", ");
  return String::null;
}

String
MP4::Tag::comment() const
{
  if(d->items.contains("\251cmt"))
    return d->items["\251cmt"].toStringList().toString(", ");
  return String::null;
}

String
MP4::Tag::genre() const
{
  if(d->items.contains("\251gen"))
    return d->items["\251gen"].toStringList().toString(", ");
  return String::null;
}

unsigned int
MP4::Tag::year() const
{
  if(d->items.contains("\251day"))
    return d->items["\251day"].toStringList().toString().toInt();
  return 0;
}

unsigned int
MP4::Tag::track() const
{
  if(d->items.contains("trkn"))
    return d->items["trkn"].toIntPair().first;
  return 0;
}

void
MP4::Tag::setTitle(const String &value)
{
  d->items["\251nam"] = StringList(value);
}

void
MP4::Tag::setArtist(const String &value)
{
  d->items["\251ART"] = StringList(value);
}

void
MP4::Tag::setAlbum(const String &value)
{
  d->items["\251alb"] = StringList(value);
}

void
MP4::Tag::setComment(const String &value)
{
  d->items["\251cmt"] = StringList(value);
}

void
MP4::Tag::setGenre(const String &value)
{
  d->items["\251gen"] = StringList(value);
}

void
MP4::Tag::setYear(uint value)
{
  d->items["\251day"] = StringList(String::number(value));
}

void
MP4::Tag::setTrack(uint value)
{
  d->items["trkn"] = MP4::Item(value, 0);
}

MP4::ItemListMap &
MP4::Tag::itemListMap()
{
  return d->items;
}

#endif


text:
package net.oneandone.troilus;

import java.util.Set;

import net.oneandone.troilus.interceptor.DeleteQueryData;
import net.oneandone.troilus.java7.Deletion;
import net.oneandone.troilus.java7.Batchable;
import net.oneandone.troilus.java7.interceptor.CascadeOnDeleteInterceptor;
import net.oneandone.troilus.java7.interceptor.DeleteQueryRequestInterceptor;

import com.datastax.driver.core.querybuilder.Clause;
import com.datastax.driver.core.Statement;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

/**
 * delete query implementation
 */
class DeleteQuery extends MutationQuery<Deletion> implements Deletion {

    private final DeleteQueryData data;

    /**
     * @param ctx    the context
     * @param data   the data
     */
    DeleteQuery(Context ctx, DeleteQueryData data) {
        super(ctx);
        this.data = data;
    }

    ////////////////////
    // factory methods

    @Override
    protected DeleteQuery newQuery(Context newContext) {
        return new DeleteQuery(newContext, data);
    }

    private DeleteQuery newQuery(DeleteQueryData data) {
        return new DeleteQuery(getContext(), data);
    }

    //
    ////////////////////

    @Override
    public BatchMutationQuery combinedWith(Batchable<?> other) {
        return new BatchMutationQuery(getContext(), this, other);
    }

    @Override
    public DeleteQuery onlyIf(Clause... onlyIfConditions) {
        return newQuery(data.onlyIfConditions(ImmutableList.copyOf(onlyIfConditions)));
    }

    @Override
    public DeleteQuery ifExists() {
        return newQuery(data.ifExists(true));
    }

    @Override
    public ListenableFuture<Result> executeAsync() {
        ListenableFuture<Result> future = super.executeAsync();

        Function<Result, Result> validateOnlyIfFunction = new Function<Result, Result>() {
            @Override
            public Result apply(Result result) {
                if (!data.getOnlyIfConditions().isEmpty() && !result.wasApplied()) {
                    throw new IfConditionException(result, "if condition does not match");
                }
                return result;
            }
        };
        return Futures.transform(future, validateOnlyIfFunction);
    }

    @Override
    public ListenableFuture<Statement> getStatementAsync() {

        // perform request executors
        ListenableFuture<DeleteQueryData> queryDataFuture = executeRequestInterceptorsAsync(Futures.<DeleteQueryData>immediateFuture(data));

        // query data to statement
        Function<DeleteQueryData, ListenableFuture<Statement>> queryDataToStatement = new Function<DeleteQueryData, ListenableFuture<Statement>>() {
            @Override
            public ListenableFuture<Statement> apply(DeleteQueryData queryData) {
                if (queryData == null) {
                    throw new NullPointerException();
                }
                return DeleteQueryDataImpl.toStatementAsync(queryData, getContext());
            }
        };

        ListenableFuture<Statement> statementFuture = ListenableFutures.transform(queryDataFuture, queryDataToStatement, getContext().getTaskExecutor());
        if (getContext().getInterceptorRegistry().getInterceptors(CascadeOnDeleteInterceptor.class).isEmpty()) {
            return statementFuture;

        // cascading statements
        } else {
            ListenableFuture<ImmutableSet<Statement>> cascadingStatmentsFuture = executeCascadeInterceptorsAsync(queryDataFuture);
            return mergeStatements(statementFuture, cascadingStatmentsFuture);
        }
    }

    private ListenableFuture<DeleteQueryData> executeRequestInterceptorsAsync(ListenableFuture<DeleteQueryData> queryDataFuture) {

        for (DeleteQueryRequestInterceptor interceptor : getContext().getInterceptorRegistry().getInterceptors(DeleteQueryRequestInterceptor.class).reverse()) {
            final DeleteQueryRequestInterceptor icptor = interceptor;

            Function<DeleteQueryData, ListenableFuture<DeleteQueryData>> mapperFunction = new Function<DeleteQueryData, ListenableFuture<DeleteQueryData>>() {
                @Override
                public ListenableFuture<DeleteQueryData> apply(DeleteQueryData queryData) {
                    return icptor.onDeleteRequestAsync(queryData);
                }
            };

            // running interceptors within dedicated threads!
            queryDataFuture = ListenableFutures.transform(queryDataFuture, mapperFunction, getContext().getTaskExecutor());
        }

        return queryDataFuture;
    }

    private ListenableFuture<ImmutableSet<Statement>> executeCascadeInterceptorsAsync(ListenableFuture<DeleteQueryData> queryDataFuture) {
        Set<ListenableFuture<ImmutableSet<Statement>>> statmentFutures = Sets.newHashSet();

        for (CascadeOnDeleteInterceptor interceptor : getContext().getInterceptorRegistry().getInterceptors(CascadeOnDeleteInterceptor.class).reverse()) {
            final CascadeOnDeleteInterceptor icptor = interceptor;

            Function<DeleteQueryData, ListenableFuture<ImmutableSet<? extends Batchable<?>>>> querydataToBatchables = new Function<DeleteQueryData, ListenableFuture<ImmutableSet<? extends Batchable<?>>>>() {
                @Override
                public ListenableFuture<ImmutableSet<? extends Batchable<?>>> apply(DeleteQueryData queryData) {
                    return icptor.onDeleteAsync(queryData);
                }
            };
            ListenableFuture<ImmutableSet<? extends Batchable<?>>> batchablesFutureSet = ListenableFutures.transform(queryDataFuture, querydataToBatchables);

            ListenableFuture<ImmutableSet<Statement>> flattenStatementFutureSet = transformBatchablesToStatement(batchablesFutureSet);
            statmentFutures.add(flattenStatementFutureSet);
        }

        // running interceptors within dedicated threads!
        return ListenableFutures.flat(ImmutableSet.copyOf(statmentFutures), getContext().getTaskExecutor());
    }
}


text:
<?php
// src/OC/PlatformBundle/DoctrineListener/ApplicationNotification.php

namespace OC\PlatformBundle\DoctrineListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use OC\PlatformBundle\Entity\Application;

class ApplicationNotification
{
  private $mailer;

  public function __construct(\Swift_Mailer $mailer)
  {
    $this->mailer = $mailer;
  }

  public function postPersist(LifecycleEventArgs $args)
  {
    $entity = $args->getEntity();

    // On veut envoyer un email que pour les entités Application
    if (!$entity instanceof Application) {
      return;
    }

    $message = new \Swift_Message(
      'Nouvelle candidature',
      'Vous avez reçu une nouvelle candidature.'
    );

    $message
      ->addTo($entity->getAdvert()->getAuthor()) // Ici bien sûr il faudrait un attribut "email", j'utilise "author" à la place
      ->addFrom('admin@votresite.com')
    ;

    $this->mailer->send($message);
  }
}


text:
package stripe

import (
	"encoding/json"
	"testing"

	assert "github.com/stretchr/testify/require"
)

func TestBitcoinTransaction_UnmarshalJSON(t *testing.T) {
	// Unmarshals from a JSON string
	{
		var v BitcoinTransaction
		err := json.Unmarshal([]byte(`"btctxn_123"`), &v)
		assert.NoError(t, err)
		assert.Equal(t, "btctxn_123", v.ID)
	}

	// Unmarshals from a JSON object
	{
		v := BitcoinTransaction{ID: "btctxn_123"}
		data, err := json.Marshal(&v)
		assert.NoError(t, err)

		err = json.Unmarshal(data, &v)
		assert.NoError(t, err)
		assert.Equal(t, "btctxn_123", v.ID)
	}
}


text:
import re

# Initialize an empyt paragraph
paragraph = []
found_match = False
# These are the regexs that we are going to use
#    Gold E. Locks (case insensitive, E. or E) Three bears or 3 bears 571 209-4000
patterns = ['gold e\.? locks', 'three bears', '3 bears', '\(?571\)? ?209-?4000']
with open('evidence.txt', 'r') as fh:
    for line in fh:
        # If it is the end of a paragraph,
        # print the paragraph if we found a match to the regex
        if line == '\n':
            if found_match:
                print((''.join(paragraph)))
            # Reset found_match and paragraph for the next paragraph
            found_match = False
            paragraph = []

        # seach each pattern, and if there is a match, set found_match flag to True
        for pattern in patterns:
            if re.search(pattern, line, re.IGNORECASE):
                found_match = True
        # Append line to paragraph
        paragraph.append(line)


text:
package govsw

import (
	"github.com/vishvananda/netlink"
	"golang.org/x/sys/unix"

	log "github.com/sirupsen/logrus"
)

type Listener interface {
	PacketIn(*Packet)
}

type Server struct {
	Listener Listener
	DB       *DB
	SyncCh   <-chan string

	linkMon *LinkMonitor
	pktInCh chan *Packet

	log *log.Entry
}

func (s *Server) init() {
	s.linkMon = &LinkMonitor{}
	s.pktInCh = make(chan *Packet)
	s.log = log.WithFields(log.Fields{"module": "server"})
}

func (s *Server) syncLinks(targetIfname string) {
	links, err := netlink.LinkList()
	if err != nil {
		s.log.Errorf("list link error. %s", err)
		return
	}

FOR_LOOP:
	for _, link := range links {
		ifname := link.Attrs().Name
		if len(targetIfname) > 0 && targetIfname != "*" {
			if ifname != targetIfname {
				continue FOR_LOOP
			}
		}

		upd := netlink.LinkUpdate{}
		upd.Link = link
		upd.Header.Type = func() uint16 {
			if has := s.DB.Ifname().Has(ifname); has {
				return unix.RTM_NEWLINK
			}
			return unix.RTM_DELLINK
		}()

		s.linkMon.Put(upd)
	}
}

func (s *Server) Serve(done <-chan struct{}) {
FOR_LOOP:
	for {
		select {
		case upd := <-s.linkMon.Recv():
			state := upd.Link.Attrs().OperState
			ifname := upd.Link.Attrs().Name

			switch upd.Header.Type {
			case unix.RTM_NEWLINK:
				if has := s.DB.Ifname().Has(ifname); !has {
					s.log.Debugf("Serve: NEWLINK %s not registered.", ifname)
					continue FOR_LOOP
				}

				s.log.Debugf("Serve: NEWLINK %s", ifname)

				s.DB.Link().GetOrAdd(upd.Link, func(link *Link) {
					if state == netlink.OperUp {
						s.log.Debugf("Serve: NEWLINK/Up %s", ifname)

						if err := link.Start(s.pktInCh); err != nil {
							s.log.Errorf("Serve: Link Start error. %s", err)
						}

					} else if state == netlink.OperDown {
						s.log.Debugf("Serve: NEWLINK/Down %s", ifname)

						link.Stop()

					} else {
						s.log.Debugf("Serve: NEWLINK/%d %s", state, ifname)
					}
				})

			case unix.RTM_DELLINK:
				if link, ok := s.DB.Link().Delete(upd.Link.Attrs().Index); ok {
					s.log.Debugf("Serve: DELLINK %s", ifname)

					link.Destroy()
				}

			default:
				s.log.Debugf("Serve: Bad type. %d", upd.Header.Type)
			}

		case ifname := <-s.SyncCh:
			go s.syncLinks(ifname)

		case pkt := <-s.pktInCh:
			s.Listener.PacketIn(pkt)

		case <-done:
			s.log.Infof("Server: exit(done).")
			break FOR_LOOP
		}
	}
}

func (s *Server) Start(done <-chan struct{}) error {
	s.init()

	if err := s.linkMon.Start(done); err != nil {
		s.log.Errorf("Start: link reload error. %s", err)
		return err
	}

	go s.Serve(done)

	s.log.Infof("Start: success.")

	return nil
}


text:
<link rel="import" href="chrome://resources/html/polymer.html">

<link rel="import" href="chrome://resources/cr_elements/cr_button/cr_button.html">
<link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html">
<link rel="import" href="chrome://resources/html/i18n_behavior.html">
<link rel="import" href="crostini_browser_proxy.html">
<link rel="import" href="../../settings_shared_css.html">
<link rel="import" href="../metrics_recorder.html">

<dom-module id="settings-crostini-arc-adb-confirmation-dialog">
  <template>

    <cr-dialog id="dialog" close-text="$i18n{close}">

        $i18n{crostiniArcAdbConfirmationTitleEnable}

        $i18n{crostiniArcAdbConfirmationTitleDisable}

        $i18n{crostiniArcAdbConfirmationMessageEnable}

        $i18n{crostiniArcAdbConfirmationMessageDisable}

        <cr-button id="cancel" class="cancel-button" on-click="onCancelTap_">
          $i18n{cancel}
        </cr-button>
        <cr-button id="continue" class="action-button" on-click="onRestartTap_">
          $i18n{crostiniArcAdbRestartButton}
        </cr-button>

    </cr-dialog>
  </template>

</dom-module>


text:
package edu.grinnell.callaway.jsonsource;

import java.io.PrintWriter;

import edu.grinnell.callaway.JSONParser;

//Citation: http://www.mkyong.com/java/how-to-get-url-content-in-java/
//http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm
/**
 * Changes the user input obtained by an InterfaceView into a JSON object
 * and displays the object as a string.
 * @author Shaun, Mataire
 * @author Mulhall, Elias
 * @author Callaway, Erin M
 */
public class InterfaceControl
{
  /**
   * The InterfaceView used to obtain a JSON string or location.
   */
  InterfaceView view;

  /**
   * A constructor for InterfaceControl.
   * @param view
   *          an InterfaceView
   */
  public InterfaceControl(InterfaceView view)
  {
    this.view = view;
  }//SourceControl(SourceModel model, SourceView view)

  /**
   * Changes the given JSON string into a Java Object representing a
   * JSON Object and displays the result as a string.
   * @return
   * @throws Exception
   *            if the input is not a JSON string or the location of one
   */
  public Object control()
    throws Exception
  {
    JSONParser parser = new JSONParser();
    PrintWriter pen = new PrintWriter(System.out, true);

    Object result = null;

    InterfaceView inputPackage = new InterfaceView();
    inputPackage.getInputType();
    String inputSignal = inputPackage.parseSignal;
    String packageString = inputPackage.inputString;

    if (inputSignal.equalsIgnoreCase("A"))
      {
        result = parser.parseFromString(packageString);
        pen.println("The JSON you entered was: ");
      } // if (A)
    else if (inputSignal.equalsIgnoreCase("B"))
      {
        result = parser.parseFromFile(packageString);
        pen.println("The JSON in the file was: ");
      } // else if (B)
    else if (inputSignal.equalsIgnoreCase("C"))
      {
        result = parser.parseFromHTTP(packageString);
        pen.println("The JSON in the file was: ");
      } // else if (C)
    else
      throw new Exception("wrong input");

    pen.println(parser.toJSONString(result));
    return result;
  }//control()
}//SourceControl


text:
package com.logginghub.logging.commandline.editscreen;

public interface EditorGetter<T> {
    String get(T t);
}


text:
#import <Foundation/NSObject.h>
#import <Security/Security.h>

@class NSString;
@class NSArray;

/*!
   @const NSURLProtectionSpaceHTTP
   @abstract The protocol for HTTP
*/
FOUNDATION_EXPORT NSString * const NSURLProtectionSpaceHTTP NS_AVAILABLE(10_5, 2_0);

/*!
   @const NSURLProtectionSpaceHTTPS
   @abstract The protocol for HTTPS
*/
FOUNDATION_EXPORT NSString * const NSURLProtectionSpaceHTTPS NS_AVAILABLE(10_5, 2_0);

/*!
   @const NSURLProtectionSpaceFTP
   @abstract The protocol for FTP
*/
FOUNDATION_EXPORT NSString * const NSURLProtectionSpaceFTP NS_AVAILABLE(10_5, 2_0);

/*!
    @const NSURLProtectionSpaceHTTPProxy
    @abstract The proxy type for http proxies
*/
FOUNDATION_EXPORT NSString * const NSURLProtectionSpaceHTTPProxy;

/*!
    @const NSURLProtectionSpaceHTTPSProxy
    @abstract The proxy type for https proxies
*/
FOUNDATION_EXPORT NSString * const NSURLProtectionSpaceHTTPSProxy;

/*!
    @const NSURLProtectionSpaceFTPProxy
    @abstract The proxy type for ftp proxies
*/
FOUNDATION_EXPORT NSString * const NSURLProtectionSpaceFTPProxy;

/*!
    @const NSURLProtectionSpaceSOCKSProxy
    @abstract The proxy type for SOCKS proxies
*/
FOUNDATION_EXPORT NSString * const NSURLProtectionSpaceSOCKSProxy;

/*!
    @const NSURLAuthenticationMethodDefault
    @abstract The default authentication method for a protocol
*/
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodDefault;

/*!
    @const NSURLAuthenticationMethodHTTPBasic
    @abstract HTTP basic authentication. Equivalent to
    NSURLAuthenticationMethodDefault for http.
*/
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodHTTPBasic;

/*!
    @const NSURLAuthenticationMethodHTTPDigest
    @abstract HTTP digest authentication.
*/
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodHTTPDigest;

/*!
    @const NSURLAuthenticationMethodHTMLForm
    @abstract HTML form authentication. Applies to any protocol.
*/
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodHTMLForm;

/*!
   @const NSURLAuthenticationMethodNTLM
   @abstract NTLM authentication.
*/
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodNTLM NS_AVAILABLE(10_5, 2_0);

/*!
   @const NSURLAuthenticationMethodNegotiate
   @abstract Negotiate authentication.
*/
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodNegotiate NS_AVAILABLE(10_5, 2_0);

/*!
    @const NSURLAuthenticationMethodClientCertificate
    @abstract SSL Client certificate.  Applies to any protocol.
 */
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodClientCertificate NS_AVAILABLE(10_6, 3_0);

/*!
    @const NSURLAuthenticationMethodServerTrust
    @abstract SecTrustRef validation required.  Applies to any protocol.
 */
FOUNDATION_EXPORT NSString * const NSURLAuthenticationMethodServerTrust NS_AVAILABLE(10_6, 3_0);

@class NSURLProtectionSpaceInternal;

/*!
    @class NSURLProtectionSpace
    @discussion This class represents a protection space requiring authentication.
*/

@interface NSURLProtectionSpace : NSObject <NSSecureCoding, NSCopying>
{
@private
    NSURLProtectionSpaceInternal *_internal;
}

/*!
    @method initWithHost:port:protocol:realm:authenticationMethod:
    @abstract Initialize a protection space representing an origin server, or a realm on one
    @param host The hostname of the server
    @param port The port for the server
    @param protocol The sprotocol for this server - e.g. "http", "ftp", "https"
    @param realm A string indicating a protocol-specific subdivision
    of a single host. For http and https, this maps to the realm
    string in http authentication challenges. For many other protocols
    it is unused.
    @param authenticationMethod The authentication method to use to access this protection space -
    valid values include nil (default method), @"digest" and @"form".
    @result The initialized object.
*/
- (instancetype)initWithHost:(NSString *)host port:(NSInteger)port protocol:(NSString *)protocol realm:(NSString *)realm authenticationMethod:(NSString *)authenticationMethod;

/*!
    @method initWithProxyHost:port:type:realm:authenticationMethod:
    @abstract Initialize a protection space representing a proxy server, or a realm on one
    @param host The hostname of the proxy server
    @param port The port for the proxy server
    @param type The type of proxy - e.g. "http", "ftp", "SOCKS"
    @param realm A string indicating a protocol-specific subdivision
    of a single host. For http and https, this maps to the realm
    string in http authentication challenges. For many other protocols
    it is unused.
    @param authenticationMethod The authentication method to use to access this protection space -
    valid values include nil (default method) and @"digest"
    @result The initialized object.
*/
- (instancetype)initWithProxyHost:(NSString *)host port:(NSInteger)port type:(NSString *)type realm:(NSString *)realm  authenticationMethod:(NSString *)authenticationMethod;

/*!
    @method realm
    @abstract Get the authentication realm for which the protection space that
    needs authentication
    @discussion This is generally only available for http
    authentication, and may be nil otherwise.
    @result The realm string
*/
@property (readonly, copy) NSString *realm;

/*!
    @method receivesCredentialSecurely
    @abstract Determine if the password for this protection space can be sent securely
    @result YES if a secure authentication method or protocol will be used, NO otherwise
*/
@property (readonly) BOOL receivesCredentialSecurely;

/*!
    @method isProxy
    @abstract Determine if this authenticating protection space is a proxy server
    @result YES if a proxy, NO otherwise
*/
@property (readonly) BOOL isProxy;

/*!
    @method host
    @abstract Get the proxy host if this is a proxy authentication, or the host from the URL.
    @result The host for this protection space.
*/
@property (readonly, copy) NSString *host;

/*!
    @method port
    @abstract Get the proxy port if this is a proxy authentication, or the port from the URL.
    @result The port for this protection space, or 0 if not set.
*/
@property (readonly) NSInteger port;

/*!
    @method proxyType
    @abstract Get the type of this protection space, if a proxy
    @result The type string, or nil if not a proxy.
 */
@property (readonly, copy) NSString *proxyType;

/*!
    @method protocol
    @abstract Get the protocol of this protection space, if not a proxy
    @result The type string, or nil if a proxy.
*/
@property (readonly, copy) NSString *protocol;

/*!
    @method authenticationMethod
    @abstract Get the authentication method to be used for this protection space
    @result The authentication method
*/
@property (readonly, copy) NSString *authenticationMethod;

@end

/*!
    @class NSURLProtectionSpace(NSClientCertificateSpace)
    @discussion This category supplies additional information for use when a client certificate is required by the server in order to complete authentication.
 */
@interface NSURLProtectionSpace(NSClientCertificateSpace)

/*!
    @method distinguishedNames
    @abstract Returns an array of acceptable certificate issuing authorities for client certification authentication. Issuers are identified by their distinguished name and returned as a DER encoded data.
    @result An array of NSData objects.  (Nil if the authenticationMethod is not NSURLAuthenticationMethodClientCertificate)
 */
@property (readonly, copy) NSArray *distinguishedNames NS_AVAILABLE(10_6, 3_0);

@end

/*!
    @class NSURLProtectionSpace(NSServerTrustValidationSpace)
    @discussion This category supplies additional information for use by the client to evaluate whether to trust a given server during a security handshake.
 */
@interface NSURLProtectionSpace(NSServerTrustValidationSpace)

/*!
    @method serverTrust
    @abstract Returns a SecTrustRef which represents the state of the servers SSL transaction state
    @result A SecTrustRef from Security.framework.  (Nil if the authenticationMethod is not NSURLAuthenticationMethodServerTrust)
 */
@property (readonly) SecTrustRef serverTrust NS_AVAILABLE(10_6, 3_0);

@end


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Sql.Models
{
    public partial class JobStepExecutionOptions : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(TimeoutSeconds))
            {
                writer.WritePropertyName("timeoutSeconds");
                writer.WriteNumberValue(TimeoutSeconds.Value);
            }
            if (Optional.IsDefined(RetryAttempts))
            {
                writer.WritePropertyName("retryAttempts");
                writer.WriteNumberValue(RetryAttempts.Value);
            }
            if (Optional.IsDefined(InitialRetryIntervalSeconds))
            {
                writer.WritePropertyName("initialRetryIntervalSeconds");
                writer.WriteNumberValue(InitialRetryIntervalSeconds.Value);
            }
            if (Optional.IsDefined(MaximumRetryIntervalSeconds))
            {
                writer.WritePropertyName("maximumRetryIntervalSeconds");
                writer.WriteNumberValue(MaximumRetryIntervalSeconds.Value);
            }
            if (Optional.IsDefined(RetryIntervalBackoffMultiplier))
            {
                writer.WritePropertyName("retryIntervalBackoffMultiplier");
                writer.WriteNumberValue(RetryIntervalBackoffMultiplier.Value);
            }
            writer.WriteEndObject();
        }

        internal static JobStepExecutionOptions DeserializeJobStepExecutionOptions(JsonElement element)
        {
            Optional<int> timeoutSeconds = default;
            Optional<int> retryAttempts = default;
            Optional<int> initialRetryIntervalSeconds = default;
            Optional<int> maximumRetryIntervalSeconds = default;
            Optional<float> retryIntervalBackoffMultiplier = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("timeoutSeconds"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    timeoutSeconds = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("retryAttempts"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    retryAttempts = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("initialRetryIntervalSeconds"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    initialRetryIntervalSeconds = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("maximumRetryIntervalSeconds"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    maximumRetryIntervalSeconds = property.Value.GetInt32();
                    continue;
                }
                if (property.NameEquals("retryIntervalBackoffMultiplier"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    retryIntervalBackoffMultiplier = property.Value.GetSingle();
                    continue;
                }
            }
            return new JobStepExecutionOptions(Optional.ToNullable(timeoutSeconds), Optional.ToNullable(retryAttempts), Optional.ToNullable(initialRetryIntervalSeconds), Optional.ToNullable(maximumRetryIntervalSeconds), Optional.ToNullable(retryIntervalBackoffMultiplier));
        }
    }
}


text:
import q from 'steal-qunit';
import can from 'can';

import { ViewModel } from './crud-manager';
import { ViewMap } from './ViewMap';
import { Connection, TaskMap } from '../../test/data/connection';
import { TOPICS } from './crud-manager';
import PubSub from 'pubsub-js';
let vm;

q.config.testTimeout = 10000;

q.module('crud-manager.ViewModel', {
  beforeEach: () => {
    localStorage.clear();
    vm = new ViewModel();
  },
  afterEach: () => {
    vm = null;
    PubSub.clearAllSubscriptions();
    localStorage.clear();
  }
});

test('totalPages get()', assert => {
  let cases = [{
    items: 99,
    perPage: 10,
    expected: 10
  }, {
    items: 100,
    perPage: 10,
    expected: 10
  }, {
    items: 101,
    perPage: 10,
    expected: 11
  }];
  cases.forEach(c => {
    vm.attr({
      view: {
        connection: {
          metadata: {
            total: c.items
          }
        },
        parameters: {
          perPage: c.perPage
        }
      }
    });
    assert.equal(vm.attr('totalPages'), c.expected, 'totalPages should be calculated correctly');
  });
});

test('perPageOptions get()', assert => {
  let tests = [{
    total: 1,
    expected: []
  }, {
    total: 15,
    expected: [10, 20]
  }, {
    total: 50,
    expected: [10, 20, 50]
  }, {
    total: 99,
    expected: [10, 20, 50, 100]
  }];
  tests.forEach(t => {
    vm.attr({
      view: {
        connection: {
          metadata: {
            total: t.total
          }
        }
      }
    });
    assert.deepEqual(vm.attr('perPageOptions').serialize(), t.expected, 'per page options should be filtered correctly');
  });

});

test('showPaginate get()', assert => {
  vm.attr({
    view: {
      connection: {
        metadata: {
          total: 10
        }
      }
    }
  });
  vm.attr('parameters.perPage', 25);
  assert.equal(vm.attr('showPaginate'), false, 'pagination should not be shown with one page');

  vm.attr({
    view: {
      metadata: {
        total: 10
      }
    }
  });
  vm.attr('parameters.perPage', 5);
  assert.equal(vm.attr('showPaginate'), true, 'pagination should be shown with more than one page');
});

test('objects get()', assert => {
  let done = assert.async();
  vm.attr('view', { connection: Connection });
  vm.attr('objects').then(data => {
    assert.ok(data.length, 'data should be retrieved correctly');
    done();
  });
});

test('focusObject get()', assert => {
  let done = assert.async();
  vm.attr({
    view: {
      connection: Connection
    },
    viewId: 11
  });
  vm.attr('focusObject').then(data => {
    assert.equal(data.attr('id'), 11, 'data should be retrieved correctly');
    done();
  });

});

test('buttons get()', assert => {
  assert.equal(vm.attr('buttons').length, 3, 'buttons should be edit buttons');
  vm.attr('view', {
    disableEdit: true
  });

  assert.equal(vm.attr('buttons').length, 1, 'buttons should be default buttons');
});

test('_fields get()', assert => {
  vm.attr('view', {
    objectTemplate: TaskMap
  });
  assert.equal(vm.attr('_fields').length, 2, 'if no fields exist on the view, they should be created from the objectTemplate');

  vm.attr('view', {
    fields: ['test1', 'test2', 'test3', 'test4']
  });
  assert.equal(vm.attr('_fields').length, 4, 'if fields do exist on the view, they should be created correctly');
});

test('init() with parameters', assert => {
  vm = new ViewModel({
    view: {
      parameters: { test: 'text' }
    }
  });
  assert.equal(vm.attr('parameters.test'), 'text', 'parameters should be mixed in');

  vm = new ViewModel({
    relatedField: 'test',
    relatedValue: 'testVal'
  });
  assert.equal(vm.attr('parameters.filters.length'), 1, 'should create filters parameter when initialized with related field and value');
});

test('editObject(scope, dom, event, obj)', assert => {
  let done = assert.async();
  let id = 11;
  let obj = Connection.get({ id: id }).then(obj => {
    vm.attr('view', {
      connection: Connection
    });
    vm.editObject(null, null, null, obj);
    assert.equal(vm.attr('viewId'), 11, 'viewId should be set correctly');
    assert.equal(vm.attr('page'), 'edit', 'edit page should be displayed');
    done();
  });
});

test('viewObject(scope, dom, event, obj)', assert => {
  let done = assert.async();
  let id = 11;
  let def = Connection.get({ id: id });
  def.then(obj => {
    vm.attr('view', {
      connection: Connection
    });
    vm.viewObject(null, null, null, obj);
    assert.equal(vm.attr('viewId'), 11, 'viewId should be set correctly');
    assert.equal(vm.attr('page'), 'details', 'details page should be displayed');
    done();
  });
});

test('saveObject(obj) success', assert => {
  let done = assert.async(3);
  let view = {
    connection: Connection
  };
  let token = PubSub.subscribe(TOPICS.ADD_MESSAGE, (name, message) => {
    assert.ok(message.message, 'message should be published');
    done();
  });

  let id = 6;
  let obj = Connection.get({ id: id }).then(obj => {
    vm.attr('view', view);

    let def = vm.saveObject(obj);
    def.then(result => {
      assert.ok(result, 'deferred should be resolved');
      done();
    });
  });

  id = 999;
  vm.attr('view', view);

  let def = vm.saveObject(new TaskMap({ title: 'title' }));
  def.fail(result => {
    assert.ok(result, 'deferred should be resolved');
    done();
  });
});

test('beforeCreate and afterCreate events', assert => {
  let done = assert.async(4);
  let myMap = new TaskMap({ name: 'do stuff' });
  let view = {
    connection: Connection,
    beforeCreate(obj) {
      assert.notOk(obj.attr('id'), 'event should pass object not yet be saved with id');
      done();
    },
    afterCreate(obj) {
      assert.ok(typeof obj.attr('id') === 'number', 'event should have object passed with a new id');
      done();
    }
  };
  vm.attr('view', view);

  vm.on('beforeCreate', (event, obj) => {
    assert.notOk(obj.attr('id'), 'event should pass object not yet be saved with id');
    done();
  });

  vm.on('afterCreate', (event, obj) => {
    assert.ok(typeof obj.attr('id') === 'number', 'event should have object passed with a new id');
    done();
  });

  vm.setPage('add');
  vm.saveObject(myMap);
});

test('setPage(page)', assert => {
  vm.attr({
    'page': 'edit',
    viewId: 999
  });

  vm.setPage('list');
  assert.equal(vm.attr('page'), 'list', 'page should be set correctly');
  assert.equal(vm.attr('viewId'), 0, 'viewId should be reset');
});

test('getNewObject()', assert => {
  vm.attr('view', {
    objectTemplate: TaskMap
  });
  assert.deepEqual(vm.getNewObject().attr(), new TaskMap().attr(), 'new object should be created');
});

test('deleteObject(obj, skipConfirm) ', assert => {
  let id = 11;
  let done = assert.async(5);
  let view = {
    connection: Connection,
    beforeDelete(obj) {
      assert.equal(obj.attr('id'), id, 'object should be passed with before delete event');
      done();
    },
    afterDelete(obj) {
      assert.equal(obj.attr('id'), id, 'object should be passed with after delete event');
      done();
    }
  };
  let token = PubSub.subscribe(TOPICS.ADD_MESSAGE, (name, message) => {
    assert.ok(message.message, 'message should be published');
    done();
  });

  vm.attr('view', view);

  vm.on('beforeDelete', (event, obj) => {
    assert.equal(obj.attr('id'), id, 'object should be passed with before delete event');
    done();
  });
  vm.on('afterDelete', (event, obj) => {
    assert.equal(obj.attr('id'), id, 'object should be passed with after delete event');
    done();
  });

  //delete the object skip confirm
  vm.deleteObject(new TaskMap({ id: id }), true);
});

test('deleteMmultiple()', assert => {
  let done = assert.async(4);
  let view = {
    connection: Connection
  };
  let token = PubSub.subscribe(TOPICS.ADD_MESSAGE, (name, message) => {
    assert.ok(message.message, 'message should be published');
    done();
  });

  let id = 11;
  vm.attr({
    view: view,
    selectedObjects: new can.List([new TaskMap({
      id: 11
    }), new TaskMap({
      id: 1
    })])
  });
  let defs = vm.deleteMultiple(true);
  defs.forEach(def => {
    def.then(r => {
      assert.ok(r, 'then is resolved');
      done();
    }).fail(r => {
      assert.ok(r, 'fail is resolved');
      done();
    });
  });
});

test('toggleFilter(val)', assert => {
  vm.toggleFilter();
  assert.ok(vm.attr('filterVisible'), 'filter should be visible after toggling');

  vm.toggleFilter();
  assert.notOk(vm.attr('filterVisible'), 'filter should not be visible after toggling again');

  vm.toggleFilter(false);
  assert.notOk(vm.attr('filterVisible'), 'filter should not be visible after toggling to false');
});

test('getRelatedValue(foreignKey, focusObject)', assert => {
  let map = new TaskMap({
    test: 'testValue'
  });
  assert.equal(vm.getRelatedValue('test', map), 'testValue', 'related value should be returned');
});


text:
package com.me.flappybird;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.forever;

import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.actions.MoveByAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;

public class Pipe extends Image {

	private boolean getScore;
	private Chim bird;
	public static int PIPE_HIT;

	public Pipe(TextureRegion region, Chim bird, boolean getScore) {
		super(region);
		this.bird = bird;
		this.getScore = getScore;
		actionmoveLeft();
	}

	@Override
	public void act(float delta) {
		super.act(delta);
		if (bird.isDie) {
			clearActions();
			return;
		}
		if (getX() < -getWidth()) {
			remove();
		}
		addScore();
		checkcolistion();
	}

	public static int getPIPE_HIT() {
		return PIPE_HIT;
	}

	public static void setPIPE_HIT(int pIPE_HIT) {
		PIPE_HIT = pIPE_HIT;
	}

	public void actionmoveLeft() {
		MoveByAction moveLeft = new MoveByAction();
		moveLeft.setDuration(config.KmoveLeftDura);
		moveLeft.setAmountX(-config.KlandWidth);
		addAction(forever(moveLeft));
	}

	public void addScore() {
		if (getX() <= bird.getX()) {
			if (bird.getY() >= Flappybird.VIEWPORT.y) {
				bird.hitMe();
				Screenplay.land.clearActions();
				Flappybird.Sounds.get(config.SoundsHit).play();
			}
			if (getScore) {
				getScore = false;
				bird.updateScore();
				Flappybird.Sounds.get(config.SoundsScore).play();
			}
		}
	}

	public void checkcolistion() {
		if (iscolistion()) {
			PIPE_HIT = 0;
			bird.hitMe();
			Screenplay.land.clearActions();
			Flappybird.Sounds.get(config.SoundsHit).play();
		}
	}

	public boolean iscolistion() {
		float d = 2;
		float maxx1 = getX() + getWidth();
		float minx1 = getX() + d;
		float maxy1 = getY() + getHeight();
		float miny1 = getY() + d;
		float maxx2 = bird.getX() + bird.getWidth();
		float minx2 = bird.getX() + d;
		float maxy2 = bird.getY() + bird.getHeight();
		float miny2 = bird.getY() + d;
		return !(maxx1 < minx2 || maxx2 < minx1 || maxy2 < miny1 || maxy1 < miny2);
	}

}