text:
#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <QCoreApplication>
#include <QDateTime>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QProcess>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTemporaryDir>
#include <QTextStream>
#include <QTimer>
#include <QUrl>
#include <QUrlQuery>

#include <memory>

#define Z                                                                    \
    do {                                                                     \
        if (::testing::Test::HasFatalFailure()) {                            \
            std::cerr << "At: " << __FILE__ << ":" << __LINE__ << std::endl; \
            return;                                                          \
        }                                                                    \
    } while (0)

#ifndef ZNC_BIN_DIR
#define ZNC_BIN_DIR ""
#endif

using testing::AnyOf;
using testing::Eq;
using testing::HasSubstr;

namespace {

template <typename Device>
class IO {
  public:
    IO(Device* device, bool verbose = false)
        : m_device(device), m_verbose(verbose) {}
    virtual ~IO() {}
    void ReadUntil(QByteArray pattern) {
        auto deadline = QDateTime::currentDateTime().addSecs(60);
        while (true) {
            int search = m_readed.indexOf(pattern);
            if (search != -1) {
                m_readed.remove(0, search + pattern.length());
                return;
            }
            if (m_readed.length() > pattern.length()) {
                m_readed = m_readed.right(pattern.length());
            }
            const int timeout_ms =
                QDateTime::currentDateTime().msecsTo(deadline);
            ASSERT_GT(timeout_ms, 0) << "Wanted:" << pattern.toStdString();
            ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms))
                << "Wanted: " << pattern.toStdString();
            QByteArray chunk = m_device->readAll();
            if (m_verbose) {
                std::cout << chunk.toStdString() << std::flush;
            }
            m_readed += chunk;
        }
    }
    /*
     * Reads from Device until pattern is matched and returns this pattern
     * up to and excluding the first newline. Pattern itself can contain a newline.
     * Have to use second param as the ASSERT_*'s return a non-QByteArray.
     */
    void ReadUntilAndGet(QByteArray pattern, QByteArray& match) {
        auto deadline = QDateTime::currentDateTime().addSecs(60);
        while (true) {
            int search = m_readed.indexOf(pattern);
            if (search != -1) {
                int start = 0;
                /* Don't look for what we've already found */
                if (pattern != "\n") {
                  int patlen = pattern.length();
                  start = search;
                  pattern = QByteArray("\n");
                  search = m_readed.indexOf(pattern, start + patlen);
                }
                if (search != -1) {
                  match += m_readed.mid(start, search - start);
                  m_readed.remove(0, search + 1);
                  return;
                }
                /* No newline yet, add to retvalue and trunc output */
                match += m_readed.mid(start);
                m_readed.resize(0);
            }
            if (m_readed.length() > pattern.length()) {
                m_readed = m_readed.right(pattern.length());
            }
            const int timeout_ms =
                QDateTime::currentDateTime().msecsTo(deadline);
            ASSERT_GT(timeout_ms, 0) << "Wanted:" << pattern.toStdString();
            ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms))
                << "Wanted: " << pattern.toStdString();
            QByteArray chunk = m_device->readAll();
            if (m_verbose) {
                std::cout << chunk.toStdString() << std::flush;
            }
            m_readed += chunk;
        }
    }
    void Write(QByteArray s = "", bool new_line = true) {
        if (!m_device) return;
        if (m_verbose) {
            std::cout << s.toStdString() << std::flush;
            if (new_line) {
                std::cout << std::endl;
            }
        }
        s += "\n";
        while (!s.isEmpty()) {
            auto res = m_device->write(s);
            ASSERT_NE(res, -1);
            s.remove(0, res);
        }
        FlushIfCan(m_device);
    }
    void Close() {
#ifdef __CYGWIN__
        // Qt on cygwin silently doesn't send the rest of buffer from socket
        // without this line
        sleep(1);
#endif
        m_device->disconnectFromHost();
    }

  private:
    // Need to flush QTcpSocket, and QIODevice doesn't have flush at all...
    static void FlushIfCan(QIODevice*) {}
    static void FlushIfCan(QTcpSocket* sock) { sock->flush(); }

    Device* m_device;
    bool m_verbose;
    QByteArray m_readed;
};

template <typename Device>
IO<Device> WrapIO(Device* d) {
    return IO<Device>(d);
}

using Socket = IO<QTcpSocket>;

class Process : public IO<QProcess> {
  public:
    Process(QString cmd, QStringList args,
            std::function<void(QProcess*)> setup = [](QProcess*) {})
        : IO(&m_proc, true) {
        auto env = QProcessEnvironment::systemEnvironment();
        env.insert("ZNC_DEBUG_TIMER", "1");
        // Default exit codes of sanitizers upon error:
        // ASAN - 1
        // LSAN - 23 (part of ASAN, but uses a different value)
        // TSAN - 66
        //
        // ZNC uses 1 too to report startup failure.
        // But we don't want to confuse expected startup failure with ASAN
        // error.
        env.insert("ASAN_OPTIONS", "exitcode=57");
        m_proc.setProcessEnvironment(env);
        setup(&m_proc);
        m_proc.start(cmd, args);
        EXPECT_TRUE(m_proc.waitForStarted())
            << "Failed to start ZNC, did you install it?";
    }
    ~Process() override {
        if (m_kill) m_proc.terminate();
        [this]() {
            ASSERT_TRUE(m_proc.waitForFinished());
            if (!m_allowDie) {
                ASSERT_EQ(QProcess::NormalExit, m_proc.exitStatus());
                if (m_allowLeak) {
                    ASSERT_THAT(m_proc.exitStatus(), AnyOf(Eq(23), Eq(m_exit)));
                } else {
                    ASSERT_EQ(m_exit, m_proc.exitCode());
                }
            }
        }();
    }
    void ShouldFinishItself(int code = 0) {
        m_kill = false;
        m_exit = code;
    }
    void CanDie() { m_allowDie = true; }

    // I can't do much about SWIG...
    void CanLeak() { m_allowLeak = true; }

  private:
    bool m_kill = true;
    int m_exit = 0;
    bool m_allowDie = false;
    bool m_allowLeak = false;
    QProcess m_proc;
};

void WriteConfig(QString path) {
    // clang-format off
    Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug"
                                                << "--datadir" << path
                                                << "--makeconf");
    p.ReadUntil("Listen on port");Z;          p.Write("12345");
    p.ReadUntil("Listen using SSL");Z;        p.Write();
    p.ReadUntil("IPv6");Z;                    p.Write();
    p.ReadUntil("Username");Z;                p.Write("user");
    p.ReadUntil("password");Z;                p.Write("hunter2", false);
    p.ReadUntil("Confirm");Z;                 p.Write("hunter2", false);
    p.ReadUntil("Nick [user]");Z;             p.Write();
    p.ReadUntil("Alternate nick [user_]");Z;  p.Write();
    p.ReadUntil("Ident [user]");Z;            p.Write();
    p.ReadUntil("Real name");Z;               p.Write();
    p.ReadUntil("Bind host");Z;               p.Write();
    p.ReadUntil("Set up a network?");Z;       p.Write();
    p.ReadUntil("Name [freenode]");Z;         p.Write("test");
    p.ReadUntil("Server host (host only)");Z; p.Write("127.0.0.1");
    p.ReadUntil("Server uses SSL?");Z;        p.Write();
    p.ReadUntil("6667");Z;                    p.Write();
    p.ReadUntil("password");Z;                p.Write();
    p.ReadUntil("channels");Z;                p.Write();
    p.ReadUntil("Launch ZNC now?");Z;         p.Write("no");
    p.ShouldFinishItself();
    // clang-format on
}

TEST(Config, AlreadyExists) {
    QTemporaryDir dir;
    WriteConfig(dir.path());
    Z;
    Process p(ZNC_BIN_DIR "/znc", QStringList() << "--debug"
                                                << "--datadir" << dir.path()
                                                << "--makeconf");
    p.ReadUntil("already exists");
    Z;
    p.CanDie();
}

// Can't use QEventLoop without existing QCoreApplication
class App {
  public:
    App() : m_argv(new char{}), m_app(m_argc, &m_argv) {}
    ~App() { delete m_argv; }

  private:
    int m_argc = 1;
    char* m_argv;
    QCoreApplication m_app;
};

class ZNCTest : public testing::Test {
  protected:
    void SetUp() override {
        WriteConfig(m_dir.path());
        Z;
        ASSERT_TRUE(m_server.listen(QHostAddress::LocalHost, 6667))
            << m_server.errorString().toStdString();
        Z;
    }

    Socket ConnectIRCd() {
        [this] {
            ASSERT_TRUE(m_server.waitForNewConnection(30000 /* msec */));
        }();
        return WrapIO(m_server.nextPendingConnection());
    }

    Socket ConnectClient() {
        m_clients.emplace_back();
        QTcpSocket& sock = m_clients.back();
        sock.connectToHost("127.0.0.1", 12345);
        [&] {
            ASSERT_TRUE(sock.waitForConnected())
                << sock.errorString().toStdString();
        }();
        return WrapIO(&sock);
    }

    std::unique_ptr<Process> Run() {
        return std::unique_ptr<Process>(new Process(
            ZNC_BIN_DIR "/znc", QStringList() << "--debug"
                                              << "--datadir" << m_dir.path(),
            [](QProcess* proc) {
                proc->setProcessChannelMode(QProcess::ForwardedChannels);
            }));
    }

    Socket LoginClient() {
        auto client = ConnectClient();
        client.Write("PASS :hunter2");
        client.Write("NICK nick");
        client.Write("USER user/test x x :x");
        return client;
    }

    std::unique_ptr<QNetworkReply> HttpGet(QNetworkRequest request) {
        return HandleHttp(m_network.get(request));
    }
    std::unique_ptr<QNetworkReply> HttpPost(
        QNetworkRequest request, QList<QPair<QString, QString>> data) {
        request.setHeader(QNetworkRequest::ContentTypeHeader,
                          "application/x-www-form-urlencoded");
        QUrlQuery q;
        q.setQueryItems(data);
        return HandleHttp(m_network.post(request, q.toString().toUtf8()));
    }
    std::unique_ptr<QNetworkReply> HandleHttp(QNetworkReply* reply) {
        QEventLoop loop;
        QObject::connect(reply, &QNetworkReply::finished, [&]() {
            std::cout << "Got HTTP reply" << std::endl;
            loop.quit();
        });
        QObject::connect(
            reply,
            static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(
                &QNetworkReply::error),
            [&](QNetworkReply::NetworkError e) {
                ADD_FAILURE() << reply->errorString().toStdString();
            });
        QTimer::singleShot(30000 /* msec */, &loop, [&]() {
            ADD_FAILURE() << "connection timeout";
            loop.quit();
        });
        std::cout << "Start HTTP loop.exec()" << std::endl;
        loop.exec();
        std::cout << "Finished HTTP loop.exec()" << std::endl;
        return std::unique_ptr<QNetworkReply>(reply);
    }

