text:
class CEvoDB;
class CScheduler;

namespace llmq
{
// <signHash, quorumMember>
typedef std::pair<uint256, uint16_t> SigShareKey;

// this one does not get transmitted over the wire as it is batched inside CBatchedSigShares
class CSigShare
{
public:
    uint8_t llmqType;
    uint256 quorumHash;
    uint16_t quorumMember;
    uint256 id;
    uint256 msgHash;
    CBLSLazySignature sigShare;

    SigShareKey key;

public:
    void UpdateKey();
    const SigShareKey& GetKey() const
    {
        return key;
    }
    const uint256& GetSignHash() const
    {
        assert(!key.first.IsNull());
        return key.first;
    }
};

// Nodes will first announce a signing session with a sessionId to be used in all future P2P messages related to that
// session. We locally keep track of the mapping for each node. We also assign new sessionIds for outgoing sessions
// and send QSIGSESANN messages appropriately. All values except the max value for uint32_t are valid as sessionId
class CSigSesAnn
{
public:
    uint32_t sessionId{(uint32_t)-1};
    uint8_t llmqType;
    uint256 quorumHash;
    uint256 id;
    uint256 msgHash;

    ADD_SERIALIZE_METHODS

    template<typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action) {
        READWRITE(VARINT(sessionId));
        READWRITE(llmqType);
        READWRITE(quorumHash);
        READWRITE(id);
        READWRITE(msgHash);
    }

    std::string ToString() const;
};

class CSigSharesInv
{
public:
    uint32_t sessionId{(uint32_t)-1};
    std::vector<bool> inv;

public:
    ADD_SERIALIZE_METHODS

    template<typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action)
    {
        uint64_t invSize = inv.size();

        READWRITE(VARINT(sessionId));
        READWRITE(COMPACTSIZE(invSize));
        READWRITE(AUTOBITSET(inv, (size_t)invSize));
    }

    void Init(size_t size);
    bool IsSet(uint16_t quorumMember) const;
    void Set(uint16_t quorumMember, bool v);
    void SetAll(bool v);
    void Merge(const CSigSharesInv& inv2);

    size_t CountSet() const;
    std::string ToString() const;
};

// sent through the message QBSIGSHARES as a vector of multiple batches
class CBatchedSigShares
{
public:
    uint32_t sessionId{(uint32_t)-1};
    std::vector<std::pair<uint16_t, CBLSLazySignature>> sigShares;

public:
    ADD_SERIALIZE_METHODS;

    template<typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action)
    {
        READWRITE(VARINT(sessionId));
        READWRITE(sigShares);
    }

    std::string ToInvString() const;
};

template<typename T>
class SigShareMap
{
private:
    std::unordered_map<uint256, std::unordered_map<uint16_t, T>, StaticSaltedHasher> internalMap;

public:
    bool Add(const SigShareKey& k, const T& v)
    {
        auto& m = internalMap[k.first];
        return m.emplace(k.second, v).second;
    }

    void Erase(const SigShareKey& k)
    {
        auto it = internalMap.find(k.first);
        if (it == internalMap.end()) {
            return;
        }
        it->second.erase(k.second);
        if (it->second.empty()) {
            internalMap.erase(it);
        }
    }

    void Clear()
    {
        internalMap.clear();
    }

    bool Has(const SigShareKey& k) const
    {
        auto it = internalMap.find(k.first);
        if (it == internalMap.end()) {
            return false;
        }
        return it->second.count(k.second) != 0;
    }

    T* Get(const SigShareKey& k)
    {
        auto it = internalMap.find(k.first);
        if (it == internalMap.end()) {
            return nullptr;
        }

        auto jt = it->second.find(k.second);
        if (jt == it->second.end()) {
            return nullptr;
        }

        return &jt->second;
    }

    T& GetOrAdd(const SigShareKey& k)
    {
        T* v = Get(k);
        if (!v) {
            Add(k, T());
            v = Get(k);
        }
        return *v;
    }

    const T* GetFirst() const
    {
        if (internalMap.empty()) {
            return nullptr;
        }
        return &internalMap.begin()->second.begin()->second;
    }

    size_t Size() const
    {
        size_t s = 0;
        for (auto& p : internalMap) {
            s += p.second.size();
        }
        return s;
    }

    size_t CountForSignHash(const uint256& signHash) const
    {
        auto it = internalMap.find(signHash);
        if (it == internalMap.end()) {
            return 0;
        }
        return it->second.size();
    }

    bool Empty() const
    {
        return internalMap.empty();
    }

    const std::unordered_map<uint16_t, T>* GetAllForSignHash(const uint256& signHash)
    {
        auto it = internalMap.find(signHash);
        if (it == internalMap.end()) {
            return nullptr;
        }
        return &it->second;
    }

    void EraseAllForSignHash(const uint256& signHash)
    {
        internalMap.erase(signHash);
    }

    template<typename F>
    void EraseIf(F&& f)
    {
        for (auto it = internalMap.begin(); it != internalMap.end(); ) {
            SigShareKey k;
            k.first = it->first;
            for (auto jt = it->second.begin(); jt != it->second.end(); ) {
                k.second = jt->first;
                if (f(k, jt->second)) {
                    jt = it->second.erase(jt);
                } else {
                    ++jt;
                }
            }
            if (it->second.empty()) {
                it = internalMap.erase(it);
            } else {
                ++it;
            }
        }
    }

    template<typename F>
    void ForEach(F&& f)
    {
        for (auto& p : internalMap) {
            SigShareKey k;
            k.first = p.first;
            for (auto& p2 : p.second) {
                k.second = p2.first;
                f(k, p2.second);
            }
        }
    }
};

class CSigSharesNodeState
{
public:
    // Used to avoid holding locks too long
    struct SessionInfo
    {
        uint32_t recvSessionId;
        Consensus::LLMQType llmqType;
        uint256 quorumHash;
        uint256 id;
        uint256 msgHash;
        uint256 signHash;

        CQuorumCPtr quorum;
    };

    struct Session {
        uint32_t recvSessionId{(uint32_t)-1};
        uint32_t sendSessionId{(uint32_t)-1};

        Consensus::LLMQType llmqType;
        uint256 quorumHash;
        uint256 id;
        uint256 msgHash;
        uint256 signHash;

        CQuorumCPtr quorum;

        CSigSharesInv announced;
        CSigSharesInv requested;
        CSigSharesInv knows;
    };
    // TODO limit number of sessions per node
    std::unordered_map<uint256, Session, StaticSaltedHasher> sessions;

    std::unordered_map<uint32_t, Session*> sessionByRecvId;
    uint32_t nextSendSessionId{1};

    SigShareMap<CSigShare> pendingIncomingSigShares;
    SigShareMap<int64_t> requestedSigShares;

    bool banned{false};

    Session& GetOrCreateSessionFromShare(const CSigShare& sigShare);
    Session& GetOrCreateSessionFromAnn(const CSigSesAnn& ann);
    Session* GetSessionBySignHash(const uint256& signHash);
    Session* GetSessionByRecvId(uint32_t sessionId);
    bool GetSessionInfoByRecvId(uint32_t sessionId, SessionInfo& retInfo);

    void RemoveSession(const uint256& signHash);
};

class CSigSharesManager : public CRecoveredSigsListener
{
    static const int64_t SESSION_NEW_SHARES_TIMEOUT = 60;
    static const int64_t SIG_SHARE_REQUEST_TIMEOUT = 5;

    // we try to keep total message size below 10k
    const size_t MAX_MSGS_CNT_QSIGSESANN = 100;
    const size_t MAX_MSGS_CNT_QGETSIGSHARES = 200;
    const size_t MAX_MSGS_CNT_QSIGSHARESINV = 200;
    // 400 is the maximum quorum size, so this is also the maximum number of sigs we need to support
    const size_t MAX_MSGS_TOTAL_BATCHED_SIGS = 400;

private:
    CCriticalSection cs;

    std::thread workThread;
    CThreadInterrupt workInterrupt;

    SigShareMap<CSigShare> sigShares;

    // stores time of last receivedSigShare. Used to detect timeouts
    std::unordered_map<uint256, int64_t, StaticSaltedHasher> timeSeenForSessions;

    std::unordered_map<NodeId, CSigSharesNodeState> nodeStates;
    SigShareMap<std::pair<NodeId, int64_t>> sigSharesRequested;
    SigShareMap<bool> sigSharesToAnnounce;

    std::vector<std::tuple<const CQuorumCPtr, uint256, uint256>> pendingSigns;

    // must be protected by cs
    FastRandomContext rnd;

    int64_t lastCleanupTime{0};
    std::atomic<uint32_t> recoveredSigsCounter{0};

public:
    CSigSharesManager();
    ~CSigSharesManager();

    void StartWorkerThread();
    void StopWorkerThread();
    void RegisterAsRecoveredSigsListener();
    void UnregisterAsRecoveredSigsListener();
    void InterruptWorkerThread();

public:
    void ProcessMessage(CNode* pnode, const std::string& strCommand, CDataStream& vRecv, CConnman& connman);

    void AsyncSign(const CQuorumCPtr& quorum, const uint256& id, const uint256& msgHash);
    void Sign(const CQuorumCPtr& quorum, const uint256& id, const uint256& msgHash);
    void ForceReAnnouncement(const CQuorumCPtr& quorum, Consensus::LLMQType llmqType, const uint256& id, const uint256& msgHash);

    void HandleNewRecoveredSig(const CRecoveredSig& recoveredSig);

private:
    // all of these return false when the currently processed message should be aborted (as each message actually contains multiple messages)
    bool ProcessMessageSigSesAnn(CNode* pfrom, const CSigSesAnn& ann, CConnman& connman);
    bool ProcessMessageSigSharesInv(CNode* pfrom, const CSigSharesInv& inv, CConnman& connman);
    bool ProcessMessageGetSigShares(CNode* pfrom, const CSigSharesInv& inv, CConnman& connman);
    bool ProcessMessageBatchedSigShares(CNode* pfrom, const CBatchedSigShares& batchedSigShares, CConnman& connman);

    bool VerifySigSharesInv(NodeId from, Consensus::LLMQType llmqType, const CSigSharesInv& inv);
    bool PreVerifyBatchedSigShares(NodeId nodeId, const CSigSharesNodeState::SessionInfo& session, const CBatchedSigShares& batchedSigShares, bool& retBan);

    void CollectPendingSigSharesToVerify(size_t maxUniqueSessions,
            std::unordered_map<NodeId, std::vector<CSigShare>>& retSigShares,
            std::unordered_map<std::pair<Consensus::LLMQType, uint256>, CQuorumCPtr, StaticSaltedHasher>& retQuorums);
    bool ProcessPendingSigShares(CConnman& connman);

    void ProcessPendingSigSharesFromNode(NodeId nodeId,
            const std::vector<CSigShare>& sigShares,
            const std::unordered_map<std::pair<Consensus::LLMQType, uint256>, CQuorumCPtr, StaticSaltedHasher>& quorums,
            CConnman& connman);

