text:
namespace llmq
{

static const std::string CLSIG_REQUESTID_PREFIX = "clsig";

CChainLocksHandler* chainLocksHandler;

bool CChainLockSig::IsNull() const
{
    return nHeight == -1 && blockHash == uint256();
}

std::string CChainLockSig::ToString() const
{
    return strprintf("CChainLockSig(nHeight=%d, blockHash=%s, signers: hex=%s size=%d count=%d)",
                nHeight, blockHash.ToString(), CLLMQUtils::ToHexStr(signers), signers.size(),
                std::count(signers.begin(), signers.end(), true));
}

CChainLocksHandler::CChainLocksHandler(CConnman& _connman, PeerManager& _peerman, ChainstateManager& _chainman):
    connman(_connman),
    peerman(_peerman),
    chainman(_chainman)
{
    scheduler = new CScheduler();
    CScheduler::Function serviceLoop = std::bind(&CScheduler::serviceQueue, scheduler);
    scheduler_thread = new std::thread(std::bind(&TraceThread<CScheduler::Function>, "cl-schdlr", serviceLoop));
}

CChainLocksHandler::~CChainLocksHandler()
{
    if(scheduler)
        scheduler->stop();
    if (scheduler_thread->joinable())
        scheduler_thread->join();
    delete scheduler_thread;
    delete scheduler;
}

void CChainLocksHandler::Start()
{
    quorumSigningManager->RegisterRecoveredSigsListener(this);
    scheduler->scheduleEvery([&]() {
        CheckActiveState();
        bool enforced = false;
        const CBlockIndex* pindex;
        {
            LOCK(cs);
            pindex = bestChainLockBlockIndex;
            enforced = isEnforced;
        }
        if(enforced) {
            AssertLockNotHeld(cs);
            chainman.ActiveChainstate().EnforceBestChainLock(pindex);
        }
        TrySignChainTip();
    }, std::chrono::seconds{5});
}

void CChainLocksHandler::Stop()
{
    if(scheduler)
        scheduler->stop();
    if(scheduler_thread)
        scheduler_thread->join();
    quorumSigningManager->UnregisterRecoveredSigsListener(this);
}

bool CChainLocksHandler::AlreadyHave(const uint256& hash) const
{
    LOCK(cs);
    return seenChainLocks.count(hash) != 0;
}

bool CChainLocksHandler::GetChainLockByHash(const uint256& hash, llmq::CChainLockSig& ret) const
{
    LOCK(cs);

    if (::SerializeHash(mostRecentChainLockShare) == hash) {
        ret = mostRecentChainLockShare;
        return true;
    }

    if (::SerializeHash(bestChainLockWithKnownBlock) == hash) {
        ret = bestChainLockWithKnownBlock;
        return true;
    }

    for (const auto& pair : bestChainLockCandidates) {
        if (::SerializeHash(*pair.second) == hash) {
            ret = *pair.second;
            return true;
        }
    }

    for (const auto& pair : bestChainLockShares) {
        for (const auto& pair2 : pair.second) {
            if (::SerializeHash(*pair2.second) == hash) {
                ret = *pair2.second;
                return true;
            }
        }
    }

    return false;
}

const CChainLockSig CChainLocksHandler::GetMostRecentChainLock() const
{
    LOCK(cs);
    return mostRecentChainLockShare;
}
const CChainLockSig CChainLocksHandler::GetBestChainLock() const
{
    LOCK(cs);
    return bestChainLockWithKnownBlock;
}
const std::map<CQuorumCPtr, CChainLockSigCPtr> CChainLocksHandler::GetBestChainLockShares() const
{

    LOCK(cs);
    auto it = bestChainLockShares.find(bestChainLockWithKnownBlock.nHeight);
    if (it == bestChainLockShares.end()) {
        return {};
    }

    return it->second;
}

bool CChainLocksHandler::TryUpdateBestChainLock(const CBlockIndex* pindex)
{
    AssertLockHeld(cs);

    if (pindex == nullptr || pindex->nHeight <= bestChainLockWithKnownBlock.nHeight) {
        return false;
    }

    auto it1 = bestChainLockCandidates.find(pindex->nHeight);
    if (it1 != bestChainLockCandidates.end()) {
        bestChainLockWithKnownBlock = *it1->second;
        bestChainLockBlockIndex = pindex;
        LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- CLSIG from candidates (%s)\n", __func__, bestChainLockWithKnownBlock.ToString());
        return true;
    }

    auto it2 = bestChainLockShares.find(pindex->nHeight);
    if (it2 == bestChainLockShares.end()) {
        return false;
    }
    const auto& consensus = Params().GetConsensus();
    const auto& llmqParams = consensus.llmqs.at(consensus.llmqTypeChainLocks);
    const size_t& threshold = llmqParams.signingActiveQuorumCount / 2 + 1;

    std::vector<CBLSSignature> sigs;
    CChainLockSig clsigAgg;

    for (const auto& pair : it2->second) {
        if (pair.second->blockHash == pindex->GetBlockHash()) {
            assert(std::count(pair.second->signers.begin(), pair.second->signers.end(), true) <= 1);
            sigs.emplace_back(pair.second->sig);
            if (clsigAgg.IsNull()) {
                clsigAgg = *pair.second;
            } else {
                assert(clsigAgg.signers.size() == pair.second->signers.size());
                std::transform(clsigAgg.signers.begin(), clsigAgg.signers.end(), pair.second->signers.begin(), clsigAgg.signers.begin(), std::logical_or<bool>());
            }
            if (sigs.size() >= threshold) {
                // all sigs should be validated already
                clsigAgg.sig = CBLSSignature::AggregateInsecure(sigs);
                bestChainLockWithKnownBlock = clsigAgg;
                bestChainLockBlockIndex = pindex;
                bestChainLockCandidates[clsigAgg.nHeight] = std::make_shared<const CChainLockSig>(clsigAgg);
                LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- CLSIG aggregated (%s)\n", __func__, bestChainLockWithKnownBlock.ToString());
                return true;
            }
        }
    }
    return false;
}

bool CChainLocksHandler::VerifyChainLockShare(const CChainLockSig& clsig, const CBlockIndex* pindexScan, const uint256& idIn, std::pair<int, CQuorumCPtr>& ret)
{
    const auto& consensus = Params().GetConsensus();
    const auto& llmqType = consensus.llmqTypeChainLocks;
    const auto& llmqParams = consensus.llmqs.at(consensus.llmqTypeChainLocks);
    const auto& signingActiveQuorumCount = llmqParams.signingActiveQuorumCount;

    if (clsig.signers.size() != (size_t)signingActiveQuorumCount) {
        return false;
    }

    if (std::count(clsig.signers.begin(), clsig.signers.end(), true) > 1) {
        // too may signers
        return false;
    }
    bool fHaveSigner{std::count(clsig.signers.begin(), clsig.signers.end(), true) > 0};
    const auto quorums_scanned = llmq::quorumManager->ScanQuorums(llmqType, pindexScan, signingActiveQuorumCount);

    for (size_t i = 0; i < quorums_scanned.size(); ++i) {
        const CQuorumCPtr& quorum = quorums_scanned[i];
        if (quorum == nullptr) {
            return false;
        }
        uint256 requestId = ::SerializeHash(std::make_tuple(CLSIG_REQUESTID_PREFIX, clsig.nHeight, quorum->qc->quorumHash));
        if ((!idIn.IsNull() && idIn != requestId)) {
            continue;
        }
        if (fHaveSigner && !clsig.signers[i]) {
            continue;
        }
        uint256 signHash = CLLMQUtils::BuildSignHash(llmqType, quorum->qc->quorumHash, requestId, clsig.blockHash);
        LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- CLSIG (%s) requestId=%s, signHash=%s\n",
                __func__, clsig.ToString(), requestId.ToString(), signHash.ToString());

        if (clsig.sig.VerifyInsecure(quorum->qc->quorumPublicKey, signHash)) {
            if (idIn.IsNull() && !quorumSigningManager->HasRecoveredSigForId(llmqType, requestId)) {
                // We can reconstruct the CRecoveredSig from the clsig and pass it to the signing manager, which
                // avoids unnecessary double-verification of the signature. We can do this here because we just
                // verified the sig.
                std::shared_ptr<CRecoveredSig> rs = std::make_shared<CRecoveredSig>();
                rs->llmqType = llmqType;
                rs->quorumHash = quorum->qc->quorumHash;
                rs->id = requestId;
                rs->msgHash = clsig.blockHash;
                rs->sig.Set(clsig.sig);
                rs->UpdateHash();
                quorumSigningManager->PushReconstructedRecoveredSig(rs);
            }
            ret = std::make_pair(i, quorum);
            return true;
        }
        if (!idIn.IsNull() || fHaveSigner) {
            return false;
        }
    }
    return false;
}

bool CChainLocksHandler::VerifyAggregatedChainLock(const CChainLockSig& clsig, const CBlockIndex* pindexScan)
{
    const auto& consensus = Params().GetConsensus();
    const auto& llmqType = consensus.llmqTypeChainLocks;
    const auto& llmqParams = consensus.llmqs.at(consensus.llmqTypeChainLocks);
    const auto& signingActiveQuorumCount = llmqParams.signingActiveQuorumCount;

    std::vector<uint256> hashes;
    std::vector<CBLSPublicKey> quorumPublicKeys;

    if (clsig.signers.size() != (size_t)signingActiveQuorumCount) {
        return false;
    }

    if (std::count(clsig.signers.begin(), clsig.signers.end(), true) < (signingActiveQuorumCount / 2 + 1)) {
        // not enough signers
        return false;
    }
    const auto quorums_scanned = llmq::quorumManager->ScanQuorums(llmqType, pindexScan, signingActiveQuorumCount);

    for (size_t i = 0; i < quorums_scanned.size(); ++i) {
        const CQuorumCPtr& quorum = quorums_scanned[i];
        if (quorum == nullptr) {
            return false;
        }
        if (!clsig.signers[i]) {
            continue;
        }
        quorumPublicKeys.emplace_back(quorum->qc->quorumPublicKey);
        uint256 requestId = ::SerializeHash(std::make_tuple(CLSIG_REQUESTID_PREFIX, clsig.nHeight, quorum->qc->quorumHash));
        uint256 signHash = CLLMQUtils::BuildSignHash(llmqType, quorum->qc->quorumHash, requestId, clsig.blockHash);
        hashes.emplace_back(signHash);
        LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- CLSIG (%s) requestId=%s, signHash=%s\n",
                __func__, clsig.ToString(), requestId.ToString(), signHash.ToString());
    }
    return clsig.sig.VerifyInsecureAggregated(quorumPublicKeys, hashes);
}