    void InstallModule(QString name, QString content) {
        QDir dir(m_dir.path());
        ASSERT_TRUE(dir.mkpath("modules"));
        ASSERT_TRUE(dir.cd("modules"));
        if (name.endsWith(".cpp")) {
            QTemporaryDir srcdir;
            QFile file(QDir(srcdir.path()).filePath(name));
            ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text));
            QTextStream out(&file);
            out << content;
            file.close();
            Process p(
                ZNC_BIN_DIR "/znc-buildmod", QStringList() << file.fileName(),
                [&](QProcess* proc) {
                    proc->setWorkingDirectory(dir.absolutePath());
                    proc->setProcessChannelMode(QProcess::ForwardedChannels);
                });
            p.ShouldFinishItself();
        } else {
            QFile file(dir.filePath(name));
            ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text));
            QTextStream out(&file);
            out << content;
        }
    }

    App m_app;
    QNetworkAccessManager m_network;
    QTemporaryDir m_dir;
    QTcpServer m_server;
    std::list<QTcpSocket> m_clients;
};

TEST_F(ZNCTest, Connect) {
    auto znc = Run();
    Z;

    auto ircd = ConnectIRCd();
    Z;
    ircd.ReadUntil("CAP LS");
    Z;

    auto client = ConnectClient();
    Z;
    client.Write("PASS :hunter2");
    client.Write("NICK nick");
    client.Write("USER user/test x x :x");
    client.ReadUntil("Welcome");
    Z;
    client.Close();

    client = ConnectClient();
    Z;
    client.Write("PASS :user:hunter2");
    client.Write("NICK nick");
    client.Write("USER u x x x");
    client.ReadUntil("Welcome");
    Z;
    client.Close();

    client = ConnectClient();
    Z;
    client.Write("NICK nick");
    client.Write("USER user x x x");
    client.ReadUntil("Configure your client to send a server password");
    client.Close();

    ircd.Write(":server 001 nick :Hello");
    ircd.ReadUntil("WHO");
    Z;
}

TEST_F(ZNCTest, Channel) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;

    auto client = LoginClient();
    Z;
    client.ReadUntil("Welcome");
    Z;
    client.Write("JOIN #znc");
    client.Close();

    ircd.Write(":server 001 nick :Hello");
    ircd.ReadUntil("JOIN #znc");
    Z;
    ircd.Write(":nick JOIN :#znc");
    ircd.Write(":server 353 nick #znc :nick");
    ircd.Write(":server 366 nick #znc :End of /NAMES list");
    ircd.Write(":server PING :1");
    ircd.ReadUntil("PONG 1");

    client = LoginClient();
    Z;
    client.ReadUntil(":nick JOIN :#znc");
    Z;
}

TEST_F(ZNCTest, HTTP) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto reply = HttpGet(QNetworkRequest(QUrl("http://127.0.0.1:12345/")));
    Z;
    EXPECT_THAT(reply->rawHeader("Server").toStdString(), HasSubstr("ZNC"));
}

TEST_F(ZNCTest, FixCVE20149403) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    ircd.Write(":server 001 nick :Hello");
    ircd.Write(":server 005 nick CHANTYPES=# :supports");
    ircd.Write(":server PING :1");
    ircd.ReadUntil("PONG 1");
    Z;

    QNetworkRequest request;
    request.setRawHeader("Authorization",
                         "Basic " + QByteArray("user:hunter2").toBase64());
    request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
    HttpPost(request, {
                          {"user", "user"},
                          {"network", "test"},
                          {"submitted", "1"},
                          {"name", "znc"},
                          {"enabled", "1"},
                      });
    EXPECT_THAT(HttpPost(request,
                         {
                             {"user", "user"},
                             {"network", "test"},
                             {"submitted", "1"},
                             {"name", "znc"},
                             {"enabled", "1"},
                         })
                    ->readAll()
                    .toStdString(),
                HasSubstr("Channel [#znc] already exists"));
}

TEST_F(ZNCTest, FixFixOfCVE20149403) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    ircd.Write(":server 001 nick :Hello");
    ircd.Write(":nick JOIN @#znc");
    ircd.ReadUntil("MODE @#znc");
    Z;
    ircd.Write(":server 005 nick STATUSMSG=@ :supports");
    ircd.Write(":server PING :12345");
    ircd.ReadUntil("PONG 12345");
    Z;

    QNetworkRequest request;
    request.setRawHeader("Authorization",
                         "Basic " + QByteArray("user:hunter2").toBase64());
    request.setUrl(QUrl("http://127.0.0.1:12345/mods/global/webadmin/addchan"));
    auto reply = HttpPost(request, {
                                       {"user", "user"},
                                       {"network", "test"},
                                       {"submitted", "1"},
                                       {"name", "@#znc"},
                                       {"enabled", "1"},
                                   });
    EXPECT_THAT(reply->readAll().toStdString(),
                HasSubstr("Could not add channel [@#znc]"));
}

TEST_F(ZNCTest, InvalidConfigInChan) {
    QFile conf(m_dir.path() + "/configs/znc.conf");
    ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
    QTextStream out(&conf);
    out << R"(
        <User foo>
            <Network bar>
                <Chan #baz>
                    Invalid = Line
                </Chan>
            </Network>
        </User>
    )";
    out.flush();
    auto znc = Run();
    Z;
    znc->ShouldFinishItself(1);
}

TEST_F(ZNCTest, NotifyConnectModule) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    client.Write("znc loadmod notify_connect");
    client.ReadUntil("Loaded module");
    Z;

    auto client2 = ConnectClient();
    client2.Write("PASS :hunter2");
    client2.Write("NICK nick");
    client2.Write("USER user/test x x :x");
    client.ReadUntil("NOTICE nick :*** user attached (from 127.0.0.1)");
    Z;

    auto client3 = ConnectClient();
    client3.Write("PASS :hunter2");
    client3.Write("NICK nick");
    client3.Write("USER user@identifier/test x x :x");
    client.ReadUntil(
        "NOTICE nick :*** user@identifier attached (from 127.0.0.1)");
    Z;
    client2.ReadUntil(
        "NOTICE nick :*** user@identifier attached (from 127.0.0.1)");
    Z;

    client2.Write("QUIT");
    client.ReadUntil("NOTICE nick :*** user detached (from 127.0.0.1)");
    Z;

    client3.Close();
    client.ReadUntil(
        "NOTICE nick :*** user@identifier detached (from 127.0.0.1)");
    Z;
}

TEST_F(ZNCTest, ShellModule) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    client.Write("znc loadmod shell");
    client.Write("PRIVMSG *shell :echo blahblah");
    client.ReadUntil("PRIVMSG nick :blahblah");
    Z;
    client.ReadUntil("PRIVMSG nick :znc$");
    Z;
}

TEST_F(ZNCTest, WatchModule) {
    // TODO test other messages
    // TODO test options
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    client.Write("znc loadmod watch");
    client.Write("PRIVMSG *watch :add *");
    client.ReadUntil("Adding entry:");
    Z;
    ircd.Write(":server 001 nick :Hello");
    ircd.Write(":nick JOIN :#znc");
    ircd.Write(":n!i@h PRIVMSG #znc :\001ACTION foo\001");
    client.ReadUntil(
        ":$*!watch@znc.in PRIVMSG nick :* CTCP: n [ACTION foo] to [#znc]");
}

TEST_F(ZNCTest, Modperl) {
    if (QProcessEnvironment::systemEnvironment().value(
            "DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
        return;
    }
    auto znc = Run();
    Z;
    znc->CanLeak();
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    client.Write("znc loadmod modperl");
    client.Write("znc loadmod perleval");
    client.Write("PRIVMSG *perleval :2+2");
    client.ReadUntil(":*perleval!znc@znc.in PRIVMSG nick :Result: 4");
    Z;
    client.Write("PRIVMSG *perleval :$self->GetUser->GetUserName");
    client.ReadUntil("Result: user");
    Z;
}

TEST_F(ZNCTest, Modpython) {
    if (QProcessEnvironment::systemEnvironment().value(
            "DISABLED_ZNC_PERL_PYTHON_TEST") == "1") {
        return;
    }
    auto znc = Run();
    Z;
    znc->CanLeak();
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    client.Write("znc loadmod modpython");
    client.Write("znc loadmod pyeval");
    client.Write("PRIVMSG *pyeval :2+2");
    client.ReadUntil(":*pyeval!znc@znc.in PRIVMSG nick :4");
    Z;
    client.Write("PRIVMSG *pyeval :module.GetUser().GetUserName()");
    client.ReadUntil("nick :'user'");
    Z;
    ircd.Write(":server 001 nick :Hello");
    ircd.Write(":n!u@h PRIVMSG nick :Hi\xF0, github issue #1229");
    // "replacement character"
    client.ReadUntil("Hi\xEF\xBF\xBD, github issue");
    Z;
}

TEST_F(ZNCTest, Encoding) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    ircd.Write(":server 001 nick :hello");
    // legacy
    ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
    client.ReadUntil("Hello\xE6world");
    Z;
    client.Write("PRIVMSG *controlpanel :SetNetwork Encoding $me $net UTF-8");
    client.ReadUntil("Encoding = UTF-8");
    Z;
    ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
    client.ReadUntil("Hello\xEF\xBF\xBDworld");
    Z;
    client.Write(
        "PRIVMSG *controlpanel :SetNetwork Encoding $me $net ^CP-1251");
    client.ReadUntil("Encoding = ^CP-1251");
    Z;
    ircd.Write(":n!u@h PRIVMSG nick :Hello\xE6world");
    client.ReadUntil("Hello\xD0\xB6world");
    Z;
    ircd.Write(":n!u@h PRIVMSG nick :Hello\xD0\xB6world");
    client.ReadUntil("Hello\xD0\xB6world");
    Z;
}

TEST_F(ZNCTest, BuildMod) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    QTemporaryDir srcd;
    QDir srcdir(srcd.path());
    QFile file(srcdir.filePath("testmod.cpp"));
    ASSERT_TRUE(file.open(QIODevice::WriteOnly | QIODevice::Text));
    QTextStream out(&file);
    out << R"(
        #include <znc/Modules.h>
        class TestModule : public CModule {
          public:
            MODCONSTRUCTOR(TestModule) {}
            void OnModCommand(const CString& sLine) override {
                PutModule("Lorem ipsum");
            }
        };
        MODULEDEFS(TestModule, "Test")
    )";
    file.close();
    QDir dir(m_dir.path());
    EXPECT_TRUE(dir.mkdir("modules"));
    EXPECT_TRUE(dir.cd("modules"));
    {
        Process p(ZNC_BIN_DIR "/znc-buildmod",
                  QStringList() << srcdir.filePath("file-not-found.cpp"),
                  [&](QProcess* proc) {
                      proc->setWorkingDirectory(dir.absolutePath());
                      proc->setProcessChannelMode(QProcess::ForwardedChannels);
                  });
        p.ShouldFinishItself(1);
    }
    {
        Process p(ZNC_BIN_DIR "/znc-buildmod",
                  QStringList() << srcdir.filePath("testmod.cpp"),
                  [&](QProcess* proc) {
                      proc->setWorkingDirectory(dir.absolutePath());
                      proc->setProcessChannelMode(QProcess::ForwardedChannels);
                  });
        p.ShouldFinishItself();
    }
    client.Write("znc loadmod testmod");
    client.Write("PRIVMSG *testmod :hi");
    client.ReadUntil("Lorem ipsum");
    Z;
}