    void ProcessSigShare(NodeId nodeId, const CSigShare& sigShare, CConnman& connman, const CQuorumCPtr& quorum);
    void TryRecoverSig(const CQuorumCPtr& quorum, const uint256& id, const uint256& msgHash, CConnman& connman);

private:
    bool GetSessionInfoByRecvId(NodeId nodeId, uint32_t sessionId, CSigSharesNodeState::SessionInfo& retInfo);
    CSigShare RebuildSigShare(const CSigSharesNodeState::SessionInfo& session, const CBatchedSigShares& batchedSigShares, size_t idx);

    void Cleanup();
    void RemoveSigSharesForSession(const uint256& signHash);
    void RemoveBannedNodeStates();

    void BanNode(NodeId nodeId);

    bool SendMessages();
    void CollectSigSharesToRequest(std::unordered_map<NodeId, std::unordered_map<uint256, CSigSharesInv, StaticSaltedHasher>>& sigSharesToRequest);
    void CollectSigSharesToSend(std::unordered_map<NodeId, std::unordered_map<uint256, CBatchedSigShares, StaticSaltedHasher>>& sigSharesToSend);
    void CollectSigSharesToAnnounce(std::unordered_map<NodeId, std::unordered_map<uint256, CSigSharesInv, StaticSaltedHasher>>& sigSharesToAnnounce);
    bool SignPendingSigShares();
    void WorkThreadMain();
};

extern CSigSharesManager* quorumSigSharesManager;

}

#endif //DASH_QUORUMS_SIGNING_SHARES_H


text:
namespace opencv_test {

typedef tuple<string, double, double, double> Image_RhoStep_ThetaStep_Threshold_t;
typedef perf::TestBaseWithParam<Image_RhoStep_ThetaStep_Threshold_t> Image_RhoStep_ThetaStep_Threshold;

PERF_TEST_P(Image_RhoStep_ThetaStep_Threshold, HoughLines,
            testing::Combine(
                testing::Values( "cv/shared/pic5.png", "stitching/a1.png" ),
                testing::Values( 1, 10 ),
                testing::Values( 0.01, 0.1 ),
                testing::Values( 0.5, 1.1 )
                )
            )
{
    string filename = getDataPath(get<0>(GetParam()));
    double rhoStep = get<1>(GetParam());
    double thetaStep = get<2>(GetParam());
    double threshold_ratio = get<3>(GetParam());

    Mat image = imread(filename, IMREAD_GRAYSCALE);
    if (image.empty())
        FAIL() << "Unable to load source image" << filename;

    Canny(image, image, 32, 128);

    // add some synthetic lines:
    line(image, Point(0, 0), Point(image.cols, image.rows), Scalar::all(255), 3);
    line(image, Point(image.cols, 0), Point(image.cols/2, image.rows), Scalar::all(255), 3);

    vector<Vec2f> lines;
    declare.time(60);

    int hough_threshold = (int)(std::min(image.cols, image.rows) * threshold_ratio);

    TEST_CYCLE() HoughLines(image, lines, rhoStep, thetaStep, hough_threshold);

    printf("%dx%d: %d lines\n", image.cols, image.rows, (int)lines.size());

    if (threshold_ratio < 1.0)
    {
        EXPECT_GE(lines.size(), 2u);
    }

    EXPECT_LT(lines.size(), 3000u);

#if 0
    cv::cvtColor(image,image,cv::COLOR_GRAY2BGR);
    for( size_t i = 0; i < lines.size(); i++ )
    {
        float rho = lines[i][0], theta = lines[i][1];
        Point pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        line(image, pt1, pt2, Scalar(0,0,255), 1, cv::LINE_AA);
    }
    cv::imshow("result", image);
    cv::waitKey();
#endif

    SANITY_CHECK_NOTHING();
}

PERF_TEST_P(Image_RhoStep_ThetaStep_Threshold, HoughLines3f,
            testing::Combine(
                testing::Values( "cv/shared/pic5.png", "stitching/a1.png" ),
                testing::Values( 1, 10 ),
                testing::Values( 0.01, 0.1 ),
                testing::Values( 0.5, 1.1 )
                )
            )
{
    string filename = getDataPath(get<0>(GetParam()));
    double rhoStep = get<1>(GetParam());
    double thetaStep = get<2>(GetParam());
    double threshold_ratio = get<3>(GetParam());

    Mat image = imread(filename, IMREAD_GRAYSCALE);
    if (image.empty())
        FAIL() << "Unable to load source image" << filename;

    Canny(image, image, 32, 128);

    // add some synthetic lines:
    line(image, Point(0, 0), Point(image.cols, image.rows), Scalar::all(255), 3);
    line(image, Point(image.cols, 0), Point(image.cols/2, image.rows), Scalar::all(255), 3);

    vector<Vec3f> lines;
    declare.time(60);

    int hough_threshold = (int)(std::min(image.cols, image.rows) * threshold_ratio);

    TEST_CYCLE() HoughLines(image, lines, rhoStep, thetaStep, hough_threshold);

    printf("%dx%d: %d lines\n", image.cols, image.rows, (int)lines.size());

    if (threshold_ratio < 1.0)
    {
        EXPECT_GE(lines.size(), 2u);
    }

    EXPECT_LT(lines.size(), 3000u);

    SANITY_CHECK_NOTHING();
}

} // namespace

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Pages\Doc;

use Zippy\Html\DataList\DataView;
use Zippy\Html\Form\AutocompleteTextInput;
use Zippy\Html\Form\Button;
use Zippy\Html\Form\CheckBox;
use Zippy\Html\Form\Date;
use Zippy\Html\Form\DropDownChoice;
use Zippy\Html\Form\Form;
use Zippy\Html\Form\SubmitButton;
use Zippy\Html\Form\TextInput;
use Zippy\Html\Label;
use Zippy\Html\Link\ClickLink;
use Zippy\Html\Link\SubmitLink;
use App\Entity\Customer;
use App\Entity\Item;
use App\Entity\Doc\BankStatement as BS;
use App\Entity\Doc\Document;
use App\Helper as H;
use App\Application as App;

/**
 * Банковская   выписка
 */
class BankStatement extends \App\Pages\Base
{

    public $_list = array();
    private $_doc;

    public function __construct($docid = 0) {
        parent::__construct();
        $this->add(new Form('docform'));
        $this->docform->add(new Date('document_date', time()));
        $this->docform->add(new TextInput('document_number'));

        //  $this->docform->add(new DropDownChoice('bankaccount', \ZippyERP\ERP\Entity\MoneyFund::findArray('title', "bankaccount <> '' and ftype>0")));

        $this->docform->add(new SubmitLink('addrow'))->onClick($this, 'addrowOnClick');
        $this->docform->add(new SubmitButton('savedoc'))->onClick($this, 'savedocOnClick');
        $this->docform->add(new SubmitButton('execdoc'))->onClick($this, 'savedocOnClick');
        $this->docform->add(new Button('backtolist'))->onClick($this, 'backtolistOnClick');

        $this->add(new Form('editdetail'))->setVisible(false);
        $this->editdetail->add(new DropDownChoice('editoptype', BS::getTypes(), BS::IN))->onChange($this, 'typeOnClick');
        $this->editdetail->add(new DropDownChoice('editcustomer'));
        $this->editdetail->add(new DropDownChoice('editstore', \App\Entity\Store::getList()))->setVisible(false);
        $this->editdetail->add(new CheckBox('editprepayment'))->setChecked(1);

        $this->editdetail->add(new DropDownChoice('editpayment'))->setOptionList(H::getTaxesList());
        $this->editdetail->editpayment->setVisible(false);
        $docinput = $this->editdetail->add(new AutocompleteTextInput('editdoc'));
        $docinput->onText($this, 'OnDocAutocomplete');
        $docinput->onChange($this, 'OnDocChange', true);
        $this->editdetail->add(new TextInput('editamount'))->setText("1");
        $this->editdetail->add(new TextInput('editnds'))->setText("0");
        $this->editdetail->add(new TextInput('editcomment'));
        $this->editdetail->add(new CheckBox('editnoentry'));
        $this->editdetail->add(new Button('cancelrow'))->onClick($this, 'cancelrowOnClick');
        $this->editdetail->add(new SubmitButton('submitrow'))->onClick($this, 'saverowOnClick');

        if ($docid > 0) {    //загружаем   содержимок  документа на страницу
            $this->_doc = Document::load($docid);

            $this->docform->document_number->setText($this->_doc->document_number);

            // $this->docform->bankaccount->setValue($this->_doc->headerdata['bankaccount']);
            $this->docform->document_date->setText(date('Y-m-d', $this->_doc->document_date));

            foreach ($this->_doc->detaildata as $item) {
                $entry = new Item($item);
                $this->_list[$entry->entry_id] = $entry;
            }
            $this->docform->document_date->setText(date('Y-m-d', $this->_doc->document_date));
        } else {
            $this->_doc = Document::create('BankStatement');
        }

        $this->docform->add(new DataView('detail', new \Zippy\Html\DataList\ArrayDataSource(new \Zippy\Binding\PropertyBinding($this, '_list')), $this, 'detailOnRow'));

        $this->docform->detail->Reload();

        $this->typeOnClick($this->editdetail->editoptype);
    }

    public function detailOnRow($row) {
        $item = $row->getDataItem();
        $types = BS::getTypes();
        $row->add(new Label('optype', $types[$item->optype]));
        $row->add(new Label('customer', $item->customername));
        $row->add(new Label('amount', H::famt($item->amount)));
        $row->add(new Label('document', $item->docnumber));
        $row->add(new Label('comment', $item->comment));
        $row->add(new ClickLink('delete'))->onClick($this, 'deleteOnClick');
    }

    public function deleteOnClick($sender) {
        $entry = $sender->owner->getDataItem();
        // unset($this->_entrylist[$tovar->tovar_id]);

        $this->_list = array_diff_key($this->_list, array($entry->entry_id => $this->_list[$entry->entry_id]));
        $this->docform->detail->Reload();
    }

    public function addrowOnClick($sender) {
        $this->editdetail->setVisible(true);
        $this->docform->setVisible(false);
    }

