text:
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>

#include "bgp/bgp_factory.h"
#include "bgp/bgp_mvpn.h"
#include "bgp/bgp_sandesh.h"
#include "bgp/bgp_xmpp_sandesh.h"
#include "bgp/bgp_session_manager.h"
#include "bgp/bgp_xmpp_channel.h"
#include "bgp/mvpn/mvpn_table.h"
#include "bgp/test/bgp_server_test_util.h"
#include "bgp/xmpp_message_builder.h"
#include "io/test/event_manager_test.h"
#include "control-node/control_node.h"
#include "control-node/test/network_agent_mock.h"
#include "schema/xmpp_mvpn_types.h"
#include "xmpp/xmpp_factory.h"
#include "xmpp/test/xmpp_test_util.h"

using namespace autogen;
using namespace boost::asio;
using namespace boost::assign;
using namespace std;
using namespace test;

class BgpXmppMvpnTest : public ::testing::Test {
protected:
    BgpXmppMvpnTest() : thread_(&evm_), xs_x_(NULL) { }

    static void ValidateShowRouteResponse(Sandesh *sandesh,
        vector<size_t> &result) {
        ShowRouteResp *resp = dynamic_cast<ShowRouteResp *>(sandesh);
        EXPECT_NE((ShowRouteResp *)NULL, resp);

        TASK_UTIL_EXPECT_EQ(result.size(), resp->get_tables().size());

        cout << "*******************************************************"<<endl;
        for (size_t i = 0; i < resp->get_tables().size(); i++) {
            cout << resp->get_tables()[i].routing_instance << " "
                 << resp->get_tables()[i].routing_table_name << endl;
            for (size_t j = 0; j < resp->get_tables()[i].routes.size(); j++) {
                cout << resp->get_tables()[i].routes[j].prefix << " "
                        << resp->get_tables()[i].routes[j].paths.size() << endl;
            }
            TASK_UTIL_EXPECT_EQ(result[i], resp->get_tables()[i].routes.size());
        }
        cout << "*******************************************************"<<endl;
        validate_done_ = 1;
    }

    static void ValidateShowManagerMvpnDetailResponse(Sandesh *sandesh,
        vector<string> &result) {
        ShowMvpnManagerDetailResp *resp =
            dynamic_cast<ShowMvpnManagerDetailResp *>(sandesh);
        EXPECT_NE((ShowMvpnManagerDetailResp *)NULL, resp);

        TASK_UTIL_EXPECT_EQ(result.size(), resp->get_neighbors().size());
        cout << "*******************************************************"<<endl;
        for (size_t i = 0; i < resp->get_neighbors().size(); ++i) {
            cout << resp->get_neighbors()[i].log() << endl;
            bool found = false;
            BOOST_FOREACH(const string &rd, result) {
                if (resp->get_neighbors()[i].get_rd() == rd) {
                    found = true;
                    break;
                }
            }
            EXPECT_TRUE(found);
        }
        cout << "*******************************************************"<<endl;
        validate_done_ = 1;
    }

    static void ValidateShowProjectManagerMvpnDetailResponse(Sandesh *sandesh,
        vector<string> &result) {
        ShowMvpnProjectManagerDetailResp *resp =
            dynamic_cast<ShowMvpnProjectManagerDetailResp *>(sandesh);
        EXPECT_NE((ShowMvpnProjectManagerDetailResp *)NULL, resp);

        TASK_UTIL_EXPECT_EQ(result.size(), resp->get_states().size());
        cout << "*******************************************************"<<endl;
        for (size_t i = 0; i < resp->get_states().size(); ++i) {
            cout << resp->get_states()[i].log() << endl;
            bool found = false;
            BOOST_FOREACH(const string &group, result) {
                if (resp->get_states()[i].get_group() == group) {
                    found = true;
                    break;
                }
            }
            EXPECT_TRUE(found);
        }
        cout << "*******************************************************"<<endl;
        validate_done_ = 1;
    }

    void AddMvpnRoute(BgpTable *table, const string &prefix_str,
                      const string &target, bool add_leaf_req = false) {
        MvpnPrefix prefix(MvpnPrefix::FromString(prefix_str));
        DBRequest add_req;
        add_req.key.reset(new MvpnTable::RequestKey(prefix, NULL));

        BgpAttrSpec attr_spec;
        ExtCommunitySpec *commspec(new ExtCommunitySpec());
        RouteTarget tgt = RouteTarget::FromString(target);
        commspec->communities.push_back(tgt.GetExtCommunityValue());
        attr_spec.push_back(commspec);

    if (add_leaf_req) {
            PmsiTunnelSpec *pmsi_spec(new PmsiTunnelSpec());
            pmsi_spec->tunnel_flags = PmsiTunnelSpec::LeafInfoRequired;
            attr_spec.push_back(pmsi_spec);
    }

        BgpAttrPtr attr = bs_x_->attr_db()->Locate(attr_spec);
        STLDeleteValues(&attr_spec);
        add_req.data.reset(new MvpnTable::RequestData(attr, 0, 20));
        add_req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
        table->Enqueue(&add_req);
        task_util::WaitForIdle();
    }

    void DeleteMvpnRoute(BgpTable *table, const string &prefix_str) {
        DBRequest delete_req;
        MvpnPrefix prefix(MvpnPrefix::FromString(prefix_str));
        delete_req.key.reset(new MvpnTable::RequestKey(prefix, NULL));
        delete_req.oper = DBRequest::DB_ENTRY_DELETE;
        table->Enqueue(&delete_req);
        task_util::WaitForIdle();
    }

    virtual void SetUp() {
        bs_x_.reset(new BgpServerTest(&evm_, "X"));
        bs_x_->set_mvpn_ipv4_enable(true);
        xs_x_ = new XmppServer(&evm_, test::XmppDocumentMock::kControlNodeJID);
        bs_x_->session_manager()->Initialize(0);
        xs_x_->Initialize(0, false);
        bcm_x_.reset(new BgpXmppChannelManager(xs_x_, bs_x_.get()));

        thread_.Start();
    }

    virtual void TearDown() {
        xs_x_->Shutdown();
        task_util::WaitForIdle();
        bs_x_->Shutdown();
        task_util::WaitForIdle();
        bcm_x_.reset();
        TcpServerManager::DeleteServer(xs_x_);
        xs_x_ = NULL;

        agent_xa_->Delete();
        agent_xb_->Delete();
        agent_xc_->Delete();

        evm_.Shutdown();
        thread_.Join();
        task_util::WaitForIdle();
    }

    virtual void SessionUp() {
        agent_xa_.reset(new test::NetworkAgentMock(
            &evm_, "agent-xa", xs_x_->GetPort(), "127.0.0.1", "127.0.0.101"));
        TASK_UTIL_EXPECT_TRUE(agent_xa_->IsEstablished());
        agent_xb_.reset(new test::NetworkAgentMock(
            &evm_, "agent-xb", xs_x_->GetPort(), "127.0.0.2", "127.0.0.101"));
        TASK_UTIL_EXPECT_TRUE(agent_xb_->IsEstablished());
        agent_xc_.reset(new test::NetworkAgentMock(
            &evm_, "agent-xc", xs_x_->GetPort(), "127.0.0.3", "127.0.0.101"));
        TASK_UTIL_EXPECT_TRUE(agent_xc_->IsEstablished());
    }

    virtual void SessionDown() {
        agent_xa_->SessionDown();
        agent_xb_->SessionDown();
        agent_xc_->SessionDown();
        task_util::WaitForIdle();
    }

    virtual void Subscribe(const string net, int id) {
        agent_xa_->MvpnSubscribe(net, id);
        agent_xb_->MvpnSubscribe(net, id);
        agent_xc_->MvpnSubscribe(net, id);
        agent_xa_->McastSubscribe(BgpConfigManager::kFabricInstance, 1000);
        agent_xb_->McastSubscribe(BgpConfigManager::kFabricInstance, 1000);
        agent_xc_->McastSubscribe(BgpConfigManager::kFabricInstance, 1000);
        task_util::WaitForIdle();
    }

    virtual void Configure(const char *config_tmpl) {
        char config[8192];
        snprintf(config, sizeof(config), config_tmpl,
            bs_x_->session_manager()->GetPort());
        bs_x_->Configure(config);
    }

    BgpTable *GetVrfTable(BgpServerTestPtr server, const string &name,
                          Address::Family family = Address::MVPN) {
        RoutingInstanceMgr *rim = server->routing_instance_mgr();
        TASK_UTIL_EXPECT_TRUE(rim->GetRoutingInstance(name) != NULL);
        RoutingInstance *rtinstance = rim->GetRoutingInstance(name);
        TASK_UTIL_EXPECT_TRUE(rtinstance->GetTable(family) != NULL);
        BgpTable *table = rtinstance->GetTable(family);
        return table;
    }

    const BgpTable *GetVrfTable(BgpServerTestPtr server,
                                const string &name,
                                Address::Family family = Address::MVPN) const {
        RoutingInstanceMgr *rim = server->routing_instance_mgr();
        TASK_UTIL_EXPECT_TRUE(rim->GetRoutingInstance(name) != NULL);
        const RoutingInstance *rtinstance = rim->GetRoutingInstance(name);
        TASK_UTIL_EXPECT_TRUE(rtinstance->GetTable(family) != NULL);
        const BgpTable *table = rtinstance->GetTable(family);
        return table;
    }

    size_t GetVrfTableSize(BgpServerTestPtr server, const string &name,
                           Address::Family family = Address::MVPN) const {
        return GetVrfTable(server, name, family)->Size();
    }

    EventManager evm_;
    ServerThread thread_;
    BgpServerTestPtr bs_x_;
    XmppServer *xs_x_;
    boost::scoped_ptr<BgpXmppChannelManager> bcm_x_;
    boost::shared_ptr<test::NetworkAgentMock> agent_xa_;
    boost::shared_ptr<test::NetworkAgentMock> agent_xb_;
    boost::shared_ptr<test::NetworkAgentMock> agent_xc_;

    static int validate_done_;
};

int BgpXmppMvpnTest::validate_done_;

static const char *config_tmpl1 = "\
<config>\
    <bgp-router name=\'X\'>\
        <identifier>192.168.0.101</identifier>\
        <address>127.0.0.101</address>\
        <port>%d</port>\
    </bgp-router>\
    <virtual-network name='default-domain:default-project:ip-fabric'>\
        <network-id>1000</network-id>\
    </virtual-network>\
    <routing-instance name='default-domain:default-project:ip-fabric:ip-fabric'>\
        <virtual-network>blue</virtual-network>\
        <vrf-target>target:1:100</vrf-target>\
    </routing-instance>\
    <virtual-network name='blue'>\
        <network-id>1</network-id>\
    </virtual-network>\
    <routing-instance name='blue'>\
        <virtual-network>blue</virtual-network>\
        <vrf-target>target:1:1</vrf-target>\
    </routing-instance>\
</config>\
";

class BgpXmppMvpnErrorTest : public BgpXmppMvpnTest {
protected:
    virtual void SetUp() {
        BgpXmppMvpnTest::SetUp();

        Configure(config_tmpl1);
        task_util::WaitForIdle();

        BgpXmppMvpnTest::SessionUp();
        BgpXmppMvpnTest::Subscribe("blue", 1);
        task_util::WaitForIdle();
    }

    virtual void TearDown() {
        BgpXmppMvpnTest::SessionDown();
        BgpXmppMvpnTest::TearDown();
    }
};

TEST_F(BgpXmppMvpnErrorTest, BadGroupAddress) {
    agent_xa_->AddType7MvpnRoute("blue", "225.0.0,90.1.1.1");
    TASK_UTIL_EXPECT_EQ(1, GetVrfTableSize(bs_x_, "blue"));
}

TEST_F(BgpXmppMvpnErrorTest, BadSourceAddress) {
    agent_xa_->AddType7MvpnRoute("blue", "225.0.0.1,90.1.1");
    TASK_UTIL_EXPECT_EQ(1, GetVrfTableSize(bs_x_, "blue"));
}

class BgpXmppMvpnSubscriptionTest : public BgpXmppMvpnTest {
protected:
    static const int kTimeoutSeconds = 15;
    virtual void SetUp() {
        BgpXmppMvpnTest::SetUp();

        Configure(config_tmpl1);
        task_util::WaitForIdle();
        BgpXmppMvpnTest::SessionUp();
    }