TEST_F(ZNCTest, AutoAttachModule) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    InstallModule("testmod.cpp", R"(
        #include <znc/Modules.h>
        #include <znc/Client.h>
        class TestModule : public CModule {
          public:
            MODCONSTRUCTOR(TestModule) {}
            EModRet OnChanBufferPlayMessage(CMessage& Message) override {
                PutIRC("TEST " + Message.GetClient()->GetNickMask());
                return CONTINUE;
            }
        };
        MODULEDEFS(TestModule, "Test")
    )");
    Z;
    client.Write("znc loadmod testmod");
    client.Write("PRIVMSG *controlpanel :Set AutoClearChanBuffer $me no");
    client.Write("znc loadmod autoattach");
    client.Write("PRIVMSG *autoattach :Add * * *");
    client.ReadUntil("Added to list");
    Z;
    ircd.Write(":server 001 nick :Hello");
    ircd.Write(":nick JOIN :#znc");
    ircd.Write(":server 353 nick #znc :nick");
    ircd.Write(":server 366 nick #znc :End of /NAMES list");
    ircd.Write(":foo PRIVMSG #znc :hi");
    client.ReadUntil(":foo PRIVMSG");
    Z;
    client.Write("detach #znc");
    client.ReadUntil("Detached");
    Z;
    ircd.Write(":foo PRIVMSG #znc :hello");
    ircd.ReadUntil("TEST");
    Z;
    client.ReadUntil("hello");
    Z;
}

TEST_F(ZNCTest, KeepNickModule) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    client.Write("znc loadmod keepnick");
    client.ReadUntil("Loaded module");
    Z;
    ircd.ReadUntil("NICK user");
    ircd.Write(":server 433 * nick :Nickname is already in use.");
    ircd.ReadUntil("NICK user_");
    Z;
    ircd.Write(":server 001 user_ :Hello");
    client.ReadUntil("Connected!");
    Z;
    ircd.ReadUntil("NICK user");
    Z;
    ircd.Write(":server 435 user_ user #error :Nope :-P");
    client.ReadUntil(
        ":*keepnick!znc@znc.in PRIVMSG user_ "
        ":Unable to obtain nick user: Nope :-P, #error");
}

TEST_F(ZNCTest, ModuleCSRFOverride) {
    auto znc = Run();
    Z;
    auto ircd = ConnectIRCd();
    Z;
    auto client = LoginClient();
    Z;
    client.Write("znc loadmod samplewebapi");
    client.ReadUntil("Loaded module");
    Z;
    auto request = QNetworkRequest(QUrl("http://127.0.0.1:12345/mods/global/samplewebapi/"));
    auto reply = HttpPost(request, {
        {"text", "ipsum"}
    })->readAll().toStdString();
    Z;
    EXPECT_THAT(reply, HasSubstr("ipsum"));
}

TEST_F(ZNCTest, ModuleCrypt) {
    QFile conf(m_dir.path() + "/configs/znc.conf");
    ASSERT_TRUE(conf.open(QIODevice::Append | QIODevice::Text));
    QTextStream(&conf) << "ServerThrottle = 1\n";
    auto znc = Run();
    Z;
    auto ircd1 = ConnectIRCd();
    Z;
    auto client1 = LoginClient();
    Z;
    client1.Write("znc loadmod controlpanel");
    client1.Write("PRIVMSG *controlpanel :CloneUser user user2");
    client1.ReadUntil("User user2 added!");
    client1.Write("PRIVMSG *controlpanel :Set Nick user2 nick2");
    Z;
    client1.Write("znc loadmod crypt");
    client1.ReadUntil("Loaded module");
    Z;
    auto ircd2 = ConnectIRCd();
    Z;
    auto client2 = ConnectClient();
    client2.Write("PASS user2:hunter2");
    client2.Write("NICK nick2");
    client2.Write("USER user2/test x x :x");
    Z;
    client2.Write("znc loadmod crypt");
    client2.ReadUntil("Loaded module");
    Z;

    client1.Write("PRIVMSG *crypt :keyx nick2");
    client1.ReadUntil("Sent my DH1080 public key to nick2");
    Z;

    QByteArray pub1("");
    ircd1.ReadUntilAndGet("NOTICE nick2 :DH1080_INIT ", pub1);
    ircd2.Write(":user!user@user/test " + pub1);
    Z;

    client2.ReadUntil("Received DH1080 public key from user");
    Z;
    client2.ReadUntil("Key for user successfully set.");
    Z;

    QByteArray pub2("");
    ircd2.ReadUntilAndGet("NOTICE user :DH1080_FINISH ", pub2);
    ircd1.Write(":nick2!user2@user2/test " + pub2);
    Z;

    client1.ReadUntil("Key for nick2 successfully set.");
    Z;

    client1.Write("PRIVMSG *crypt :listkeys");
    QByteArray key1("");
    client1.ReadUntilAndGet("| nick2  | ", key1);
    Z;
    client2.Write("PRIVMSG *crypt :listkeys");
    QByteArray key2("");
    client2.ReadUntilAndGet("| user   | ", key2);
    Z;
    ASSERT_EQ(key1.mid(11), key2.mid(11));
    client1.Write("PRIVMSG .nick2 :Hello");
    QByteArray secretmsg;
    ircd1.ReadUntilAndGet("PRIVMSG nick2 :+OK ", secretmsg);
    Z;
    ircd2.Write(":user!user@user/test " + secretmsg);
    client2.ReadUntil("Hello");
    Z;
}

}  // namespace


text:
package org.griphyn.vdl.directive;

import edu.isi.pegasus.common.util.Separator;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.MissingResourceException;
import org.griphyn.vdl.classes.*;
import org.griphyn.vdl.dax.ADAG;
import org.griphyn.vdl.dbschema.*;
import org.griphyn.vdl.router.*;

/**
 * This class generates the DAX per the request for LFNs or DVs
 *
 * @author Jens-S. Vöckler
 * @author Yong Zhao
 * @version $Revision$
 * @see org.griphyn.vdl.router.Route
 * @see org.griphyn.vdl.router.BookKeeper
 * @see org.griphyn.vdl.dbschema.VDC
 */
public class Explain extends Directive {
    /** Maintains the link to the VDC. */
    private DatabaseSchema m_dbschema = null;

    /** Provides a routing object to traverse dependencies in the VDC. */
    private Route m_route = null;

    /** Helpful object for routing requests. */
    private BookKeeper m_state = null;

    /**
     * Constructor
     *
     * @throws java.io.IOException exception
     */
    public Explain() throws IOException, MissingResourceException {
        super();
    }

    /**
     * Constructor: Sets the database schema instance, and initializes the internal Route
     *  accordingly.
     *
     * @param dbs the database schema instance
     * @throws java.io.IOException exception
     * @see org.griphyn.vdl.router.Route
     * @see org.griphyn.vdl.router.BookKeeper
     */
    public Explain(DatabaseSchema dbs) throws IOException, MissingResourceException {
        m_dbschema = dbs;
        m_route = new Route(m_dbschema);
        m_state = new BookKeeper();
    }

    /**
     * Sets database schema, and initialzes the internal Route accordingly.
     *
     * @param dbs the database schema instance
     * @see org.griphyn.vdl.router.Route
     * @see org.griphyn.vdl.router.BookKeeper
     */
    public void setDatabaseSchema(DatabaseSchema dbs) {
        m_dbschema = dbs;
        m_route = new Route(m_dbschema);
        m_state = new BookKeeper();
    }

    /**
     * Allows to limit the maximum depth that the router is willing to go.
     *
     * @param depth is the maximum depth. Use Integer.MAX_VALUE for (virtually) unlimited depth.
     */
    public void setMaximumDepth(int depth) {
        m_route.setMaximumDepth(depth);
    }

    /**
     * Requests a data product logical filename.As a result, the complete build-style DAG for
     * producing the requested filename will be constructed.
     *
     * @param filename is the name of the requested LFN.
     * @return true if the request is successful
     * @throws java.sql.SQLException exception
     * @see #requestLFN( java.util.Collection )
     * @see org.griphyn.vdl.router.BookKeeper
     */
    public boolean requestLFN(String filename) throws java.sql.SQLException {
        ArrayList al = new ArrayList(1);
        al.add(filename);
        return requestLFN(al);
    }

    /**
     * Requests a set of logical filenames.As a result, the complete build-style DAG for producing
     * the requested LFNs will be constructed.
     *
     * @param filenames is the list or set of logical filenames requested.
     * @return true if the request is successful
     * @throws java.sql.SQLException exception
     * @see org.griphyn.vdl.router.Route#requestLfn( Collection, BookKeeper )
     * @see org.griphyn.vdl.router.BookKeeper
     */
    public boolean requestLFN(java.util.Collection filenames) throws java.sql.SQLException {
        // FIXME: What about previous results?
        m_route.requestLfn(filenames, m_state);
        return (m_state != null && !m_state.isEmpty());
    }

    /**
     * Requests for a specific derivation. As a result, a build-style DAG will be produced and
     * maintained in the book-keeping structure.
     *
     * @param namespace is the namespace of the derivation.
     * @param name is the name of the derivation.
     * @param version is the version of the derivation.
     * @return true if the request is successful
     * @see org.griphyn.vdl.router.Route#requestDerivation( String, String, String, BookKeeper )
     * @see org.griphyn.vdl.router.BookKeeper
     */
    public boolean requestDerivation(String namespace, String name, String version) {
        return m_route.requestDerivation(namespace, name, version, m_state);
    }

    /**
     * Requests for a specific derivation. As a result, a build-style DAG will be produced and
     * maintained in the book-keeping structure.
     *
     * @param fqdn is the fully qualified name of the derivation.
     * @return true if the request is successful
     * @see edu.isi.pegasus.common.util.Separator#splitFQDI( String )
     * @see org.griphyn.vdl.router.Route#requestDerivation( String, String, String, BookKeeper )
     * @see org.griphyn.vdl.router.BookKeeper
     */
    public boolean requestDerivation(String fqdn) throws IllegalArgumentException {
        String[] name = Separator.splitFQDI(fqdn);
        return m_route.requestDerivation(name[0], name[1], name[2], m_state);
    }

    /**
     * Requests a set of specific derivations. As a result, a build-style DAG will be produced and
     * maintained in the book-keeping structure.
     *
     * @param symbolicList is a collecting of symbolic FQDN derivation triples.
     * @return true if the request is successful
     * @see edu.isi.pegasus.common.util.Separator#splitFQDI( String )
     * @see org.griphyn.vdl.router.Route#requestDerivation( Collection, BookKeeper )
     * @see org.griphyn.vdl.router.BookKeeper
     */
    public boolean requestDerivation(java.util.Collection symbolicList)
            throws IllegalArgumentException {
        return m_route.requestDerivation(symbolicList, m_state);
    }