    public function saverowOnClick($sender) {

        $doc = $this->editdetail->editdoc->getKey();
        if ($doc == 0 && $this->editdetail->editdoc->isVisible()) {
            $this->setError("Не выбран  документ   ");
            return;
        }
        if ($this->editdetail->editcustomer->isVisible() && $this->editdetail->editcustomer->getValue() <= 0) {
            $this->setError('Не выбран   контрагент');
            return;
        }

        $entry = new Item();   //используем   класс  проводки  для   строки
        $entry->optype = $this->editdetail->editoptype->getValue();

        $entry->doc = $this->editdetail->editdoc->getKey();
        $entry->docnumber = $this->editdetail->editdoc->getValue();
        $entry->customer = $this->editdetail->editcustomer->getValue();
        $entry->customername = $this->editdetail->editcustomer->getValueName();
        $entry->store = $this->editdetail->editstore->getValue();
        if ($entry->store > 0) {
            $entry->customername = $this->editdetail->editstore->getValueName();
        }
        $entry->prepayment = $this->editdetail->editprepayment->isChecked();
        $entry->prepayment = $this->editdetail->editprepayment->isChecked();

        $entry->amount = $this->editdetail->editamount->getText();
        $entry->nds = $this->editdetail->editnds->getText();
        $entry->tax = $this->editdetail->editpayment->getValue();
        $entry->comment = $this->editdetail->editcomment->getText();
        $entry->noentry = $this->editdetail->editnoentry->isChecked();
        $entry->entry_id = time();
        $this->_list[$entry->entry_id] = $entry;
        $this->editdetail->setVisible(false);
        $this->docform->setVisible(true);
        $this->docform->detail->Reload();

        //очищаем  форму
        $this->editdetail->editoptype->setValue(0);
        $this->editdetail->editpayment->setValue(0);
        $this->editdetail->editdoc->setKey(0);
        $this->editdetail->editdoc->setText('');
        $this->editdetail->editcustomer->setValue(0);

        ;
        $this->editdetail->editamount->setText("0");
        $this->editdetail->editnds->setText("0");
        $this->editdetail->editcomment->setText("");
    }

    public function cancelrowOnClick($sender) {
        $this->editdetail->setVisible(false);
        $this->docform->setVisible(true);
    }

    public function savedocOnClick($sender) {
        if ($this->checkForm() == false) {
            return;
        }

        $this->_doc->detaildata = array();
        $total = 0;
        foreach ($this->_list as $entry) {
            $this->_doc->detaildata[] = $entry->getData();
            $total += $entry->amount;
        }

        $this->_doc->amount = $total;
        $this->_doc->document_date = strtotime($this->docform->document_date->getText());
        $this->_doc->document_number = $this->docform->document_number->getText();

        // $this->_doc->headerdata['bankaccount'] = $this->docform->bankaccount->getValue();
        $isEdited = $this->_doc->document_id > 0;

        $conn = \ZDB\DB::getConnect();
        $conn->BeginTrans();
        try {
            $this->_doc->save();

            if ($sender->id == 'execdoc') {
                $this->_doc->updateStatus(Document::STATE_EXECUTED);
            } else {
                $this->_doc->updateStatus($isEdited ? Document::STATE_EDITED : Document::STATE_NEW);
            }
            $conn->CommitTrans();
            App::RedirectBack();
        } catch (\Exception $ee) {
            global $logger;
            $conn->RollbackTrans();
            $this->setError($ee->getMessage());

            $logger->error($ee->getMessage() . " Документ " . $this->_doc->meta_desc);

            return;
        }
    }

    /**
     * Валидация   формы
     *
     */
    private function checkForm() {

        if (count($this->_list) == 0) {
            $this->setError("Не  введены строки");
        }

        return !$this->isError();
    }

    public function backtolistOnClick($sender) {
        App::RedirectBack();
    }

    public function typeOnClick($sender) {
        $this->editdetail->editstore->setVisible(false);
        $this->editdetail->editnds->setVisible(true);
        $this->editdetail->editdoc->setVisible(true);
        $this->editdetail->editcustomer->setVisible(true);
        $this->editdetail->editprepayment->setVisible(true);
        $this->editdetail->editnoentry->setVisible(true);
        //$list = array();
        $type = $sender->getValue();

        if ($type == BS::TAX) {

            $this->editdetail->editnds->setVisible(false);
            $this->editdetail->editdoc->setVisible(false);
            $this->editdetail->editpayment->setVisible(true);
            $this->editdetail->editcustomer->setVisible(false);
            $this->editdetail->editprepayment->setVisible(false);
        } else {
            $this->editdetail->editpayment->setVisible(false);
            $this->editdetail->editcustomer->setVisible(true);
        }
        if ($type == BS::CASHIN || $sender->getValue() == BS::CASHOUT) {
            $this->editdetail->editnds->setVisible(false);
            $this->editdetail->editdoc->setVisible(false);
            $this->editdetail->editcustomer->setVisible(false);
            $this->editdetail->editprepayment->setVisible(false);
        }
        if ($type == BS::OUT_COMMON) {
            $this->editdetail->editnds->setVisible(false);
            $this->editdetail->editdoc->setVisible(false);
            $this->editdetail->editcustomer->setVisible(false);
            $this->editdetail->editprepayment->setVisible(false);
            $this->editdetail->editpayment->setVisible(false);
        }
        if ($type == BS::OUT_CARD) {
            $this->editdetail->editnds->setVisible(false);
            $this->editdetail->editdoc->setVisible(false);
            $this->editdetail->editcustomer->setVisible(false);
            $this->editdetail->editprepayment->setVisible(false);
            $this->editdetail->editpayment->setVisible(false);
            $this->editdetail->editnoentry->setVisible(false);
            $this->editdetail->editstore->setVisible(true);
        }

        $where = "";

        $this->editdetail->editcustomer->setOptionList(Customer::findArray('customer_name', $where, 'customer_name'));
        $this->editdetail->editcustomer->setValue(0);
    }

    public function OnDocAutocomplete($sender) {
        $text = $sender->getValue();
        $answer = array();
        $conn = \ZDB\DB::getConnect();
        $sql = "select document_id,document_number from documents where document_number  like '%{$text}%' and document_id <> {$this->_doc->document_id} and state = " . Document::STATE_EXECUTED . "  order  by document_id desc  limit 0,20";
        $rs = $conn->Execute($sql);
        foreach ($rs as $row) {
            $answer[$row['document_id']] = $row['document_number'];
        }
        return $answer;
    }

    //выбран документ
    public function OnDocChange($sender) {
        $id = $sender->getKey();
        $doc = Document::load($id);
        if ($doc instanceof Document) {
            $this->editdetail->editamount->setText(H::famt($doc->amount));
            $this->editdetail->editnds->setText(H::famt($doc->headerdata['nds']));
        }
        $this->updateAjax(array('editnds', 'editamount'));
    }

}


text:
UART_HandleTypeDef UartHandle;

static void UART1_Init(void)
{
	UartHandle.Instance        = USART1;

	UartHandle.Init.BaudRate     = 115200;
	UartHandle.Init.WordLength   = UART_WORDLENGTH_8B;
	UartHandle.Init.StopBits     = UART_STOPBITS_1;
	UartHandle.Init.Parity       = UART_PARITY_NONE;
	UartHandle.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
	UartHandle.Init.Mode         = UART_MODE_TX_RX;
	UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;
	UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;

	HAL_UART_DeInit(&UartHandle);

	if(HAL_UART_Init(&UartHandle) != HAL_OK)
	{
		while(1);
	}
}

void uart_hal_init(uart_port port)
{
	switch(port)
	{
		case UART_PORT1:
			UART1_Init();
			break;
		default:
			break;
	}
}

void uart_hal_send_byte_blocking(uart_port port, uint8_t data)
{
	switch(port)
	{
		case UART_PORT1:
			while((__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_TXE) ? SET : RESET) == RESET);
			UartHandle.Instance->TDR = (uint16_t)data;
			break;
		default:
			break;
	}
}

uint8_t uart_hal_get_byte_blocking(uart_port port)
{
	switch(port)
	{
		case UART_PORT1:
			while((__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_RXNE) ? SET : RESET) == RESET);
			return UartHandle.Instance->RDR;
		default:
			return 0;
	}
}


text:
'use strict';

var expect = require('chai').expect;
var walkUp = require('../../../lib/utilities/walk-up-path');

describe('walk-up-path', function() {
  it('walks up paths', function() {
    var paths = walkUp('app/templates/my/test.hbs');

    expect(paths).to.deep.equal([
      'app/templates/my',
      'app/templates',
      'app',
    ]);
  });

  it('walks up paths beginning with a slash', function() {
    var paths = walkUp('/app/templates/my/test.hbs');

    expect(paths).to.deep.equal([
      '/app/templates/my',
      '/app/templates',
      '/app',
    ]);
  });

  it('walks up paths that have same folder names', function() {
    var paths = walkUp('foo/foo/bar.hbs');

    expect(paths).to.deep.equal([
      'foo/foo',
      'foo'
    ]);
  });
});


text:
using System;
using System.Collections.Generic;

namespace bsn.GoldParser.Semantic {
	/// <summary>
	/// This attribute is used to define specific trim rules.
	/// </summary>
	/// <seealso cref="TerminalAttribute"/>
	/// <seealso cref="RuleAttribute"/>
	[AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Class, AllowMultiple=true, Inherited=false)]
	public sealed class RuleTrimAttribute: RuleAttributeBase {
		private delegate ArgumentException ArgumentExceptionDelegate();

		private static ArgumentException SymbolNotFoundException() {
			return new ArgumentException("The specified symbol is not part of the rule", "trimSymbol");
		}

		private static ArgumentOutOfRangeException SymbolIndexOutOfRangeException() {
			return new ArgumentOutOfRangeException("trimSymbolIndex");
		}

		private readonly int trimSymbolIndex;
		private Type semanticTokenType;

		/// <summary>
		/// Initializes a new instance of the <see cref="RuleTrimAttribute"/> class.
		/// </summary>
		/// <param name="rule">The rule.</param>
		/// <param name="trimSymbol">The trim symbol name.</param>
		public RuleTrimAttribute(string rule, string trimSymbol): this(rule, -1, trimSymbol, SymbolNotFoundException) {}

		/// <summary>
		/// Initializes a new instance of the <see cref="RuleTrimAttribute"/> class.
		/// </summary>
		/// <param name="rule">The rule.</param>
		/// <param name="trimSymbolIndex">Index of the trim symbol.</param>
		public RuleTrimAttribute(string rule, int trimSymbolIndex): this(rule, trimSymbolIndex, string.Empty, SymbolIndexOutOfRangeException) {}

		private RuleTrimAttribute(string rule, int trimSymbolIndex, string trimSymbol, ArgumentExceptionDelegate notFoundException): base(rule) {
			if (trimSymbol == null) {
				throw new ArgumentNullException("trimSymbol");
			}
			int ruleHandleCount = 0;
			using (IEnumerator<string> ruleHandleEnumerator = RuleDeclarationParser.GetRuleHandleNames(ParsedRule).GetEnumerator()) {
				while (ruleHandleEnumerator.MoveNext()) {
					if (trimSymbol.Equals(ruleHandleEnumerator.Current)) {
						if (trimSymbolIndex >= 0) {
							throw new ArgumentException("The given symbol is ambigious in this rule", "trimSymbol");
						}
						trimSymbolIndex = ruleHandleCount;
					}
					ruleHandleCount++;
				}
			}
			if ((trimSymbolIndex < 0) || (trimSymbolIndex >= ruleHandleCount)) {
				throw notFoundException();
			}
			this.trimSymbolIndex = trimSymbolIndex;
		}

		/// <summary>
		/// Gets or sets the type of the semantic token for which the trim rule has been defined.
		/// </summary>
		/// <value>The type of the semantic token.</value>
		public Type SemanticTokenType {
			get {
				return semanticTokenType;
			}
			set {
				semanticTokenType = value;
			}
		}

		/// <summary>
		/// Gets the handle index of the trim symbol.
		/// </summary>
		/// <value>The handle index of the trim symbol.</value>
		public int TrimSymbolIndex {
			get {
				return trimSymbolIndex;
			}
		}
	}
}