void CChainLocksHandler::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv)
{
    if (!AreChainLocksEnabled()) {
        return;
    }

    if (strCommand == NetMsgType::CLSIG) {
        CChainLockSig clsig;
        vRecv >> clsig;

        ProcessNewChainLock(pfrom->GetId(), clsig, ::SerializeHash(clsig));
    }
}

void CChainLocksHandler::ProcessNewChainLock(const NodeId from, llmq::CChainLockSig& clsig, const uint256&hash, const uint256& idIn )
{
    assert((from == -1) ^ idIn.IsNull());
    bool enforced = false;
    if (from != -1) {
        LOCK(cs_main);
        peerman.ReceivedResponse(from, hash);
    }
    CheckActiveState();

    bool bReturn = false;
    {
        LOCK(cs);
        if (!seenChainLocks.emplace(hash, GetTimeMillis()).second) {
            bReturn = true;
        }

        if (!bestChainLockWithKnownBlock.IsNull() && clsig.nHeight <= bestChainLockWithKnownBlock.nHeight) {
            // no need to process/relay older CLSIGs
            bReturn = true;
        }
    }
    // don't hold lock while relaying which locks nodes/mempool
    if (from != -1) {
        LOCK(cs_main);
        peerman.ForgetTxHash(from, hash);
    }
    if(bReturn) {
        return;
    }
    CBlockIndex* pindexSig{nullptr};
    CBlockIndex* pindexScan{nullptr};
    {
        LOCK(cs_main);
        if (clsig.nHeight > chainman.ActiveHeight() + CSigningManager::SIGN_HEIGHT_OFFSET) {
            // too far into the future
            LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- future CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from);
            return;
        }
        pindexSig = pindexScan = chainman.m_blockman.LookupBlockIndex(clsig.blockHash);
         if (pindexScan == nullptr) {
            // we don't know the block/header for this CLSIG yet
            if (clsig.nHeight <= chainman.ActiveHeight()) {
                // could be a parallel fork at the same height, try scanning quorums at the same height
                pindexScan = chainman.ActiveTip()->GetAncestor(clsig.nHeight);
            } else {
                // no idea what kind of block it is, try scanning quorums at chain tip
                pindexScan = chainman.ActiveTip();
            }
        }
        if (pindexSig != nullptr && pindexSig->nHeight != clsig.nHeight) {
            // Should not happen
            LogPrintf("CChainLocksHandler::%s -- height of CLSIG (%s) does not match the expected block's height (%d)\n",
                    __func__, clsig.ToString(), pindexSig->nHeight);
            if (from != -1) {
                peerman.Misbehaving(from, 10, "invalid CLSIG");
            }
            return;
        }
    }
    const auto& consensus = Params().GetConsensus();
    const auto& llmqType = consensus.llmqTypeChainLocks;
    const auto& llmqParams = consensus.llmqs.at(llmqType);
    const auto& signingActiveQuorumCount = llmqParams.signingActiveQuorumCount;
    size_t signers_count = std::count(clsig.signers.begin(), clsig.signers.end(), true);
    if (from != -1 && (clsig.signers.empty() || signers_count == 0)) {
        LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- invalid signers count (%d) for CLSIG (%s), peer=%d\n", __func__, signers_count, clsig.ToString(), from);
        peerman.Misbehaving(from, 10, "invalid CLSIG");
        return;
    }
    if (from == -1 || signers_count == 1) {
        // A part of a multi-quorum CLSIG signed by a single quorum
        std::pair<int, CQuorumCPtr> ret;
        clsig.signers.resize(signingActiveQuorumCount, false);
        if (!VerifyChainLockShare(clsig, pindexScan, idIn, ret)) {
            LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- invalid CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from);
            if (from != -1) {
                peerman.Misbehaving(from, 10, "invalid CLSIG");
            }
            return;
        }
        CInv clsigAggInv;
        {
            LOCK(cs);
            clsig.signers[ret.first] = true;
            if (std::count(clsig.signers.begin(), clsig.signers.end(), true) > 1) {
                // this should never happen
                LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- ERROR in VerifyChainLockShare, CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from);
                return;
            }
            auto it = bestChainLockShares.find(clsig.nHeight);
            if (it == bestChainLockShares.end()) {
                bestChainLockShares[clsig.nHeight].emplace(ret.second, std::make_shared<const CChainLockSig>(clsig));
            } else {
                it->second.emplace(ret.second, std::make_shared<const CChainLockSig>(clsig));
            }
            mostRecentChainLockShare = clsig;
            if (TryUpdateBestChainLock(pindexSig)) {
                clsigAggInv = CInv(MSG_CLSIG, ::SerializeHash(bestChainLockWithKnownBlock));
            }
        }
        // Note: do not hold cs while calling RelayInv
        AssertLockNotHeld(cs);
        if (clsigAggInv.type == MSG_CLSIG) {
            // We just created an aggregated CLSIG, relay it
            connman.RelayOtherInv(clsigAggInv);
        } else {
            CInv clsigInv(MSG_CLSIG, ::SerializeHash(clsig));
            // Relay partial CLSIGs to full nodes only, SPV wallets should wait for the aggregated CLSIG.
            connman.ForEachNode([&](CNode* pnode) {
                bool fSPV{false};
                if(pnode->m_tx_relay != nullptr) {
                    LOCK(pnode->m_tx_relay->cs_filter);
                    fSPV = pnode->m_tx_relay->pfilter != nullptr;
                }
                if (!fSPV && pnode->CanRelay()) {
                    pnode->PushOtherInventory(clsigInv);
                }
            });
            // Try signing the tip ourselves
            TrySignChainTip();
        }
    } else {
        CInv clsigInv(MSG_CLSIG, hash);
        // An aggregated CLSIG
        if (!VerifyAggregatedChainLock(clsig, pindexScan)) {
            LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- invalid CLSIG (%s), peer=%d\n", __func__, clsig.ToString(), from);
            if (from != -1) {
                peerman.Misbehaving(from, 10, "invalid CLSIG");
            }
            return;
        }
        {
            LOCK(cs);
            bestChainLockCandidates[clsig.nHeight] = std::make_shared<const CChainLockSig>(clsig);
            mostRecentChainLockShare = clsig;
            TryUpdateBestChainLock(pindexSig);
        }
        // Note: do not hold cs while calling RelayInv
        AssertLockNotHeld(cs);
        connman.RelayOtherInv(clsigInv);
    }

    if (pindexSig == nullptr) {
        // we don't know the block/header for this CLSIG yet, so bail out for now
        // when the block or the header later comes in, we will enforce the correct chain
        return;
    }
    bool bChainLockMatchSigIndex = WITH_LOCK(cs, return bestChainLockBlockIndex == pindexSig);
    if (bChainLockMatchSigIndex) {
        CheckActiveState();
        const CBlockIndex* pindex;
        {
            LOCK(cs);
            pindex = bestChainLockBlockIndex;
            enforced = isEnforced;
        }
        if(enforced) {
            AssertLockNotHeld(cs);
            chainman.ActiveChainstate().EnforceBestChainLock(pindex);
        }
        LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- processed new CLSIG (%s), peer=%d\n",
              __func__, clsig.ToString(), from);
    }
}

void CChainLocksHandler::AcceptedBlockHeader(const CBlockIndex* pindexNew)
{
    LOCK(cs);

    auto it = bestChainLockCandidates.find(pindexNew->nHeight);
    if (it == bestChainLockCandidates.end()) {
        return;
    }

    LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- block header %s came in late, updating and enforcing\n", __func__, pindexNew->GetBlockHash().ToString());

    // when EnforceBestChainLock is called later, it might end up invalidating other chains but not activating the
    // CLSIG locked chain. This happens when only the header is known but the block is still missing yet. The usual
    // block processing logic will handle this when the block arrives
    TryUpdateBestChainLock(pindexNew);
}

void CChainLocksHandler::UpdatedBlockTip(const CBlockIndex* pindexNew, bool fInitialDownload)
{
    if(fInitialDownload)
        return;

    CheckActiveState();
    bool enforced;
    const CBlockIndex* pindex;
    {
        LOCK(cs);
        if (tryLockChainTipScheduled) {
            return;
        }
        tryLockChainTipScheduled = true;
        pindex = bestChainLockBlockIndex;
        enforced = isEnforced;
    }

    if(enforced) {
        AssertLockNotHeld(cs);
        chainman.ActiveChainstate().EnforceBestChainLock(pindex);
    }
    TrySignChainTip();
    {
        LOCK(cs);
        tryLockChainTipScheduled = false;
    }
}

void CChainLocksHandler::CheckActiveState()
{
    bool sporkActive = AreChainLocksEnabled();
    {
        LOCK(cs);
        bool oldIsEnforced = isEnforced;
        isEnabled = sporkActive;
        isEnforced = isEnabled;
        if (!oldIsEnforced && isEnforced) {

            // ChainLocks got activated just recently, but it's possible that it was already running before, leaving
            // us with some stale values which we should not try to enforce anymore (there probably was a good reason
            // to disable spork19)
            mostRecentChainLockShare = bestChainLockWithKnownBlock = CChainLockSig();
            bestChainLockBlockIndex = nullptr;
            bestChainLockCandidates.clear();
            bestChainLockShares.clear();
        }
    }
}

static struct SigningState
{
private:
    const static int ATTEMPT_START{-2}; // let a couple of extra attempts to wait for busy/slow quorums

    int attempt GUARDED_BY(cs) {ATTEMPT_START};
    int lastSignedHeight GUARDED_BY(cs) {-1};

public:
    mutable RecursiveMutex cs;
    void SetLastSignedHeight(int _lastSignedHeight)
    {
        LOCK(cs);
        lastSignedHeight = _lastSignedHeight;
        attempt = ATTEMPT_START;
    }
    int GetLastSignedHeight() const
    {
        LOCK(cs);
        return lastSignedHeight;
    }
    void BumpAttempt()
    {
        LOCK(cs);
        ++attempt;
    }
    int GetAttempt() const
    {
        LOCK(cs);
        return attempt;
    }
} signingState;