    /**
     * Writes the abstract DAX from the accumulated results.
     *
     * @param writer the output writer
     * @param label the label of the dax
     * @throws java.io.IOException exception
     * @see org.griphyn.vdl.router.BookKeeper#getDAX
     */
    public void writeDAX(Writer writer, String label) throws IOException {
        this.writeDAX(writer, label, null);
    }

    /**
     * Writes the abstract DAX with a namespace prefix.
     *
     * @param writer the output writer
     * @param label the label of the dax
     * @param xmlns the xml namespace prefix
     * @throws java.io.IOException exception
     * @see org.griphyn.vdl.router.BookKeeper#getDAX
     */
    public void writeDAX(Writer writer, String label, String xmlns) throws IOException {
        if (m_state == null || m_state.isEmpty()) {
            // whatever we did, there are no results for us
            m_logger.log("explain", 0, "WARNING: The requested DAX is empty!\n");
        } else {
            ADAG dax = m_state.getDAX(label == null ? "test" : label);
            m_logger.log(
                    "explain",
                    2,
                    "DAX has "
                            + dax.getFilenameCount()
                            + " LFNs, "
                            + dax.getJobCount()
                            + " jobs, "
                            + dax.getChildCount()
                            + " deps.");
            dax.toXML(writer, "", xmlns);
        }
    }

    /**
     * Checks if the result is empty or not.
     *
     * @return true, if the result is undefined or empty, false otherwise.
     */
    public boolean isEmpty() {
        return (m_state == null || m_state.isEmpty());
    }
}

redpajama_set_name: RedPajamaGithub


text:
{
    onFormIdentified: function(formId) {
        if(window.addEventListener) {
            (function(formId) {
                var ii, forms, checkChat;
                // we need to make sure that this page has a chat Agent ID before running it.
                forms = [];
                veTagData.captureConfig.Forms.forEach(function(form) {
                    if(form.ChatAgentId != null) {
                        forms.push(form.FormId);
                    }
                });
                for(ii = 0; ii < forms.length; ii++) {
                    if(formId == forms[ii]) {
                        console.info('Form identified');
                        setupListeners();
                        return formId;
                    }
                }

                function setupAnimations(target, observer) {
                    // disconect the mutation observer for performance gains.
                    if(observer != null) observer.disconnect();
                    // make sure this is properly configured.
                    if(!veTagData.settings.animations) return;
                    // use $ as the jQuery here for ease of use within this function.
                    var $ = VEjQuery;
                    // Collect all the elements
                    var $main = $('#ChatMainDiv'),
                        $cta = $('#VeChatCTA'),
                        $proactivecta = $('#veProactiveButton'),
                        $close = $('#WindowCloseBtn'),
                        $submit = $('#ChatButtonsDiv'),
                        animation = veTagData.settings.animations;
                    //Entry Animations
                    $main.addClass(animation.entry.main);
                    $cta.addClass(animation.entry.cta);
                    $proactivecta.addClass(animation.entry.proactivecta);
                    $close.addClass(animation.entry.close);
                    $submit.addClass(animation.entry.submit);
                    // LoopState Animations
                    setTimeout(function() {
                        // Remove Entry Animations
                        $main.removeClass(animation.entry.main);
                        $cta.removeClass(animation.entry.cta);
                        $proactivecta.removeClass(animation.entry.proactivecta);
                        $close.removeClass(animation.entry.close);
                        $submit.removeClass(animation.entry.submit);
                        setTimeout(function() {
                            // onHover Animation Classes
                            $main.addClass(animation.hover.main);
                            $cta.addClass(animation.hover.cta);
                            $proactivecta.addClass(animation.hover.proactivecta);
                            $close.addClass(animation.hover.close);
                            $submit.addClass(animation.hover.submit);
                            // Loop Animations
                            $main.addClass(animation.loop.main);
                            $cta.addClass(animation.loop.cta);
                            $proactivecta.addClass(animation.loop.proactivecta);
                            $close.addClass(animation.loop.close);
                            $submit.addClass(animation.loop.submit);
                        }, 1);
                    }, 100);
                }

                function setupListeners() {
                    checkChat = setInterval(function() {
                        var target = document.getElementById('ChatMainDiv');
                        if(target) {
                            if(VeAPI.browser.browser() !== 'Chrome') {
                                clearInterval(checkChat);
                                window.addEventListener('beforeunload', setupAnimations, true);
                                return;
                            } else {
                                setUpMutationObserver(target);
                                return;
                            }
                        } else {
                            return;
                        }
                    }, 100);
                }

                function setUpMutationObserver(target) {
                    console.info('Setting up observer');
                    clearInterval(checkChat);
                    setTimeout(function() {
                        var updateTarget = document.querySelector('#ChatMainDiv');
                        var observer = new window.MutationObserver(function(mutations) {
                            mutations.forEach(function(mutation) {
                                if(mutation.target.style.visibility === 'visible') {
                                    setupAnimations(updateTarget, observer);
                                }
                            });
                        });
                        var config = {
                            attributes: true,
                            attributeOldValue: true
                        };
                        observer.observe(updateTarget, config);
                        observerLive = true;
                    }, 1);
                }
            })(formId);
        }
        return formId;
    }
}


text:
//Here you put extra Typescript interfaces and declarations for external libraries.
declare const ngDescribe:any;


text:
import pandas as pd
import sqlite3

con = sqlite3.connect('test.db')
df = pd.read_sql_query('select * from telemetry where boat_id =33', con)

if __name__ == '__main__':
    import pdb
    pdb.set_trace()


text:
import unittest

import mock
import uuid
import six
import socket
import struct
from nsq import response
from nsq import constants
from nsq import exceptions

class TestResponse(unittest.TestCase):
    '''Test our response class'''
    def test_from_raw_response(self):
        '''Make sure we can construct a raw response'''
        raw = struct.pack('>l5s', constants.FRAME_TYPE_RESPONSE, b'hello')
        res = response.Response.from_raw(None, raw)
        self.assertEqual(res.__class__, response.Response)
        self.assertEqual(res.data, b'hello')

    def test_from_raw_unknown_frame(self):
        '''Raises an exception for unknown frame types'''
        raw = struct.pack('>l5s', 9042, b'hello')
        self.assertRaises(TypeError, response.Response.from_raw, None, raw)

    def test_str(self):
        '''Has a reasonable string value'''
        raw = struct.pack('>l5s', constants.FRAME_TYPE_RESPONSE, b'hello')
        res = response.Response.from_raw(None, raw)
        if six.PY2:
            self.assertEqual(str(res), 'Response - hello')
        else:
            self.assertEqual(str(res), "Response - b'hello'")

    def test_pack(self):
        '''Can pack itself up'''
        packed = response.Response.pack(b'hello')[4:]
        unpacked = response.Response.from_raw(None, packed)
        self.assertIsInstance(unpacked, response.Response)
        self.assertEqual(unpacked.data, b'hello')

class TestError(unittest.TestCase):
    '''Test our error response class'''
    def test_from_raw_error(self):
        '''Can identify an error type'''
        raw = struct.pack('>l5s', constants.FRAME_TYPE_ERROR, b'hello')
        res = response.Response.from_raw(None, raw)
        self.assertEqual(res.__class__, response.Error)
        self.assertEqual(res.data, b'hello')

    def test_str(self):
        '''Has a reasonable string value'''
        raw = struct.pack('>l5s', constants.FRAME_TYPE_ERROR, b'hello')
        res = response.Response.from_raw(None, raw)
        if six.PY2:
            self.assertEqual(str(res), 'Error - hello')
        else:
            self.assertEqual(str(res), "Error - b'hello'")

    def test_find(self):
        '''Can correctly identify the appropriate exception'''
        expected = {
            b'E_INVALID': exceptions.InvalidException,
            b'E_BAD_BODY': exceptions.BadBodyException,
            b'E_BAD_TOPIC': exceptions.BadTopicException,
            b'E_BAD_CHANNEL': exceptions.BadChannelException,
            b'E_BAD_MESSAGE': exceptions.BadMessageException,
            b'E_PUB_FAILED': exceptions.PubFailedException,
            b'E_MPUB_FAILED': exceptions.MpubFailedException,
            b'E_FIN_FAILED': exceptions.FinFailedException,
            b'E_REQ_FAILED': exceptions.ReqFailedException,
            b'E_TOUCH_FAILED': exceptions.TouchFailedException
        }
        for key, klass in expected.items():
            self.assertEqual(response.Error.find(key), klass)

    def test_find_missing(self):
        '''Raises an exception if it can't find the appropriate exception'''
        self.assertRaises(TypeError, response.Error.find, 'woruowijklf')

    def test_exception(self):
        '''Can correctly raise the appropriate exception'''
        raw = struct.pack('>l13s', constants.FRAME_TYPE_ERROR, b'E_INVALID foo')
        res = response.Response.from_raw(None, raw)
        exc = res.exception()
        self.assertIsInstance(exc, exceptions.InvalidException)
        if six.PY2:
            self.assertEqual(str(exc), 'foo')
        else:
            self.assertEqual(str(exc), "b'foo'")

    def test_pack(self):
        '''Can pack itself up'''
        packed = response.Error.pack(b'hello')[4:]
        unpacked = response.Response.from_raw(None, packed)
        self.assertIsInstance(unpacked, response.Error)
        self.assertEqual(unpacked.data, b'hello')