text:
#ifndef WEBRTC_AUDIO_AUDIO_SEND_STREAM_H_
#define WEBRTC_AUDIO_AUDIO_SEND_STREAM_H_

#include <memory>
#include <vector>

#include "webrtc/base/constructormagic.h"
#include "webrtc/base/thread_checker.h"
#include "webrtc/call/audio_send_stream.h"
#include "webrtc/call/audio_state.h"
#include "webrtc/call/bitrate_allocator.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h"
#include "webrtc/voice_engine/transport_feedback_packet_loss_tracker.h"

namespace webrtc {
class VoiceEngine;
class RtcEventLog;
class RtcpBandwidthObserver;
class RtcpRttStats;
class RtpTransportControllerSendInterface;

namespace voe {
class ChannelProxy;
}  // namespace voe

namespace internal {
class AudioSendStream final : public webrtc::AudioSendStream,
                              public webrtc::BitrateAllocatorObserver,
                              public webrtc::PacketFeedbackObserver {
 public:
  AudioSendStream(const webrtc::AudioSendStream::Config& config,
                  const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
                  rtc::TaskQueue* worker_queue,
                  RtpTransportControllerSendInterface* transport,
                  BitrateAllocator* bitrate_allocator,
                  RtcEventLog* event_log,
                  RtcpRttStats* rtcp_rtt_stats,
                  const rtc::Optional<RtpState>& suspended_rtp_state);
  ~AudioSendStream() override;

  // webrtc::AudioSendStream implementation.
  void Reconfigure(const webrtc::AudioSendStream::Config& config) override;

  void Start() override;
  void Stop() override;
  bool SendTelephoneEvent(int payload_type, int payload_frequency, int event,
                          int duration_ms) override;
  void SetMuted(bool muted) override;
  webrtc::AudioSendStream::Stats GetStats() const override;

  void SignalNetworkState(NetworkState state);
  bool DeliverRtcp(const uint8_t* packet, size_t length);

  // Implements BitrateAllocatorObserver.
  uint32_t OnBitrateUpdated(uint32_t bitrate_bps,
                            uint8_t fraction_loss,
                            int64_t rtt,
                            int64_t bwe_period_ms) override;

  // From PacketFeedbackObserver.
  void OnPacketAdded(uint32_t ssrc, uint16_t seq_num) override;
  void OnPacketFeedbackVector(
      const std::vector<PacketFeedback>& packet_feedback_vector) override;

  const webrtc::AudioSendStream::Config& config() const;
  void SetTransportOverhead(int transport_overhead_per_packet);

  RtpState GetRtpState() const;

 private:
  VoiceEngine* voice_engine() const;

  // These are all static to make it less likely that (the old) config_ is
  // accessed unintentionally.
  static void ConfigureStream(AudioSendStream* stream,
                              const Config& new_config,
                              bool first_time);
  static bool SetupSendCodec(AudioSendStream* stream, const Config& new_config);
  static bool ReconfigureSendCodec(AudioSendStream* stream,
                                   const Config& new_config);
  static void ReconfigureANA(AudioSendStream* stream, const Config& new_config);
  static void ReconfigureCNG(AudioSendStream* stream, const Config& new_config);
  static void ReconfigureBitrateObserver(AudioSendStream* stream,
                                         const Config& new_config);

  void ConfigureBitrateObserver(int min_bitrate_bps, int max_bitrate_bps);
  void RemoveBitrateObserver();

  void RegisterCngPayloadType(int payload_type, int clockrate_hz);

  rtc::ThreadChecker worker_thread_checker_;
  rtc::ThreadChecker pacer_thread_checker_;
  rtc::TaskQueue* worker_queue_;
  webrtc::AudioSendStream::Config config_;
  rtc::scoped_refptr<webrtc::AudioState> audio_state_;
  std::unique_ptr<voe::ChannelProxy> channel_proxy_;
  RtcEventLog* const event_log_;

  BitrateAllocator* const bitrate_allocator_;
  RtpTransportControllerSendInterface* const transport_;
  std::unique_ptr<RtcpBandwidthObserver> bandwidth_observer_;

  rtc::CriticalSection packet_loss_tracker_cs_;
  TransportFeedbackPacketLossTracker packet_loss_tracker_
      GUARDED_BY(&packet_loss_tracker_cs_);

  RtpRtcp* rtp_rtcp_module_;
  rtc::Optional<RtpState> const suspended_rtp_state_;

  RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(AudioSendStream);
};
}  // namespace internal
}  // namespace webrtc

#endif  // WEBRTC_AUDIO_AUDIO_SEND_STREAM_H_


text:
package main

// This file is intentionally empty to force early versions of Go
// to test compilation for tests.


text:
@implementation FYRoundRectButton
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setUI];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)setUI
{
    self.clipsToBounds = YES;

}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];
    self.layer.cornerRadius = self.bounds.size.height * 0.5;
}

@end


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>gluon.shell</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

web2py Web Framework

        Package gluon ::
        Module shell

[hide private]

[frames] | no frames]

Module shell

source code

| This file is part of the web2py Web Framework | Developed by Massimo
  Di Pierro <mdipierro@cs.depaul.edu>, | limodou
  <limodou@gmail.com> and srackham <srackham@gmail.com>. |
  License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)

Web2py environment in the shell --------------------------------

        Functions
        [hide private]

          enable_autocomplete_and_history(adir,
        env)

            source code

          exec_environment(pyfile='',
        request=None,
        response=None,
        session=None)

      Environment builder and module loader.

            source code

          env(a,
        import_models=False,
        c=None,
        f=None,
        dir='',
        extra_request={})

      Returns web2py execution environment for application (a), controller
      (c), function (f).

            source code

          exec_pythonrc()

            source code

          run(appname,
        plain=False,
        import_models=False,
        startfile=None,
        bpython=False,
        python_code=False,
        cronjob=False)

      Start interactive shell or run Python script (startfile) in web2py
controller environment.

            source code

          parse_path_info(path_info,
        av=False)

      Parses path info formatted like a/c/f where c and f are optional and
      a leading `/` is accepted.

            source code

          die(msg)

            source code

          test(testpath,
        import_models=True,
        verbose=False)

      Run doctests in web2py environment.

            source code

          get_usage()

            source code

          execute_from_command_line(argv=None)

            source code

        Variables
        [hide private]

        logger = logging.getLogger("web2py")

        __package__ = 'gluon'

        Function Details
        [hide private]

exec_environment(pyfile='',
        request=None,
        response=None,
        session=None)

  	source code

Environment builder and module loader.

Builds a web2py environment and optionally executes a Python file into
  the environment.

A Storage dictionary containing the resulting environment is returned.
  The working directory must be web2py root -- this is the web2py
  default.

env(a,
        import_models=False,
        c=None,
        f=None,
        dir='',
        extra_request={})

  	source code

Returns web2py execution environment for application (a), controller
  (c), function (f). If import_models is True the exec all application
  models into the environment.

extra_request allows you to pass along any extra variables to the
  request object before your models get executed. This was mainly done to
  support web2py_utils.test_runner, however you can use it with any wrapper
  scripts that need access to the web2py environment.

run(appname,
        plain=False,
        import_models=False,
        startfile=None,
        bpython=False,
        python_code=False,
        cronjob=False)

  	source code

Start interactive shell or run Python script (startfile) in web2py
controller environment. appname is formatted like:

- a : web2py application name
- a/c : exec the controller c into the application environment

parse_path_info(path_info,
        av=False)

  	source code

Parses path info formatted like a/c/f where c and f are optional and a
  leading `/` is accepted. Return tuple (a, c, f). If invalid path_info a
  is set to None. If c or f are omitted they are set to None. If av=True,
  parse args and vars

test(testpath,
        import_models=True,
        verbose=False)

  	source code

Run doctests in web2py environment. testpath is formatted like:

- a: tests all controllers in application a
- a/c: tests controller c in application a
- a/c/f  test function f in controller c, application a

Where a, c and f are application, controller and function names
respectively. If the testpath is a file name the file is tested.
If a controller is specified models are executed by default.

         Home

         Trees

         Indices

         Help

web2py Web Framework

    Generated by Epydoc 3.0.1 on Sat Mar 29 21:55:15 2014

      http://epydoc.sourceforge.net


text:
package com.jboss.transaction.txinterop.webservices.bainterop.participant;

import com.arjuna.wst.BusinessAgreementWithCoordinatorCompletionParticipant;
import com.arjuna.wst.SystemException;
import com.arjuna.wst.WrongStateException;

class CoordinatorCompletionParticipantAdapter extends ParticipantCompletionParticipantAdapter implements BusinessAgreementWithCoordinatorCompletionParticipant
{
    public void complete()
        throws WrongStateException, SystemException
    {
    }
}


text:
from collections import OrderedDict

import yaml
import numpy as np

def create_reader(ReadClass, group):
    read_instance = ReadClass.__new__(ReadClass)
    reader = Reader(group, read_instance)
    return read_instance, reader

def crs_to_list(data, index, items_container=list):
    """
    >>> data = np.array([1, 5, 2, 6, 0, 1, 3,  4, 7])
    >>> index = np.array([0, 3, 5, 5, 8, 9])
    >>> list_of_items = crs_to_list(data, index)
    >>> print(list_of_items)
    [[1, 5, 2], [6, 0], [], [1, 3, 4], [7]]
    """
    list_of_items = []
    nitems = len(index) - 1
    for item in range(nitems):
        i0 = index[item]
        i1 = index[item+1]
        items = items_container(data[i0:i1])
        list_of_items.append(items)
    return list_of_items

def get_iterable_converter(h5obj):
    converter = h5obj.attrs.get('iterable', '')
    return eval(converter) if converter else lambda obj: obj

def read_crs(group, name):
    subgroup = group[name]
    data = subgroup['data'].value
    index = subgroup['index'].value
    t = get_iterable_converter(subgroup)
    list_of_items = crs_to_list(data, index, items_container=t)
    return list_of_items