void CChainLocksHandler::TrySignChainTip()
{
    Cleanup();

    if (!fMasternodeMode) {
        return;
    }

    if (!masternodeSync.IsBlockchainSynced()) {
        return;
    }

    const CBlockIndex* pindex = WITH_LOCK(cs_main, return chainman.ActiveTip());

    if (!pindex || !pindex->pprev) {
        return;
    }
    const uint256 msgHash = pindex->GetBlockHash();
    const int32_t nHeight = pindex->nHeight;

    // DIP8 defines a process called "Signing attempts" which should run before the CLSIG is finalized
    // To simplify the initial implementation, we skip this process and directly try to create a CLSIG
    // This will fail when multiple blocks compete, but we accept this for the initial implementation.
    // Later, we'll add the multiple attempts process.

    {
        LOCK(cs);

        if (!isEnabled) {
            return;
        }

        if (pindex->nHeight == signingState.GetLastSignedHeight()) {
            // already signed this one
            return;
        }

        if (bestChainLockWithKnownBlock.nHeight >= pindex->nHeight) {
            // already got the same CLSIG or a better one, reset and bail out
            signingState.SetLastSignedHeight(bestChainLockWithKnownBlock.nHeight);
            return;
        }

        if (InternalHasConflictingChainLock(pindex->nHeight, pindex->GetBlockHash())) {
            // don't sign if another conflicting CLSIG is already present. EnforceBestChainLock will later enforce
            // the correct chain.
            return;
        }
        mapSignedRequestIds.clear();
    }

    LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- trying to sign %s, height=%d\n", __func__, msgHash.ToString(), nHeight);
    const auto& consensus = Params().GetConsensus();
    const auto& llmqType = consensus.llmqTypeChainLocks;
    const auto& llmqParams = consensus.llmqs.at(consensus.llmqTypeChainLocks);
    const auto& signingActiveQuorumCount = llmqParams.signingActiveQuorumCount;

    const auto quorums_scanned = llmq::quorumManager->ScanQuorums(llmqType, pindex, signingActiveQuorumCount);
    std::map<CQuorumCPtr, CChainLockSigCPtr> mapSharesAtTip;
    {
        LOCK(cs);
        const auto it = bestChainLockShares.find(pindex->nHeight);
        if (it != bestChainLockShares.end()) {
            mapSharesAtTip = it->second;
        }
    }
    bool fMemberOfSomeQuorum{false};
    signingState.BumpAttempt();
    for (size_t i = 0; i < quorums_scanned.size(); ++i) {
        int nQuorumIndex = (pindex->nHeight + i) % quorums_scanned.size();
        const CQuorumCPtr& quorum = quorums_scanned[nQuorumIndex];
        if (quorum == nullptr) {
            return;
        }
        if (!quorum->IsValidMember(activeMasternodeInfo.proTxHash)) {
                continue;
            }
        fMemberOfSomeQuorum = true;
        if (i > 0) {
            int nQuorumIndexPrev = (nQuorumIndex + 1) % quorums_scanned.size();
            auto it2 = mapSharesAtTip.find(quorums_scanned[nQuorumIndexPrev]);
            if (it2 == mapSharesAtTip.end() && signingState.GetAttempt() > (int)i) {
                // look deeper after 'i' attempts
                while (nQuorumIndexPrev != nQuorumIndex) {
                    nQuorumIndexPrev = (nQuorumIndexPrev + 1) % quorums_scanned.size();
                    it2 = mapSharesAtTip.find(quorums_scanned[nQuorumIndexPrev]);
                    if (it2 != mapSharesAtTip.end()) {
                        break;
                    }
                    LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- previous quorum (%d, %s) didn't sign a chainlock at height %d yet\n",
                            __func__, nQuorumIndexPrev, quorums_scanned[nQuorumIndexPrev]->qc->quorumHash.ToString(), pindex->nHeight);
                }
            }
            if (it2 == mapSharesAtTip.end()) {
                if (signingState.GetAttempt() <= (int)i) {
                    // previous quorum did not sign a chainlock, bail out for now
                    LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- previous quorum did not sign a chainlock at height %d yet\n", __func__, pindex->nHeight);
                    return;
                }
                // else
                // waiting for previous quorum(s) to sign anything for too long already,
                // just sign whatever we think is a good tip
            } else if (it2->second->blockHash != pindex->GetBlockHash()) {
                LOCK(cs_main);
                auto shareBlockIndex = chainman.m_blockman.LookupBlockIndex(it2->second->blockHash);
                if (shareBlockIndex != nullptr && shareBlockIndex->nHeight == pindex->nHeight) {
                    // previous quorum signed an alternative chain tip, sign it too instead
                    LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- previous quorum (%d, %s) signed an alternative chaintip (%s != %s) at height %d, join it\n",
                            __func__, nQuorumIndexPrev, quorums_scanned[nQuorumIndexPrev]->qc->quorumHash.ToString(), it2->second->blockHash.ToString(), pindex->GetBlockHash().ToString(), pindex->nHeight);
                    pindex = shareBlockIndex;
                } else if (signingState.GetAttempt() <= (int)i) {
                    // previous quorum signed some different hash we have no idea about, bail out for now
                    LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- previous quorum (%d, %s) signed an unknown or an invalid blockHash (%s != %s) at height %d\n",
                            __func__, nQuorumIndexPrev, quorums_scanned[nQuorumIndexPrev]->qc->quorumHash.ToString(), it2->second->blockHash.ToString(), pindex->GetBlockHash().ToString(), pindex->nHeight);
                    return;
                }
                // else
                // waiting the unknown/invalid hash for too long already,
                // just sign whatever we think is a good tip
            }
        }
        LogPrint(BCLog::CHAINLOCKS, "CChainLocksHandler::%s -- use quorum (%d, %s) and try to sign %s at height %d\n",
                __func__, nQuorumIndex, quorums_scanned[nQuorumIndex]->qc->quorumHash.ToString(), pindex->GetBlockHash().ToString(), pindex->nHeight);
        uint256 requestId = ::SerializeHash(std::make_tuple(CLSIG_REQUESTID_PREFIX, pindex->nHeight, quorum->qc->quorumHash));
        {
            LOCK(cs);
            if (bestChainLockWithKnownBlock.nHeight >= pindex->nHeight) {
                // might have happened while we didn't hold cs
                return;
            }
            mapSignedRequestIds.emplace(requestId, std::make_pair(pindex->nHeight, pindex->GetBlockHash()));
        }
        quorumSigningManager->AsyncSignIfMember(llmqType, requestId, pindex->GetBlockHash(), quorum->qc->quorumHash);
    }
    if (!fMemberOfSomeQuorum || signingState.GetAttempt() >= (int)quorums_scanned.size()) {
        // not a member or tried too many times, nothing to do
        signingState.SetLastSignedHeight(pindex->nHeight);
    }
}

void CChainLocksHandler::HandleNewRecoveredSig(const llmq::CRecoveredSig& recoveredSig)
{
    CChainLockSig clsig;
    {
        LOCK(cs);

        if (!isEnabled) {
            return;
        }

        auto it = mapSignedRequestIds.find(recoveredSig.id);
        if (it == mapSignedRequestIds.end() || recoveredSig.msgHash != it->second.second) {
            // this is not what we signed, so lets not create a CLSIG for it
            return;
        }
        if (bestChainLockWithKnownBlock.nHeight >= it->second.first) {
            // already got the same or a better CLSIG through the CLSIG message
            return;
        }

        clsig.nHeight = it->second.first;
        clsig.blockHash = it->second.second;
        clsig.sig = recoveredSig.sig.Get();
        mapSignedRequestIds.erase(recoveredSig.id);
    }
    ProcessNewChainLock(-1, clsig, ::SerializeHash(clsig), recoveredSig.id);
}

bool CChainLocksHandler::HasChainLock(int nHeight, const uint256& blockHash) const
{
    LOCK(cs);
    return InternalHasChainLock(nHeight, blockHash);
}

bool CChainLocksHandler::InternalHasChainLock(int nHeight, const uint256& blockHash) const
{
    AssertLockHeld(cs);

    if (!isEnforced) {
        return false;
    }

    if (!bestChainLockBlockIndex) {
        return false;
    }

    if (nHeight > bestChainLockBlockIndex->nHeight) {
        return false;
    }

    if (nHeight == bestChainLockBlockIndex->nHeight) {
        return blockHash == bestChainLockBlockIndex->GetBlockHash();
    }

    auto pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight);
    return pAncestor && pAncestor->GetBlockHash() == blockHash;
}

bool CChainLocksHandler::HasConflictingChainLock(int nHeight, const uint256& blockHash) const
{
    LOCK(cs);
    return InternalHasConflictingChainLock(nHeight, blockHash);
}

bool CChainLocksHandler::InternalHasConflictingChainLock(int nHeight, const uint256& blockHash) const
{
    AssertLockHeld(cs);

    if (!isEnforced) {
        return false;
    }

    if (!bestChainLockBlockIndex) {
        return false;
    }

    if (nHeight > bestChainLockBlockIndex->nHeight) {
        return false;
    }

    if (nHeight == bestChainLockBlockIndex->nHeight) {
        return blockHash != bestChainLockBlockIndex->GetBlockHash();
    }

    auto pAncestor = bestChainLockBlockIndex->GetAncestor(nHeight);
    assert(pAncestor);
    return pAncestor->GetBlockHash() != blockHash;
}

void CChainLocksHandler::Cleanup()
{
    if (!masternodeSync.IsBlockchainSynced()) {
        return;
    }

    {
        LOCK(cs);
        if (GetTimeMillis() - lastCleanupTime < CLEANUP_INTERVAL) {
            return;
        }
    }

    LOCK(cs);

    for (auto it = seenChainLocks.begin(); it != seenChainLocks.end(); ) {
        if (GetTimeMillis() - it->second >= CLEANUP_SEEN_TIMEOUT) {
            it = seenChainLocks.erase(it);
        } else {
            ++it;
        }
    }

    if (bestChainLockBlockIndex != nullptr) {
        for (auto it = bestChainLockCandidates.begin(); it != bestChainLockCandidates.end(); ) {
            if (it->first == bestChainLockBlockIndex->nHeight) {
                it = bestChainLockCandidates.erase(++it, bestChainLockCandidates.end());
            } else {
                ++it;
            }
        }
        for (auto it = bestChainLockShares.begin(); it != bestChainLockShares.end(); ) {
            if (it->first == bestChainLockBlockIndex->nHeight) {
                it = bestChainLockShares.erase(++it, bestChainLockShares.end());
            } else {
                ++it;
            }
        }
    }
    lastCleanupTime = GetTimeMillis();
}