class TestMessage(unittest.TestCase):
    '''Test our message case'''
    def setUp(self):
        self.id = uuid.uuid4().hex[:16].encode()
        self.timestamp = 0
        self.attempt = 1
        self.body = b'hello'
        self.packed = struct.pack('>qH16s5s', 0, 1, self.id, self.body)
        self.response = response.Response.from_raw(mock.Mock(),
            struct.pack('>l31s', constants.FRAME_TYPE_MESSAGE, self.packed))

    def test_str(self):
        '''Has a reasonable string value'''
        if six.PY2:
            self.assertEqual(str(self.response), 'Message - 0 1 {} hello'.format(self.id))
        else:
            self.assertEqual(str(self.response), "Message - 0 1 {!r} b'hello'".format(self.id))

    def test_from_raw_message(self):
        '''Can identify a message type'''
        self.assertEqual(self.response.__class__, response.Message)

    def test_timestamp(self):
        '''Can identify the timestamp'''
        self.assertEqual(self.response.timestamp, self.timestamp)

    def test_attempts(self):
        '''Can identify the number of attempts'''
        self.assertEqual(self.response.attempts, self.attempt)

    def test_id(self):
        '''Can identify the ID of the message'''
        self.assertEqual(self.response.id, self.id)

    def test_message(self):
        '''Can properly detect the message'''
        self.assertEqual(self.response.body, self.body)

    def test_fin(self):
        '''Invokes the fin method'''
        self.response.fin()
        self.response.connection.fin.assert_called_with(self.id)

    def test_req(self):
        '''Invokes the req method'''
        self.response.req(1)
        self.response.connection.req.assert_called_with(self.id, 1)

    def test_touch(self):
        '''Invokes the touch method'''
        self.response.touch()
        self.response.connection.touch.assert_called_with(self.id)

    def test_pack(self):
        '''Can pack itself up'''
        packed = response.Message.pack(
            self.timestamp, self.attempt, self.id, self.body)[4:]
        unpacked = response.Response.from_raw(None, packed)
        self.assertIsInstance(unpacked, response.Message)
        self.assertEqual(unpacked.timestamp, self.timestamp)
        self.assertEqual(unpacked.attempts, self.attempt)
        self.assertEqual(unpacked.id, self.id)
        self.assertEqual(unpacked.body, self.body)

    def test_handle_yields(self):
        '''The handle method should yield the message'''
        with self.response.handle() as msg:
            self.assertEqual(msg, self.response)

    def test_handle_exception(self):
        '''Handles exceptions by requeueing'''
        try:
            with self.response.handle():
                raise ValueError('foo')
        except ValueError:
            self.response.connection.req.assert_called_with(
                self.response.id, self.response.delay())
        else:
            self.assertTrue(False, 'No exception was raised')

    def test_handle_success(self):
        '''Handles success by calling fin'''
        with self.response.handle():
            pass
        self.response.connection.fin.assert_called_with(self.response.id)

    def test_handle_already_requeued(self):
        '''If we've already requeued a message, doesn't requeue it again'''
        try:
            with self.response.handle():
                self.response.req(10)
                raise ValueError('foo')
        except ValueError:
            self.assertEqual(self.response.connection.req.call_count, 1)

    def test_handle_already_finish(self):
        '''If we've already finished a messages, doesn't finish it again'''
        with self.response.handle():
            self.response.fin()
        self.assertEqual(self.response.connection.fin.call_count, 1)

    def test_handle_exception_socket_error(self):
        '''Handles socket errors when catching exceptions'''
        try:
            self.response.connection.req = mock.Mock(side_effect=socket.error)
            with self.response.handle():
                raise ValueError('foo')
        except ValueError:
            # The connection should have been closed
            self.response.connection.close.assert_called_with()

    def test_handle_success_socket_error(self):
        '''Handles socket errors when trying to complete the message'''
        try:
            self.response.connection.fin = mock.Mock(side_effect=socket.error)
            with self.response.handle():
                pass
        except ValueError:
            # The connection should have been closed
            self.response.connection.close.assert_called_with()


text:
(function() {
d3.verticallegend = function(g) {
  g.each(function() {
    var g= d3.select(this),
        items = {},
        svg = d3.select(g.property("nearestViewportElement")),
        legendPadding = g.attr("data-style-padding") || 5,
        lb = g.selectAll(".legend-box").data([true]),
        li = g.selectAll(".legend-items").data([true])

    lb.enter().append("rect").classed("legend-box",true)
    li.enter().append("g").classed("legend-items",true)

    svg.selectAll("[data-legend]").each(function() {
        var self = d3.select(this)
        items[self.attr("data-legend")] = {
          pos : self.attr("data-legend-pos") || this.getBBox().y,
          color : self.attr("data-legend-color") != undefined ? self.attr("data-legend-color") : self.style("fill") != 'none' ? self.style("fill") : self.style("stroke")
        }
      })

    items = d3.entries(items).sort(function(a,b) { return a.value.pos-b.value.pos})

    li.selectAll("text")
        .data(items,function(d) { return d.key})
        .call(function(d) { d.enter().append("text")})
        .call(function(d) { d.exit().remove()})
        .attr("y",function(d,i) { return i+"em"})
        .attr("x","1em")
        .text(function(d) { ;return d.key})
        .style("font-size","10px")

    li.selectAll("circle")
        .data(items,function(d) { return d.key})
        .call(function(d) { d.enter().append("circle")})
        .call(function(d) { d.exit().remove()})
        .attr("cy",function(d,i) { return (i*0.83)-0.25+"em"})
        .attr("cx",0)
        .attr("r","0.3em")
        .style("fill",function(d) {return d.value.color})

    // Reposition and resize the box
    var lbbox = li[0][0].getBBox()
    lb.attr("x",(lbbox.x-legendPadding))
        .attr("y",(lbbox.y-legendPadding))
        .attr("height",(lbbox.height+2*legendPadding))
        .attr("width",(lbbox.width+2*legendPadding))
        .style("fill", "white")
        .style("opacity", "0.8")
  })
  return g
}
})()


text:
<?php

namespace Alabaster\Route;

/**
 * Handle HTTP request
 */

class Route
{
    protected $name;

    protected $routeTables;

    /**
     * Initialize a route item
     */
    public function __construct($name)
    {
        $this->routeTables = [];
        $this->name = $name;
    }

    /**
     * @throws UnexpectedValueException
     */
    public function setHandlers($method, $handler, array $supportedTypes)
    {
        if (count($supportedTypes) == 0) {
            throw new \UnexpectedValueException("Supported response type cannot be empty");
        }

        $method = strtoupper($method);
        if (!isset($this->routeTables[$method])) {
            $this->routeTables[$method] = [];
        }

        foreach ($supportedTypes as $type) {
            $this->routeTables[$method][$type] = $handler;
        }
    }

    /**
     *
     */
    public function getHandlersForMethod($method)
    {
        $method = strtoupper($method);
        return array_key_exists($method, $this->routeTables) ? $this->routeTables[$method] : null;
    }