class Reader:

    def __init__(self, group, to_object=None, to_dict=None):
        self.group = group
        self.to_object = to_object
        self.to_dict = to_dict

    def __call__(self, name, store_as='array'):
        if store_as == 'array':
            return self.array(name)
        elif store_as == 'scalar':
            return self.scalar(name)
        elif store_as == 'crs':
            return self.crs(name)
        elif store_as == 'dict':
            return self.dict(name)
        elif store_as == 'dict_crs':
            return self.dict_crs(name)
        elif store_as == 'yaml':
            return self.yaml(name)
        else:
            raise ValueError("No such type: %r" % (store_as,))

    def array(self, name):
        data = self.group[name].value
        return self._set(name, data)

    def arrays(self, *names):
        assert self.to_object is not None or self.to_dict is not None
        for name in names:
            self.array(name)

    def scalar(self, name):
        data = self.group[name][()]
        return self._set(name, data)

    def crs(self, name):
        list_of_items = read_crs(self.group, name)
        return self._set(name, list_of_items)

    def dict(self, name):
        subgroup = self.group[name]
        keys = self._read_obj_list(subgroup['keys'])
        values = self._read_obj_list(subgroup['values'])
        ordered = subgroup['ordered'][()]
        if ordered:
            d = dict(zip(keys,values))
        else:
            d = OrderedDict(zip(keys,values))
        return self._set(name, d)

    def dict_crs(self, name):
        subgroup = self.group[name]
        keys = self._read_obj_list(subgroup['keys'])
        values = read_crs(subgroup, 'values')
        ordered = subgroup['ordered'][()]
        if ordered:
            d = dict(zip(keys,values))
        else:
            d = OrderedDict(zip(keys,values))
        return self._set(name, d)

    def yaml(self, name):
        data = self.group[name].value
        obj = yaml.load(data)
        return self._set(name, obj)

    def _read_obj_list(self, dset):
        t = get_iterable_converter(dset)
        return [t(obj) for obj in dset.value]

    def _set(self, name, data):
        if self.to_object:
            setattr(self.to_object, name,  data)
        elif self.to_dict:
            self.to_dict[name] = data
        else:
            return data


text:
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.PythonTools.Intellisense {
#if !DEV14_OR_LATER
    [Export(typeof(IIntellisenseControllerProvider)), ContentType(PythonCoreConstants.ContentType), Order]
    [TextViewRole(PredefinedTextViewRoles.Analyzable)]
    [TextViewRole(PredefinedTextViewRoles.Editable)]
    class SmartTagControllerProvider : IIntellisenseControllerProvider {
        [Import]
        public ISmartTagBroker smartTagBroker = null;

        public IIntellisenseController TryCreateIntellisenseController(ITextView textView,
                                                                       IList<ITextBuffer> subjectBuffers) {
            return SmartTagController.CreateInstance(this.smartTagBroker, textView, subjectBuffers);
        }
    }
#endif
}


text:
package sim.configuration;

import sim.scheduling.graders.AvailableMemoryGrader;
import sim.scheduling.graders.Grader;

public class WorseFitConfiguration extends ProductionSimbaConfiguration
{
	@Override
	protected Grader grader()
	{
		return new AvailableMemoryGrader();
	}
}


text:
const nconf = require('nconf');
const Promise = require('bluebird');

const jwt = Promise.promisifyAll(require('jsonwebtoken'));

/**
 * @param {Object} userCtrl User controller instance
 * @param {number} userUuid The User UUID to create a token for
 * @returns {Promise} The signed token
 */
module.exports = ({
  userCtrl,
  userUuid,
}) => {
  const models = userCtrl.models;
  if (!userUuid) {
    return Promise.reject(new Error('User UUID is required.'));
  }
  return models.User.findById(userUuid, {
    attributes: ['email', 'uuid'],
    include: [{
      attributes: ['name', 'uuid'],
      model: models.Household,
      required: true,
    }, {
      attributes: ['first_name', 'last_name', 'middle_name', 'user_uuid'],
      model: models.UserProfile,
      required: true,
    }],
  }).then((user) => {
    if (!user) {
      return Promise.reject(new Error('User not found.'));
    }
    return jwt.signAsync({
      email: user.get('email'),
      first_name: user.UserProfile.get('first_name'),
      household_name: user.Household.get('name'),
      last_name: user.UserProfile.get('last_name'),
      middle_name: user.UserProfile.get('middle_name'),
      uuid: user.get('uuid'),
    }, nconf.get('jwtPrivateKey'), {
      algorithm: userCtrl.jwtAlgorithm,
      expiresIn: userCtrl.tokenExpiresIn,
    });
  });
};


text:
'''
TestStoragePath
===============

Tested platforms:

* macOS
'''

import unittest

from plyer.tests.common import platform_import, PlatformTest

class TestStoragePath(unittest.TestCase):
    '''
    TestCase for plyer.storagepath.
    '''

    @PlatformTest('macosx')
    def test_storagepath_macosx(self):
        '''
        Test macOS for plyer.storagepath.
        '''
        storagepath = platform_import(
            platform='macosx',
            module_name='storagepath'
        )

        self.assertIn('OSXStoragePath', dir(storagepath))
        storagepath = storagepath.instance()
        self.assertIn('OSXStoragePath', str(storagepath))

        path_format = 'file:///Users/'

        self.assertIn(path_format, storagepath.get_home_dir())
        self.assertIn('/', storagepath.get_root_dir())
        self.assertIn(path_format, storagepath.get_documents_dir())
        self.assertIn(path_format, storagepath.get_downloads_dir())
        self.assertIn(path_format, storagepath.get_videos_dir())
        self.assertIn(path_format, storagepath.get_music_dir())
        self.assertIn(path_format, storagepath.get_pictures_dir())
        self.assertIn(path_format, storagepath.get_application_dir())

    @PlatformTest('win')
    def test_storagepath_windows(self):
        '''
        Test win for plyer.storagepath.
        '''
        storagepath = platform_import(
            platform='win',
            module_name='storagepath'
        )

        self.assertIn('WinStoragePath', dir(storagepath))
        storagepath = storagepath.instance()
        self.assertIn('WinStoragePath', str(storagepath))

        path_format = ':\\'

        self.assertIn(path_format, storagepath.get_home_dir())
        self.assertIn(path_format, storagepath.get_root_dir())
        self.assertIn(path_format, storagepath.get_documents_dir())
        self.assertIn(path_format, storagepath.get_downloads_dir())
        self.assertIn(path_format, storagepath.get_videos_dir())
        self.assertIn(path_format, storagepath.get_music_dir())
        self.assertIn(path_format, storagepath.get_pictures_dir())
        self.assertIn(path_format, storagepath.get_application_dir())

if __name__ == '__main__':
    unittest.main()


text:
import javax.swing.*;

/// Entry point to program.
/**
 * This class acts as the entry point to the program and is responsible for parsing command line arguments
 * and setting up the GameController.  Run the program with the --help command-line parameter for more
 * information.
 *
 * @author Leonid Shamis
 */
public class Main
{
	/// Prints the commandline instructions.
	public static void helpPrinter()
	{
		System.out.println("  Command Line Parameters are as follows:");
		System.out.println("    \"--help\" : You're looking at it");
		System.out.println("    \"-p1 [AI Class Name]\" : Set player 1 to the appropriate AI");
		System.out.println("      Example: -p1 StupidAI");
		System.out.println("    \"-p2 [AI Class Name]\" : Set player 2 to the appropriate AI");
		System.out.println("      Example: -p2 RandomAI");
		System.out.println("    \"-t [Time in ms]\" : Set the maximum amount of time alloted per AI move");
		System.out.println("      Example: -t 500");
		System.out.println("    \"-w [int]\" : Set the width of the game board");
		System.out.println("      Example: -w 7");
		System.out.println("    \"-h [int]\" : Set the height of the game board");
		System.out.println("      Example: -h 6");
		System.out.println("    \"-seed [int]\" : Set the random seed of hte game");
		System.out.println("      Example: -s 1");
		System.out.println("    \"-text\" : Prints using a text-based I/O");
		System.out.println("Note: Later command-line options override earlier ones if they are incompatable\n");
	}