bool AreChainLocksEnabled()
{
    return sporkManager.IsSporkActive(SPORK_19_CHAINLOCKS_ENABLED);
}

} // namespace llmq


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

global $SITE;

if (($hassiteconfig || has_any_capability(array(
            'moodle/badges:viewawarded',
            'moodle/badges:createbadge',
            'moodle/badges:manageglobalsettings',
            'moodle/badges:awardbadge',
            'moodle/badges:configurecriteria',
            'moodle/badges:configuremessages',
            'moodle/badges:configuredetails',
            'moodle/badges:deletebadge'), $systemcontext))) {

    require_once($CFG->libdir . '/badgeslib.php');

    $globalsettings = new admin_settingpage('badgesettings', new lang_string('badgesettings', 'badges'),
            array('moodle/badges:manageglobalsettings'), empty($CFG->enablebadges));

    $globalsettings->add(new admin_setting_configtext('badges_defaultissuername',
            new lang_string('defaultissuername', 'badges'),
            new lang_string('defaultissuername_desc', 'badges'),
            $SITE->fullname ? $SITE->fullname : $SITE->shortname, PARAM_TEXT));

    $globalsettings->add(new admin_setting_configtext('badges_defaultissuercontact',
            new lang_string('defaultissuercontact', 'badges'),
            new lang_string('defaultissuercontact_desc', 'badges'),
            get_config('moodle','supportemail'), PARAM_EMAIL));

    $globalsettings->add(new admin_setting_configtext('badges_badgesalt',
            new lang_string('badgesalt', 'badges'),
            new lang_string('badgesalt_desc', 'badges'),
            'badges' . $SITE->timecreated, PARAM_ALPHANUM));

    $globalsettings->add(new admin_setting_configcheckbox('badges_allowexternalbackpack',
            new lang_string('allowexternalbackpack', 'badges'),
            new lang_string('allowexternalbackpack_desc', 'badges'), 1));

    $globalsettings->add(new admin_setting_configcheckbox('badges_allowcoursebadges',
            new lang_string('allowcoursebadges', 'badges'),
            new lang_string('allowcoursebadges_desc', 'badges'), 1));

    $ADMIN->add('badges', $globalsettings);

    $ADMIN->add('badges',
        new admin_externalpage('managebadges',
            new lang_string('managebadges', 'badges'),
            new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_SITE)),
            array(
                'moodle/badges:viewawarded',
                'moodle/badges:createbadge',
                'moodle/badges:awardbadge',
                'moodle/badges:configurecriteria',
                'moodle/badges:configuremessages',
                'moodle/badges:configuredetails',
                'moodle/badges:deletebadge'
            ),
            empty($CFG->enablebadges)
        )
    );

    $ADMIN->add('badges',
        new admin_externalpage('newbadge',
            new lang_string('newbadge', 'badges'),
            new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_SITE)),
            array('moodle/badges:createbadge'), empty($CFG->enablebadges)
        )
    );
}

redpajama_set_name: RedPajamaGithub


text:
#include <QDateTime>

#include "abstracttableitem.h"

static const QString dateTimeFormat = "yyyy-MM-dd hh:mm:ss";

AbstractTableItem::AbstractTableItem(const QString &path,
                                     const QString &fileName) :
    AbstractSettings(path, fileName)
{
    ;
}

QJsonObject& AbstractTableItem::getJsonObject() const
{
    return AbstractSettings::getSettings();
}

bool AbstractTableItem::saveJsonObjectToCache() const
{
    const QString &&status = get("status");
    if (status == "passed" || status == "failed") {
        return writeSettings();
    }
    return false;
}

qint64 AbstractTableItem::calcDuration(const QString &started,
                                       const QString &finished) const
{
    if (started.isEmpty() || finished.isEmpty())
        return 0;

    const QDateTime t1 = QDateTime::fromString(started,  dateTimeFormat);
    const QDateTime t2 = QDateTime::fromString(finished, dateTimeFormat);
    return t1.secsTo(t2);
}

bool AbstractTableItem::requiresUpdate(const int pkgVer) const
{
    if (getSettings().isEmpty())
        return true;

    return (getInt("pkg_ver") < pkgVer);
}


text:
<?php

namespace Skydrop\ShippingRate\Modifier;

use Respect\Validation\Validator as v;
use Respect\Validation\Exceptions\NestedValidationException;

class CodeEncoder
{
    use \Skydrop\Validations\ValidationTrait;

    public $rates;

    public function __construct($rates = [], $options = array())
    {
        $this->validator = v::attribute('rates', v::arrayType()->length(1, null));

        $this->rates = $rates;
    }

    public function call()
    {
        $this->validate();

        foreach ($this->rates as $rate) {
            $rate->service_code = urlencode($this->stringifiedCode($rate));
        }
        return $this->rates;
    }

    private function stringifiedCode($rate)
    {
        return json_encode([
            'service_code'  => $rate->service_code,
            'vehicle_type'  => $rate->vehicle_type,
            'schedule_date' => $this->_getScheduleDate($rate),
            'starting_hour' => $rate->starting_hour,
            'ending_hour'   => $rate->ending_hour
        ]);
    }

    private function _getScheduleDate($rate)
    {
        // commented to fix bug in Skydrop server
        // if ($rate->service_code == 'next_day') {
        //     return $this->_getNextDayDate();
        // }
        return $this->_getSameDayDate();
    }

    private function _getNextDayDate()
    {
        $date = new \DateTime();
        $date->setTimezone(new \DateTimeZone('America/Monterrey'));
        $date->add(new \DateInterval('P1D')); // Add 1 day;
        return $date->format('Y-m-d');
    }

    private function _getSameDayDate()
    {
        $date = new \DateTime();
        $date->setTimezone(new \DateTimeZone('America/Monterrey'));
        return $date->format('Y-m-d');
    }
}


text:
<?php

namespace NotificationChannels\HipChat;

interface CardAttributeStyles
{
    const SUCCESS = 'lozenge-success';
    const ERROR = 'lozenge-error';
    const CURRENT = 'lozenge-current';
    const COMPLETE = 'lozenge-complete';
    const MOVED = 'lozenge-moved';
    const GENERAL = 'lozenge';
}


text:
[CmdletBinding()]
param()

[hashtable]$script:mocks = @{ }
. $PSScriptRoot/PrivateFunctions.ps1
. $PSScriptRoot/PublicFunctions.ps1

Export-ModuleMember -Verbose:$false -Function @(
    'Assert-AreEqual'
    'Assert-AreNotEqual'
    'Assert-IsNotNullOrEmpty'
    'Assert-IsNullOrEmpty'
    'Assert-IsGreaterThan'
    'Assert-Throws'
    'Assert-WasCalled'
    'Register-Mock'
    'Unregister-Mock'
)


text:
package org.cinchapi.concourse.http;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.cinchapi.concourse.test.ConcourseIntegrationTest;
import org.cinchapi.concourse.server.ConcourseServer;
import org.cinchapi.concourse.server.http.HttpServer;
import org.cinchapi.concourse.test.Variables;
import org.cinchapi.concourse.time.Time;
import org.cinchapi.concourse.util.Networking;
import org.cinchapi.concourse.util.Reflection;

import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

/**
 * A class that defines methods and basic tests for interacting with the HTTP
 * functionality of Concourse Server.
 *
 * @author Jeff Nelson
 */
public class HttpTest extends ConcourseIntegrationTest {

    /**
     * Return the response body as the appropriate Java object.
     *
     * @param response
     * @return the response body
     */
    protected static <T> T bodyAsJava(Response response, TypeToken<T> type) {
        Type type0 = type.getType();
        return new Gson().fromJson(bodyAsJson(response), type0);
    }

    /**
     * Return a JsonElement representation of the response body.
     *
     * @param response
     * @param the json response
     */
    protected static JsonElement bodyAsJson(Response response) {
        try {
            String body = response.body().string();
            JsonElement json = new JsonParser().parse(body);
            Variables.register("json_body_" + response.hashCode(), body);
            return json;
        }
        catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

    /**
     * Do anything that is necessary to clean up the URL args. For example, make
     * sure any records (represented as an int or long) does not get rendered
     * using comma separators.
     *
     * @param args
     * @return the clean args
     */
    private static Object[] cleanUrlArgs(Object... args) {
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            if(arg.getClass() == long.class || arg.getClass() == int.class) {
                args[i] = Long.toString((long) arg);
            }
            else if(arg.getClass() == Long.class
                    || arg.getClass() == Integer.class) {
                args[i] = arg.toString();
            }
        }
        return args;
    }

    /**
     * Go through the {@code args} and filter out any that shouldn't be
     * considered URL args. It is possible that some of the filtered args will
     * be passed as arguments to the {@code builder}.
     *
     * @param builder
     * @param args
     * @return the filtered args
     */
    private static Object[] filterArgs(Request.Builder builder, Object... args) {
        List<Object> argsList = Lists.newArrayList(args);
        Iterator<Object> it = argsList.iterator();
        while (it.hasNext()) {
            Object arg = it.next();
            if(arg instanceof Headers) {
                builder.headers((Headers) arg);
                it.remove();
            }
        }
        args = argsList.size() != args.length ? argsList.toArray() : args;
        return args;
    }

    /**
     * JSON media type
     */
    private static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");

    /**
     * The base URL.
     */
    private String base = "http://localhost:";

    /**
     * The HTTP Client.
     */
    private OkHttpClient http = new OkHttpClient();

    /**
     * A reference to the HttpServer that interacts with Concourse Server.
     * Subclasses should never need to interact with this directly.
     */
    private HttpServer httpServer;

    {
        // Setup support for cookies
        CookieManager cm = new CookieManager();
        cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        http.setCookieHandler(cm);
    }

    @Override
    public void afterEachTest() {
        httpServer.stop();
        clearClientCookies();
    }

    @Override
    public void beforeEachTest() {
        int port = Networking.getOpenPort();
        httpServer = HttpServer.create(
                Reflection.<ConcourseServer> get("server", this), port);
        httpServer.start();
        // Wait for the HTTP server to start
        Request req = new Request.Builder().url(base).head().build();
        long start = Time.now();
        boolean escape = false;
        while (!escape) {
            try {
                http.newCall(req).execute();
                escape = true;
            }
            catch (IOException e) {
                escape = TimeUnit.SECONDS.convert(Time.now() - start,
                        TimeUnit.MICROSECONDS) > 5;
            }
        }
        base += port;
    }