    virtual void TearDown() {
        BgpXmppMvpnTest::SessionDown();
        BgpXmppMvpnTest::TearDown();
    }
};

TEST_F(BgpXmppMvpnSubscriptionTest, PendingSubscribeType5) {
    const char *mroute = "225.0.0.1,20.1.1.10";

    // Register agent a to the multicast table and add a mvpn route of type 5
    // without waiting for the subscription to be processed.
    agent_xa_->MvpnSubscribe("blue", 1);
    agent_xa_->MvpnSubscribe(BgpConfigManager::kFabricInstance, 1000);
    agent_xa_->AddType5MvpnRoute("blue", mroute, "20.1.1.11");

    // Verify that the route gets added
    TASK_UTIL_EXPECT_EQ(2, GetVrfTableSize(bs_x_, "blue"));

    // Add the route again, there should still be only 1 route
    agent_xa_->AddType5MvpnRoute("blue", mroute, "20.1.1.11");
    TASK_UTIL_EXPECT_EQ(2, GetVrfTableSize(bs_x_, "blue"));

    // Add another route, there should be 2 routes
    const char *mroute2 = "225.0.0.1,20.1.1.20";
    agent_xa_->AddType5MvpnRoute("blue", mroute2, "20.1.1.12");
    TASK_UTIL_EXPECT_EQ(3, GetVrfTableSize(bs_x_, "blue"));

    // Delete one mvpn route, there should still be a route
    agent_xa_->DeleteMvpnRoute("blue", mroute2, MvpnPrefix::SourceActiveADRoute);
    TASK_UTIL_EXPECT_EQ(2, GetVrfTableSize(bs_x_, "blue"));

    // Delete second route, it should get deleted
    agent_xa_->DeleteMvpnRoute("blue", mroute, MvpnPrefix::SourceActiveADRoute);
    TASK_UTIL_EXPECT_EQ(1, GetVrfTableSize(bs_x_, "blue"));
}

TEST_F(BgpXmppMvpnSubscriptionTest, PendingSubscribeType7) {
    const char *mroute = "225.0.0.1,20.1.1.10";

    // Register agent a to the multicast table and add a mvpn route of type 7
    // without waiting for the subscription to be processed.
    agent_xa_->MvpnSubscribe("blue", 1);
    agent_xa_->MvpnSubscribe(BgpConfigManager::kFabricInstance, 1000);
    agent_xa_->AddType5MvpnRoute("blue", mroute, "20.1.1.11");

    // Verify that the route gets added
    TASK_UTIL_EXPECT_EQ(2, GetVrfTableSize(bs_x_, "blue"));

    // Add the route again, there should still be only 1 route
    agent_xb_->MvpnSubscribe("blue", 1);
    agent_xb_->MvpnSubscribe(BgpConfigManager::kFabricInstance, 1000);
    agent_xb_->AddType5MvpnRoute("blue", mroute, "20.1.1.12");
    agent_xa_->AddType5MvpnRoute("blue", mroute, "20.1.1.11");
    TASK_UTIL_EXPECT_EQ(2, GetVrfTableSize(bs_x_, "blue"));

    // Delete mvpn route from one agent, there should still be a route
    agent_xa_->DeleteMvpnRoute("blue", mroute, MvpnPrefix::SourceActiveADRoute);
    TASK_UTIL_EXPECT_EQ(2, GetVrfTableSize(bs_x_, "blue"));

    // Delete route from second agent, it should get deleted
    agent_xb_->DeleteMvpnRoute("blue", mroute, MvpnPrefix::SourceActiveADRoute);
    // Delete route from second agent, it should get deleted
    TASK_UTIL_EXPECT_EQ(1, GetVrfTableSize(bs_x_, "blue"));
}

TEST_F(BgpXmppMvpnSubscriptionTest, PendingUnsubscribe) {
    const char *mroute = "225.0.0.1,10.1.1.10";

    // Register agent a to the multicast table and add a mvpn route
    // without waiting for the subscription to be processed. Then go
    // ahead and unsubscribe right away.
    agent_xa_->MvpnSubscribe("blue", 1);
    agent_xa_->MvpnSubscribe(BgpConfigManager::kFabricInstance, 1000);
    agent_xa_->AddType7MvpnRoute("blue", mroute);
    agent_xa_->MvpnUnsubscribe("blue");
    agent_xa_->MvpnUnsubscribe(BgpConfigManager::kFabricInstance);

    // Verify number of routes.
    TASK_UTIL_EXPECT_EQ(1, GetVrfTableSize(bs_x_, "blue"));
}

TEST_F(BgpXmppMvpnSubscriptionTest, SubsequentSubscribeUnsubscribe) {
    const char *mroute = "225.0.0.1,10.1.1.10";

    // Register agent b to the multicast table and add a mvpn route
    // after waiting for the subscription to be processed.
    agent_xb_->MvpnSubscribe("blue", 1);
    agent_xb_->MvpnSubscribe(BgpConfigManager::kFabricInstance, 1000);
    task_util::WaitForIdle();
    agent_xb_->AddType7MvpnRoute("blue", mroute);
    MvpnTable *blue_table_ = static_cast<MvpnTable *>(
        bs_x_->database()->FindTable("blue.mvpn.0"));

    // Register agent a to the multicast table and add a mvpn route
    // without waiting for the subscription to be processed. Then go
    // ahead and unsubscribe right away. Then subscribe again with a
    // different id and add the route again.
    agent_xa_->MvpnSubscribe("blue", 1);
    agent_xa_->MvpnSubscribe(BgpConfigManager::kFabricInstance, 1000);
    agent_xa_->AddType7MvpnRoute("blue", mroute);
    agent_xa_->MvpnUnsubscribe("blue");
    agent_xa_->MvpnUnsubscribe(BgpConfigManager::kFabricInstance);
    agent_xa_->MvpnSubscribe("blue", 2);
    agent_xa_->MvpnSubscribe(BgpConfigManager::kFabricInstance, 1000);
    agent_xa_->AddType7MvpnRoute("blue", mroute);

    // Verify number of routes in blue table.
    TASK_UTIL_EXPECT_EQ(2, GetVrfTableSize(bs_x_, "blue"));

    // Verify that agent a mvpn route was added.
    const char *route = "7-0:0,0,10.1.1.10,225.0.0.1";
    MvpnPrefix prefix(MvpnPrefix::FromString(route));
    MvpnTable::RequestKey key(prefix, NULL);
    TASK_UTIL_EXPECT_TRUE(
        dynamic_cast<MvpnRoute *>(blue_table_->Find(&key)) != NULL);

    // Delete mvpn route for all agents.
    agent_xa_->DeleteMvpnRoute("blue", mroute);
    agent_xb_->DeleteMvpnRoute("blue", mroute);
    task_util::WaitForIdle();
};

class BgpXmppMvpnMultiAgentTest : public BgpXmppMvpnTest {
protected:
    virtual void SetUp() {
        BgpXmppMvpnTest::SetUp();

        Configure(config_tmpl1);
        task_util::WaitForIdle();

        BgpXmppMvpnTest::SessionUp();
        BgpXmppMvpnTest::Subscribe("blue", 1);
    }

    virtual void TearDown() {
        BgpXmppMvpnTest::SessionDown();
        BgpXmppMvpnTest::TearDown();
    }
};

TEST_F(BgpXmppMvpnMultiAgentTest, MultipleRoutes) {
    const char *mroute_list[] = {
        "225.0.0.1,90.1.1.1",
        "225.0.0.1,90.1.1.2",
        "225.0.0.2,90.1.1.1",
        "225.0.0.2,90.1.1.2"
    };

    // Add mvpn routes for all agents.
    BOOST_FOREACH(const char *mroute, mroute_list) {
        agent_xa_->AddType7MvpnRoute("blue", mroute);
        agent_xb_->AddType7MvpnRoute("blue", mroute);
        task_util::WaitForIdle();
    }

    // Verify that all routes are added once.
    TASK_UTIL_EXPECT_EQ(sizeof(mroute_list)/sizeof(mroute_list[0]) + 1,
                        GetVrfTableSize(bs_x_, "blue"));

    // Delete mvpn route for all agents.
    BOOST_FOREACH(const char *mroute, mroute_list) {
        agent_xa_->DeleteMvpnRoute("blue", mroute);
        agent_xb_->DeleteMvpnRoute("blue", mroute);
        task_util::WaitForIdle();
    }
};

TEST_F(BgpXmppMvpnMultiAgentTest, ValidateShowRoute) {
    const char *mroute_list[] = {
        "225.0.0.1,90.1.1.1",
    };

    // Add mvpn routes for all agents.
    BOOST_FOREACH(const char *mroute, mroute_list) {
        agent_xa_->AddType7MvpnRoute("blue", mroute);
        agent_xb_->AddType7MvpnRoute("blue", mroute);
        task_util::WaitForIdle();
    }

    // Verify that all routes are added once.
    TASK_UTIL_EXPECT_EQ(sizeof(mroute_list)/sizeof(mroute_list[0]) + 1,
                        GetVrfTableSize(bs_x_, "blue"));
    TASK_UTIL_EXPECT_EQ(4, GetVrfTableSize(bs_x_,
                        BgpConfigManager::kFabricInstance, Address::ERMVPN));

    // Verify routes via sandesh.
    BgpSandeshContext sandesh_context;
    RegisterSandeshShowXmppExtensions(&sandesh_context);
    sandesh_context.bgp_server = bs_x_.get();
    sandesh_context.xmpp_peer_manager = bcm_x_.get();
    Sandesh::set_client_context(&sandesh_context);

    // First get all tables.
    // blue.mvpn.0, bgp.ermvpn.0, bgp.mvpn.0, bgp.rtarget.0,
    // default-domain:default-project:ip-fabric:ip-fabric.ermvpn.0,
    // default-domain:default-project:ip-fabric:ip-fabric.mvpn.0
    std::vector<size_t> result = list_of(2)(2)(2)(5)(4)(1);
    Sandesh::set_response_callback(
        boost::bind(ValidateShowRouteResponse, _1, result));
    ShowRouteReq *show_req = new ShowRouteReq;
    validate_done_ = 0;
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);

    // Now get blue.mvpn.0.
    result = list_of(2);
    Sandesh::set_response_callback(
        boost::bind(ValidateShowRouteResponse, _1, result));
    show_req = new ShowRouteReq;
    show_req->set_routing_table("blue.mvpn.0");
    validate_done_ = 0;
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);

    // Now get bgp.mvpn.0.
    result = list_of(2);
    Sandesh::set_response_callback(
        boost::bind(ValidateShowRouteResponse, _1, result));
    show_req = new ShowRouteReq;
    show_req->set_routing_table("bgp.mvpn.0");
    validate_done_ = 0;
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);

    // Delete mvpn route for all agents.
    BOOST_FOREACH(const char *mroute, mroute_list) {
        agent_xa_->DeleteMvpnRoute("blue", mroute);
        agent_xb_->DeleteMvpnRoute("blue", mroute);
        task_util::WaitForIdle();
    }

    // Verify that all routes are deleted.
    TASK_UTIL_EXPECT_EQ(1, GetVrfTableSize(bs_x_, "blue"));

    // Get blue.mvpn.0 again.
    result = list_of(1);
    Sandesh::set_response_callback(
        boost::bind(ValidateShowRouteResponse, _1, result));
    show_req = new ShowRouteReq;
    show_req->set_routing_table("blue.mvpn.0");
    validate_done_ = 0;
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);

    // Get bgp.mvpn.0 again.
    result = list_of(2);
    Sandesh::set_response_callback(
        boost::bind(ValidateShowRouteResponse, _1, result));
    show_req = new ShowRouteReq;
    show_req->set_routing_table("bgp.mvpn.0");
    validate_done_ = 0;
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);
};