	/// Program startup function.
	public static void main(String[] args)
	{
		final AIModule[] players = new AIModule[2];

		// Default max ai time is 500 ms
		int AI_time = 500;
		// Default width to 7
		int width = 7;
		// Default height to 6
		int height = 6;
		boolean text = false;
		long seed = System.currentTimeMillis();

		// Parse through the command line arguements
		try
		{
			int i = 0;
			while(i < args.length)
			{
				if(args[i].equalsIgnoreCase("-p1"))
					players[0] = (AIModule) Class.forName(args[i + 1]).newInstance();
				else if(args[i].equalsIgnoreCase("-p2"))
					players[1] = (AIModule) Class.forName(args[i + 1]).newInstance();
				else if(args[i].equalsIgnoreCase("-t"))
				{
					AI_time = Integer.parseInt(args[i + 1]);
					if(AI_time <= 0)
						throw new IllegalArgumentException("AI think time must be positive");
				}
				else if(args[i].equalsIgnoreCase("-w"))
				{
					width = Integer.parseInt(args[i + 1]);
					if(width < 4)
						throw new IllegalArgumentException("Widths must be at least four.");
				}
				else if(args[i].equalsIgnoreCase("-h"))
				{
					height = Integer.parseInt(args[i + 1]);
					if(width < 4)
						throw new IllegalArgumentException("Heights must be at least four.");
				}
				else if(args[i].equalsIgnoreCase("-text"))
				{
					text = true;
					// Compensate for i += 2
					i--;
				}
				else if(args[i].equalsIgnoreCase("--help"))
				{
					helpPrinter();
					System.exit(0);
				}
//		                else if(args[i].equalsIgnoreCase("-seed"))
//               			{
//			                seed = Integer.parseInt(args[i + 1]);
//		                }:q!:q:
				else if(args[i].equalsIgnoreCase("-seed"))
				{
			                seed = Integer.parseInt(args[i + 1]);
				}
				else
					throw new IllegalArgumentException();
				i += 2;
			}
		}
		catch(ClassNotFoundException cnf)
		{
			System.err.println("Player Not Found: " + cnf.getMessage());
			System.exit(1);
		}
		catch(IndexOutOfBoundsException ioob)
		{
			System.err.println("Invalid Arguments");
			System.exit(2);
		}
		catch(NumberFormatException e)
		{
			System.err.println("Invalid Integer: " + e.getMessage());
			System.exit(3);
		}
		catch(IllegalArgumentException ia)
		{
			System.err.println("Invalid Arguments: " + ia.getMessage());
			System.exit(4);
		}
		catch(Exception e)
		{
			System.err.println("Unknown Error");
			System.exit(5);
		}

		// Create a new game
		GameStateModule game;
		try
		{
			// Load an optimized game representation if possible
			game = (GameStateModule) Class.forName("GameState_Opt" + Integer.toString(width) + "x" + Integer.toString(height)).newInstance();
		}
		catch(Exception e)
		{
			// Otherwise use a generic game representation
			game = new GameState_General(width, height);
		}

		IOModule io;

		// If told so then make a graphical version of the action
		if(text)
			io = new TextDisplay();
		else
		{
			final Display display = new Display();
			io = display;
			final JFrame frame = new JFrame("Connect Four");
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.add(display);
			frame.pack();
			frame.setVisible(true);
		}

		// Turn on the turn based system
		GameController controller = new GameController(game, io, players, AI_time);
		controller.play();
		// Print out the results of the match
		if(game.getWinner() == 0)
			System.out.println("Draw Game");
		else
			System.out.println("Player " + game.getWinner() + " won");
	}
}
/**
 * @mainpage Project 1: Connect Four
 *
 * @section intro_sec Introduction
 *
 * In this assignment, you'll write a computer program to play the classic game Connect Four.  This is a great
 * way to practice the minimax and heuristic algorithms we've covered in class, and once you've finished you'll
 * have created a silicon foe capable of defeating mere mortals like you and I...
 *
 * @section rules_sec How to Play
 *
 * Connect Four is a tic-tac-toe variant played on a 7x6 grid.  Players alternate turns dropping coins into one
 * of the seven different columns.  Unlike tic-tac-toe, Connect Four worlds are affected by gravity and you may
 * only place coins at the lowest possible positions in each column.  In other words, moves in Connect Four are
 * made by dropping the coins into the columns, rather than placing them into specific squares.
 *
 * As the name implies, the goal of Connect Four is to get four of your colored coins in a row, either horizontally,
 * diagonally, or vertically.  The first player to do so wins.  If all forty-two locations are filled without a
 * player getting four in a row, the game is a draw.
 *
 * Connect Four is known to be biased in favor of the first player, so when testing your AI make sure that you
 * have it play as both the first and second player.  A decent AI will never lose as the first player, and
 * a truly gifted AI will be able to win going second.
 *
 * @section instruct_sec Instructions
 *
 * As with PathFinder, we've provided you with a good amount of starter code to handle most of the complicated
 * setup.  The provided starter code is a working Connect Four engine that allows you to mix and match human
 * and computer opponents using the command line.  Your assignment is to create an instance of the AIModule
 * class that plays Connect Four.  To do so, you'll need to familiarize yourself with the workings of the
 * GameStateModule and AIModule classes.
 *
 * Because even a simple minimax player can play perfectly given unlimited time, in this assignment part of your
 * task will be to create a player that can work in limited time conditions.  During game play, your player will
 * have to select a move within a given time frame.  Make sure you understand what the chosenMove field of the
 * AIModule class is for before writing your player.  Take a look at MonteCarloAI for an example of how to write
 * a working AI.
 *
 * @section code_sec The Provided Framework
 *
 * The starter code we've provided will work out of the box and should require no changes on your part.  As with
 * the previous assignment, if you want to make any changes to our code, please let us know in advance.
 *
 * The Connect Four program has several different command-line switches that you can use to control how the game
 * is played.  By default, the two players are human-controlled.  You can choose which AI modules to use by using
 * the -p1 and -p2 switches to select the AIModules to use as the first and second player.  For example, to pit
 * the RandomAI player against the MonteCarloAI player, you could use:
 *
 * java Main -p1 RandomAI -p2 MonteCarloAI
 *
 * Any unspecified players will be filled in with human players.
 *
 * You can also customize how much time is available to the AI players.  By default, each computer has 500ms to
 * think.  You can use the -time switch to change this.  Use the --help switch to learn more about the options
 * available to you.
 *
 * @section grading_sec Grading
 *
 * // TODO: This!
 *
 */


text:
package com.khartec.waltz.model.system.job_log;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.khartec.waltz.model.DescriptionProvider;
import com.khartec.waltz.model.EntityKind;
import com.khartec.waltz.model.NameProvider;
import org.immutables.value.Value;

import java.time.LocalDateTime;
import java.util.Optional;

@Value.Immutable
@JsonSerialize(as = ImmutableJobLog.class)
@JsonDeserialize(as = ImmutableJobLog.class)
public abstract class JobLog implements
        NameProvider,
        DescriptionProvider {

    public abstract JobStatus status();
    public abstract EntityKind entityKind();
    public abstract LocalDateTime start();
    public abstract Optional<LocalDateTime> end();

}


text:
/**
	This CSS file contains descrptions for the front page. The goal is, to reuse these
	descriptions for other places such as showXXX.

	Author: Martin Homik
*/
#lastCreatedCompetencies, #lastModifiedCompetencies, #lastCreatedProcesses, #lastModifiedProcesses,
#lastCreatedTopics, #lastModifiedTopics, #lastCreatedTopicGroups, #lastModifiedTopicGroups, cMenuConcrete,
cMenuProcess, tMenuConcrete, tMenuAbstract {
	border-bottom: 0px dotted #999999;
	position: relative;
	width: 350px;
	/* margin: 0 0 0 60px; */
}

#lastCreatedCompetencies h3, #lastModifiedCompetencies h3, #cMenuConcrete h3 {
	background-image: url(images/64x64/ksirtet.png);
	background-repeat: no-repeat;
	background-position: left bottom;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 50px;
	text-align: right;
	font-size: large;
}

#lastCreatedProcesses h3, #lastModifiedProcesses h3, #cMenuProcess h3 {
	background-image: url(images/64x64/blockdevice.png);
	background-repeat: no-repeat;
	background-position: left bottom;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 50px;
	text-align: right;
	font-size: large;
}

#lastCreatedTopics h3, #lastModifiedTopics h3 {
	background-image: url(images/64x64/kivio.png);
	background-repeat: no-repeat;
	background-position: left bottom;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 50px;
	text-align: right;
	font-size: large;
}

#lastCreatedTopicGroups h3, #lastModifiedTopicGroups h3 {
	background-image: url(images/64x64/kivio.png);
	background-repeat: no-repeat;
	background-position: left bottom;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 50px;
	text-align: right;
	font-size: large;
}

#cMenuConcrete h3 {
	background-image: url(images/64x64/ksirtet.png);
	background-repeat: no-repeat;
	background-position: left bottom;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 70px;
	text-align: left;
	font-size: large;
}

#cMenuProcess h3 {
	background-image: url(images/64x64/blockdevice.png);
	background-repeat: no-repeat;
	background-position: left bottom;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 70px;
	text-align: left;
	font-size: large;
}

#tMenuConcrete h3 {
	background-image: url(images/64x64/kivio.png);
	background-repeat: no-repeat;
	background-position: left bottom;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 70px;
	text-align: left;
	font-size: large;
}

#tMenuAbstract h3 {
	background-image: url(images/64x64/kivio.png);
	background-repeat: no-repeat;
	background-position: left top;
	width: 286px;
	height: 66px;
	margin-bottom: -5px;
	text-indent: 70px;
	text-align: left;
	font-size: large;
}

/* not in use */
.help {
	background-image: url(images/16x16/support.png);
	background-repeat: no-repeat;
	background-position: left;
	text-align: left;
	text-indent: 50px;
	width:32px;
	height:32px;
}

.user {
	background-image: url(images/16x16/personal.png);
	background-repeat: no-repeat;
	background-position: left;
	padding-left:23px;
	text-align: left;
}


text:
<template name="Footer">

</template>


text:
import os
import re
import threading

import sublime

from .preferences_filename import preferences_filename
from .thread_progress import ThreadProgress
from .package_manager import PackageManager
from .upgraders.git_upgrader import GitUpgrader
from .upgraders.hg_upgrader import HgUpgrader
from .versions import version_comparable

class PackageInstaller():
    """
    Provides helper functionality related to installing packages
    """

    def __init__(self):
        self.manager = PackageManager()

    def make_package_list(self, ignore_actions=[], override_action=None,
            ignore_packages=[]):
        """
        Creates a list of packages and what operation would be performed for
        each. Allows filtering by the applicable action or package name.
        Returns the information in a format suitable for displaying in the
        quick panel.

        :param ignore_actions:
            A list of actions to ignore packages by. Valid actions include:
            `install`, `upgrade`, `downgrade`, `reinstall`, `overwrite`,
            `pull` and `none`. `pull` andd `none` are for Git and Hg
            repositories. `pull` is present when incoming changes are detected,
            where as `none` is selected if no commits are available. `overwrite`
            is for packages that do not include version information via the
            `package-metadata.json` file.

        :param override_action:
            A string action name to override the displayed action for all listed
            packages.

        :param ignore_packages:
            A list of packages names that should not be returned in the list

        :return:
            A list of lists, each containing three strings:
              0 - package name
              1 - package description
              2 - action; [extra info;] package url
        """

        packages = self.manager.list_available_packages()
        installed_packages = self.manager.list_packages()

        package_list = []
        for package in sorted(iter(packages.keys()), key=lambda s: s.lower()):
            if ignore_packages and package in ignore_packages:
                continue
            package_entry = [package]
            info = packages[package]
            download = info['download']

            if package in installed_packages:
                installed = True
                metadata = self.manager.get_metadata(package)
                if metadata.get('version'):
                    installed_version = metadata['version']
                else:
                    installed_version = None
            else:
                installed = False

            installed_version_name = 'v' + installed_version if \
                installed and installed_version else 'unknown version'
            new_version = 'v' + download['version']

            vcs = None
            package_dir = self.manager.get_package_dir(package)
            settings = self.manager.settings

            if override_action:
                action = override_action
                extra = ''

            else:
                if os.path.exists(os.path.join(package_dir, '.git')):
                    if settings.get('ignore_vcs_packages'):
                        continue
                    vcs = 'git'
                    incoming = GitUpgrader(settings.get('git_binary'),
                        settings.get('git_update_command'), package_dir,
                        settings.get('cache_length'), settings.get('debug')
                        ).incoming()
                elif os.path.exists(os.path.join(package_dir, '.hg')):
                    if settings.get('ignore_vcs_packages'):
                        continue
                    vcs = 'hg'
                    incoming = HgUpgrader(settings.get('hg_binary'),
                        settings.get('hg_update_command'), package_dir,
                        settings.get('cache_length'), settings.get('debug')
                        ).incoming()

                if installed:
                    if vcs:
                        if incoming:
                            action = 'pull'
                            extra = ' with ' + vcs
                        else:
                            action = 'none'
                            extra = ''
                    elif not installed_version:
                        action = 'overwrite'
                        extra = ' %s with %s' % (installed_version_name,
                            new_version)
                    else:
                        installed_version = version_comparable(installed_version)
                        download_version = version_comparable(download['version'])
                        if download_version > installed_version:
                            action = 'upgrade'
                            extra = ' to %s from %s' % (new_version,
                                installed_version_name)
                        elif download_version < installed_version:
                            action = 'downgrade'
                            extra = ' to %s from %s' % (new_version,
                                installed_version_name)
                        else:
                            action = 'reinstall'
                            extra = ' %s' % new_version
                else:
                    action = 'install'
                    extra = ' %s' % new_version
                extra += ';'

                if action in ignore_actions:
                    continue

            description = info.get('description')
            if not description:
                description = 'No description provided'
            package_entry.append(description)
            package_entry.append(action + extra + ' ' +
                re.sub('^https?://', '', info['homepage']))
            package_list.append(package_entry)
        return package_list

    def disable_packages(self, packages):
        """
        Disables one or more packages before installing or upgrading to prevent
        errors where Sublime Text tries to read files that no longer exist, or
        read a half-written file.

        :param packages: The string package name, or an array of strings
        """

        if not isinstance(packages, list):
            packages = [packages]

        # Don't disable Package Control so it does not get stuck disabled
        if 'Package Control' in packages:
            packages.remove('Package Control')

        disabled = []

        settings = sublime.load_settings(preferences_filename())
        ignored = settings.get('ignored_packages')
        if not ignored:
            ignored = []
        for package in packages:
            if not package in ignored:
                ignored.append(package)
                disabled.append(package)
        settings.set('ignored_packages', ignored)
        sublime.save_settings(preferences_filename())
        return disabled

    def reenable_package(self, package):
        """
        Re-enables a package after it has been installed or upgraded

        :param package: The string package name
        """

        settings = sublime.load_settings(preferences_filename())
        ignored = settings.get('ignored_packages')
        if not ignored:
            return
        if package in ignored:
            settings.set('ignored_packages',
                list(set(ignored) - set([package])))
            sublime.save_settings(preferences_filename())

    def on_done(self, picked):
        """
        Quick panel user selection handler - disables a package, installs or
        upgrades it, then re-enables the package

        :param picked:
            An integer of the 0-based package name index from the presented
            list. -1 means the user cancelled.
        """

        if picked == -1:
            return
        name = self.package_list[picked][0]

        if name in self.disable_packages(name):
            on_complete = lambda: self.reenable_package(name)
        else:
            on_complete = None

        thread = PackageInstallerThread(self.manager, name, on_complete)
        thread.start()
        ThreadProgress(thread, 'Installing package %s' % name,
            'Package %s successfully %s' % (name, self.completion_type))