    /**
     * Remove all the client side cookies.
     *
     * @return {@code true} if the cookies are removed
     */
    protected boolean clearClientCookies() {
        return ((CookieManager) http.getCookieHandler()).getCookieStore()
                .removeAll();
    }

    /**
     * Perform a DELETE request
     *
     * @param route
     * @param args - include a {@link Headers} object to set the request headers
     * @return the response
     */
    protected Response delete(String route, Object... args) {
        try {
            Request.Builder builder = new Request.Builder();
            args = filterArgs(builder, args);
            args = cleanUrlArgs(args);
            route = MessageFormat.format(route, args);
            Request request = builder.url(base + route).delete().build();
            Response response = http.newCall(request).execute();
            long ts = response.hashCode();
            Variables.register("request_" + ts, request);
            Variables.register("response_" + ts, response);
            return response;
        }
        catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

    /**
     * Perform a GET request
     *
     * @param route
     * @param args - include a {@link Headers} object to set the request headers
     * @return the response
     */
    protected Response get(String route, Object... args) {
        try {
            Request.Builder builder = new Request.Builder();
            args = filterArgs(builder, args);
            args = cleanUrlArgs(args);
            route = MessageFormat.format(route, args);
            Request request = builder.url(base + route).get().build();
            Response response = http.newCall(request).execute();
            long ts = response.hashCode();
            Variables.register("request_" + ts, request);
            Variables.register("response_" + ts, response);
            return response;
        }
        catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

    /**
     * Perform a login request to the default environment.
     *
     * @return the response
     */
    protected Response login() {
        return login("");
    }

    /**
     * Perform a login request.
     *
     * @param environment
     * @return the response
     */
    protected Response login(String environment) {
        environment = Strings.isNullOrEmpty(environment) ? "" : "/"
                + environment;
        JsonObject creds = new JsonObject();
        creds.addProperty("username", "admin");
        creds.addProperty("password", "admin");
        Response resp = post(environment + "/login", creds.toString());
        return resp;
    }

    /**
     * Perform a POST request.
     *
     * @param route
     * @param data
     * @param args - include a {@link Headers} object to set the request headers
     * @return the response
     */
    protected Response post(String route, String data, Object... args) {
        try {
            RequestBody body = RequestBody.create(JSON, data);
            Request.Builder builder = new Request.Builder();
            args = filterArgs(builder, args);
            args = cleanUrlArgs(args);
            route = MessageFormat.format(route, args);
            Request request = builder.url(base + route).post(body).build();
            Response response = http.newCall(request).execute();
            long ts = response.hashCode();
            Variables.register("request_" + ts, request);
            Variables.register("response_" + ts, response);
            return response;
        }
        catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

    /**
     * Perform a PUT request.
     *
     * @param route
     * @param data
     * @param args - include a {@link Headers} object to set the request headers
     * @return the response
     */
    protected Response put(String route, String data, Object... args) {
        try {
            RequestBody body = RequestBody.create(JSON, data);
            Request.Builder builder = new Request.Builder();
            args = filterArgs(builder, args);
            args = cleanUrlArgs(args);
            route = MessageFormat.format(route, args);
            Request request = builder.url(base + route).put(body).build();
            Response response = http.newCall(request).execute();
            long ts = response.hashCode();
            Variables.register("request_" + ts, request);
            Variables.register("response_" + ts, response);
            return response;
        }
        catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }

}


text:
import CSSClassnames from './CSSClassnames';

const CLASS_ROOT = CSSClassnames.APP;

function clearAnnouncer() {
  const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
  announcer.innerHTML = '';
};

export function announcePageLoaded (title) {
  announce(`${title} page was loaded`);
}

export function announce (message, mode = 'assertive') {
  const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
  announcer.setAttribute('aria-live', 'off');
  announcer.innerHTML = message;
  setTimeout(clearAnnouncer, 500);
  announcer.setAttribute('aria-live', mode);
}

export default { announce, announcePageLoaded };


text:
import {
    makeBoldEndTag,
    makeBoldStartTag,
    makeCodeEndTag,
    makeCodeStartTag,
    makeItalicsEndTag,
    makeItalicsStartTag,
    makeUrlEndTag,
    makeUrlStartTag,
    makeUserLinkEndTag,
    makeUserLinkStartTag,
    newLineTag,
} from '../chat-service/discord/misc';

export const makeBold = (text: string | number): string => `${ makeBoldStartTag }${ text }${ makeBoldEndTag }`;

export const makeItalics = (text: string | number): string => `${ makeItalicsStartTag }${ text }${ makeItalicsEndTag }`;

export const makeCode = (text: string | number): string => `${ makeCodeStartTag }${ text }${ makeCodeEndTag }`;

export const makeURL = (text: string | number): string => `${ makeUrlStartTag }${ text }${ makeUrlEndTag }`;

export const makeUserLink = (text: string): string => `${ makeUserLinkStartTag }${ text }${ makeUserLinkEndTag }`;

export const newLine = (amount = 1): string => newLineTag.repeat(amount);

export const itemFormat = (text: string | number): string => makeCode(text);

export const regionFormat = (text: string | number): string => makeBold(text);


text:
"""
 This script can be used to delete unwanted AWS IAM user accounts.
 It can be used on individual AWS accounts or for all ops accounts at once.

 Usage:

 For individual accounts:
 delete_iam_account -u <user-to-delete> -p ded-stage-aws -p ded-int-aws -p <some-other-account>

 For all accounts found in /etc/openshift_tools/aws_accounts.txt:
 delete_iam_account -u <user-to-delete> --all
"""

from __future__ import print_function

import argparse
import os
import sys
import yaml

# pylint: disable=import-error, no-name-in-module
import boto3
import botocore

from openshift_tools import saml_aws_creds

class DeleteUser(object):
    """ Class to delete an iam user from ops acounts. """

    def __init__(self):
        """ constructor """
        self.response = None

    @staticmethod
    def check_arguments():
        """ Ensure that an argument was passed in from the command line.

        Returns:
            Parsed argument(s), if provided
        """

        parser = argparse.ArgumentParser(description='Delete unwanted IAM accounts')
        parser.add_argument('-a', '--all',
                            help='Delete IAM user from every profile in ~/.aws/credentials',
                            action='store_true')
        parser.add_argument('-p', '--profile',
                            help='Delete IAM user from the specified profile',
                            action='append')
        parser.add_argument('-u', '--user',
                            help='Specify a username for the account')
        args = parser.parse_args()

        if not args.all and not args.profile:
            print('Specify an account ID or profile name.\n'
                  'To delete the user\'s IAM account from all AWS accounts on file, use \"--all\"\n'
                  'Usage:\n'
                  'example: {0} -u <user-to-delete> -p <account-name>\n'
                  'example: {0} -u <user-to-delete> --all'.format(parser.prog))
            sys.exit(10)
        if args.user != 'root':
            return args

    @staticmethod
    def get_ops_accounts():
        """ Retrieves a list of the config-managed ops AWS accounts.

        Returns:
            A list containing each of the lines found in the aws accounts file

        Raises:
            A ValueError if the path does not exist
        """

        config_path = '/etc/openshift_tools/sso-config.yaml'
        if os.path.isfile(config_path):
            with open(config_path, 'r') as sso_config:
                yaml_config = yaml.load(sso_config)

                if yaml_config["aws_account_file"]:
                    path = yaml_config["aws_account_file"]

        accounts_list = []

        if os.path.isfile(path):
            with open(path) as open_file:
                stripped_line = list([line.rstrip() for line in open_file.readlines()])
                for line in stripped_line:
                    if line is not None:
                        accounts_list.append(line)
                return accounts_list
        else:
            raise ValueError(path + 'does not exist')

    @staticmethod
    def delete_user(user_name, client):
        """ Delete an IAM user account. """

        client.remove_user_from_group(GroupName='admin', UserName=user_name)

        response = client.delete_user(
            UserName=user_name
            )

        return response

    def check_user(self, aws_account, user_name, client):
        """ Check if the user exists locally and in AWS. Deletes the IAM user if found. """

        try:
            client.get_user(UserName=user_name)
        except botocore.exceptions.ClientError as client_exception:
            if client_exception.response['Error']['Code'] == 'NoSuchEntity':
                print('IAM user does not exist in account:', aws_account)
                return True

        else:
            if user_name != 'root':
                try:
                    self.delete_login_profile(user_name, client)
                except botocore.exceptions.ClientError as client_exception:
                    if client_exception.response['Error']['Code'] == 'NoSuchEntity':
                        print('IAM user does not have a password for account:', aws_account)

                print("Found existing IAM account in %s\n"
                      "deleting IAM account for user %s" % (aws_account, user_name))
                response = self.delete_user(user_name, client)

                return response
            else:
                print('Unable to delete this user. Only ops users can be deleted with this tool.')

    @staticmethod
    def get_keys(user_name, client, aws_account):
        """ Get the Access Key IDs of the user, and return them in a list.

        Returns:
            All access keys found for the IAM user, in a list.
            List will be empty if the user has no keys.
         """

        try:
            client.list_access_keys(
                UserName=user_name)
        except botocore.exceptions.ClientError as client_exception:
            if client_exception.response['Error']['Code'] == 'NoSuchEntity':
                print('IAM user does not have any keys for account:', aws_account)
                keys_list = []
                return keys_list

        else:
            existing_keys = client.list_access_keys(
                UserName=user_name)

            all_keys = existing_keys['AccessKeyMetadata']
            keys_list = []

            if all_keys:
                for ekey in all_keys:
                    keys_list.append(ekey['AccessKeyId'])

            return keys_list

    @staticmethod
    def delete_key(aws_account, user_name, key, client):
        """ Delete an API key for the specified account. """

        response = client.delete_access_key(
            UserName=user_name,
            AccessKeyId=key
            )

        print('Found and deleted api key for:', aws_account)
        return response

    @staticmethod
    def delete_login_profile(user_name, client):
        """ Delete the login profile from the IAM account. """

        response = client.delete_login_profile(
            UserName=user_name
            )

        return response

    @staticmethod
    def get_token(aws_account, class_type, user_name):
        """ Generate temporary SSO access credentials.

        Requires the config file containing the IDP hostname.

        Returns:
            A temporary boto3 client created with a session token provided by the IDP host.

        Raises:
            A ValueError if the config path can not be found.
        """

        sso_config_path = '/etc/openshift_tools/sso-config.yaml'

        if os.path.isfile(sso_config_path):
            with open(sso_config_path, 'r') as sso_config:
                yaml_config = yaml.load(sso_config)

                if yaml_config["idp_host"]:
                    ops_idp_host = yaml_config["idp_host"]

                creds = saml_aws_creds.get_temp_credentials(
                    metadata_id='urn:amazon:webservices:%s' % aws_account,
                    idp_host=ops_idp_host
                    )

                if class_type == 'iam':
                    client = boto3.client(
                        'iam',
                        aws_access_key_id=creds['AccessKeyId'],
                        aws_secret_access_key=creds['SecretAccessKey'],
                        aws_session_token=creds['SessionToken']
                        )

                    return client

                elif class_type == 'user':
                    client = boto3.resource(
                        'iam',
                        aws_access_key_id=creds['AccessKeyId'],
                        aws_secret_access_key=creds['SecretAccessKey'],
                        aws_session_token=creds['SessionToken']
                        )

                    user = client.User(user_name)
                    return user

        else:
            raise ValueError(sso_config_path + 'does not exist.')

    @staticmethod
    def get_policies(aws_account, user_name, client):
        """ Get the Access Key IDs of the user, and return them in a list.

        Returns:
            All access policies found for the IAM user, in a list.
            List will be empty if the user has no policies.
         """

        pols_list = []

        try:
            managed_pols = client.list_attached_user_policies(
                UserName=user_name)

            man_pol_list = managed_pols['AttachedPolicies']

            if man_pol_list:
                for epol in man_pol_list:
                    if epol.get('PolicyArn'):
                        pols_list.append(epol['PolicyArn'])

        except botocore.exceptions.ClientError as client_exception:
            if client_exception.response['Error']['Code'] == 'NoSuchEntity':
                print('IAM user does not have any managed policies for account:', aws_account)

        return pols_list

    @staticmethod
    def detach_policy(user_name, client, policy):
        """ Detach the specified policy from the provided user. """

        response = client.detach_policy(
            PolicyArn=policy,
            UserName=user_name
        )

        print('Found and deleted policy:', policy)
        return response

    def main(self):
        """ Main function. """
        args = self.check_arguments()
        ops_accounts = self.get_ops_accounts()

        if args.profile and args.user:

            for aws_account in args.profile:
                matching = [s for s in ops_accounts if aws_account in s]
                account_number = matching[0].split(':')[1]
                client = self.get_token(account_number, 'iam', args.user)
                existing_keys = self.get_keys(args.user, client, aws_account)

                if existing_keys:
                    for key in existing_keys:
                        self.delete_key(aws_account, args.user, key, client)

                self.get_policies(aws_account, args.user, client)
                self.check_user(aws_account, args.user, client)

        elif args.all and args.user:

            for aws_account in ops_accounts:
                matching = [s for s in ops_accounts if aws_account in s]
                account_number = matching[0].split(':')[1]
                client = self.get_token(account_number, 'iam', args.user)

                existing_keys = self.get_keys(args.user, client, aws_account)

                if existing_keys:
                    for key in existing_keys:
                        self.delete_key(aws_account, args.user, key, client)

                user_client = self.get_token(account_number, 'user', args.user)

                policy_list = self.get_policies(aws_account, args.user, client)

                if policy_list:
                    for policy in policy_list:
                        self.detach_policy(args.user, user_client, policy)

                self.check_user(aws_account, args.user, client)

        else:
            raise ValueError('No suitable arguments provided.')

if __name__ == '__main__':
    DELETE = DeleteUser()
    DELETE.main()


text:
@import Foundation;

NS_ASSUME_NONNULL_BEGIN

@interface OBAURLHelpers : NSObject
+ (NSURL*)normalizeURLPath:(NSString*)path relativeToBaseURL:(NSString*)baseURLString parameters:(NSDictionary* _Nullable)params;
@end

NS_ASSUME_NONNULL_END


text:
package gov.nih.nci.caintegrator.domain.annotation.protein.bean;
import gov.nih.nci.caintegrator.domain.annotation.protein.bean.*;
import java.util.*;

/**
 * <!-- LICENSE_TEXT_START -->
 * <!-- LICENSE_TEXT_END -->
 */

  /**
   * The unique genomic identifier for a protein sequence assigned by the Universal Protein Resource
   * Knowledge Base.
   *
   */

public  class UniprotAccession

	implements java.io.Serializable
{

	private static final long serialVersionUID = 1234567890L;

    /**
   * unique identifier for the instance of UniprotAccession.
   */

    private java.lang.String id;
    /**
   * unique identifier for the instance of UniprotAccession.
   */

	public  java.lang.String getId(){
        return id;
    }
    public void setId( java.lang.String id){
        this.id = id;
    }

    /**
   * The unique genomic identifier for a protein sequence assigned by the Universal Protein Resource
   * Knowledge Base.
   *
   */

    private java.lang.String number;
    /**
   * The unique genomic identifier for a protein sequence assigned by the Universal Protein Resource
   * Knowledge Base.
   *
   */

	public  java.lang.String getNumber(){
        return number;
    }
    public void setNumber( java.lang.String number){
        this.number = number;
    }

		public boolean equals(Object obj){
			boolean eq = false;
			if(obj instanceof UniprotAccession) {
				UniprotAccession c =(UniprotAccession)obj;
				String thisId = getId();

					if(thisId != null && thisId.equals(c.getId())) {
					   eq = true;
				    }

			}
			return eq;
		}

		public int hashCode(){
			int h = 0;

			if(getId() != null) {
				h += getId().hashCode();
			}

			return h;
	}

      /**
   * A ProteinBiomarker is a protein or antibody based biological parameter that is indicative of a physiological
   * or pathological state. For example, HER2 is a biomarker used to identify risk of breast cancer.
   *
   */

    private gov.nih.nci.caintegrator.domain.annotation.protein.bean.ProteinBiomarker proteinBiomarker;
      /**
   * A ProteinBiomarker is a protein or antibody based biological parameter that is indicative of a physiological
   * or pathological state. For example, HER2 is a biomarker used to identify risk of breast cancer.
   *
   */

    public gov.nih.nci.caintegrator.domain.annotation.protein.bean.ProteinBiomarker getProteinBiomarker(){
        return proteinBiomarker;
    }

    public void setProteinBiomarker(gov.nih.nci.caintegrator.domain.annotation.protein.bean.ProteinBiomarker proteinBiomarker){
        this.proteinBiomarker = proteinBiomarker;
    }

}


text:
<?php

namespace ChatApp\Controller\Api;

use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

class ProfileController implements ControllerProviderInterface
{
    /**
     * List of properties allowed to get/set.
     *
     * @var array
     */
    protected $allowedProperties = array(
        'username',
        'email',
        'phoneNumber',
        'password',
        'name',
        'gender',
        'birthday',
        'ethnicity',
        'region',
        'interest',
        'aboutme',
        'greeting',
        'latitude',
        'longitude',
        'endroidGcmId',
        'iosDeviceId',
        'photo',
        'background',
    );

    /**
     * {@inheritDoc}
     */
    public function connect(Application $app)
    {
        $index = $app['controllers_factory'];

        $index->post('/delete', 'ChatApp\Controller\Api\ProfileController::deleteAction')->before($app['apiSecurityCheck']);
        $index->post('/report', 'ChatApp\Controller\Api\ProfileController::reportAction')->before($app['apiSecurityCheck']);
        $index->get('/get_info/{username}', 'ChatApp\Controller\Api\ProfileController::getInfoAction')->before($app['apiSecurityCheck']);
        $index->match('/get_infos', 'ChatApp\Controller\Api\ProfileController::getInfosAction')->before($app['apiSecurityCheck']);
        $index->match('/get_property', 'ChatApp\Controller\Api\ProfileController::getPropertyAction')->before($app['apiSecurityCheck']);
        $index->match('/set_property', 'ChatApp\Controller\Api\ProfileController::setPropertyAction')->before($app['apiSecurityCheck']);
        $index->match('/update_password', 'ChatApp\Controller\Api\ProfileController::updatePasswordAction')->before($app['apiSecurityCheck']);
        $index->match('/upload_photo', 'ChatApp\Controller\Api\ProfileController::uploadPhotoAction')->before($app['apiSecurityCheck']);
        $index->match('/reset_photo', 'ChatApp\Controller\Api\ProfileController::resetPhotoAction')->before($app['apiSecurityCheck']);

        return $index;
    }

    /**
     * Deletes user and all related data.
     *
     * @param string $username The User username, phone number, or email
     *
     * @Route("/api/profile/delete")
     * @method("POST")
     */
    public function deleteAction(Application $app, Request $request)
    {
        $user = $app['user'];

        // allow admin to delete any profile
        if ($app['security']->isGranted('ROLE_ADMIN')) {
            if ($username = $request->get('username')) {
                if (!$user = $app['user.repository']->findUserByUsernameOrPhoneNumberOrEmail($username)) {
                    throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
                }
            }
        }

        // unlink all images
        foreach ($user->getMoments() as $moment) {
            foreach ((array) $moment->getImages() as $filename) {
                $filename = $app['media_dir'].$filename;

                if ($filename && is_file($filename) && file_exists($filename)) {
                    unlink($filename);
                }
            }
        }

        // unlink profile photo
        if ($user->getPhoto() && file_exists($app['media_dir'].$user->getPhoto())) {
            unlink($app['media_dir'].$user->getPhoto());
        }

        // unlink profile background photo
        if ($user->getBackground() && file_exists($app['media_dir'].$user->getBackground())) {
            unlink($app['media_dir'].$user->getBackground());
        }

        $app['user.repository']->delete($user);

        return $app->json(array(
            'success' => true,
        ));
    }

    /**
     * Reports user.
     *
     * @param string $username The User username, phone number, or email
     *
     * @Route("/api/profile/report/{username}")
     * @method("POST")
     */
    public function reportAction(Application $app, Request $request)
    {
        if (!$username = $request->get('username')) {
            throw new \Exception('Invalid username.');
        }
        if (!$user = $app['user.repository']->findUserByUsernameOrPhoneNumberOrEmail($username)) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
        }

        $user->setReported(true);

        $app['user.repository']->update($user);

        return $app->json(array(
            'success' => true,
        ));
    }

    /**
     * Get infos
     *
     * @param array usernames List of usernames to retrieve profile info
     *
     * @Route("/api/profile/get_infos")
     * @method("POST")
     */
    public function getInfosAction(Application $app, Request $request)
    {
        $usernames = (array) $request->get('usernames');

        $properties = $app['user.repository']->findUsersByUsername($usernames);

        return $app->json(array(
            'success' => true,
            'data' => array(
                'properties' => $properties,
            ),
        ));
    }

    /**
     * Gets all user property and related data.
     *
     * @param string $username The User username, phone number, or email
     *
     * @return array
     *
     * @Route("/api/profile/get_info/{username}")
     * @method({"GET", "POST"})
     */
    public function getInfoAction(Application $app, Request $request)
    {
        $username = $request->get('username', $app['user']->getUsername());

        if (!$user = $app['user.repository']->findUserByUsernameOrPhoneNumberOrEmail($username)) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
        }

        // get all properties
        $properties = array();
        foreach ($this->allowedProperties as $property) {
            $properties[$property] = $user->__get($property);
        }

        // get all contacts
        $request = new Request(array(
            'type' => 'friends',
            'page' => -1,
            'limit' => -1
        ));
        $contacts = $app['api.contacts.controller']->searchAction($app, $request);
        $contacts = json_decode($contacts->getContent(), true);
        $contacts = $contacts['data']['contacts']['result'];

        // get all moments
        $request = new Request(array(
            'username' => $user->getUsername(),
            'page' => -1,
            'limit' => -1
        ));
        $moments = $app['api.moments.controller']->searchAction($app, $request);
        $moments = json_decode($moments->getContent(), true);
        $moments = $moments['data']['moments']['result'];

        // get all open messages
        $chats = $app['chat_participant.repository']->findOpenChats($user);

        // chat history
        foreach ($chats['result'] as $key => $value) {
            if (!$chat = $app['chat.repository']->find($value['chat_id'])) {
                continue;
            }

            // get recent messages
            $request = new Request(array(
                'chat_id' => $value['chat_id'],
            ));
            $messages = $app['api.messages.controller']->historyAction($app, $request);
            $messages = json_decode($messages->getContent(), true);
            $messages = $messages['data']['messages']['result'];

            $chats['result'][$key]['history'] = $messages;
        }

        return $app->json(array(
            'success' => true,
            'data' => array(
                'properties' => $properties,
                'contacts' => $contacts,
                'moments' => $moments,
                'chats' => $chats,
            ),
        ));
    }

    /**
     * Gets user property value.
     *
     * @param string $property The property name
     *
     * @return mix Property value
     *
     * @Route("/api/profile/get_property")
     * @method({"GET", "POST"})
     */
    public function getPropertyAction(Application $app, Request $request)
    {
        $property = $request->get('property');

        if (!in_array($property, $this->allowedProperties)) {
            throw new \Exception('Invalid property.');
        }

        return $app->json(array(
            'success' => true,
            'data' => array(
                'property' => $app['user']->__get($property),
            ),
        ));
    }

    /**
     * Sets the user property with a value.
     *
     * @param string $property The property name
     * @param string $value    The new value
     *
     * @return mix Property value
     *
     * @Route("/api/profile/set_property")
     * @method({"GET", "POST"})
     */
    public function setPropertyAction(Application $app, Request $request)
    {
        $property = $request->get('property');
        $value = $request->get('value');

        if (!in_array($property, $this->allowedProperties)) {
            throw new \Exception('Invalid property.');
        }

        switch ($property) {
            case 'birthday':
                $birthday = sprintf('%04d-%02d-%02d', $property['year'], $property['month'], $property['day']);
                if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $birthday)) {
                    $birthday = new \DateTime($birthday);
                    if ($birthday->diff(new \DateTime())->format('%y') < 13) {
                        throw new \Exception('User must be older than 13 year old.');
                    }
                } else {
                    throw new \Exception(sprintf('Birthday "%s" is invalid.', $birthday));
                }
                break;
        }