TEST_F(BgpXmppMvpnMultiAgentTest, ValidateShowMvpnManagerDetail) {
    // Inject Type-1 AD Route directly into the bgp.mvpn.0 table.
    string prefix = "1-10.1.1.1:65535,9.8.7.6";
    BgpTable *master = GetVrfTable(bs_x_, BgpConfigManager::kMasterInstance);
    BgpTable *blue = GetVrfTable(bs_x_, "blue");
    AddMvpnRoute(master, prefix, "target:1:1");

    // Verify that all routes are added once.
    TASK_UTIL_EXPECT_EQ(2, blue->Size());

    // Verify multicast manager detail via sandesh.
    BgpSandeshContext sandesh_context;
    RegisterSandeshShowXmppExtensions(&sandesh_context);
    sandesh_context.bgp_server = bs_x_.get();
    sandesh_context.xmpp_peer_manager = bcm_x_.get();
    Sandesh::set_client_context(&sandesh_context);
    vector<string> result = list_of("10.1.1.1:65535");
    Sandesh::set_response_callback(
        boost::bind(ValidateShowManagerMvpnDetailResponse, _1, result));
    ShowMvpnManagerDetailReq *show_req = new ShowMvpnManagerDetailReq;
    validate_done_ = 0;
    show_req->set_name("blue.mvpn.0");
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);

    DeleteMvpnRoute(master, prefix);
    TASK_UTIL_EXPECT_EQ(1, blue->Size());
    TASK_UTIL_EXPECT_EQ(2, master->Size());

    // Get blue.mvpn.0 again.
    result.resize(0);
    Sandesh::set_response_callback(
        boost::bind(ValidateShowManagerMvpnDetailResponse, _1, result));
    show_req = new ShowMvpnManagerDetailReq;
    validate_done_ = 0;
    show_req->set_name("blue.mvpn.0");
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);
};

TEST_F(BgpXmppMvpnMultiAgentTest, ValidateShowMvpnProjectManagerDetail) {
    BgpTable *master = GetVrfTable(bs_x_, BgpConfigManager::kMasterInstance);
    BgpTable *blue = GetVrfTable(bs_x_, "blue");

    const char *mroute_list[] = {
        "225.0.0.1,9.8.7.6",
    };

    // Add mvpn routes for all agents.
    BOOST_FOREACH(const char *mroute, mroute_list) {
        agent_xa_->AddType7MvpnRoute("blue", mroute);
        agent_xb_->AddType7MvpnRoute("blue", mroute);
        task_util::WaitForIdle();
    }

    string prefix = "3-10.1.1.1:65535,9.8.7.6,225.0.0.1,192.168.1.1";
    AddMvpnRoute(master, prefix, "target:1:1", true);

    // Verify that all routes are added once.
    TASK_UTIL_EXPECT_EQ(sizeof(mroute_list)/sizeof(mroute_list[0]) + 2,
                        GetVrfTableSize(bs_x_, "blue"));

    // Verify that all routes are added once.
    TASK_UTIL_EXPECT_EQ(3, master->Size());
    TASK_UTIL_EXPECT_EQ(3, blue->Size());

    // Verify multicast manager detail via sandesh.
    BgpSandeshContext sandesh_context;
    RegisterSandeshShowXmppExtensions(&sandesh_context);
    sandesh_context.bgp_server = bs_x_.get();
    sandesh_context.xmpp_peer_manager = bcm_x_.get();
    Sandesh::set_client_context(&sandesh_context);
    vector<string> result = list_of("225.0.0.1");
    Sandesh::set_response_callback(
        boost::bind(ValidateShowProjectManagerMvpnDetailResponse, _1, result));
    ShowMvpnProjectManagerDetailReq *show_req =
        new ShowMvpnProjectManagerDetailReq;
    validate_done_ = 0;
    show_req->set_name(string(BgpConfigManager::kFabricInstance) + ".ermvpn.0");
    show_req->HandleRequest();
    show_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);

    // Add mvpn routes for all agents.
    BOOST_FOREACH(const char *mroute, mroute_list) {
        agent_xa_->DeleteMvpnRoute("blue", mroute);
        agent_xb_->DeleteMvpnRoute("blue", mroute);
        task_util::WaitForIdle();
    }
    DeleteMvpnRoute(master, prefix);

    // Verify that only type-1 ad route remains.
    TASK_UTIL_EXPECT_EQ(1, blue->Size());
    TASK_UTIL_EXPECT_EQ(2, master->Size());

    result.resize(0);
    Sandesh::set_response_callback(
        boost::bind(ValidateShowManagerMvpnDetailResponse, _1, result));
    ShowMvpnManagerDetailReq *show_pm_req = new ShowMvpnManagerDetailReq;
    validate_done_ = 0;
    show_pm_req->set_name(
        string(BgpConfigManager::kFabricInstance) + ".ermvpn.0");
    show_pm_req->HandleRequest();
    show_pm_req->Release();
    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(1, validate_done_);
};

class TestEnvironment : public ::testing::Environment {
    virtual ~TestEnvironment() { }
    virtual void SetUp() {
    }
    virtual void TearDown() {
    }
};

static void SetUp() {
    BgpServer::Initialize();
    ControlNode::SetDefaultSchedulingPolicy();
    BgpServerTest::GlobalSetUp();
    BgpObjectFactory::Register<StateMachine>(
        boost::factory<StateMachineTest *>());
    BgpObjectFactory::Register<BgpXmppMessageBuilder>(
        boost::factory<BgpXmppMessageBuilder *>());
    XmppObjectFactory::Register<XmppStateMachine>(
        boost::factory<XmppStateMachineTest *>());
}

static void TearDown() {
    BgpServer::Terminate();
    TaskScheduler *scheduler = TaskScheduler::GetInstance();
    scheduler->Terminate();
}

int main(int argc, char **argv) {
    bgp_log_test::init();
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::AddGlobalTestEnvironment(new TestEnvironment());
    SetUp();
    int result = RUN_ALL_TESTS();
    TearDown();

    return result;
}


text:
package org.apache.camel.spring.cloud;

import java.util.List;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.NoTypeConversionAvailableException;
import org.apache.camel.cloud.ServiceDiscovery;
import org.apache.camel.impl.cloud.StaticServiceDiscovery;
import org.apache.camel.spring.boot.util.GroupCondition;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

@Configuration
@EnableConfigurationProperties(CamelCloudConfigurationProperties.class)
@Conditional(CamelCloudServiceDiscoveryAutoConfiguration.Condition.class)
public class CamelCloudServiceDiscoveryAutoConfiguration {

    @Lazy
    @Bean(name = "static-service-discovery")
    public ServiceDiscovery staticServiceDiscovery(CamelCloudConfigurationProperties properties) {
        StaticServiceDiscovery staticServiceDiscovery = new StaticServiceDiscovery();

        Map<String, List<String>> services = properties.getServiceDiscovery().getServices();
        for (Map.Entry<String, List<String>> entry : services.entrySet()) {
            staticServiceDiscovery.addServers(entry.getKey(), entry.getValue());
        }

        return staticServiceDiscovery;
    }

    @Lazy
    @Bean(name = "service-discovery")
    public CamelCloudServiceDiscovery serviceDiscovery(
            CamelContext camelContext, CamelCloudConfigurationProperties properties, List<ServiceDiscovery> serviceDiscoveryList) throws NoTypeConversionAvailableException {

        String cacheTimeout = properties.getServiceDiscovery().getCacheTimeout();
        Long timeout = null;

        if (cacheTimeout != null) {
            timeout = camelContext.getTypeConverter().mandatoryConvertTo(Long.class, timeout);
        }

        return new CamelCloudServiceDiscovery(timeout, serviceDiscoveryList);
    }

    // *******************************
    // Condition
    // *******************************