class PackageInstallerThread(threading.Thread):
    """
    A thread to run package install/upgrade operations in so that the main
    Sublime Text thread does not get blocked and freeze the UI
    """

    def __init__(self, manager, package, on_complete):
        """
        :param manager:
            An instance of :class:`PackageManager`

        :param package:
            The string package name to install/upgrade

        :param on_complete:
            A callback to run after installing/upgrading the package
        """

        self.package = package
        self.manager = manager
        self.on_complete = on_complete
        threading.Thread.__init__(self)

    def run(self):
        try:
            self.result = self.manager.install_package(self.package)
        finally:
            if self.on_complete:
                sublime.set_timeout(self.on_complete, 1)


text:
<?php

/**
 * Finish page
 *
 * @phpstub
 *
 * @param resource $pdfdoc
 * @param string $optlist
 *
 * @return bool
 */
function PDF_end_page_ext($pdfdoc, $optlist)
{
}


text:
<?php

class locations
{
	private static $locations = null;

	public function __construct()
	{
		self::loadLocations();
	}

	/**
	 * Returns the current array of locations
	 */
	public static function getLocations()
	{
		if (null === self::$locations) self::loadLocations();

		return self::$locations;
	}

	/**
	 * Loads the current locations from the disk and stores them statically
	 */
	private static function loadLocations()
	{
		self::$locations = json_decode(file_get_contents('locations.json'));
	}

	/**
	 * Stores the locations to disk
	 */
	private function storeLocations()
	{
		usort(self::$locations, array("self", "locSortCompare"));

		file_put_contents('locations.json', json_encode(self::$locations));

		// Sleeping 1/10s to avoid race conditions and reloading the file
		usleep(100000);
		self::loadLocations();
	}

	/**
	 * Backs up the locations
	 */
	private function archiveLocations()
	{
		file_put_contents('archive/'.date('Ymd').time().'_locations.json', json_encode(self::$locations));
	}

	/**
	 * Adds a new location to the array of locations
	 *
	 * @param string $zone
	 * @param string $location
	 * @param string $link
	 */
	public function add($zone, $location, $link)
	{
		// City and location must be set
		if (!trim($zone) || !trim($location)) return 'City Name and Specific Location are Required.';

		if (trim($link) != '' && !filter_var($link, FILTER_VALIDATE_URL)) return 'Specified Link is not a Valid URL.';

		$locationObject = new stdClass();

		$locationObject->zone = ucfirst(trim($zone));
		$locationObject->location = ucfirst(trim($location));
		$locationObject->link = trim($link);
		$locationObject->id = md5(microtime());

		self::archiveLocations();

		self::$locations[] = $locationObject;

		self::storeLocations();
	}

	private static function locSortCompare($a, $b)
	{
	    return strcasecmp($a->zone.$a->location, $b->zone.$b->location);
	}

}


text:
#ifndef GrDashLinePathRenderer_DEFINED
#  define GrDashLinePathRenderer_DEFINED
#  include "src/gpu/GrPathRenderer.h"
class GrGpu;
class GrDashLinePathRenderer : public GrPathRenderer
{
private:
  CanDrawPath onCanDrawPath(const CanDrawPathArgs&) const override;
  StencilSupport onGetStencilSupport(const GrShape&) const override
  {
    return kNoSupport_StencilSupport;
  }
  bool onDrawPath(const DrawPathArgs&) override;
  sk_sp<GrGpu> fGpu;
  typedef GrPathRenderer INHERITED;
};
#endif


text:
local components = {}
local lua_object = class("lua_object")

local function load_component(name)
    if components[name] == nil then
        components[name] = require("components/" .. name)
    end
    return components[name]
end

local function get_component_name(path)
    local _, b, name = string.find(path, "[%.,%/]*(%a+_*%a+)$")
    return name
end

function lua_object:initialize(name)
    self.name = name or "lua_object"
    self.components = {}
    self.updatecomponents = {}
    self.active = true
    self.parent = nil
    self.is_disposed = false
end

function lua_object:add_component(arg)
    local name = get_component_name(arg)
    if self.components[name] then
        return self.components[name]
    end
    local cmp = load_component(arg)
    assert(cmp, "component " .. name .. " does not exist!")

    local loadedcmp = cmp(self)
    self.components[name] = loadedcmp
    loadedcmp.name = name
    if loadedcmp.start then
        loadedcmp:start()
    end

    if loadedcmp.on_update then
        if not self.updatecomponents then
            self.updatecomponents = {}
        end
        self.updatecomponents[name] = loadedcmp
    end

    return loadedcmp
end

function lua_object:remove_component(name)
    local cmp = self.components[name]
    if cmp and cmp.remove then
        cmp:remove()
    end

    self.components[name] = nil
    self.updatecomponents[name] = nil
end

function lua_object:dispose()
    table.clear(self.components)
    table.clear(self.updatecomponents)
    self.active = false
    self.is_disposed = true
end

function lua_object:register_event(event, method, ...)
    if self.event_fun == nil then
        self.event_fun = {}
    end

    local event_call = self.event_fun[event]
    if event_call == nil then
        event_call = {}
        self.event_fun[event] = event_call
    end

    event_call[method] = {...}
end

function lua_object:call_event(event)
    if self.event_fun == nil then
        return
    end

    local event_call = self.event_fun[event]
    if event_call and not self.is_disposed then
        local t
        for k, v in pairs(event_call) do
            t = type(k)
            if t == "string" then
                local fn = self[k]
                if fn then
                    fn(self, unpack(v))
                elseif t == "function" then
                    k(self, unpack(v))
                end
            end
        end
    end
    self.event_fun[event] = nil
end

function lua_object:send_message(method, ...)
    local cmps = self.components
    local fn

    fn = self[method]
    if type(fn) == "function" then
        fn(self, ...)
    end

    if cmps then
        for k, v in pairs(cmps) do
            fn = v[method]
            if type(fn) == "function" then
                fn(v, ...)
            end
        end
    end
end

function lua_object:__tostring()
    return string.format("lua_object.name = %s", self.name)
end

return lua_object


text:
package Tests;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import static Data.Constants.Urls.ADMIN_PAGE_GROUPS;

/**
 * Created by orozumniuk on 7/1/2016.
 */
public class DeleteExperienceTest extends TestBase {

    @Before
    public void deleteGroupPreconditions(){

        app.go().toStartPage(ADMIN_PAGE_GROUPS);
        app.login().toAdminsModule("barney");
        // TODO: 7/1/2016 сделать проверку на наличие группы с названием, которое содержит expNAME

    }

    @Test
    public void deleteExperience() throws Exception {
        app.go().toGroupDetailsPage("AUTO_TEST_DO_NOT_change_PLEASE");
        int countGroupBeforeDelete = app.groups().getCount();
        app.experience().deleteAllExperiencesWichFinishedWith("expNAME");
        int countGroupAfterDelete = app.groups().getCount();
        Assert.assertEquals(countGroupBeforeDelete,countGroupAfterDelete);
    }
}


text:
<?php

namespace Fi\FormazioneBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * moduliCorsoGiornata
 */
class moduliCorsoGiornata
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var integer
     */
    private $moduli_corso_id;

    /**
     * @var integer
     */
    private $giornata_id;

    /**
     * @var \Fi\FormazioneBundle\Entity\moduliCorso
     */
    private $moduli_corso;

    /**
     * @var \Fi\FormazioneBundle\Entity\giornata
     */
    private $giornata;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set moduli_corso_id
     *
     * @param integer $moduliCorsoId
     * @return moduliCorsoGiornata
     */
    public function setModuliCorsoId($moduliCorsoId)
    {
        $this->moduli_corso_id = $moduliCorsoId;

        return $this;
    }

    /**
     * Get moduli_corso_id
     *
     * @return integer
     */
    public function getModuliCorsoId()
    {
        return $this->moduli_corso_id;
    }

    /**
     * Set giornata_id
     *
     * @param integer $giornataId
     * @return moduliCorsoGiornata
     */
    public function setGiornataId($giornataId)
    {
        $this->giornata_id = $giornataId;

        return $this;
    }

    /**
     * Get giornata_id
     *
     * @return integer
     */
    public function getGiornataId()
    {
        return $this->giornata_id;
    }

    /**
     * Set moduli_corso
     *
     * @param \Fi\FormazioneBundle\Entity\moduliCorso $moduliCorso
     * @return moduliCorsoGiornata
     */
    public function setModuliCorso(\Fi\FormazioneBundle\Entity\moduliCorso $moduliCorso)
    {
        $this->moduli_corso = $moduliCorso;

        return $this;
    }

    /**
     * Get moduli_corso
     *
     * @return \Fi\FormazioneBundle\Entity\moduliCorso
     */
    public function getModuliCorso()
    {
        return $this->moduli_corso;
    }

    /**
     * Set giornata
     *
     * @param \Fi\FormazioneBundle\Entity\giornata $giornata
     * @return moduliCorsoGiornata
     */
    public function setGiornata(\Fi\FormazioneBundle\Entity\giornata $giornata)
    {
        $this->giornata = $giornata;

        return $this;
    }

    /**
     * Get giornata
     *
     * @return \Fi\FormazioneBundle\Entity\giornata
     */
    public function getGiornata()
    {
        return $this->giornata;
    }
}


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