        $app['user']->__set($property, $value);
        $app['user.repository']->update($app['user']);

        return $app->json(array(
            'success' => true,
            'data' => array(
                'property' => $app['user']->__get($property),
            ),
        ));
    }

    /**
     * Updated user password.
     *
     * @param string $curent The current password
     * @param string $new    The new password
     *
     * @Route("/api/profile/update_password")
     * @method({"GET", "POST"})
     */
    public function updatePasswordAction(Application $app, Request $request)
    {
        $current = $request->get('current');
        $new = $request->get('new');

        if ($app['user'] != $current) {
            throw new \Exception('Invalid Password.');
        }

        $app['user']->setPassword($new);
        $app['user.repository']->update($app['user']);

        return $app->json(array(
            'success' => true,
        ));
    }

    /**
     * Uploads a user photo.
     *
     * @param string  $photo         The photo filename
     * @param Boolean $is_background Whether or not to set background photo
     *
     * @return string The saved photo filename
     *
     * @Route("/api/profile/upload_photo")
     * @method({"GET", "POST"})
     */
    public function uploadPhotoAction(Application $app, Request $request)
    {
        $filename = $request->get('photo');
        $isBackground = $request->get('is_background');

        if (!$filename || !file_exists($app['media_dir'].$filename)) {
            throw new \Exception('Missing file.');
        }

        if ($isBackground) {
            $app['user']->setBackground($filename);
        } else {
            $app['user']->setPhoto($filename);
        }
        $app['user.repository']->update($app['user']);

        return $app->json(array(
            'success' => true,
            'data' => array(
                'image' => $filename,
            ),
        ));
    }

    /**
     * Resets the user photo.
     *
     * @param string  $username      The User username, phone number, or email
     * @param Boolean $is_background Whether or not to set background photo
     *
     * @Route("/api/profile/reset_photo")
     * @method("POST")
     */
    public function resetPhotoAction(Application $app, Request $request)
    {
        $user = $app['user'];

        // allow admin to delete any profile
        if ($app['security']->isGranted('ROLE_ADMIN')) {
            if ($username = $request->get('username')) {
                if (!$user = $app['user.repository']->findUserByUsernameOrPhoneNumberOrEmail($username)) {
                    throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
                }
            }
        }

        $isBackground = $request->get('is_background');

        $filename = $isBackground
            ? $app['media_dir'].$user->getBackground()
            : $app['media_dir'].$user->getPhoto()
        ;

        if ($filename && is_file($filename) && file_exists($filename)) {
            unlink($filename);
        }

        if ($isBackground) {
            $user->setBackground(null);
        } else {
            $user->setPhoto(null);
        }
        $app['user.repository']->update($user);

        return $app->json(array(
            'success' => true,
            'data' => array(
                'image' => $filename,
            ),
        ));
    }
}