    public static class Condition extends GroupCondition {
        public Condition() {
            super(
                "camel.cloud",
                "camel.cloud.service-discovery"
            );
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
C
C
*+ do_perc_map

       subroutine do_perc_map(map_array,status)
C      ----------------------------------------
C
C construct a %mI/error map from an mI/I map
C
C Given:
C   map data
       real*4        map_array(*)
C Returned:
C   error status word
       integer       status
C
C A %mI map with an associated error map are calculated from an mI and
C an I map.
*-
       include '../include/error_file_full.inc'

C Local variables
       integer    minirt(8), imapmi, ip_mapmi, iu, iv,
     *            iwarn, imapo, ip_mapo, imape, ip_mape, imapi, ip_mapi
       real*4     i_noise, p_noise, gate, val_lim_mi, val_lim_i,
     *            val_i, val_mi, val_per
       real*4     freq, blank
       integer    ipoln
       character  name*16, unit*16

C check status on entry
       if (status.ne.0) return

C find mI and I maps
       call map_getmap('Map-mI : ','Default-Map','READ',imapmi,status)
       call io_getr('noise on mi-map : ','0.0',p_noise,status)
       call map_getmap('Map-I : ','Default-Map','READ',imapi,status)
       call io_getr('Noise on I-map : ','0.0',i_noise,status)
       call io_getr('Gate : ','0.0',gate,status)
       if (status.ne.0) goto 999

C check redtape
       iwarn = 2
       call redt_comp(imapmi,imapi,iwarn,status)
       if (status.ne.0. .or. iwarn.gt.5) goto 999

C check input polarizations
       call redt_load(imapmi,status)
       call entype(freq,ipoln,name,unit,status)
       if (ipoln.ne.10) then
         call cmd_wrerr('PERC-MAP','Invalid polarization code')
         call cmd_wrerr('PERC-MAP','Warning Input mI-map')
       end if
       call redt_load(imapi,status)
       call entype(freq,ipoln,name,unit,status)
       if (ipoln.ne.1) then
         call cmd_wrerr('PERC-MAP','Invalid polarization code')
         call cmd_wrerr('PERC-MAP','Warning Input I-map')
       end if

C allocate maps
       call map_alloc_in(imapi,'SEQUENTIAL',map_array,ip_mapi,status)
       call map_alloc_in(imapmi,'SEQUENTIAL',map_array,ip_mapmi,status)
       call map_alloc_out(0,0,'SEQUENTIAL',imapo,ip_mapo,status)
       call map_alloc_out(0,0,'SEQUENTIAL',imape,ip_mape,status)

C construct the mI map
       call ennull(blank,status)
       call enminirt(minirt,status)
       val_lim_mi = p_noise*gate
       val_lim_i =  i_noise*gate
       do iv = minirt(3),minirt(4),-1
         call map_row_read(imapi,iv,map_array,ip_mapi,status)
         call map_row_read(imapmi,iv,map_array,ip_mapmi,status)
         do iu = 1,minirt(5)
           val_i  = map_array(ip_mapi+iu-1)
           val_mi = map_array(ip_mapmi+iu-1)
           if (val_mi.gt.val_lim_mi .and. val_i.gt.val_lim_i) then
             val_per = 100.0*val_mi/val_i
             map_array(ip_mapo+iu-1) = val_per
             map_array(ip_mape+iu-1) = sqrt((p_noise**2)/(val_mi**2)
     *                             + (i_noise**2)/(val_i**2))*val_per
           else
             map_array(ip_mapo+iu-1) = 0.0
             map_array(ip_mape+iu-1) = blank
           end if
         end do
         call map_row_write(imapo,iv,map_array,ip_mapo,status)
         call map_row_write(imape,iv,map_array,ip_mape,status)
       end do

C update the redtape
       call adredt('created','PERC-ERR',status)
       call redt_update('PERC',12,-1.0,'Error %mI','PERCENT',status)

C end error map
999    call map_end_alloc(imape,map_array,status)

C main map
       call redt_update('PERC',12,-1.0,'%mI','PERCENT',status)
       call adredt('created','PERC-MAP',status)
       call map_end_alloc(imapo,map_array,status)

C input maps
       call map_end_alloc(imapi,map_array,status)
       call map_end_alloc(imapmi,map_array,status)

C check status value
       call cmd_err(status,'PERC-MAP','Failed ')
       end


text:
from random import randrange
from django.db.models import (
    DateField,
    IntegerField,
    CharField,
    EmailField,
    BooleanField,
    DateTimeField
)
from django.utils import timezone
from django.contrib.auth.models import(
    AbstractBaseUser,
    UserManager,
    PermissionsMixin
)

def my_random_key():
    return randrange(100)

class User(AbstractBaseUser, PermissionsMixin):
    username = CharField(max_length=20, unique=True)
    email = EmailField(max_length=254, unique=True)
    birthday = DateField(blank=False, null=False)
    number = IntegerField(blank=False, null=True, default=my_random_key)
    is_staff = BooleanField(default=False)
    is_active = BooleanField(default=False)
    date_joined = DateTimeField(default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.username

    def get_short_name(self):
        return self.email

    def get_year(self):
        return self.birthday.year


text:
package org.wso2.carbon.utils.component.xml.config;

public class HTTPGetRequestProcessorConfig implements ComponentConfig {

    private String item;
    private String className;

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}


text:
import { deepStrictEqual as deepEqual, strictEqual as equal } from 'node:assert'

import { temporaryFile } from 'tempy'

import { JSONFileSync } from './JSONFileSync.js'

export function testJSONFileSync(): void {
  const obj = { a: 1 }
  const file = new JSONFileSync(temporaryFile())

  // Null if file doesn't exist
  equal(file.read(), null)

  // Write
  equal(file.write(obj), undefined)

  // Read
  deepEqual(file.read(), obj)
}


text:
"""Test basic initialization for the Legacy Nest API using mocks for the Nest python library."""

import time
from unittest.mock import MagicMock, PropertyMock, patch

from homeassistant.setup import async_setup_component

from tests.common import MockConfigEntry

DOMAIN = "nest"

CONFIG = {
    "nest": {
        "client_id": "some-client-id",
        "client_secret": "some-client-secret",
    },
}

CONFIG_ENTRY_DATA = {
    "auth_implementation": "local",
    "tokens": {
        "expires_at": time.time() + 86400,
        "access_token": {
            "token": "some-token",
        },
    },
}

def make_thermostat():
    """Make a mock thermostat with dummy values."""
    device = MagicMock()
    type(device).device_id = PropertyMock(return_value="a.b.c.d.e.f.g")
    type(device).name = PropertyMock(return_value="My Thermostat")
    type(device).name_long = PropertyMock(return_value="My Thermostat")
    type(device).serial = PropertyMock(return_value="serial-number")
    type(device).mode = "off"
    type(device).hvac_state = "off"
    type(device).target = PropertyMock(return_value=31.0)
    type(device).temperature = PropertyMock(return_value=30.1)
    type(device).min_temperature = PropertyMock(return_value=10.0)
    type(device).max_temperature = PropertyMock(return_value=50.0)
    type(device).humidity = PropertyMock(return_value=40.4)
    type(device).software_version = PropertyMock(return_value="a.b.c")
    return device

async def test_thermostat(hass):
    """Test simple initialization for thermostat entities."""

    thermostat = make_thermostat()

    structure = MagicMock()
    type(structure).name = PropertyMock(return_value="My Room")
    type(structure).thermostats = PropertyMock(return_value=[thermostat])
    type(structure).eta = PropertyMock(return_value="away")

    nest = MagicMock()
    type(nest).structures = PropertyMock(return_value=[structure])

    config_entry = MockConfigEntry(domain=DOMAIN, data=CONFIG_ENTRY_DATA)
    config_entry.add_to_hass(hass)
    with patch("homeassistant.components.nest.legacy.Nest", return_value=nest), patch(
        "homeassistant.components.nest.legacy.sensor._VALID_SENSOR_TYPES",
        ["humidity", "temperature"],
    ), patch(
        "homeassistant.components.nest.legacy.binary_sensor._VALID_BINARY_SENSOR_TYPES",
        {"fan": None},
    ):
        assert await async_setup_component(hass, DOMAIN, CONFIG)
        await hass.async_block_till_done()

    climate = hass.states.get("climate.my_thermostat")
    assert climate is not None
    assert climate.state == "off"

    temperature = hass.states.get("sensor.my_thermostat_temperature")
    assert temperature is not None
    assert temperature.state == "-1.1"

    humidity = hass.states.get("sensor.my_thermostat_humidity")
    assert humidity is not None
    assert humidity.state == "40.4"

    fan = hass.states.get("binary_sensor.my_thermostat_fan")
    assert fan is not None
    assert fan.state == "on"


text:
jsreport is mainly distributed through [node package manager](https://www.npmjs.com/package/jsreport), but for windows users we ship also convenient distribution in the single executable file. You simple [download](/on-prem) the file `jsreport.exe` and run it. The executable automatically unpacks required files and runs the node process hosting jsreport server. Except .net runtime there is no need for any other dependency.

## Usage

Start server with default config file on the https 443
> jsreport.exe

Override configuration through command line parameters
> jsreport.exe --httpPort 2000 --httpsPort 0

Install windows service
> jsreport.exe --httpsPort 5000 --install

Uninstall windows service
> jsreport.exe --httpsPort 5000 --uninstall

Get help
> jsreport.exe  --help

## Just rendering
`jsreport.exe` can be also used for command line report rendering without starting a server or REST API.

>jsreport.exe --render request.json --output file.pdf

Where `request.json` is json formatted file with report specification. The file has the same structure as API call so you can use the same instructions as in the [API documentation](/learn/api).

Example `request.json`:
```js
{
  "template": {
    "content": "Hello World {{:foo}}",
    "recipe": "phantom-pdf",
    "engine": "jsrender"
  },
  "data": {
    "foo": "from jsreport command line"
  }
}
```

Additionally you can use `--template` option to specify report template separately. The request is then merged from both `--render` and `--template` values.

>jsreport.exe --render request.json --template tmpl.json --output file.pdf

Example `tmpl.json`:
```js
{
  "content": "Template World {{:foo}}",
  "recipe": "phantom-pdf",
  "engine": "jsrender"
}
```


text:
<?php

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('task_queue', false, true, false, false);

echo " [*] Waiting for messages. To exit press CTRL+C\n";

$callback = function ($msg) {
    echo ' [x] Received ', $msg->body, "\n";
    sleep(substr_count($msg->body, '.'));
    echo " [x] Done\n";
    $msg->ack();
};

$channel->basic_qos(null, 1, null);
$channel->basic_consume('task_queue', '', false, false, false, false, $callback);

while ($channel->is_open()) {
    $channel->wait();
}

$channel->close();
$connection->close();
?>


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">

	<title>restify.io - For RESTful requests.</title>

	<?php echo HTML::style($path . 'css/reset.css'), PHP_EOL; ?>
	<?php echo HTML::style($path . 'css/smoothness/jquery-ui-1.8.23.custom.css'), PHP_EOL; ?>
	<?php echo HTML::style($path . 'css/prettify.css'), PHP_EOL; ?>
	<?php echo HTML::style($path . 'css/styles.css'); ?>

	<?php echo HTML::script($path . 'js/jquery-1.8.1.min.js'), PHP_EOL; ?>
	<?php echo HTML::script($path . 'js/jquery-ui-1.8.23.custom.min.js'), PHP_EOL; ?>
	<?php echo HTML::script($path . 'js/prettify/prettify.js'), PHP_EOL; ?>
	<?php echo HTML::script($path . 'js/json2.min.js'), PHP_EOL; ?>
	<?php echo HTML::script($path . 'js/json_parse.min.js'), PHP_EOL; ?>
	<?php echo HTML::script($path . 'js/global.js'), PHP_EOL; ?>
	<script>
		var restify = {
			controller: '<?php echo URL::site('restify/request') ?>',
			template: {
				data: '<?php echo View::factory('restify/row', array('prefix' => 'data')); ?>',
				header: '<?php echo View::factory('restify/row', array('prefix' => 'header')); ?>'
			}
		};
	</script>
</head>

<body>


text:
<?php

namespace helicon\doctrine\lib\types;

/**
 * UTC-Timestamp Field
 *
 * Stores and reads timestamps as UTC
 */
class UtcDateTimeType extends \Doctrine\DBAL\Types\DateTimeType
{
    static private $utcTz = null;

    const TYPE_NAME = 'utcdatetime';

    public function getName()
    {
        return self::TYPE_NAME;
    }

    public function convertToDatabaseValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {

      $value = new \DateTime ($value, (self::$utcTz) ? self::$utcTz : (self::$utcTz = new \DateTimeZone('UTC')));

      return parent::convertToDatabaseValue($value, $platform);
    }

    public function convertToPHPValue($value, \Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
      $value = new \DateTime ($value, (self::$utcTz) ? self::$utcTz : (self::$utcTz = new \DateTimeZone('UTC')));

      return parent::convertToPHPValue($value, $platform);
    }

    public function requiresSQLCommentHint(\Doctrine\DBAL\Platforms\AbstractPlatform $platform)
    {
        return true;
    }
}


text:
package org.springframework.boot.autoconfigure.neo4j;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.util.Arrays;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.neo4j.driver.AuthToken;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Config;
import org.neo4j.driver.Config.ConfigBuilder;
import org.neo4j.driver.Driver;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties.Authentication;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties.Security.TrustStrategy;
import org.springframework.boot.context.properties.source.InvalidConfigurationPropertyValueException;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.core.env.Environment;
import org.springframework.mock.env.MockEnvironment;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;

/**
 * Tests for {@link Neo4jAutoConfiguration}.
 *
 * @author Michael J. Simons
 * @author Stephane Nicoll
 */
class Neo4jAutoConfigurationTests {

	private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
			.withConfiguration(AutoConfigurations.of(Neo4jAutoConfiguration.class));

	@Test
	void driverNotConfiguredWithoutDriverApi() {
		this.contextRunner.withPropertyValues("spring.neo4j.uri=bolt://localhost:4711")
				.withClassLoader(new FilteredClassLoader(Driver.class))
				.run((ctx) -> assertThat(ctx).doesNotHaveBean(Driver.class));
	}

	@Test
	void driverShouldNotRequireUri() {
		this.contextRunner.run((ctx) -> assertThat(ctx).hasSingleBean(Driver.class));
	}

	@Test
	void driverShouldInvokeConfigBuilderCustomizers() {
		this.contextRunner.withPropertyValues("spring.neo4j.uri=bolt://localhost:4711")
				.withBean(ConfigBuilderCustomizer.class, () -> ConfigBuilder::withEncryption)
				.run((ctx) -> assertThat(ctx.getBean(Driver.class).isEncrypted()).isTrue());
	}

	@ParameterizedTest
	@ValueSource(strings = { "bolt", "neo4j" })
	void uriWithSimpleSchemeAreDetected(String scheme) {
		this.contextRunner.withPropertyValues("spring.neo4j.uri=" + scheme + "://localhost:4711").run((ctx) -> {
			assertThat(ctx).hasSingleBean(Driver.class);
			assertThat(ctx.getBean(Driver.class).isEncrypted()).isFalse();
		});
	}

	@ParameterizedTest
	@ValueSource(strings = { "bolt+s", "bolt+ssc", "neo4j+s", "neo4j+ssc" })
	void uriWithAdvancedSchemesAreDetected(String scheme) {
		this.contextRunner.withPropertyValues("spring.neo4j.uri=" + scheme + "://localhost:4711").run((ctx) -> {
			assertThat(ctx).hasSingleBean(Driver.class);
			Driver driver = ctx.getBean(Driver.class);
			assertThat(driver.isEncrypted()).isTrue();
		});
	}

	@ParameterizedTest
	@ValueSource(strings = { "bolt+routing", "bolt+x", "neo4j+wth" })
	void uriWithInvalidSchemesAreDetected(String invalidScheme) {
		this.contextRunner.withPropertyValues("spring.neo4j.uri=" + invalidScheme + "://localhost:4711")
				.run((ctx) -> assertThat(ctx).hasFailed().getFailure()
						.hasMessageContaining("'%s' is not a supported scheme.", invalidScheme));
	}

	@Test
	void connectionTimeout() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.setConnectionTimeout(Duration.ofMillis(500));
		assertThat(mapDriverConfig(properties).connectionTimeoutMillis()).isEqualTo(500);
	}

	@Test
	void maxTransactionRetryTime() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.setMaxTransactionRetryTime(Duration.ofSeconds(2));
		assertThat(mapDriverConfig(properties)).extracting("retrySettings")
				.hasFieldOrPropertyWithValue("maxRetryTimeMs", 2000L);
	}

	@Test
	void determineServerUriShouldDefaultToLocalhost() {
		assertThat(determineServerUri(new Neo4jProperties(), new MockEnvironment()))
				.isEqualTo(URI.create("bolt://localhost:7687"));
	}

	@Test
	void determineServerUriWithCustomUriShouldOverrideDefault() {
		URI customUri = URI.create("bolt://localhost:4242");
		Neo4jProperties properties = new Neo4jProperties();
		properties.setUri(customUri);
		assertThat(determineServerUri(properties, new MockEnvironment())).isEqualTo(customUri);
	}

	@Test
	void authenticationShouldDefaultToNone() {
		assertThat(mapAuthToken(new Authentication())).isEqualTo(AuthTokens.none());
	}

	@Test
	void authenticationWithUsernameShouldEnableBasicAuth() {
		Authentication authentication = new Authentication();
		authentication.setUsername("Farin");
		authentication.setPassword("Urlaub");
		assertThat(mapAuthToken(authentication)).isEqualTo(AuthTokens.basic("Farin", "Urlaub"));
	}

	@Test
	void authenticationWithUsernameAndRealmShouldEnableBasicAuth() {
		Authentication authentication = new Authentication();
		authentication.setUsername("Farin");
		authentication.setPassword("Urlaub");
		authentication.setRealm("Test Realm");
		assertThat(mapAuthToken(authentication)).isEqualTo(AuthTokens.basic("Farin", "Urlaub", "Test Realm"));
	}

	@Test
	void authenticationWithKerberosTicketShouldEnableKerberos() {
		Authentication authentication = new Authentication();
		authentication.setKerberosTicket("AABBCCDDEE");
		assertThat(mapAuthToken(authentication)).isEqualTo(AuthTokens.kerberos("AABBCCDDEE"));
	}

	@Test
	void authenticationWithBothUsernameAndKerberosShouldNotBeAllowed() {
		Authentication authentication = new Authentication();
		authentication.setUsername("Farin");
		authentication.setKerberosTicket("AABBCCDDEE");
		assertThatIllegalStateException().isThrownBy(() -> mapAuthToken(authentication))
				.withMessage("Cannot specify both username ('Farin') and kerberos ticket ('AABBCCDDEE')");
	}

	@Test
	void poolWithMetricsEnabled() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getPool().setMetricsEnabled(true);
		assertThat(mapDriverConfig(properties).isMetricsEnabled()).isTrue();
	}

	@Test
	void poolWithLogLeakedSessions() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getPool().setLogLeakedSessions(true);
		assertThat(mapDriverConfig(properties).logLeakedSessions()).isTrue();
	}