    /**
     * Get the name of the current route
     */
    public function getName()
    {
        return $this->name;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Layout;
using DevExpress.ExpressApp.Model.NodeGenerators;
using DevExpress.ExpressApp.SystemModule;
using DevExpress.ExpressApp.Templates;
using DevExpress.ExpressApp.Utils;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.Validation;
using System.IO;
using DevExpress.ExpressApp.Xpo.Updating;
using DevExpress.Xpo;
using System.ComponentModel;
using CIIP;
using CIIP.Persistent.BaseImpl;
using SR = System.Reflection;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using CIIP.ProjectManager;

namespace CIIP.ProjectManager
{
    // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/clsDevExpressExpressAppWindowControllertopic.aspx.
    public partial class GenerateBusinessModuleController : WindowController
    {
        public GenerateBusinessModuleController()
        {
            InitializeComponent();
            this.TargetWindowType = WindowType.Main;
        }

        private void 生成业务模型_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            Compile(e,false);
        }

        //Solution GenateAssembly()
        //{
        //    var ObjectSpace = this.Application.CreateObjectSpace();
        //    var allTypes = ObjectSpace.GetObjects<BusinessObject>();
        //    var builder = new AssemblyBuilder();
        //    var rst = builder.GenerateModuleAssembly(allTypes);
        //    #region 删除模块信息,让系统执行更新表结构动作
        //    if (rst == null)
        //    {
        //        var moduleInfo = ObjectSpace.FindObject<ModuleInfo>(new BinaryOperator("Name", "ERPModule"));
        //        if (moduleInfo != null)
        //        {
        //            ObjectSpace.Delete(moduleInfo);
        //            ObjectSpace.CommitChanges();
        //        }
        //        var restart = Application as IRestartApplication;
        //        if (restart != null)
        //        {
        //            restart.RestartApplication();
        //        }
        //    }
        //    return rst;

        //    #endregion
        //}

        //private void GenerateModuleAssembly()
        //{
        //    #region GetVersion

        //    Version ver = BusinessBuilder.GetVersion(AdmiralEnvironment.UserDefineBusinessFile);

        //    if (ver != null)
        //    {
        //        ver = new Version(ver.Major + 1, ver.Minor, ver.Build, ver.Revision);
        //    }
        //    else
        //    {
        //        ver = new Version(1, 0, 0, 0);
        //    }

        //    #endregion

        //    var assemblyName = "AdmiralDynamicDC";
        //    var newFileName = AdmiralEnvironment.UserDefineBusinessTempFile.FullName;

        //    #region 定义程序集

        //    var asmName = new AssemblyNameDefinition(assemblyName, ver);
        //    //[assembly: AssemblyFileVersionAttribute("1.0.0.12")]
        //    var assembly =
        //        AssemblyDefinition.CreateAssembly(
        //            asmName,
        //            "MainModule",
        //            ModuleKind.Dll
        //            );
        //    //AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save, AdmiralEnvironment.UserDefineBusinessDirectoryInfo.FullName);

        //    #region 定义模块

        //    var module = assembly.MainModule;

        //    #endregion

        //    #endregion

        //    #region 设置文件版本

        //    var asmFileVerCtor = typeof(SR.AssemblyFileVersionAttribute).GetConstructor(new[] { typeof(string) });

        //    var asmFileVerCtorRef = assembly.MainModule.ImportReference(asmFileVerCtor);
        //    var ca = new Mono.Cecil.CustomAttribute(asmFileVerCtorRef);
        //    ca.ConstructorArguments.Add(new CustomAttributeArgument(
        //        assembly.MainModule.ImportReference(typeof(string)), ver.ToString()));
        //    assembly.CustomAttributes.Add(ca);

        //    #endregion

        //    #region XafModule

        //    var xafModule = new TypeDefinition("", "RuntimeModule",
        //        TypeAttributes.Public | TypeAttributes.Class,
        //        assembly.MainModule.ImportReference(typeof(RuntimeModuleBase)));

        //    //module.DefineType("RuntimeModule", TypeAttributes.Public | TypeAttributes.Class, typeof(RuntimeModuleBase));
        //    var ctor = new MethodDefinition(".ctor",
        //        MethodAttributes.Public
        //        | MethodAttributes.HideBySig
        //        | MethodAttributes.SpecialName
        //        | MethodAttributes.RTSpecialName,
        //        module.ImportReference(typeof(void))
        //        );
        //    //.method public hidebysig specialname rtspecialname instance void .ctor() cil managed

        //    //xafModule.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis, Type.EmptyTypes);
        //    var baseCtor = typeof(RuntimeModuleBase).GetConstructor(Type.EmptyTypes);

        //    var il = ctor.Body.Instructions;

        //    //.maxstack 8
        //    //L_0000: ldarg.0
        //    //L_0001: call instance void Admiral.ERP.Module.RuntimeModuleBase::.ctor()
        //    //L_0006: ret
        //    il.Add(Instruction.Create(OpCodes.Ldarg_0));
        //    il.Add(Instruction.Create(OpCodes.Call, module.ImportReference(baseCtor)));
        //    il.Add(Instruction.Create(OpCodes.Ret));
        //    xafModule.Methods.Add(ctor);
        //    module.Types.Add(xafModule);

        //    #endregion

        //    #region 创建业务对象
        //    var ObjectSpace = this.Application.CreateObjectSpace();
        //    var allTypes = ObjectSpace.GetObjects<BusinessObjectBase>();

        //    var userDefinedBos = allTypes.OfType<BusinessObject>().Where(x => x.IsRuntimeDefine).ToList(); //ObjectSpace.GetObjects<BusinessObject>(new BinaryOperator("IsRuntimeDefine", true)).OrderBy(x => x.CreateIndex).ToArray();
        //    var dllTypes = allTypes.Except(userDefinedBos); //ObjectSpace.GetObjects<BusinessObject>(new BinaryOperator("IsRuntimeDefine", false));
        //    module.InitializeTypeReferences(dllTypes);

        //    //第一步只生成类型定义,是因为可能有交叉使用类型,如,基类是未定义的类型,则无法使用
        //    #region 定义类型生成的代码,包含属性修饰:-->[NonPersistent]pubic class {    }
        //    foreach (var bo in userDefinedBos)
        //    {
        //        var typeAtt = TypeAttributes.Class | TypeAttributes.Public;
        //        if (bo.IsAbstract)
        //        {
        //            typeAtt |= TypeAttributes.Abstract;
        //        }
        //        else if (!bo.CanInherits)
        //        {
        //            typeAtt |= TypeAttributes.Sealed;
        //        }

        //        var type = new TypeDefinition(bo.Category.FullName, bo.名称, typeAtt);
        //        module.Types.Add(type);

        //        if (!bo.IsPersistent)
        //        {
        //            type.AddNonPersistentDc();
        //        }

        //        if (bo.IsCloneable.HasValue)
        //        {
        //            type.ModelDefault("IsCloneable", bo.IsCloneable.Value.ToString().ToLower() );
        //        }

        //        if (bo.IsCreatableItem.HasValue)
        //        {
        //            type.ModelDefault("IsCreatableItem", bo.IsCreatableItem.Value.ToString().ToLower());
        //        }

        //        if (bo.IsVisibileInReports.HasValue)
        //        {
        //            type.VisibileInReport(bo.IsVisibileInReports.Value);
        //        }
        //        type.AddToTypeReferences(bo);
        //    }
        //    #endregion

        //    #region 生成剩下的内容
        //    foreach (var bo in userDefinedBos)
        //    {
        //        var type = bo.GetTypeDefintion();
        //        if (type == null)
        //            throw new Exception("错误!");

        //        #region 处理基类

        //        var boBaseType = bo.Base.GetTypeReference() ?? module.ImportReference(typeof(SimpleObject));
        //        MethodReference boBaseCtor;

        //        if (boBaseType.HasGenericParameters)
        //        {
        //            type.BaseType = boBaseType.MakeGenericType(bo.GenericParameters.Select(gp => gp.ParameterValue.GetTypeReference()).ToArray());

        //            //var tb = boBaseType.Resolve().MakeGenericType(bo.GenericParameters.Select(gp => gp.ParameterValue.FindType(typeReferences)).ToArray());

        //            boBaseCtor =
        //                //(tb as TypeDefinition).Methods.Single(x => x.Name == ".ctor" && x.Parameters.First().ParameterType.FullName == typeof(Session).FullName);
        //                module.ImportReference(
        //                    type.BaseType.Resolve()
        //                        .Methods.Single(
        //                            x => x.Name == ".ctor" && x.Parameters.First().ParameterType.FullName == typeof(Session).FullName)
        //                    );
        //            boBaseCtor = boBaseCtor.MakeGeneric(bo.GenericParameters.Select(gp => gp.ParameterValue.GetTypeReference()).ToArray());
        //        }
        //        else
        //        {
        //            type.BaseType = boBaseType;
        //            boBaseCtor = module.ImportReference(
        //                boBaseType.Resolve().Methods.Single(x => x.Name == ".ctor" && x.Parameters.Count == 1 && x.Parameters.Single().ParameterType.FullName == typeof(Session).FullName)
        //                );
        //        }

        //        if (boBaseCtor != null)
        //        {
        //            var boctor = new MethodDefinition(".ctor",
        //                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName,
        //                //CallingConventions.Standard | CallingConventions.HasThis,
        //                module.ImportReference(typeof(void))
        //                );
        //            // type.DefineConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName, CallingConventions.Standard | CallingConventions.HasThis, new Type[] { typeof(Session) });
        //            var p = new ParameterDefinition("session", ParameterAttributes.None, module.ImportReference(typeof(Session)));
        //            boctor.Parameters.Add(p);
        //            var boil = boctor.Body.GetILProcessor();
        //            //.GetILGenerator();

        //            boil.Emit(OpCodes.Ldarg_0);
        //            boil.Emit(OpCodes.Ldarg_1);
        //            boil.Emit(OpCodes.Call, boBaseCtor);
        //            boil.Emit(OpCodes.Nop);
        //            boil.Emit(OpCodes.Nop);
        //            boil.Emit(OpCodes.Ret);

        //            //L_0000: ldarg.0
        //            //L_0001: ldarg.1
        //            //L_0002: call instance void IMatrix.ERP.Module.BusinessObjects.订单`1 <class IMatrix.ERP.Module.BusinessObjects.PMS.采购订单明细>::.ctor(class [DevExpress.Xpo.v15.2]
        //            //DevExpress.Xpo.Session)
        //            //L_0007: nop
        //            //L_0008: nop
        //            //L_0009: ret

        //            //.method public hidebysig specialname rtspecialname
        //            //instance void  .ctor(class ['DevExpress.Xpo.v15.2']DevExpress.Xpo.Session session) cil managed
        //            //{
        //            //// 代码大小       10 (0xa)
        //            //.maxstack  8
        //            //IL_0000:  ldarg.0
        //            //IL_0001:  ldarg.1
        //            //IL_0002:  call       instance void [IMatrix.ERP.Module]IMatrix.ERP.Module.BusinessObjects.'订单`1'::.ctor<class '业务'.'采购计划明细'>(class ['DevExpress.Xpo.v15.2']DevExpress.Xpo.Session)
        //            //IL_0007:  nop
        //            //IL_0008:  nop
        //            //IL_0009:  ret
        //            //} // end of method '采购计划'::.ctor

        //            type.Methods.Add(boctor);
        //        }

        //        #endregion

        //        #region 填加属性

        //        foreach (var p in bo.Properties)
        //        {
        //            BuildPropertyCore(p, type);
        //        }

        //        #endregion

        //        #region 填加集合属性
        //        foreach (var item in bo.CollectionProperties)
        //        {
        //            BuildCollectionProperty(item, type);
        //        }
        //        #endregion
        //    }
        //    #endregion

        //    #endregion

        //    #region 保存生成的程序集
        //    assembly.Write(newFileName);
        //    #endregion

        //    #region 删除模块信息,让系统执行更新表结构动作

        //    var moduleInfo = ObjectSpace.FindObject<ModuleInfo>(new BinaryOperator("Name", "RuntimeModule"));
        //    if (moduleInfo != null)
        //    {
        //        ObjectSpace.Delete(moduleInfo);
        //        ObjectSpace.CommitChanges();
        //    }
        //    var restart = Application as IRestartApplication;
        //    if (restart != null)
        //    {
        //        restart.RestartApplication();
        //    }
        //    #endregion

        //}

        //public PropertyDefinition BuildCollectionProperty(CollectionProperty property,TypeDefinition type)
        //{
        //    //如果是一对多关系,即关联属性是单值属性时,直接在上面加上关联关系
        //    //如果是多对多,则不需要处理,因为所属类型会执行这个动作

        //    var mod = type.Module;
        //    var elementType = property.PropertyType.GetTypeReference();
        //    var ptype = mod.ImportReference(typeof(XPCollection<>)).MakeGenericType(elementType);
        //    var propertyInfo = new PropertyDefinition(property.名称, PropertyAttributes.None, ptype) { HasThis = true };
        //    type.Properties.Add(propertyInfo);

        //    propertyInfo.Assocication(property);
        //    if (property.Aggregated)
        //    {
        //        propertyInfo.Aggregate();
        //    }

        //    #region getter
        //    //.method public hidebysig specialname instance string get_创建者() cil managedMono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.SpecialName
        //    var attr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.FamANDAssem | MethodAttributes.Family;

        //    var getMethod = new MethodDefinition("get_" + property.名称, attr, ptype);

        //    var getMethodIl = getMethod.Body.GetILProcessor();
        //    getMethod.Body.Variables.Add(new VariableDefinition(ptype));

        //    getMethod.Body.MaxStackSize = 8;

        //    getMethod.Body.InitLocals = true;
        //    //.maxstack 2
        //    //.locals init ([0] class [DevExpress.Xpo.v15.2]DevExpress.Xpo.XPCollection`1<class IMatrix.ERP.Module.BusinessObjects.员工> xps)
        //    //L_0000: nop
        //    //L_0001: ldarg.0
        //    //L_0002: ldstr "\u8054\u7cfb\u4eba"
        //    //L_0007: call instance class [DevExpress.Xpo.v15.2]DevExpress.Xpo.XPCollection`1<!!0> [DevExpress.Xpo.v15.2]DevExpress.Xpo.XPBaseObject::GetCollection<class IMatrix.ERP.Module.BusinessObjects.员工>(string)
        //    //L_000c: stloc.0
        //    //L_000d: br.s L_000f
        //    //L_000f: ldloc.0
        //    //L_0010: ret
        //    getMethodIl.Emit(OpCodes.Nop);
        //    getMethodIl.Emit(OpCodes.Ldarg_0);
        //    getMethodIl.Emit(OpCodes.Ldstr, property.名称);
        //    var clrGetCollection = typeof(SimpleObject).GetMethods(SR.BindingFlags.NonPublic | SR.BindingFlags.Instance).Single(x => x.Name == "GetCollection" && x.ReturnType.IsGenericType);
        //    var getCollection = mod.ImportReference(clrGetCollection);    //(tb as TypeDefinition).Methods.Single(x => x.Name == ".ctor" && x.Parameters.First().ParameterType.FullName == typeof(Session).FullName);
        //    getCollection = getCollection.MakeGenericMethod(elementType);

        //    getMethodIl.Emit(OpCodes.Call, getCollection);
        //    getMethodIl.Emit(OpCodes.Stloc_0);

        //    var ldloc0 = getMethodIl.Create(OpCodes.Ldloc_0);
        //    getMethodIl.Emit(OpCodes.Br_S, ldloc0);
        //    getMethodIl.Append(ldloc0);
        //    getMethodIl.Emit(OpCodes.Ret);
        //    type.Methods.Add(getMethod);
        //    propertyInfo.GetMethod = getMethod;

        //    #endregion

        //    return propertyInfo;
        //}

        //public static PropertyDefinition BuildPropertyCore(Property property, TypeDefinition type)
        //{
        //    var mod = type.Module;
        //    //从缓存中查找clr type
        //    var ptype = property.PropertyType.GetTypeReference();

        //    var fieldInfo = new FieldDefinition("_" + property.名称, FieldAttributes.Private, ptype);
        //    type.Fields.Add(fieldInfo);
        //    // type.DefineField("_" + property.名称, ptype, FieldAttributes.Private);

        //    var propertyInfo = new PropertyDefinition(property.名称, PropertyAttributes.None, ptype) { HasThis = true };
        //    type.Properties.Add(propertyInfo);
        //    #region 基本属性设置

        //    if (property.Size != 100 && property.Size != 0)
        //    {
        //        propertyInfo.Size(property.Size);
        //    }

        //    //if (!string.IsNullOrEmpty(property.Expression))
        //    //{
        //    //    propertyInfo.PersistentAlias(property.Expression);
        //    //}

        //    #endregion;

        //    #region getter
        //    //.method public hidebysig specialname instance string get_创建者() cil managedMono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.SpecialName
        //    var attr = MethodAttributes.Public | MethodAttributes.HideBySig| MethodAttributes.SpecialName| MethodAttributes.FamANDAssem | MethodAttributes.Family;
        //    var setattr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.FamANDAssem | MethodAttributes.Family;

        //    var getMethod = new MethodDefinition("get_" + property.名称, attr, ptype);

        //    var getMethodIl = getMethod.Body.GetILProcessor();

        //    getMethod.Body.MaxStackSize = 8;
        //    getMethod.Body.InitLocals = true;

        //    getMethodIl.Emit(OpCodes.Ldarg_0);
        //    getMethodIl.Emit(OpCodes.Ldfld, fieldInfo);
        //    getMethodIl.Emit(OpCodes.Ret);
        //    type.Methods.Add(getMethod);
        //    propertyInfo.GetMethod = getMethod;

        //    #endregion

        //    #region 非计算类型

        //    if (string.IsNullOrEmpty(property.Expression))
        //    {
        //        var set = new MethodDefinition("set_" + property.名称, setattr, mod.ImportReference(typeof (void)));
        //        var para = new ParameterDefinition("value", ParameterAttributes.None, ptype);
        //        set.Parameters.Add(para);
        //        var setPropertyValue = mod.ImportReference(
        //            typeof (PersistentBase)
        //                .GetMethods(
        //                    SR.BindingFlags.InvokeMethod | SR.BindingFlags.NonPublic |
        //                    SR.BindingFlags.Instance)
        //                .Single(x => x.Name.StartsWith("SetPropertyValue") && x.IsGenericMethod &&
        //                             x.GetParameters().Length == 3)
        //            );
        //        var setPropertyValueMethod = new GenericInstanceMethod(setPropertyValue);
        //        setPropertyValueMethod.GenericArguments.Add(ptype);
        //        //setPropertyValue =  setPropertyValue.MakeGenericMethod(ptype);

        //        var setIl = set.Body.Instructions;
        //        setIl.Add(Instruction.Create(OpCodes.Ldarg_0));
        //        setIl.Add(Instruction.Create(OpCodes.Ldstr, property.名称));
        //        setIl.Add(Instruction.Create(OpCodes.Ldarg_0));
        //        setIl.Add(Instruction.Create(OpCodes.Ldflda, fieldInfo));
        //        setIl.Add(Instruction.Create(OpCodes.Ldarg_1));
        //        setIl.Add(Instruction.Create(OpCodes.Call, setPropertyValueMethod));
        //        setIl.Add(Instruction.Create(OpCodes.Pop));
        //        setIl.Add(Instruction.Create(OpCodes.Ret));
        //        propertyInfo.SetMethod = set;
        //        type.Methods.Add(set);
        //    }

        //    #endregion

        //    return propertyInfo;
        //}

        //private void AddDefaultProperty(TypeDefinition type, Property property)
        //{
        //    var ctor = typeof(DefaultPropertyAttribute).GetConstructors().Single(x => x.IsPublic && x.GetParameters().Length == 1 && x.GetParameters()[0].ParameterType == typeof(string));
        //    var att = new CustomAttributeBuilder(ctor, new object[] { property.名称 });

        //    type.SetCustomAttribute(att);
        //}

        //private Type ImportTypeReference(BusinessObjectBase bo, Dictionary<BusinessObjectBase, TypeBuilder> asm)
        //{
        //    if (bo is SimpleType)
        //    {
        //        var biType = ReflectionHelper.FindType(bo.FullName);
        //        return biType;
        //    }
        //    else
        //    {
        //        return asm[bo];
        //    }
        //}

        //public void AddNavigationItem(TypeBuilder type, string group)
        //{
        //    var ctor = typeof(NavigationItemAttribute).GetConstructors().Single(x => x.IsPublic && x.GetParameters().Length == 1 && x.GetParameters()[0].ParameterType == typeof(string));
        //    var att = new CustomAttributeBuilder(ctor, new object[] { group });

        //    type.SetCustomAttribute(att);
        //}

        private static ModuleBase GetModule()
        {
            var assembly = SR.Assembly.LoadFile(Path.GetFullPath(@".\Module1.dll"));
            ModuleBase module = (ModuleBase)assembly.GetType("Module1.Module1Module").GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
            return module;
        }

        private void simpleAction1_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            ModuleBase module = GetModule();
            if (!HasModule(module))
            {
                Application.Modules.Add(module);
                Reload();
            }
        }

        private void simpleAction2_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            ModuleBase module = GetModule();
            if (HasModule(module))
            {
                for (int i = Application.Modules.Count - 1; i >= 0; i--)
                {
                    if (AreSameModules(module, Application.Modules[i]))
                    {
                        Application.Modules.RemoveAt(i);
                        break;
                    }
                }
                Reload();
            }
        }