import org.osgi.framework.namespace.IdentityNamespace;

public class Constants {
	public static final String AriesSubsystemOriginalContent = "AriesSubsystem-OriginalContent";
	public static final String BundleSymbolicName = org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME;
	public static final String BundleVersion = org.osgi.framework.Constants.BUNDLE_VERSION;
	public static final String RegionContextBundleSymbolicNamePrefix = "org.osgi.service.subsystem.region.context.";
	public static final String ResourceTypeBundle = IdentityNamespace.TYPE_BUNDLE;
	public static final String ResourceTypeFragment = IdentityNamespace.TYPE_FRAGMENT;
	public static final String ResourceTypeSynthesized = "org.apache.aries.subsystem.resource.synthesized";
	public static final String SubsystemServicePropertyRegions = "org.apache.aries.subsystem.service.regions";

	private Constants() {}
}


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f3xx_hal.h"
#include "stm32f3xx.h"
#include "stm32f3xx_it.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_adc1;
extern DMA_HandleTypeDef hdma_adc4;
extern DMA_HandleTypeDef hdma_usart1_tx;
extern UART_HandleTypeDef huart1;

/******************************************************************************/
/*            Cortex-M4 Processor Interruption and Exception Handlers         */
/******************************************************************************/

/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  HAL_SYSTICK_IRQHandler();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F3xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f3xx.s).                    */
/******************************************************************************/

/**
* @brief This function handles DMA1 channel1 global interrupt.
*/
void DMA1_Channel1_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel1_IRQn 0 */

  /* USER CODE END DMA1_Channel1_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_adc1);
  /* USER CODE BEGIN DMA1_Channel1_IRQn 1 */

  /* USER CODE END DMA1_Channel1_IRQn 1 */
}

/**
* @brief This function handles DMA1 channel4 global interrupt.
*/
void DMA1_Channel4_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel4_IRQn 0 */

  /* USER CODE END DMA1_Channel4_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart1_tx);
  /* USER CODE BEGIN DMA1_Channel4_IRQn 1 */

  /* USER CODE END DMA1_Channel4_IRQn 1 */
}

/**
* @brief This function handles USART1 global interrupt / USART1 wake-up interrupt through EXTI line 25.
*/
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */

  /* USER CODE END USART1_IRQn 0 */
  HAL_UART_IRQHandler(&huart1);
  /* USER CODE BEGIN USART1_IRQn 1 */

  /* USER CODE END USART1_IRQn 1 */
}

/**
* @brief This function handles DMA2 channel2 global interrupt.
*/
void DMA2_Channel2_IRQHandler(void)
{
  /* USER CODE BEGIN DMA2_Channel2_IRQn 0 */

  /* USER CODE END DMA2_Channel2_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_adc4);
  /* USER CODE BEGIN DMA2_Channel2_IRQn 1 */

  /* USER CODE END DMA2_Channel2_IRQn 1 */
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
package com.amazonaws.services.kinesisanalyticsv2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.kinesisanalyticsv2.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ReferenceDataSourceUpdateMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ReferenceDataSourceUpdateMarshaller {

    private static final MarshallingInfo<String> REFERENCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReferenceId").build();
    private static final MarshallingInfo<String> TABLENAMEUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TableNameUpdate").build();
    private static final MarshallingInfo<StructuredPojo> S3REFERENCEDATASOURCEUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("S3ReferenceDataSourceUpdate").build();
    private static final MarshallingInfo<StructuredPojo> REFERENCESCHEMAUPDATE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReferenceSchemaUpdate").build();

    private static final ReferenceDataSourceUpdateMarshaller instance = new ReferenceDataSourceUpdateMarshaller();

    public static ReferenceDataSourceUpdateMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ReferenceDataSourceUpdate referenceDataSourceUpdate, ProtocolMarshaller protocolMarshaller) {

        if (referenceDataSourceUpdate == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(referenceDataSourceUpdate.getReferenceId(), REFERENCEID_BINDING);
            protocolMarshaller.marshall(referenceDataSourceUpdate.getTableNameUpdate(), TABLENAMEUPDATE_BINDING);
            protocolMarshaller.marshall(referenceDataSourceUpdate.getS3ReferenceDataSourceUpdate(), S3REFERENCEDATASOURCEUPDATE_BINDING);
            protocolMarshaller.marshall(referenceDataSourceUpdate.getReferenceSchemaUpdate(), REFERENCESCHEMAUPDATE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: RestfulException.php 28702 2012-03-08 06:43:58Z yexinhao $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class Cloud_Service_Client_RestfulException extends Exception {

	public function __construct($message, $code = 0) {
		if ($message instanceof Exception) {
			parent::__construct($message->getMessage(), intval($message->getCode()));
		} else {
			parent::__construct($message, intval($code));
		}
	}

}


text:
namespace SimpleFactory
{
    public class Coffee
    {
        public Coffee(int milk, int coffee)
        {
            this.MilkContent = milk;
            this.CoffeeContent = coffee;
        }

        public int MilkContent { get; private set; }

        public int CoffeeContent { get; private set; }
    }
}


text:
namespace Evel {

TimeoutEvent::TimeoutEvent() {
    ev_loop = 0;
}

TimeoutEvent::TimeoutEvent( VtableOnly ) {
}

TimeoutEvent::~TimeoutEvent() {
}

} // namespace Evel


text:
beforeEach(function() {
    this.addMatchers({
        isNotEmptyString: function(node) {
            var str = this.actual;
            var typeOk = (typeof str) == 'string';
            var res = typeOk && ( !! str);

            this.message = function() {
                if (!typeOk) {
                    return "Expected value to be a string ";
                }
                return "Expected string to be not empty";
            };
            return res;
        },
        toBeIn: function(variants) {
            var idx = variants.indexOf(this.actual);
            this.message = function() {
                return "Expected "+ this.actual + " to equal one of those values: " + variants.join(', ');
            };
            return idx >= 0;
        },
        isNumberGreaterThenZero: function() {
            var typeOk = (typeof this.actual) == 'number';

            this.message = function() {
                if (!typeOk) {
                    return "Expected " + (typeof str) + " to be a number";
                }
                return "Expected " + this.actual + " to be greater than 0";
            };

            return (typeOk) && (this.actual > 0);
        },
        isBoolean: function() {
            this.message = function() {
                return "Expected " + (typeof this.actual) + " to be a boolean";
            };
            return (typeof this.actual) == 'boolean';
        }
    });
});


text:
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @constructor
 * @param {string} content
 */
FormatterWorker.AcornTokenizer = function(content)
{
    this._content = content;
    this._comments = [];
    this._tokenizer = acorn.tokenizer(this._content, { onComment: this._comments });
    this._lineEndings = this._content.lineEndings();
    this._lineNumber = 0;
    this._tokenLineStart = 0;
    this._tokenLineEnd = 0;
    this._nextTokenInternal();
}

/**
 * @param {!Acorn.TokenOrComment} token
 * @param {string=} values
 * @return {boolean}
 */
FormatterWorker.AcornTokenizer.punctuator = function(token, values)
{
    return token.type !== acorn.tokTypes.num &&
        token.type !== acorn.tokTypes.regexp &&
        token.type !== acorn.tokTypes.string &&
        token.type !== acorn.tokTypes.name &&
        (!values || (token.type.label.length === 1 && values.indexOf(token.type.label) !== -1));
}

/**
 * @param {!Acorn.TokenOrComment} token
 * @param {string=} keyword
 * @return {boolean}
 */
FormatterWorker.AcornTokenizer.keyword = function(token, keyword)
{
    return !!token.type.keyword && token.type !== acorn.tokTypes._true && token.type !== acorn.tokTypes._false &&
        (!keyword || token.type.keyword === keyword);
}

/**
 * @param {!Acorn.TokenOrComment} token
 * @param {string=} identifier
 * @return {boolean}
 */
FormatterWorker.AcornTokenizer.identifier = function(token, identifier)
{
    return token.type === acorn.tokTypes.name && (!identifier || token.value === identifier);
}

/**
 * @param {!Acorn.TokenOrComment} token
 * @return {boolean}
 */
FormatterWorker.AcornTokenizer.lineComment = function(token)
{
    return token.type === "Line";
}

/**
 * @param {!Acorn.TokenOrComment} token
 * @return {boolean}
 */
FormatterWorker.AcornTokenizer.blockComment = function(token)
{
    return token.type === "Block";
}

FormatterWorker.AcornTokenizer.prototype = {
    /**
     * @return {!Acorn.TokenOrComment}
     */
    _nextTokenInternal: function()
    {
        if (this._comments.length)
            return this._comments.shift();
        var token = this._bufferedToken;

        this._bufferedToken = this._tokenizer.getToken();
        return token;
    },

    /**
     * @param {number} position
     * @return {number}
     */
    _rollLineNumberToPosition: function(position)
    {
        while (this._lineNumber + 1 < this._lineEndings.length && position > this._lineEndings[this._lineNumber])
            ++this._lineNumber;
        return this._lineNumber;
    },

    /**
     * @return {?Acorn.TokenOrComment}
     */
    nextToken: function()
    {
        var token = this._nextTokenInternal();
        if (token.type === acorn.tokTypes.eof)
            return null;

        this._tokenLineStart = this._rollLineNumberToPosition(token.start);
        this._tokenLineEnd = this._rollLineNumberToPosition(token.end);
        this._tokenColumnStart = this._tokenLineStart > 0 ? token.start - this._lineEndings[this._tokenLineStart - 1] - 1 : token.start;
        return token;
    },

    /**
     * @return {?Acorn.TokenOrComment}
     */
    peekToken: function()
    {
        if (this._comments.length)
            return this._comments[0];
        return this._bufferedToken.type !== acorn.tokTypes.eof ? this._bufferedToken : null;
    },

    /**
     * @return {number}
     */
    tokenLineStart: function()
    {
        return this._tokenLineStart;
    },

    /**
     * @return {number}
     */
    tokenLineEnd: function()
    {
        return this._tokenLineEnd;
    },

    /**
     * @return {number}
     */
    tokenColumnStart: function()
    {
        return this._tokenColumnStart;
    }
}

// A dummy javascript mode which is used only by htmlmixed mode to advance
// stream until a </script> is found.
CodeMirror.defineMode("javascript", function(config, parserConfig) {
    return {
        token: function(stream, state)
        {
            return stream.next();
        }
    }
});