	@Test
	void poolWithMaxConnectionPoolSize() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getPool().setMaxConnectionPoolSize(4711);
		assertThat(mapDriverConfig(properties).maxConnectionPoolSize()).isEqualTo(4711);
	}

	@Test
	void poolWithIdleTimeBeforeConnectionTest() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getPool().setIdleTimeBeforeConnectionTest(Duration.ofSeconds(23));
		assertThat(mapDriverConfig(properties).idleTimeBeforeConnectionTest()).isEqualTo(23000);
	}

	@Test
	void poolWithMaxConnectionLifetime() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getPool().setMaxConnectionLifetime(Duration.ofSeconds(30));
		assertThat(mapDriverConfig(properties).maxConnectionLifetimeMillis()).isEqualTo(30000);
	}

	@Test
	void poolWithConnectionAcquisitionTimeout() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getPool().setConnectionAcquisitionTimeout(Duration.ofSeconds(5));
		assertThat(mapDriverConfig(properties).connectionAcquisitionTimeoutMillis()).isEqualTo(5000);
	}

	@Test
	void securityWithEncrypted() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getSecurity().setEncrypted(true);
		assertThat(mapDriverConfig(properties).encrypted()).isTrue();
	}

	@Test
	void securityWithTrustSignedCertificates() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES);
		assertThat(mapDriverConfig(properties).trustStrategy().strategy())
				.isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES);
	}

	@Test
	void securityWithTrustAllCertificates() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_ALL_CERTIFICATES);
		assertThat(mapDriverConfig(properties).trustStrategy().strategy())
				.isEqualTo(Config.TrustStrategy.Strategy.TRUST_ALL_CERTIFICATES);
	}

	@Test
	void securityWitHostnameVerificationEnabled() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_ALL_CERTIFICATES);
		properties.getSecurity().setHostnameVerificationEnabled(true);
		assertThat(mapDriverConfig(properties).trustStrategy().isHostnameVerificationEnabled()).isTrue();
	}

	@Test
	void securityWithCustomCertificates(@TempDir File directory) throws IOException {
		File certFile = new File(directory, "neo4j-driver.cert");
		assertThat(certFile.createNewFile()).isTrue();

		Neo4jProperties properties = new Neo4jProperties();
		properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES);
		properties.getSecurity().setCertFile(certFile);
		Config.TrustStrategy trustStrategy = mapDriverConfig(properties).trustStrategy();
		assertThat(trustStrategy.strategy())
				.isEqualTo(Config.TrustStrategy.Strategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES);
		assertThat(trustStrategy.certFiles()).containsOnly(certFile);
	}

	@Test
	void securityWithCustomCertificatesShouldFailWithoutCertificate() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_CUSTOM_CA_SIGNED_CERTIFICATES);
		assertThatExceptionOfType(InvalidConfigurationPropertyValueException.class)
				.isThrownBy(() -> mapDriverConfig(properties)).withMessage(
						"Property spring.neo4j.security.trust-strategy with value 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' is invalid: Configured trust strategy requires a certificate file.");
	}

	@Test
	void securityWithTrustSystemCertificates() {
		Neo4jProperties properties = new Neo4jProperties();
		properties.getSecurity().setTrustStrategy(TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES);
		assertThat(mapDriverConfig(properties).trustStrategy().strategy())
				.isEqualTo(Config.TrustStrategy.Strategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES);
	}

	@Test
	void driverConfigShouldBeConfiguredToUseUseSpringJclLogging() {
		assertThat(mapDriverConfig(new Neo4jProperties()).logging()).isNotNull()
				.isInstanceOf(Neo4jSpringJclLogging.class);
	}

	private URI determineServerUri(Neo4jProperties properties, Environment environment) {
		return new Neo4jAutoConfiguration().determineServerUri(properties, environment);
	}

	private AuthToken mapAuthToken(Authentication authentication, Environment environment) {
		return new Neo4jAutoConfiguration().mapAuthToken(authentication, environment);
	}

	private AuthToken mapAuthToken(Authentication authentication) {
		return mapAuthToken(authentication, new MockEnvironment());
	}

	private Config mapDriverConfig(Neo4jProperties properties, ConfigBuilderCustomizer... customizers) {
		return new Neo4jAutoConfiguration().mapDriverConfig(properties, Arrays.asList(customizers));
	}

}


text:
#ifndef _COMMON_H
#define _COMMON_H
#ifdef __cplusplus
extern "C" {
#endif

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <stdint.h>
#include <assert.h>
#include <pthread.h>
#include <jni.h>
#include <libpmemobj.h>
#include "layout.h"

void throw(JNIEnv* env, const char* msg);

void* addr_from_java(jlong addr);

jlong addr_to_java(void* p);

PMEMoid pmemobj_undirect(PMPool *pool, void *p);

void *prealloc(PMPool *pool, void *p, size_t size, int initzero);

void pfree(PMPool *pool, void *p);

#ifdef __cplusplus
}
#endif
#endif


text:
.class public final Landroid/provider/Telephony$GPRSInfo;
.super Ljava/lang/Object;
.source "Telephony.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/provider/Telephony;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "GPRSInfo"
.end annotation

# instance fields
.field public mGprsIn:J

.field public mGprsOut:J

.field public mSimId:J

# direct methods
.method private constructor <init>()V
    .locals 2

    .prologue
    const-wide/16 v0, 0x0

    .line 3197
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 3194
    iput-wide v0, p0, Landroid/provider/Telephony$GPRSInfo;->mSimId:J

    .line 3195
    iput-wide v0, p0, Landroid/provider/Telephony$GPRSInfo;->mGprsIn:J

    .line 3196
    iput-wide v0, p0, Landroid/provider/Telephony$GPRSInfo;->mGprsOut:J

    .line 3199
    return-void
.end method

.method private static fromCursor(Landroid/database/Cursor;)Landroid/provider/Telephony$GPRSInfo;
    .locals 3
    .parameter "cursor"

    .prologue
    .line 3201
    new-instance v0, Landroid/provider/Telephony$GPRSInfo;

    invoke-direct {v0}, Landroid/provider/Telephony$GPRSInfo;-><init>()V

    .line 3202
    .local v0, info:Landroid/provider/Telephony$GPRSInfo;
    const-string/jumbo v1, "sim_id"

    invoke-interface {p0, v1}, Landroid/database/Cursor;->getColumnIndexOrThrow(Ljava/lang/String;)I

    move-result v1

    invoke-interface {p0, v1}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v1

    iput-wide v1, v0, Landroid/provider/Telephony$GPRSInfo;->mSimId:J

    .line 3203
    const-string v1, "gprs_in"

    invoke-interface {p0, v1}, Landroid/database/Cursor;->getColumnIndexOrThrow(Ljava/lang/String;)I

    move-result v1

    invoke-interface {p0, v1}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v1

    iput-wide v1, v0, Landroid/provider/Telephony$GPRSInfo;->mGprsIn:J

    .line 3204
    const-string v1, "gprs_out"

    invoke-interface {p0, v1}, Landroid/database/Cursor;->getColumnIndexOrThrow(Ljava/lang/String;)I

    move-result v1

    invoke-interface {p0, v1}, Landroid/database/Cursor;->getLong(I)J

    move-result-wide v1

    iput-wide v1, v0, Landroid/provider/Telephony$GPRSInfo;->mGprsOut:J

    .line 3205
    return-object v0
.end method

.method public static getGprsInBySim(Landroid/content/Context;J)J
    .locals 9
    .parameter "context"
    .parameter "simId"

    .prologue
    const/4 v4, 0x0

    const/4 v5, 0x0

    const-wide/16 v7, 0x0

    .line 3209
    cmp-long v0, p1, v7

    if-gtz v0, :cond_1

    move-wide v0, v7

    .line 3221
    :cond_0
    :goto_0
    return-wide v0

    .line 3210
    :cond_1
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    sget-object v1, Landroid/provider/Telephony$GprsInfo;->CONTENT_URI:Landroid/net/Uri;

    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/String;

    const-string v3, "gprs_in"

    aput-object v3, v2, v5

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v5, "sim_id="

    invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p1, p2}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    move-object v5, v4

    invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;

    move-result-object v6

    .line 3213
    .local v6, cursor:Landroid/database/Cursor;
    if-eqz v6, :cond_2

    :try_start_0
    invoke-interface {v6}, Landroid/database/Cursor;->moveToFirst()Z

    move-result v0

    if-eqz v0, :cond_2

    .line 3214
    const/4 v0, 0x0

    invoke-interface {v6, v0}, Landroid/database/Cursor;->getLong(I)J
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-wide v0

    .line 3217
    if-eqz v6, :cond_0

    .line 3218
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    goto :goto_0

    .line 3217
    :cond_2
    if-eqz v6, :cond_3

    .line 3218
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_3
    move-wide v0, v7

    .line 3221
    goto :goto_0

    .line 3217
    :catchall_0
    move-exception v0

    if-eqz v6, :cond_4

    .line 3218
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_4
    throw v0
.end method

.method public static getGprsInfoBySim(Landroid/content/Context;J)Landroid/provider/Telephony$GPRSInfo;
    .locals 8
    .parameter "context"
    .parameter "simId"

    .prologue
    const/4 v2, 0x0

    .line 3241
    new-instance v7, Landroid/provider/Telephony$GPRSInfo;

    invoke-direct {v7}, Landroid/provider/Telephony$GPRSInfo;-><init>()V

    .line 3242
    .local v7, info:Landroid/provider/Telephony$GPRSInfo;
    const-wide/16 v0, 0x0

    cmp-long v0, p1, v0

    if-gtz v0, :cond_1

    .line 3254
    .end local v7           #info:Landroid/provider/Telephony$GPRSInfo;
    :cond_0
    :goto_0
    return-object v7

    .line 3243
    .restart local v7       #info:Landroid/provider/Telephony$GPRSInfo;
    :cond_1
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    sget-object v1, Landroid/provider/Telephony$GprsInfo;->CONTENT_URI:Landroid/net/Uri;

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v4, "sim_id="

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p1, p2}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    move-object v4, v2

    move-object v5, v2

    invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;

    move-result-object v6

    .line 3246
    .local v6, cursor:Landroid/database/Cursor;
    if-eqz v6, :cond_2

    :try_start_0
    invoke-interface {v6}, Landroid/database/Cursor;->moveToFirst()Z

    move-result v0

    if-eqz v0, :cond_2

    .line 3247
    invoke-static {v6}, Landroid/provider/Telephony$GPRSInfo;->fromCursor(Landroid/database/Cursor;)Landroid/provider/Telephony$GPRSInfo;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v7

    .line 3250
    .end local v7           #info:Landroid/provider/Telephony$GPRSInfo;
    if-eqz v6, :cond_0

    .line 3251
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    goto :goto_0

    .line 3250
    .restart local v7       #info:Landroid/provider/Telephony$GPRSInfo;
    :cond_2
    if-eqz v6, :cond_0

    .line 3251
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    goto :goto_0

    .line 3250
    :catchall_0
    move-exception v0

    if-eqz v6, :cond_3

    .line 3251
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_3
    throw v0