text:
package com.upscale.front.config;

/**
 * Application constants.
 */
public final class Constants {

    //Regex for acceptable logins
    public static final String LOGIN_REGEX = "^[_'.@A-Za-z0-9-]*$";
    // Spring profile for development and production, see http://jhipster.github.io/profiles/
    public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
    public static final String SPRING_PROFILE_PRODUCTION = "prod";
    // Spring profile used when deploying with Spring Cloud (used when deploying to CloudFoundry)
    public static final String SPRING_PROFILE_CLOUD = "cloud";
    // Spring profile used when deploying to Heroku
    public static final String SPRING_PROFILE_HEROKU = "heroku";
    // Spring profile used to disable swagger
    public static final String SPRING_PROFILE_NO_SWAGGER = "no-swagger";
    // Spring profile used to disable running liquibase
    public static final String SPRING_PROFILE_NO_LIQUIBASE = "no-liquibase";
    // Google Credentials Download
    public static final String GOOGLE_CREDENTIALS_URL = "https://s3.ap-south-1.amazonaws.com/upscale-mumbai/3db8973f445e.json";
    // Google Credentials File download Path
    public static final String GOOGLE_CREDENTIALS_DOWNLOAD_PATH = "/home/vcap/";
    // File download path
    public static final String FILE_TEMP_DOWNLOAD = "/home/vcap/tmp/";
    // Mifos URL
    public static final String MIFOS_URL = "https://backend.theupscale.in:8443/fineract-provider/api/v1";

    public static final String SYSTEM_ACCOUNT = "system";

    private Constants() {
    }
}


text:
package com.github.redsolo.vcm;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

public class NameValuePair {

	private Object value;
	private String name;

	public NameValuePair(Object value) {
		this.value = value;
	}
	public NameValuePair(String name, Object value) {
		this.name = name;
		this.value = value;
	}

	public Object getValue() {
		return value;
	}

	public String getName() {
		return name;
	}

	@Override
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj, false);
	}
	@Override
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this, false);
	}
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append(name);
		builder.append("={");
		builder.append(value);
		builder.append("}");
		return builder.toString();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/home_behind_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

</LinearLayout>


text:
import React from 'react';
import TimeRangePicker from './components/TimeRangePicker';

export default class App extends React.Component {
    render(){

        return (
            <div>
                <h1> Time Range Picker DEMO </h1>
                <TimeRangePicker
                    unit={30}
                    available={{start: '08:00', end: '23:00'}}
                    unavailable={[{start:'09:30', end:'10:30'}, {start:'15:00', end:'20:00'}]} />
            </div>
        );
    }
}


text:
package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"
)

func check(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

var inFilename = flag.String("i", "", "input filename")
var outFilename = flag.String("o", "", "output filename")

func main() {
	flag.Parse()

	file, err := os.Open(*inFilename)
	check(err)
	defer file.Close()

	lines := make(map[string]int)

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()

		// temporary fixup for bad lines
		pos := strings.Index(line, ",\"")
		if pos > 0 {
			line = line[0:pos]
		}

		lines[line]++
	}

	out, err := os.Create(*outFilename)
	check(err)
	defer out.Close()
	buf := bufio.NewWriter(out)

	for k, v := range lines {
		buf.WriteString(fmt.Sprintf("%06d %s\n", v, k))
	}

	buf.Flush()
	out.Sync()
}


text:
package org.ndexbio.task;

import java.io.File;

import org.ndexbio.common.access.NdexDatabase;
import org.ndexbio.common.exporter.XbelNetworkExporter;
import org.ndexbio.common.models.dao.orientdb.NetworkDocDAO;
import org.ndexbio.model.exceptions.NdexException;
import org.ndexbio.model.object.Task;
import org.ndexbio.model.object.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;

/*
 * Represents an NdexTask subclass responsible for exporting an XBEL network
 * from the NDEx database to an external file in XML format that adheres to the
 * XBEL schema. If the task type is KAMCOMPILE, the class is also responsible
 * for creating a new Task enrty in the database indicating that the new XML
 * file should be processed by the Kam compiler.
 *
 */

public class XbelExporterTask extends NdexTask {

	private String networkId;

	private static final String XBEL_FILE_EXTENSION = ".xbel";
//	private static final String EVENT_FILE_EXTENSION = ".csv";