        private void Reload()
        {
            Application.Setup();
            Application.LogOff();
        }

        private bool HasModule(ModuleBase module)
        {
            bool hasModule = false;
            if (module != null)
            {
                foreach (ModuleBase item in Application.Modules.Where(item => AreSameModules(module, item)))
                {
                    hasModule = true;
                }
            }
            return hasModule;
        }

        private static bool AreSameModules(ModuleBase one, ModuleBase two)
        {
            return two.Name == one.Name && two.AssemblyName == one.AssemblyName;
        }

        private void ViewSourceCode_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            Compile(e, true);
        }
    }
}


text:
var BigInteger = require('bigi');

(BigInteger('12345'): BigInteger);
(new BigInteger('12345'): BigInteger);
(BigInteger('12345', 16): BigInteger);
(new BigInteger('12345', 16): BigInteger);
(BigInteger([1, 2, 3]): BigInteger);
(new BigInteger([1, 2, 3]): BigInteger);
(BigInteger([1, 2, 3], 16): BigInteger);
(new BigInteger([1, 2, 3], 16): BigInteger);

var b = new BigInteger('1');

(b.toString(): string);
(b.toString(16): string);
(b.toByteArray(): Array<number>);
(b.bitLength(): number);
(b.byteLength(): number);

(b.add(b): BigInteger);
(b.subtract(b): BigInteger);
(b.multiply(b): BigInteger);
(b.divide(b): BigInteger);
(b.mod(b): BigInteger);
(b.modInverse(b): BigInteger);

(b.shiftLeft(3): BigInteger);
(b.shiftRight(3): BigInteger);

(b.isProbablePrime(): boolean);

// $ExpectError
(BigInteger(12345): BigInteger);

// $ExpectError
(new BigInteger(1, 2, 3): BigInteger);

// $ExpectError
(b.toString('foobar'): string);
// $ExpectError
(b.toString('foobar'): number);
// $ExpectError
(b.toByteArray(): Buffer);

// $ExpectError
(b.add(b): number);

// $ExpectError
(b.shiftLeft(b): BigInteger);


text:
package nl.adeda.sharelocation.Helpers;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;

import com.google.android.gms.maps.GoogleMap;

/**
 * Checks for location permissions, as this is necessary for the application to function properly.
 */

public class PermissionChecker {

    private static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;