.end method

.method public static getGprsOutBySim(Landroid/content/Context;J)J
    .locals 9
    .parameter "context"
    .parameter "simId"

    .prologue
    const/4 v4, 0x0

    const/4 v5, 0x0

    const-wide/16 v7, 0x0

    .line 3225
    cmp-long v0, p1, v7

    if-gtz v0, :cond_1

    move-wide v0, v7

    .line 3237
    :cond_0
    :goto_0
    return-wide v0

    .line 3226
    :cond_1
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v0

    sget-object v1, Landroid/provider/Telephony$GprsInfo;->CONTENT_URI:Landroid/net/Uri;

    const/4 v2, 0x1

    new-array v2, v2, [Ljava/lang/String;

    const-string v3, "gprs_out"

    aput-object v3, v2, v5

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v5, "sim_id="

    invoke-virtual {v3, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p1, p2}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    move-object v5, v4

    invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;

    move-result-object v6

    .line 3229
    .local v6, cursor:Landroid/database/Cursor;
    if-eqz v6, :cond_2

    :try_start_0
    invoke-interface {v6}, Landroid/database/Cursor;->moveToFirst()Z

    move-result v0

    if-eqz v0, :cond_2

    .line 3230
    const/4 v0, 0x0

    invoke-interface {v6, v0}, Landroid/database/Cursor;->getLong(I)J
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-wide v0

    .line 3233
    if-eqz v6, :cond_0

    .line 3234
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    goto :goto_0

    .line 3233
    :cond_2
    if-eqz v6, :cond_3

    .line 3234
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_3
    move-wide v0, v7

    .line 3237
    goto :goto_0

    .line 3233
    :catchall_0
    move-exception v0

    if-eqz v6, :cond_4

    .line 3234
    invoke-interface {v6}, Landroid/database/Cursor;->close()V

    :cond_4
    throw v0
.end method

.method public static resetGprsBySim(Landroid/content/Context;J)I
    .locals 5
    .parameter "context"
    .parameter "simId"

    .prologue
    const/4 v1, 0x0

    .line 3258
    const-wide/16 v2, 0x0

    cmp-long v2, p1, v2

    if-gtz v2, :cond_0

    .line 3262
    :goto_0
    return v1

    .line 3259
    :cond_0
    new-instance v0, Landroid/content/ContentValues;

    const/4 v2, 0x2

    invoke-direct {v0, v2}, Landroid/content/ContentValues;-><init>(I)V

    .line 3260
    .local v0, values:Landroid/content/ContentValues;
    const-string v2, "gprs_in"

    invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    invoke-virtual {v0, v2, v3}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V

    .line 3261
    const-string v2, "gprs_out"

    invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v1

    invoke-virtual {v0, v2, v1}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V

    .line 3262
    invoke-virtual {p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v1

    sget-object v2, Landroid/provider/Telephony$GprsInfo;->CONTENT_URI:Landroid/net/Uri;

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v4, "sim_id="

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p1, p2}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    const/4 v4, 0x0

    invoke-virtual {v1, v2, v0, v3, v4}, Landroid/content/ContentResolver;->update(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I

    move-result v1

    goto :goto_0
.end method


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var webLogger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var lessMiddleware = require('less-middleware');
var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'img', 'favicon.ico')));

app.use(webLogger('dev'));

if (app.get('env') === 'development') { } else {
    var compression = require('compression');
    var minify = require('express-minify');
    app.use(compression());
    app.use(minify({ cache: path.join(__dirname, 'cache') }));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(lessMiddleware(__dirname + '/public'));
app.use('/', express.static(path.join(__dirname, 'public')));
app.use('/vendor', express.static(path.join(__dirname, 'vendor')));
app.post('/api/order', function (req, res) {
    var mailer = require('./mailer')();
    var body = 'Email: ' + req.body.email + ' Message: ' + req.body.message;
    mailer.sendEmail(__env.EMAIL_ADMIN, 'New order from Portfolio', body, function (error, info) {
        if (error) {
            console.error(error);
        }
        console.log('Message sent: ' + info.response);
        res.redirect('/');
    });
});

module.exports = function () {
    var debug = require('debug')('app:server');
    var http = require('http');
    var port = normalizePort(__env.PORT || '80');
    app.set('port', port);

    var server = http.createServer(app);
    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);

    return app;

    function normalizePort(val) {
        var port = parseInt(val, 10);
        if (isNaN(port)) return val;
        if (port >= 0) return port;
        return false;
    }

    function onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }

        var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;

        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    }

    function onListening() {
        var addr = server.address();
        var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
        debug('Listening on ' + bind);
    }
};


text:
import arcpy
import sys, traceback, time, os

# Add "Root folder"\SupportFiles to sys path inorder to import
#   modules in subfolder
supportFilePath = os.path.join(os.path.dirname(
    os.path.dirname(os.path.dirname(sys.argv[0]))), "SupportFiles")
sys.path.append(supportFilePath)

from datetime import datetime
from UtilitiesArcPy import checkResults, copyGDBData

scriptName = sys.argv[0]

if len(sys.argv) <> 3:
    print "\n" + scriptName + " <SourceGeodatabase> <DestinationGeodatabase>"
    print "\nWhere:"
    print "\n\t<SourceGeodatabase> (required): path to the source geodatabase."
    print "\n\t<DestinationGeodatabase> (required): path to the destination geodatabase."
    print
    sys.exit(1)

srcPath = sys.argv[1]
destPath = sys.argv[2]

# ---------------------------------------------------------------------
# Check parameters
# ---------------------------------------------------------------------
goodParameters = True

# Check path parameter to make sure they exist

if not os.path.exists(srcPath):
    print "\nThe path specified for parameter <SourceGeodatabase>" + \
                " (" + srcPath + ") does not exist."
    goodParameters = False

if not os.path.exists(destPath):
    print "\nThe path specified for parameter <DestinationGeodatabase>" + \
                " (" + destPath + ") does not exist."
    goodParameters = False

# Exit script if parameters are not valid.
if not goodParameters:
    print "\nInvalid script parameters. Exiting " + scriptName + "."
    sys.exit(1)

printMsg = True
totalCopySuccess = True

try:

    # startTime = datetime.now()
    # print
    # print '{:<14}{:<100}'.format("Source:", srcPath)
    # print '{:<14}{:<100}'.format("Destination:", destPath)

    results = copyGDBData(srcPath, destPath)
    success = checkResults(results, printMsg)
    if not success:
        totalCopySuccess = success

except:

    # Get the traceback object
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]

    # Concatenate information together concerning the error into a message string
    pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])

    # Print Python error messages for use in Python / Python Window
    print
    print "***** ERROR ENCOUNTERED *****"
    print pymsg + "\n"

finally:
    if totalCopySuccess:
        print "\nData copy was successful."
    else:
        print "\nERROR occurred during data copy."

    # print '{:<14}{:%Y-%m-%d %H:%M:%S}'.format("Start time:", startTime)
    # print '{:<14}{:%Y-%m-%d %H:%M:%S}'.format("End time:", datetime.now())

    if totalCopySuccess:
         sys.exit(0)
    else:
         sys.exit(1)


text:
FOUNDATION_EXPORT double Pods_CBLibrary1_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_CBLibrary1_TestsVersionString[];


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<!-- 	<property> -->
<!-- 		<name>fs.default.name</name> -->
<!-- 		<value>hdfs://sandbox:8020</value> -->
<!-- 	</property> -->
	<property>
		<name>hadoop.socks.server</name>
		<value>localhost:1099</value>
	</property>
	<property>
		<name>hadoop.rpc.socket.factory.class.default</name>
		<value>org.apache.hadoop.net.SocksSocketFactory</value>
	</property>
</configuration>


text:
(function () {
  var ns = $.namespace('pskl.rendering');

  /**
   * Render an array of frames
   * @param {Array.<pskl.model.Frame>} frames
   */
  ns.FramesheetRenderer = function (frames) {
    if (frames.length > 0) {
      this.frames = frames;
    } else {
      throw 'FramesheetRenderer : Invalid argument : frames is empty';
    }
  };

  ns.FramesheetRenderer.prototype.renderAsCanvas = function (columns) {
    columns = columns || this.frames.length;
    var rows = Math.ceil(this.frames.length / columns);

    var canvas = this.createCanvas_(columns, rows);

    for (var i = 0 ; i < this.frames.length ; i++) {
      var frame = this.frames[i];
      var posX = (i % columns) * frame.getWidth();
      var posY = Math.floor(i / columns) * frame.getHeight();
      this.drawFrameInCanvas_(frame, canvas, posX, posY);
    }
    return canvas;
  };

  ns.FramesheetRenderer.prototype.drawFrameInCanvas_ = function (frame, canvas, offsetWidth, offsetHeight) {
    var context = canvas.getContext('2d');
    var imageData = context.createImageData(frame.getWidth(), frame.getHeight());
    var pixels = frame.getPixels();
    var data = new Uint8ClampedArray(pixels.buffer);
    imageData.data.set(data);
    context.putImageData(imageData, offsetWidth, offsetHeight);
  };

  ns.FramesheetRenderer.prototype.createCanvas_ = function (columns, rows) {
    var sampleFrame = this.frames[0];
    var width = columns * sampleFrame.getWidth();
    var height = rows * sampleFrame.getHeight();
    return pskl.utils.CanvasUtils.createCanvas(width, height);
  };
})();


text:
/**
 * WorldMap object, extends Phaser.Tilemap
 */

WorldMap = function(game, key, tileSprite, tileSize, collectableSprite, enemySprite, enemyAmount) {
    this._game = game;
    var state = this._game.state.getCurrentState();

    this.level = state.generate();
    this._game.load.tilemap('level', null, this.level, Phaser.Tilemap.CSV);

    Phaser.Tilemap.call(this, game, 'level', tileSize, tileSize);

    //automatically map tilemap (numbers) to images by their position
    this.addTilesetImage(tileSprite);

    //make sure the player collides (cannot walk through) all tiles except tile 0
    this.setCollisionByExclusion([0]);

    //create a group of doors
    if(this._game._level == 6 || this._game._level == 7 || this._game._level == 8){
        this._doors = new Phaser.Group(this._game, null, "doors", false);
        //spawn collectables in this group
        for (var i=0; i<3; i++){
            var spawnPosition = state.getDoorPosition();
            var door = this._game.add.sprite(spawnPosition[0], spawnPosition[1], 'door_dungeon');
            this._game.physics.enable(door);
            door.body.immovable = true;
            this._doors.add(door);
        }

        //create a group of items
        this._keys = new Phaser.Group(this._game, null, "keys", false);
        //spawn collectables in this group
        for (var i=0; i<3; i++){
            var spawnPosition = state.getKeyPosition();
            var key = this._game.add.sprite(spawnPosition[0], spawnPosition[1], 'key_dungeon');
            this._game.physics.enable(key);
            key.body.immovable = true;
            this._keys.add(key);
        }
    }

    //NPCs
    if(this._game._level > 8){
        this._npcs = new Phaser.Group(this._game, null, "NPCs", false);

        for (var i = 0; i < 3; i++){
            var choice = Math.ceil(ROT.RNG.getUniform() * 7);
            var npc = new NPC(this._game, (32/27), 'npc'+choice+'_rpg', 'default');
            this._game.physics.enable(npc);
            npc.body.immovable = true;
            this._npcs.add(npc);
        }

        // add axe NPC
        var choice = Math.ceil(ROT.RNG.getUniform() * 7);
        var npc = new NPC(this._game, (32/27), 'npc'+choice+'_rpg', 'axe');
        this._game.physics.enable(npc);
        npc.body.immovable = true;
        this._npcs.add(npc);

    }

    //enemies
    if(this._game._level > 6) {
        this._enemies = new Phaser.Group(this._game, null, "enemies", false);

        for (var i = 0; i < enemyAmount; i++){
            var spawnPosition = state.getEnemyPosition();
            var enemy = new Enemy(this._game, 1, enemySprite);
            this._enemies.add(enemy);
        }
    }

    //create a group of items
    this._items = new Phaser.Group(this._game, null, "items", false);
    //spawn collectables in this group
    if (this._game._level >= 9) {
        var numItems = 3;
    } else {
        var numItems = 6;
    }
    for (var i=0; i<numItems; i++){
        var spawnPosition = state.getItemPosition();

        var spriteName;
        if (this._game._level < 3){
            spriteName = collectableSprite + (Math.floor(i/2)+1);
        } else {
            spriteName = collectableSprite;
        }

        var collectable = this._game.add.sprite(spawnPosition[0], spawnPosition[1], spriteName);
        this._game.physics.enable(collectable);
        collectable.body.immovable = true;
        this._items.add(collectable);
    }
}