	private Status taskStatus;

	private static final Logger logger = LoggerFactory
			.getLogger(XbelExporterTask.class);

	public XbelExporterTask(Task task) throws
		IllegalArgumentException, SecurityException, NdexException{

			super(task);
			this.networkId = this.getTask().getResource();
//			this.modelService = new NdexJVMDataModelService();

	}

	@Override
	public Task call() throws Exception {
		try {
			//TODO: Event stuff was commented out bj CJ. need to review later.
	/*		String eventFilename =
					this.resolveFilename(this.NETWORK_EXPORT_EVENT_PATH, this.EVENT_FILE_EXTENSION);
			this.eventHandler = new NdexTaskEventHandler(eventFilename); */
			this.exportNetwork();
			return this.getTask();
		} catch (InterruptedException e) {
			logger.info(this.getClass().getName() +" interupted");
			return null;
		}
	}

	/*
	 * private method to invoke the xbel network exporter
	 */
	private void exportNetwork() throws Exception{
		this.taskStatus = Status.PROCESSING;
		this.startTask();
		String exportFilename = this.resolveFilename(
				Configuration.getInstance().getNdexRoot() + "/exported-networks/",
				XbelExporterTask.XBEL_FILE_EXTENSION);

		ODatabaseDocumentTx db = null;
		try {
			try ( NetworkDocDAO dao = new NetworkDocDAO (NdexDatabase.getInstance().getAConnection())) {
				XbelNetworkExporter exporter = new XbelNetworkExporter(this.getTask().getTaskOwnerId().toString(),
						this.networkId,dao, exportFilename);
				exporter.exportNetwork();
				this.taskStatus = Status.COMPLETED;
				this.updateTaskStatus(this.taskStatus);
			}
		} finally {
			if ( db !=null ) db.close();
		}
	}

	/*
	 * private method to resolve the filename for the exported file
	 * Current convention is to use a fixed based directory under /opt/ndex
	 * add a subdriectory based on the username and use the network name plus the
	 * xbel extension as a filename
	 */
	private String resolveFilename(String path, String extension) {
		// create the directory if not exists
		if (! new File(path).exists()) {
			new File(path).mkdir();
		}

		StringBuilder sb = new StringBuilder(path);
		sb.append(File.separator);
		sb.append(this.getTask().getExternalId());
		sb.append(extension);
		return sb.toString();
	}

	protected String getNetworkId() {
		return networkId;
	}
/*
	private void setNetworkId(String networkId) {
		this.networkId = networkId;
	}  */

}


text:
import React from 'react';
import {storiesOf} from '@storybook/react';
import {action} from '@storybook/addon-actions';
import {withInfo} from '@storybook/addon-info';

import LinkWithConfirmation from 'app/components/links/linkWithConfirmation';

storiesOf('UI|Links', module).add(
  'LinkWithConfirmation',
  withInfo('A link () that opens a confirmation modal.')(() => (

      <LinkWithConfirmation
        message="Message"
        title="Title"
        onConfirm={action('confirmed')}
      >
        Link With Confirmation
      </LinkWithConfirmation>

  ))
);

storiesOf('UI|Confirm', module).add(
  'LinkWithConfirmation',
  withInfo('A link () that opens a confirmation modal.')(() => (

      <LinkWithConfirmation
        message="Message"
        title="Title"
        onConfirm={action('confirmed')}
      >
        Link With Confirmation
      </LinkWithConfirmation>

  ))
);


text:
namespace content {

// Common test results.
const char MediaBrowserTest::kEnded[] = "ENDED";
const char MediaBrowserTest::kError[] = "ERROR";
const char MediaBrowserTest::kFailed[] = "FAILED";

void MediaBrowserTest::SetUp() {
  // TODO(danakj): The GPU Video Decoder needs real GL bindings.
  // crbug.com/269087
  UseRealGLBindings();

  ContentBrowserTest::SetUp();
}

void MediaBrowserTest::RunMediaTestPage(
    const char* html_page, std::vector<StringPair>* query_params,
    const char* expected, bool http) {
  GURL gurl;
  std::string query = "";
  if (query_params != NULL && !query_params->empty()) {
    std::vector<StringPair>::const_iterator itr = query_params->begin();
    query = base::StringPrintf("%s=%s", itr->first, itr->second);
    ++itr;
    for (; itr != query_params->end(); ++itr) {
      query.append(base::StringPrintf("&%s=%s", itr->first, itr->second));
    }
  }
  if (http) {
    ASSERT_TRUE(test_server()->Start());
    gurl = test_server()->GetURL(
        base::StringPrintf("files/media/%s?%s", html_page, query.c_str()));
  } else {
    base::FilePath test_file_path = GetTestFilePath("media", html_page);
    gurl = GetFileUrlWithQuery(test_file_path, query);
  }
  RunTest(gurl, expected);
}

void MediaBrowserTest::RunTest(const GURL& gurl, const char* expected) {
  const string16 kExpected = ASCIIToUTF16(expected);
  DVLOG(1) << "Running test URL: " << gurl;
  TitleWatcher title_watcher(shell()->web_contents(), kExpected);
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16(kEnded));
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16(kError));
  title_watcher.AlsoWaitForTitle(ASCIIToUTF16(kFailed));
  NavigateToURL(shell(), gurl);

  string16 final_title = title_watcher.WaitAndGetTitle();
  EXPECT_EQ(kExpected, final_title);
}

// Tests playback and seeking of an audio or video file over file or http based
// on a test parameter.  Test starts with playback, then, after X seconds or the
// ended event fires, seeks near end of file; see player.html for details.  The
// test completes when either the last 'ended' or an 'error' event fires.
class MediaTest : public testing::WithParamInterface<bool>,
                  public MediaBrowserTest {
 public:
  // Play specified audio over http:// or file:// depending on |http| setting.
  void PlayAudio(const char* media_file, bool http) {
    PlayMedia("audio", media_file, http);
  }

  // Play specified video over http:// or file:// depending on |http| setting.
  void PlayVideo(const char* media_file, bool http) {
    PlayMedia("video", media_file, http);
  }

  // Run specified color format test with the expected result.
  void RunColorFormatTest(const char* media_file, const char* expected) {
    base::FilePath test_file_path = GetTestFilePath("media", "blackwhite.html");
    RunTest(GetFileUrlWithQuery(test_file_path, media_file), expected);
  }

  void PlayMedia(const char* tag, const char* media_file, bool http) {
    std::vector<StringPair> query_params;
    query_params.push_back(std::make_pair(tag, media_file));
    RunMediaTestPage("player.html", &query_params, kEnded, http);
  }
};

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearTheora) {
  PlayVideo("bear.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentTheora) {
  PlayVideo("bear_silent.ogv", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWebm) {
  PlayVideo("bear.webm", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentWebm) {
  PlayVideo("bear_silent.webm", GetParam());
}

#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMp4) {
  PlayVideo("bear.mp4", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearSilentMp4) {
  PlayVideo("bear_silent.mp4", GetParam());
}

// While we support the big endian (be) PCM codecs on Chromium, Quicktime seems
// to be the only creator of this format and only for .mov files.
// TODO(dalecurtis/ihf): Find or create some .wav test cases for "be" format.
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS16be) {
  PlayVideo("bear_pcm_s16be.mov", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearMovPcmS24be) {
  PlayVideo("bear_pcm_s24be.mov", GetParam());
}
#endif

#if defined(OS_CHROMEOS)
#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Mpeg4) {
  PlayVideo("bear_mpeg4_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Mpeg4Asp) {
  PlayVideo("bear_mpeg4asp_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearAviMp3Divx) {
  PlayVideo("bear_divx_mp3.avi", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAacH264) {
  PlayVideo("bear_h264_aac.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBear3gpAmrnbMpeg4) {
  PlayVideo("bear_mpeg4_amrnb.3gp", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavGsmms) {
  PlayAudio("bear_gsm_ms.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavMulaw) {
  PlayAudio("bear_mulaw.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearFlac) {
  PlayAudio("bear.flac", GetParam());
}
#endif
#endif

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm) {
  PlayAudio("bear_pcm.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm3kHz) {
  PlayAudio("bear_3kHz.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoBearWavPcm192kHz) {
  PlayAudio("bear_192kHz.wav", GetParam());
}

IN_PROC_BROWSER_TEST_P(MediaTest, VideoTulipWebm) {
  PlayVideo("tulip2.webm", GetParam());
}

// Covers tear-down when navigating away as opposed to browser exiting.
IN_PROC_BROWSER_TEST_F(MediaTest, Navigate) {
  PlayVideo("bear.ogv", false);
  NavigateToURL(shell(), GURL(kAboutBlankURL));
  EXPECT_FALSE(shell()->web_contents()->IsCrashed());
}

INSTANTIATE_TEST_CASE_P(File, MediaTest, ::testing::Values(false));
INSTANTIATE_TEST_CASE_P(Http, MediaTest, ::testing::Values(true));

IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuv420pTheora)) {
  RunColorFormatTest("yuv420p.ogv", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuv422pTheora)) {
  RunColorFormatTest("yuv422p.ogv", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuv444pTheora)) {
  // TODO(scherkus): Support YUV444 http://crbug.com/104711
  RunColorFormatTest("yuv424p.ogv", "ERROR");
}

IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuv420pVp8)) {
  RunColorFormatTest("yuv420p.webm", "ENDED");
}

#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuv420pH264)) {
  RunColorFormatTest("yuv420p.mp4", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuvj420pH264)) {
  RunColorFormatTest("yuvj420p.mp4", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuv422pH264)) {
  RunColorFormatTest("yuv422p.mp4", "ENDED");
}

IN_PROC_BROWSER_TEST_F(MediaTest, MAYBE(Yuv444pH264)) {
  // TODO(scherkus): Support YUV444 http://crbug.com/104711
  RunColorFormatTest("yuv444p.mp4", "ERROR");
}

#if defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(MediaTest, Yuv420pMpeg4) {
  RunColorFormatTest("yuv420p.avi", "ENDED");
}
#endif
#endif

}  // namespace content


text:
.font-fontello { font-family: 'fontello'; }

@font-face {
  font-family: 'fontello';
  src: url('$$ asset_url("./client/lib/embedded_fonts/font/fontello.woff2") $$') format('woff2'),
       url('$$ asset_url("./client/lib/embedded_fonts/font/fontello.woff") $$') format('woff');
  font-weight: normal;
  font-style: normal;
}