    public static void locationPermissions(Activity activity, GoogleMap googleMap) {
        // Check if location request permission is granted
        if (ActivityCompat.checkSelfPermission(activity.getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Ask permission
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
    }
}


text:
A browserify transform stream for
[Chris Dickinson](http://github.com/chrisdickinson)'s
[glslify](http://github.com/chrisdickinson/glslify).

Works just the same, however instead of compiling using a separate
CLI tool you can just `require('./some-shader.glsl')` and have it
return a bundled shader string.

[![glslifyify](https://nodei.co/npm/glslifyify.png?mini=true)](https://nodei.co/npm/glslifyify)

## Usage ##

``` bash
browserify index.js -t glslifyify > bundle.js
```


text:
#pragma once
#include <aws/xray/XRay_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace XRay
{
namespace Model
{

  /**
   *
An alias for an edge.

See Also:
   AWS API
   * Reference

   */
  class AWS_XRAY_API Alias
  {
  public:
    Alias();
    Alias(Aws::Utils::Json::JsonView jsonValue);
    Alias& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The canonical name of the alias.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The canonical name of the alias.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The canonical name of the alias.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The canonical name of the alias.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The canonical name of the alias.

     */
    inline Alias& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The canonical name of the alias.

     */
    inline Alias& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The canonical name of the alias.

     */
    inline Alias& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline const Aws::Vector<Aws::String>& GetNames() const{ return m_names; }

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline void SetNames(const Aws::Vector<Aws::String>& value) { m_namesHasBeenSet = true; m_names = value; }

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline void SetNames(Aws::Vector<Aws::String>&& value) { m_namesHasBeenSet = true; m_names = std::move(value); }

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline Alias& WithNames(const Aws::Vector<Aws::String>& value) { SetNames(value); return *this;}

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline Alias& WithNames(Aws::Vector<Aws::String>&& value) { SetNames(std::move(value)); return *this;}

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline Alias& AddNames(const Aws::String& value) { m_namesHasBeenSet = true; m_names.push_back(value); return *this; }

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline Alias& AddNames(Aws::String&& value) { m_namesHasBeenSet = true; m_names.push_back(std::move(value)); return *this; }

    /**
     *
A list of names for the alias, including the canonical name.

     */
    inline Alias& AddNames(const char* value) { m_namesHasBeenSet = true; m_names.push_back(value); return *this; }

    /**
     *
The type of the alias.

     */
    inline const Aws::String& GetType() const{ return m_type; }

    /**
     *
The type of the alias.

     */
    inline void SetType(const Aws::String& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of the alias.

     */
    inline void SetType(Aws::String&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of the alias.

     */
    inline void SetType(const char* value) { m_typeHasBeenSet = true; m_type.assign(value); }

    /**
     *
The type of the alias.

     */
    inline Alias& WithType(const Aws::String& value) { SetType(value); return *this;}

    /**
     *
The type of the alias.

     */
    inline Alias& WithType(Aws::String&& value) { SetType(std::move(value)); return *this;}

    /**
     *
The type of the alias.

     */
    inline Alias& WithType(const char* value) { SetType(value); return *this;}

  private:

    Aws::String m_name;
    bool m_nameHasBeenSet;

    Aws::Vector<Aws::String> m_names;
    bool m_namesHasBeenSet;

    Aws::String m_type;
    bool m_typeHasBeenSet;
  };

} // namespace Model
} // namespace XRay
} // namespace Aws


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S15.3.4.3_A3_T6;
* @section: 15.3.4.3;
* @assertion: If thisArg is null or undefined, the called function is passed the global object as the this value;
* @description: Argument at apply function is null and it called inside function declaration;
*/

function FACTORY(){
  (function(){this.feat="kamon beyba"}).apply(null);
};

var obj = new FACTORY;

//CHECK#1
if (this["feat"] !== "kamon beyba") {
  $ERROR('#1: If thisArg is null or undefined, the called function is passed the global object as the this value');
}

//CHECK#2
if (typeof obj.feat !== "undefined") {
  $ERROR('#1: If thisArg is null or undefined, the called function is passed the global object as the this value');
}


text:
'use strict';

const { babelLoaderFinder, fileLoaderFinder } = require('./helpers');
const path = require('path');

const defaultOptions = {};

function modify(baseConfig, params, webpack, userOptions = {}) {
  const options = Object.assign({}, defaultOptions, userOptions);
  const config = Object.assign({}, baseConfig);

  config.resolve.modules = [
    ...config.resolve.modules,
    path.join(__dirname, './node_modules'),
  ];
  config.resolve.extensions = [...config.resolve.extensions, '.md', '.mdx'];

  // Safely locate Babel-Loader in Razzle's webpack internals
  const babelLoader = config.module.rules.find(babelLoaderFinder);
  if (!babelLoader) {
    throw new Error(`'babel-loader' required for nice 'MDX loader' work`);
  }

  // Don't import md and mdx files with file-loader
  const fileLoader = config.module.rules.find(fileLoaderFinder);
  fileLoader.exclude = [/\.mdx?$/, ...fileLoader.exclude];

  // Get the correct `include` option, since that hasn't changed.
  // This tells Razzle which directories to transform.
  const { include } = babelLoader;

  // Configure @mdx-js/loader
  const mdxLoader = {
    include,
    test: /\.mdx?$/,
    use: [
      ...babelLoader.use,
      {
        loader: require.resolve('@mdx-js/loader'),
        options: Object.assign({}, options),
      },
    ],
  };

  config.module.rules.push(mdxLoader);

  return config;
}

module.exports = modify;


text:
package com.twu.biblioteca;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static com.twu.biblioteca.BibliotecaApp.bookList;
import static org.junit.Assert.assertEquals;

public class BibliotecaTest {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

    @Before
    public void setUpStreams() {
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void cleanUpStreams() {
        System.setOut(null);
    }

    @Test
    public void testWelcomeBiblioteca() {
        BibliotecaApp.welcome();
        assertEquals(" +=========================+\n || Welcome to Biblioteca ||\n +=========================+\n", outContent.toString());
    }

    @Test
    public void testLibraryHasBooks() {
        assertEquals(bookList.size(), 3 );
    }

}


text:
TODO: Write a gem description

## Installation

Install it yourself as:

    $ gem install ratpoison

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package net.bytebuddy.build;

import net.bytebuddy.dynamic.ClassFileLocator;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.stubbing.Answer;

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.jar.Manifest;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class PluginEngineSourceCompoundTest {

    private static final String FOO = "foo";

    @Rule
    public MethodRule mockitoRule = MockitoJUnit.rule().silent();

    @Mock
    private Plugin.Engine.Source left;

    @Mock
    private Plugin.Engine.Source right;

    @Mock
    private Plugin.Engine.Source.Origin leftOrigin;

    @Mock
    private Plugin.Engine.Source.Origin rightOrigin;

    @Mock
    private ClassFileLocator leftLocator;

    @Mock
    private ClassFileLocator rightLocator;

    @Mock
    private Plugin.Engine.Source.Element leftElement;

    @Mock
    private Plugin.Engine.Source.Element rightElement;

    @Before
    public void setUp() throws Exception {
        when(left.read()).thenReturn(leftOrigin);
        when(right.read()).thenReturn(rightOrigin);
        when(leftOrigin.getClassFileLocator()).thenReturn(leftLocator);
        when(rightOrigin.getClassFileLocator()).thenReturn(rightLocator);
        when(leftLocator.locate(Mockito.any(String.class))).thenReturn(new ClassFileLocator.Resolution.Illegal(FOO));
        when(rightLocator.locate(Mockito.any(String.class))).thenReturn(new ClassFileLocator.Resolution.Illegal(FOO));
        when(leftOrigin.iterator()).then(new Answer<Iterator<Plugin.Engine.Source.Element>>() {
            @Override
            public Iterator<Plugin.Engine.Source.Element> answer(InvocationOnMock invocation) {
                return Collections.singleton(leftElement).iterator();
            }
        });
        when(rightOrigin.iterator()).then(new Answer<Iterator<Plugin.Engine.Source.Element>>() {
            @Override
            public Iterator<Plugin.Engine.Source.Element> answer(InvocationOnMock invocation) {
                return Collections.singleton(rightElement).iterator();
            }
        });
    }

    @Test
    public void testEmptyCompound() throws Exception {
        assertThat(new Plugin.Engine.Source.Compound(Collections.<Plugin.Engine.Source>emptyList()).read(), sameInstance((Plugin.Engine.Source.Origin) Plugin.Engine.Source.Empty.INSTANCE));
    }

    @Test
    public void testClassFileLocator() throws Exception {
        assertThat(new Plugin.Engine.Source.Compound(Arrays.asList(left, right)).read().getClassFileLocator().locate(FOO).isResolved(), is(false));
        verify(leftLocator).locate(FOO);
        verify(rightLocator).locate(FOO);
    }

    @Test
    public void testManifest() throws Exception {
        assertThat(new Plugin.Engine.Source.Compound(Arrays.asList(left, right)).read().getManifest(), nullValue(Manifest.class));
        verify(leftOrigin).getManifest();
        verify(rightOrigin).getManifest();
    }

    @Test
    public void testIteration() throws Exception {
        Iterator<Plugin.Engine.Source.Element> iterator = new Plugin.Engine.Source.Compound(Arrays.asList(left, right)).read().iterator();
        assertThat(iterator.hasNext(), is(true));
        assertThat(iterator.next(), is(leftElement));
        assertThat(iterator.hasNext(), is(true));
        assertThat(iterator.next(), is(rightElement));
        assertThat(iterator.hasNext(), is(false));

    }

    @Test
    public void testClose() throws Exception {
        new Plugin.Engine.Source.Compound(Arrays.asList(left, right)).read().close();
        verify(leftOrigin).close();
        verify(rightOrigin).close();
    }
}


text:
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/umeng_comm_comment_item_bg"
    android:descendantFocusability="blocksDescendants">

    <com.umeng.commm.ui.widgets.RoundImageView
        android:id="@+id/umeng_comm_msg_comment_header"
        android:layout_width="@dimen/umeng_comm_dimen_80px"
        android:layout_height="@dimen/umeng_comm_dimen_80px"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="@dimen/umeng_comm_dimen_24px"
        android:layout_marginTop="@dimen/umeng_comm_dimen_20px"
        android:contentDescription="@string/umeng_comm_desc"
        android:scaleType="fitXY"
        android:src="@drawable/umeng_comm_male" />

    <TextView
        android:id="@+id/umeng_comm_comment_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/umeng_comm_msg_comment_header"
        android:layout_marginLeft="@dimen/umeng_comm_dimen_20px"
        android:layout_marginTop="-2dp"
        android:layout_toRightOf="@id/umeng_comm_msg_comment_header"
        android:ellipsize="end"
        android:maxWidth="@dimen/umeng_comm_dimen_320px"
        android:singleLine="true"
        android:text=""
        android:textColor="@color/umeng_comm_color_a5"
        android:textSize="13sp" />

    <TextView
        android:id="@+id/umeng_comm_comment_floor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/umeng_comm_msg_comment_header"
        android:layout_marginRight="@dimen/umeng_comm_dimen_20px"
        android:contentDescription="@string/umeng_comm_desc"
        android:text="1 楼"
        android:textColor="@color/umeng_comm_color_a5"
        android:textSize="@dimen/umeng_comm_text_26px" />

    <TextView
        android:id="@+id/umeng_comm_msg_post_owner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/umeng_comm_msg_comment_header"
        android:layout_marginRight="@dimen/umeng_comm_dimen_20px"
        android:layout_toLeftOf="@id/umeng_comm_comment_floor"
        android:contentDescription="@string/umeng_comm_desc"
        android:text="楼主"
        android:textColor="@color/umeng_comm_feed_detail_blue"
        android:textSize="@dimen/umeng_comm_text_26px" />

    <com.umeng.commm.ui.widgets.TextViewFixTouchConsume
        android:id="@+id/umeng_comm_msg_comment_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/umeng_comm_comment_name"
        android:layout_below="@id/umeng_comm_comment_name"
        android:layout_marginRight="@dimen/umeng_comm_dimen_20px"
        android:layout_marginTop="@dimen/umeng_comm_dimen_20px"
        android:includeFontPadding="false"
        android:lineSpacingExtra="@dimen/umeng_comm_dimen_14px"
        android:text="@string/umeng_comm_desc"
        android:textColor="@color/umeng_comm_color_33"
        android:textSize="@dimen/umeng_comm_text_28px" />

    <com.umeng.commm.ui.widgets.SquareImageView
        android:id="@+id/uemng_comm_comment_img"
        android:layout_width="@dimen/umeng_comm_dimen_170px"
        android:layout_height="@dimen/umeng_comm_dimen_170px"
        android:layout_alignLeft="@id/umeng_comm_comment_name"
        android:layout_below="@id/umeng_comm_msg_comment_content"
        android:layout_marginBottom="@dimen/umeng_comm_dimen_20px"
        android:layout_marginTop="@dimen/umeng_comm_dimen_10px"
        android:scaleType="centerCrop" />

    <include
        android:id="@+id/umeng_comm_comment_reply_vs"
        layout="@layout/umeng_comm_comment_reply_stub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/umeng_comm_comment_name"
        android:layout_below="@id/uemng_comm_comment_img"
        android:layout_marginBottom="@dimen/umeng_comm_dimen_20px"
        android:layout_marginRight="@dimen/umeng_comm_dimen_20px"
        android:layout_marginTop="@dimen/umeng_comm_dimen_10px" />

    <TextView
        android:id="@+id/umeng_comm_comment_time_tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@id/umeng_comm_comment_name"
        android:layout_below="@id/umeng_comm_comment_reply_vs"
        android:layout_marginTop="@dimen/umeng_comm_dimen_10px"
        android:textColor="@color/umeng_comm_color_a5"
        android:textSize="@dimen/umeng_comm_text_24px" />

    <TextView
        android:id="@+id/umeng_comm_msg_comment_comment_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/umeng_comm_comment_time_tv"
        android:layout_marginRight="@dimen/umeng_comm_dimen_20px"
        android:drawableLeft="@drawable/umeng_comm_comment_comment_selector"
        android:gravity="center" />

    <TextView
        android:id="@+id/umeng_comm_msg_comment_like_tv"
        android:layout_width="@dimen/umeng_comm_dimen_108px"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/umeng_comm_comment_time_tv"
        android:layout_marginRight="@dimen/umeng_comm_dimen_20px"
        android:layout_toLeftOf="@id/umeng_comm_msg_comment_comment_tv"
        android:drawableLeft="@drawable/umeng_comm_comment_like_selector"
        android:drawablePadding="@dimen/umeng_comm_dimen_10px"
        android:ellipsize="end"
        android:gravity="left|center_vertical"
        android:singleLine="true"
        android:text="1000"
        android:textColor="@drawable/umeng_comm_feed_detail_tv_yellow_selector"
        android:textSize="@dimen/umeng_comm_text_24px" />

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/umeng_comm_dimen_1px"
        android:layout_alignLeft="@id/umeng_comm_comment_time_tv"
        android:layout_below="@id/umeng_comm_comment_time_tv"
        android:layout_marginTop="@dimen/umeng_comm_dimen_30px"
        android:background="@color/umeng_comm_color_de" />

</RelativeLayout>


text: A recipe program.