WorldMap.prototype = Object.create(Phaser.Tilemap.prototype);
WorldMap.prototype.constructor = WorldMap;


text:
#!/sbin/sh
OUTFD=$2
ZIP=$3
BUSYBOX=$4
chmod 755 $BUSYBOX
mkdir /tmp

SYSTEMLIB=/system/lib

ui_print() {
  echo -n -e "ui_print $1\n" > /proc/self/fd/$OUTFD
}

ch_con() {
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox chcon -h u:object_r:system_file:s0 $1
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox chcon -h u:object_r:system_file:s0 $1
  chcon -h u:object_r:system_file:s0 $1
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox chcon u:object_r:system_file:s0 $1
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox chcon u:object_r:system_file:s0 $1
  chcon u:object_r:system_file:s0 $1
}

ch_con_ext() {
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox chcon $2 $1
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox chcon $2 $1
  chcon $2 $1
}

ln_con() {
  LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox ln -s $1 $2
  LD_LIBRARY_PATH=$SYSTEMLIB /system/bin/toolbox ln -s $1 $2
  ln -s $1 $2
  ch_con $2
}

set_perm() {
  chown $1.$2 $4
  chown $1:$2 $4
  chmod $3 $4
  ch_con $4
  ch_con_ext $4 $5
}

cp_perm() {
  rm $5
  if [ -f "$4" ]; then
    cat $4 > $5
    set_perm $1 $2 $3 $5 $6
  fi
}

ui_print "*****************"
ui_print "SuperSU installer"
ui_print "*****************"

ui_print "- Mounting /system, /data and rootfs"
mount /system
mount /data
mount -o rw,remount /system
mount -o rw,remount /system /system
mount -o rw,remount /
mount -o rw,remount / /

cat /system/bin/toolbox > /system/toolbox
chmod 0755 /system/toolbox
ch_con /system/toolbox

API=$(cat /system/build.prop | grep "ro.build.version.sdk=" | dd bs=1 skip=21 count=2)
ABI=$(cat /system/build.prop /default.prop | grep -m 1 "ro.product.cpu.abi=" | dd bs=1 skip=19 count=3)
ABILONG=$(cat /system/build.prop /default.prop | grep -m 1 "ro.product.cpu.abi=" | dd bs=1 skip=19)
ABI2=$(cat /system/build.prop /default.prop | grep -m 1 "ro.product.cpu.abi2=" | dd bs=1 skip=20 count=3)
SUMOD=06755
SUGOTE=false
SUPOLICY=false
INSTALL_RECOVERY_CONTEXT=u:object_r:system_file:s0
MKSH=/system/bin/mksh
PIE=
ARCH=arm
APKFOLDER=false
APKNAME=/system/app/Superuser.apk
APPPROCESS=false
APPPROCESS64=false
if [ "$ABI" = "x86" ]; then ARCH=x86; fi;
if [ "$ABI2" = "x86" ]; then ARCH=x86; fi;
if [ "$API" -eq "$API" ]; then
  if [ "$API" -ge "17" ]; then
    SUGOTE=true
    PIE=.pie
    if [ "$ABILONG" = "armeabi-v7a" ]; then ARCH=armv7; fi;
    if [ "$ABI" = "mip" ]; then ARCH=mips; fi;
    if [ "$ABILONG" = "mips" ]; then ARCH=mips; fi;
  fi
  if [ "$API" -ge "18" ]; then
    SUMOD=0755
  fi
  if [ "$API" -ge "20" ]; then
    if [ "$ABILONG" = "arm64-v8a" ]; then ARCH=arm64; SYSTEMLIB=/system/lib64; APPPROCESS64=true; fi;
    if [ "$ABILONG" = "mips64" ]; then ARCH=mips64; SYSTEMLIB=/system/lib64; APPPROCESS64=true; fi;
    if [ "$ABILONG" = "x86_64" ]; then ARCH=x64; SYSTEMLIB=/system/lib64; APPPROCESS64=true; fi;
    APKFOLDER=true
    APKNAME=/system/app/SuperSU/SuperSU.apk
  fi
  if [ "$API" -ge "19" ]; then
    SUPOLICY=true
    if [ "$(LD_LIBRARY_PATH=$SYSTEMLIB /system/toolbox ls -lZ /system/bin/toolbox | grep toolbox_exec > /dev/null; echo $?)" -eq "0" ]; then
      INSTALL_RECOVERY_CONTEXT=u:object_r:toolbox_exec:s0
    fi
  fi
  if [ "$API" -ge "21" ]; then
    APPPROCESS=true
  fi
fi
if [ ! -f $MKSH ]; then
  MKSH=/system/bin/sh
fi

#ui_print "DBG [$API] [$ABI] [$ABI2] [$ABILONG] [$ARCH] [$MKSH]"

ui_print "- Extracting files"
cd /tmp
mkdir supersu
cd supersu

if [ -z "$BIN" ]; then
  $BUSYBOX unzip -o "$ZIP"

  BIN=/tmp/supersu/$ARCH
  COM=/tmp/supersu/common
fi

ui_print "- Disabling OTA survival"
chmod 0755 $BIN/chattr$PIE
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/bin/su
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/xbin/su
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/bin/.ext/.su
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/xbin/daemonsu
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/xbin/sugote
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/xbin/sugote_mksh
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/xbin/supolicy
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/lib/libsupol.so
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/lib64/libsupol.so
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/etc/install-recovery.sh
LD_LIBRARY_PATH=$SYSTEMLIB $BIN/chattr$PIE -i /system/bin/install-recovery.sh

ui_print "- Removing old files"

if [ -f "/system/bin/install-recovery.sh" ]; then
  if [ ! -f "/system/bin/install-recovery_original.sh" ]; then
    mv /system/bin/install-recovery.sh /system/bin/install-recovery_original.sh
    ch_con /system/bin/install-recovery_original.sh
  fi
fi
if [ -f "/system/etc/install-recovery.sh" ]; then
  if [ ! -f "/system/etc/install-recovery_original.sh" ]; then
    mv /system/etc/install-recovery.sh /system/etc/install-recovery_original.sh
    ch_con /system/etc/install-recovery_original.sh
  fi
fi

rm -f /system/bin/su
rm -f /system/xbin/su
rm -f /system/xbin/daemonsu
rm -f /system/xbin/sugote
rm -f /system/xbin/sugote-mksh
rm -f /system/xbin/supolicy
rm -f /system/lib/libsupol.so
rm -f /system/lib64/libsupol.so
rm -f /system/bin/.ext/.su
rm -f /system/bin/install-recovery.sh
rm -f /system/etc/install-recovery.sh
rm -f /system/etc/init.d/99SuperSUDaemon
rm -f /system/etc/.installed_su_daemon

rm -f /system/app/Superuser.apk
rm -f /system/app/Superuser.odex
rm -rf /system/app/Superuser
rm -f /system/app/SuperUser.apk
rm -f /system/app/SuperUser.odex
rm -rf /system/app/SuperUser
rm -f /system/app/superuser.apk
rm -f /system/app/superuser.odex
rm -rf /system/app/superuser
rm -f /system/app/Supersu.apk
rm -f /system/app/Supersu.odex
rm -rf /system/app/Supersu
rm -f /system/app/SuperSU.apk
rm -f /system/app/SuperSU.odex
rm -rf /system/app/SuperSU
rm -f /system/app/supersu.apk
rm -f /system/app/supersu.odex
rm -rf /system/app/supersu
rm -f /system/app/VenomSuperUser.apk
rm -f /system/app/VenomSuperUser.odex
rm -rf /system/app/VenomSuperUser
rm -f /data/dalvik-cache/*com.noshufou.android.su*
rm -f /data/dalvik-cache/*/*com.noshufou.android.su*
rm -f /data/dalvik-cache/*com.koushikdutta.superuser*
rm -f /data/dalvik-cache/*/*com.koushikdutta.superuser*
rm -f /data/dalvik-cache/*com.mgyun.shua.su*
rm -f /data/dalvik-cache/*/*com.mgyun.shua.su*
rm -f /data/dalvik-cache/*com.m0narx.su*
rm -f /data/dalvik-cache/*/*com.m0narx.su*
rm -f /data/dalvik-cache/*Superuser.apk*
rm -f /data/dalvik-cache/*/*Superuser.apk*
rm -f /data/dalvik-cache/*SuperUser.apk*
rm -f /data/dalvik-cache/*/*SuperUser.apk*
rm -f /data/dalvik-cache/*superuser.apk*
rm -f /data/dalvik-cache/*/*superuser.apk*
rm -f /data/dalvik-cache/*VenomSuperUser.apk*
rm -f /data/dalvik-cache/*/*VenomSuperUser.apk*
rm -f /data/dalvik-cache/*eu.chainfire.supersu*
rm -f /data/dalvik-cache/*/*eu.chainfire.supersu*
rm -f /data/dalvik-cache/*Supersu.apk*
rm -f /data/dalvik-cache/*/*Supersu.apk*
rm -f /data/dalvik-cache/*SuperSU.apk*
rm -f /data/dalvik-cache/*/*SuperSU.apk*
rm -f /data/dalvik-cache/*supersu.apk*
rm -f /data/dalvik-cache/*/*supersu.apk*
rm -f /data/dalvik-cache/*.oat
rm -f /data/app/com.noshufou.android.su*
rm -f /data/app/com.koushikdutta.superuser*
rm -f /data/app/com.mgyun.shua.su*
rm -f /data/app/com.m0narx.su*
rm -f /data/app/eu.chainfire.supersu-*
rm -f /data/app/eu.chainfire.supersu.apk

ui_print "- Placing files"

mkdir /system/bin/.ext
set_perm 0 0 0777 /system/bin/.ext
cp_perm 0 0 $SUMOD $BIN/su /system/bin/.ext/.su
cp_perm 0 0 $SUMOD $BIN/su /system/xbin/su
cp_perm 0 0 0755 $BIN/su /system/xbin/daemonsu
if ($SUGOTE); then
  cp_perm 0 0 0755 $BIN/su /system/xbin/sugote u:object_r:zygote_exec:s0
  cp_perm 0 0 0755 $MKSH /system/xbin/sugote-mksh
fi
if ($SUPOLICY); then
  cp_perm 0 0 0755 $BIN/supolicy /system/xbin/supolicy
  cp_perm 0 0 0644 $BIN/libsupol.so $SYSTEMLIB/libsupol.so
fi
if ($APKFOLDER); then
  mkdir /system/app/SuperSU
  set_perm 0 0 0755 /system/app/SuperSU
fi
cp_perm 0 0 0644 $COM/Superuser.apk $APKNAME
cp_perm 0 0 0755 $COM/install-recovery.sh /system/etc/install-recovery.sh
ln_con /system/etc/install-recovery.sh /system/bin/install-recovery.sh
if ($APPPROCESS); then
  rm /system/bin/app_process
  ln_con /system/xbin/daemonsu /system/bin/app_process
  if ($APPPROCESS64); then
    if [ ! -f "/system/bin/app_process64_original" ]; then
      mv /system/bin/app_process64 /system/bin/app_process64_original
    else
      rm /system/bin/app_process64
    fi
    ln_con /system/xbin/daemonsu /system/bin/app_process64
    if [ ! -f "/system/bin/app_process_init" ]; then
      cp_perm 0 2000 0755 /system/bin/app_process64_original /system/bin/app_process_init
    fi
  else
    if [ ! -f "/system/bin/app_process32_original" ]; then
      mv /system/bin/app_process32 /system/bin/app_process32_original
    else
      rm /system/bin/app_process32
    fi
    ln_con /system/xbin/daemonsu /system/bin/app_process32
    if [ ! -f "/system/bin/app_process_init" ]; then
      cp_perm 0 2000 0755 /system/bin/app_process32_original /system/bin/app_process_init
    fi
  fi
fi
cp_perm 0 0 0744 $COM/99SuperSUDaemon /system/etc/init.d/99SuperSUDaemon
echo 1 > /system/etc/.installed_su_daemon
set_perm 0 0 0644 /system/etc/.installed_su_daemon

ui_print "- Post-installation script"
rm /system/toolbox
LD_LIBRARY_PATH=$SYSTEMLIB /system/xbin/su --install

ui_print "- Unmounting /system and /data"
umount /system
umount /data
rm -rf /tmp

ui_print "- Done !"
exit 0


text:
class HistoryService;

namespace browser_sync {

// A ModelSafeWorker for history models that accepts requests
// from the syncapi that need to be fulfilled on the history thread.
class HistoryModelWorker : public browser_sync::ModelSafeWorker {
 public:
  explicit HistoryModelWorker(HistoryService* history_service);

  // ModelSafeWorker implementation. Called on syncapi SyncerThread.
  virtual SyncerError DoWorkAndWaitUntilDone(
      const WorkCallback& work) OVERRIDE;
  virtual ModelSafeGroup GetModelSafeGroup() OVERRIDE;

 private:
  virtual ~HistoryModelWorker();

  scoped_refptr<HistoryService> history_service_;
  // Helper object to make sure we don't leave tasks running on the history
  // thread.
  CancelableRequestConsumerT<int, 0> cancelable_consumer_;
  DISALLOW_COPY_AND_ASSIGN(HistoryModelWorker);
};

}  // namespace browser_sync

#endif  // CHROME_BROWSER_SYNC_GLUE_HISTORY_MODEL_WORKER_H_


text:
go install

quick_example tcp 127.0.0.1 1080 --timeout=110
quick_example serial 80 --baud=5800 --timeout=120

quick_example --version


text:
<?php use_stylesheets_for_form($form) ?>
<?php use_javascripts_for_form($form) ?>

  <form id="formdati" action="<?php echo url_for('proceduranotturna/' . ($form->getObject()->isNew() ? 'create' : 'update') . (!$form->getObject()->isNew() ? '?id=' . $form->getObject()->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>>
    <?php if (!$form->getObject()->isNew()): ?>
      <input type="hidden" name="sf_method" value="put" />
    <?php endif; ?>

            <?php if (!$form->getObject()->isNew()): ?>
              <a class="fm-button ui-state-default ui-corner-all fm-button-icon-left" id="sData" onclick="eliminaDettaglio({'tabella':'proceduranotturna','id':'<?= (!$form->getObject()->isNew() ? $form->getObject()->getId() : 0) ?>'});">Elimina
            <?php endif; ?>
            <a class="fm-button ui-state-default ui-corner-all fm-button-icon-left" id="sData" onclick="salvaDettaglio({'tabella':'proceduranotturna','id':'<?= (!$form->getObject()->isNew() ? $form->getObject()->getId() : 0) ?>'});">Salva

        <?php echo $form ?>

  </form>


text:
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import express from 'express';

import pkg from '../package';
import routes from './routes';
import logger from './utils/logger';
import bodyParser from 'body-parser';
import compression from 'compression';
import * as config from './config/config';
import * as errorHandler from './middlewares/errorHandler';

const app = express();

app.set('port', config.get().api.port);

app.locals.title = pkg.name;
app.locals.version = pkg.version;

app.use(cors());
app.use(helmet());
app.use(compression());
app.use(morgan('dev', { stream: logger().stream }));
app.use(bodyParser.json());

// API Routes
app.use('/api', routes);

// Error Middlewares
app.use(errorHandler.genericErrorHandler);
app.use(errorHandler.notFoundError);

app.listen(app.get('port'), () => {
  logger().info(`Server listening is on port ${app.get('port')}`);
});

export default app;


text:
#include "carla.h"

#include "embed.cpp"

extern "C"
{

Plugin::Descriptor PLUGIN_EXPORT carlapatchbay_plugin_descriptor =
{
    STRINGIFY( PLUGIN_NAME ),
    "Carla Patchbay",
    QT_TRANSLATE_NOOP( "pluginBrowser",
                       "Carla Patchbay Instrument" ),
    "falkTX <falktx/at/falktx.com>",
    0x0195,
    Plugin::Instrument,
    new PluginPixmapLoader( "logo" ),
    NULL,
    NULL
} ;

Plugin* PLUGIN_EXPORT lmms_plugin_main(Model*, void* data)
{
    return new CarlaInstrument(static_cast<InstrumentTrack*>(data), &carlapatchbay_plugin_descriptor, true);
}

}


text:
#include <signal.h>

#include "log.h"
#include "exit.h"
#include "commandline.h"
#include "network.h"
#include "homerun.h"

// This flag controls termination of the main loop.
volatile sig_atomic_t keepRunning = 1;

// Signal handler for termination signal. Stops the app
void catch_term (int sig)
{
	switch (sig)
	{
		case SIGTERM:
			LOG(debug,"SIGTERM caught, shutting down");
			break;
		case SIGINT:
			LOG(debug,"SIGINT caught, shutting down");
			break;
		default:
			LOG(debug,"Unexpected signal caught, shutting down");
	}
	keepRunning = 0;
	signal (sig, catch_term);
}

// main entry point for the app
int main(int argc, char **argv)
{
    // Establish a handler for SIGTEM signals.
    signal(SIGTERM, catch_term);
	// Use the same for SIGINT (ctrl-c)
	signal(SIGINT, catch_term);

	// Parse those args
	LOG(debug,"About to parse args");

	if (!parseArgs(argc,argv))
	{
		ABORT("Failed to parse args, exiting");
	}

	LOG(debug,"Args Parsed");

	// OK note startup
	LOG(message,"hdpirun starting up");

	// Check the tuner hosts/IPs
	LOG(debug,"Checking Tuner Hosts");
	if (!addHomeRunTuners())
	{
		ABORT("Unable to verify at least one tuner");
	}
	LOG(debug,"Tuner(s) OK");

	// Start networking
	LOG(debug,"Opening network ports");
	if (!bindDiscoverPort())
	{
		ABORT("Failed to create/bind discovery port");
	}
	if (!bindControlPort())
	{
		ABORT("Failed to create/bind control port");
	}
	LOG(debug,"Network ports open");

	LOG(message,"Waiting for network commands");
	while (keepRunning)
	{
		receive();
	}
	LOG(debug,"Shutting down");

	EXIT("hdpirun shut down");
}


text:
package com.blazebit.persistence.examples.spring.hateoas.filter;

import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Christian Beikov
 * @since 1.5.0
 */
public class Filter {

    private Kind kind;
    private String field;
    private List<String> values;

    public Filter() {
    }

    public Kind getKind() {
        return kind;
    }

    public void setKind(Kind kind) {
        this.kind = kind;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    @JsonIgnore
    public String getValue() {
        return values.get(0);
    }

    public void setValue(String value) {
        if (values == null) {
            values = new ArrayList<>();
        } else {
            values.clear();
        }
        values.add(value);
    }

    @JsonIgnore
    public String getLow() {
        if (values == null || values.isEmpty()) {
            return null;
        }
        return values.get(0);
    }

    public void setLow(String low) {
        if (values == null) {
            values = new ArrayList<>();
        } else if (values.size() > 2) {
            values = new ArrayList<>(values.subList(0, 2));
        }
        values.set(0, low);
    }

    @JsonIgnore
    public String getHigh() {
        if (values == null || values.size() < 2) {
            return null;
        }
        return values.get(1);
    }

    public void setHigh(String high) {
        if (values == null) {
            values = new ArrayList<>();
        } else if (values.size() > 2) {
            values = new ArrayList<>(values.subList(0, 2));
        }
        values.set(1, high);
    }

    public List<String> getValues() {
        return values;
    }

    public void setValues(List<String> values) {
        this.values = values;
    }

    public static enum Kind {
        EQ,
        LT,
        GT,
        GTE,
        LTE,
        BETWEEN,
        IN,
        CONTAINS,
        STARTS_WITH,
        ENDS_WITH
    }
}


text:
package com.citelic.game.entity.player.content.dialogue.impl.npcs;

import com.citelic.game.entity.player.content.actions.skills.magic.Magic;
import com.citelic.game.entity.player.content.dialogue.Dialogue;
import com.citelic.game.map.tile.Tile;

public class FireTitan extends Dialogue {

	@Override
	public void finish() {

	}

	@Override
	public void run(int interfaceId, int componentId) {
		switch (stage) {
		case 1:
			switch (componentId) {
			case OPTION_1:
				player.getPackets().sendGameMessage(
						"Why would I talk to a familiar? That's just weird.");
				end();
				break;
			case OPTION_2:
				Magic.sendNormalTeleportSpell(player, 0, 0, new Tile(3038,
						3824, 0));
				end();
				break;
			}
			break;
		}
	}

	@Override
	public void start() {
		stage = 1;
		sendOptionsDialogue(SEND_DEFAULT_OPTIONS_TITLE, "Chat", "Teleport");
	}
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Rabenhorst's Kryptogamen-Flora, Pilze - Die Flechtenparasiten 2(8): 141 (1930)

#### Original name
Discocera lichenicola A.L. Sm. & Ramsb.

### Remarks
null


text:
//  ------------------------------------------------------------------------------------
//  Copyright (c) Microsoft Corporation
//  All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this
//  file except in compliance with the License. You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
//  CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
//  NON-INFRINGEMENT.
//
//  See the Apache Version 2.0 License for specific language governing permissions and
//  limitations under the License.
//  ------------------------------------------------------------------------------------

namespace Amqp
{
    using System.Diagnostics;
    using System.Threading;

    /// <summary>
    /// Provides framework specific routines.
    /// </summary>
    public static class Fx
    {
        /// <summary>
        /// Asserts a condition is true.
        /// </summary>
        /// <param name="condition">A boolean value indicating the condition.</param>
        /// <param name="message">The error message if condition is not met.</param>
        [Conditional("DEBUG")]
        public static void Assert(bool condition, string message)
        {
            Debug.Assert(condition, message);
        }

        /// <summary>
        /// Formats a string from a format and an array of arguments.
        /// </summary>
        /// <param name="format">The format string.</param>
        /// <param name="args">The arguments.</param>
        /// <returns></returns>
        public static string Format(string format, params object[] args)
        {
            return string.Format(format, args);
        }

        /// <summary>
        /// Starts a new thread.
        /// </summary>
        /// <param name="threadStart">The thread start callback.</param>
        public static void StartThread(ThreadStart threadStart)
        {
            ThreadPool.QueueUserWorkItem(
                o => { ((ThreadStart)o)(); },
                threadStart);
        }
    }
}


text:
package org.apache.reef.tests.roguethread;

import org.apache.reef.driver.evaluator.AllocatedEvaluator;
import org.apache.reef.driver.task.TaskConfiguration;
import org.apache.reef.tang.Configuration;
import org.apache.reef.tang.annotations.Unit;
import org.apache.reef.wake.EventHandler;

import javax.inject.Inject;

@Unit
final class RogueThreadDriver {

  @Inject
  RogueThreadDriver() {
  }

  final class EvaluatorAllocationHandler implements EventHandler<AllocatedEvaluator> {

    @Override
    public void onNext(final AllocatedEvaluator allocatedEvaluator) {
      final Configuration taskConfiguration = TaskConfiguration.CONF
          .set(TaskConfiguration.IDENTIFIER, "RogueThreadTestTask")
          .set(TaskConfiguration.TASK, RogueThreadTask.class)
          .build();
      allocatedEvaluator.submitTask(taskConfiguration);
    }
  }

}