text:
namespace chrono {
namespace irrlicht {

// -----------------------------------------------------------------------------
// ChIrrAppEventReceiver
//
// A custom Irrlicht Event Receiver class.
// -----------------------------------------------------------------------------

class ChIrrAppEventReceiver : public irr::IEventReceiver {
  public:
    ChIrrAppEventReceiver(ChIrrAppInterface* m_app) : app(m_app) {}
    bool OnEvent(const irr::SEvent& event);

  private:
    ChIrrAppInterface* app;
};

bool ChIrrAppEventReceiver::OnEvent(const irr::SEvent& event) {
    // Check if there are any user-specified event receivers. Give them the
    // first chance to process the event (in the order in which the user-specified
    // event receivers were registered with the application.
    if (app) {
        for (size_t ir = 0; ir < app->user_receivers.size(); ir++) {
            if (app->user_receivers[ir]->OnEvent(event))
                return true;
        }
    }

    // Process keyboard events.
    if (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown) {
        switch (event.KeyInput.Key) {
            case irr::KEY_KEY_I:
                app->SetShowInfos(!app->GetShowInfos());
                return true;
            case irr::KEY_SPACE:
                app->pause_step = !app->pause_step;
                return true;
            case irr::KEY_KEY_P:
                app->pause_step = true;
                app->do_single_step = true;
                return true;
            case irr::KEY_F11:
                GetLog() << "---Computing linear static solution---\n";
                app->GetSystem()->DoStaticLinear();
                return true;
            case irr::KEY_F10:
                GetLog() << "---Computing NONlinear static solution, 20 steps---\n";
                app->GetSystem()->DoStaticNonlinear(20);
                return true;
            case irr::KEY_F8: {
                GetLog() << "Saving system in JSON format to dump.json file \n";
                ChStreamOutAsciiFile mfileo("dump.json");
                ChArchiveOutJSON marchiveout(mfileo);
                marchiveout.SetUseVersions(false);
                marchiveout << CHNVP(app->GetSystem(), "System");

                GetLog() << "Saving system in ASCII format to dump.txt file \n";
                ChStreamOutAsciiFile mfileo2("dump.txt");
                ChArchiveAsciiDump marchiveout2(mfileo2);
                marchiveout2.SetUseVersions(false);
                marchiveout2 << CHNVP(app->GetSystem(), "System");
            }
            case irr::KEY_F6:
                GetLog() << "Saving system vector and matrices to dump_xxyy.dat files.\n";
                app->DumpSystemMatrices();
                return true;
            case irr::KEY_F7:
                if (!app->system->GetDumpSolverMatrices()) {
                    GetLog() << "Start saving system vector and matrices to dump_xxxx_yy.dat files...\n";
                    app->system->SetDumpSolverMatrices(true);
                } else {
                    GetLog() << "Stop saving system vector and matrices to dump_xxxx_yy.dat files.\n";
                    app->system->SetDumpSolverMatrices(false);
                }
                return true;
            case irr::KEY_SNAPSHOT:
                if (app->videoframe_save == false) {
                    app->videoframe_save = true;
                    GetLog() << "Start saving frames in /video_capture/snapshotnnnnn.bmp pictures...\n";
                } else {
                    app->videoframe_save = false;
                    GetLog() << "Stop saving frames in /video_capture directory.\n";
                }
                return true;
            case irr::KEY_F4:
                if (app->camera_auto_rotate_speed <= 0)
                    app->camera_auto_rotate_speed = 0.02;
                else
                    app->camera_auto_rotate_speed *= 1.5;
                return true;
            case irr::KEY_F3:
                app->camera_auto_rotate_speed = 0;
                return true;
            case irr::KEY_F2:
                if (app->camera_auto_rotate_speed >= 0)
                    app->camera_auto_rotate_speed = -0.02;
                else
                    app->camera_auto_rotate_speed *= 1.5;
                return true;
            case irr::KEY_ESCAPE:
                app->GetDevice()->closeDevice();
                return true;
            default:
                break;
        }
    }

    irr::core::dimension2d<irr::u32> ssize = app->GetVideoDriver()->getScreenSize();

    // Process mouse events.
    if (event.EventType == irr::EET_MOUSE_INPUT_EVENT) {
        switch (event.MouseInput.Event) {
            case irr::EMIE_MMOUSE_PRESSED_DOWN: {
                irr::core::line3d<irr::f32> mline =
                    app->GetSceneManager()->getSceneCollisionManager()->getRayFromScreenCoordinates(
                        app->GetDevice()->getCursorControl()->getPosition());
                ChVector<> mfrom(mline.start.X, mline.start.Y, mline.start.Z);
                ChVector<> mto(mline.end.X, mline.end.Y, mline.end.Z);
                collision::ChCollisionSystem::ChRayhitResult mresult;
                app->GetSystem()->GetCollisionSystem()->RayHit(mfrom, mto, mresult);
                if (mresult.hit) {
                    if (ChBody* mbo = dynamic_cast<ChBody*>(mresult.hitModel->GetContactable())) {
                        app->selectedmover = new std::shared_ptr<ChBody>(mbo);
                        app->selectedpoint = (*(app->selectedmover))->Point_World2Body(mresult.abs_hitPoint);
                        app->selecteddist = (mfrom - mresult.abs_hitPoint).Length();
                        app->selectedspring = new std::shared_ptr<ChLinkSpring>(new ChLinkSpring);
                        app->selectedtruss = new std::shared_ptr<ChBody>(new ChBody);
                        (*(app->selectedtruss))->SetBodyFixed(true);
                        app->GetSystem()->AddBody(*(app->selectedtruss));
                        (*(app->selectedspring))
                            ->Initialize(*app->selectedtruss, *app->selectedmover, false, mresult.abs_hitPoint,
                                         mresult.abs_hitPoint);
                        app->GetSystem()->AddLink(*(app->selectedspring));
                    }
                }
                break;
            }
            case irr::EMIE_MMOUSE_LEFT_UP:
                if (app->selectedtruss) {
                    app->GetSystem()->RemoveBody((*(app->selectedtruss)));
                    app->GetSystem()->RemoveLink((*(app->selectedspring)));
                    delete (app->selectedtruss);
                    delete (app->selectedspring);
                    app->selectedtruss = 0;
                    app->selectedspring = 0;
                }
                break;
            case irr::EMIE_MOUSE_MOVED:
                if (app->selectedtruss) {
                    irr::core::line3d<irr::f32> mline =
                        app->GetSceneManager()->getSceneCollisionManager()->getRayFromScreenCoordinates(
                            app->GetDevice()->getCursorControl()->getPosition());
                    ChVector<> mfrom(mline.start.X, mline.start.Y, mline.start.Z);
                    ChVector<> mto(mline.end.X, mline.end.Y, mline.end.Z);
                    ChVector<> mdir = mto - mfrom;
                    mdir.Normalize();
                    ChVector<> springP1 = mfrom + mdir * app->selecteddist;
                    ChVector<> springP2 = (*(app->selectedmover))->Point_Body2World(app->selectedpoint);
                    (*(app->selectedspring))->SetEndPoint1Abs(springP1);
                    (*(app->selectedspring))->SetEndPoint2Abs(springP2);
                    (*(app->selectedspring))->Set_SpringK(25 * (*(app->selectedmover))->GetMass());
                    (*(app->selectedspring))->Set_SpringR(3 * (*(app->selectedmover))->GetMass());
                }
                break;
            default:
                break;
        }
    }

    // Check if user moved the sliders with mouse.
    if (event.EventType == irr::EET_GUI_EVENT) {
        irr::s32 id = event.GUIEvent.Caller->getID();

        switch (event.GUIEvent.EventType) {
            case irr::gui::EGET_SCROLL_BAR_CHANGED:
                switch (id) {
                    case 9904:
                        app->GetSystem()->SetMaxItersSolverSpeed(
                            ((irr::gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos());
                        break;
                    case 9905:
                        app->GetSystem()->SetMaxItersSolverStab(
                            ((irr::gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos());
                        break;
                    case 9909:
                        app->GetSystem()->SetSolverOverrelaxationParam(
                            (1.0 / 50.0) * ((irr::gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos());
                        break;
                    case 9910:
                        app->GetSystem()->SetSolverSharpnessParam(
                            (1.0 / 50.0) * ((irr::gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos());
                        break;
                    case 9911:
                        app->GetSystem()->SetMaxPenetrationRecoverySpeed(
                            (3.0 / 50.0) * ((irr::gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos());
                        break;
                    case 9912:
                        app->GetSystem()->SetMinBounceSpeed(
                            (1.0 / 200.0) * ((irr::gui::IGUIScrollBar*)event.GUIEvent.Caller)->getPos());
                        break;
                }
                break;

            case irr::gui::EGET_COMBO_BOX_CHANGED:
                if (id == 9907) {
                    int sel = ((irr::gui::IGUIComboBox*)event.GUIEvent.Caller)->getSelected();
                    switch (sel) {
                        case 0:
                            app->GetSystem()->SetSolverType(ChSolver::Type::SOR);
                            break;
                        case 1:
                            app->GetSystem()->SetSolverType(ChSolver::Type::SYMMSOR);
                            break;
                        case 2:
                            app->GetSystem()->SetSolverType(ChSolver::Type::JACOBI);
                            break;
                        case 3:
                            app->GetSystem()->SetSolverType(ChSolver::Type::SOR_MULTITHREAD);
                            break;
                        case 4:
                            app->GetSystem()->SetSolverType(ChSolver::Type::BARZILAIBORWEIN);
                            break;
                        case 5:
                            app->GetSystem()->SetSolverType(ChSolver::Type::PCG);
                            break;
                        case 6:
                            app->GetSystem()->SetSolverType(ChSolver::Type::PMINRES);
                            break;
                        case 7:
                            app->GetSystem()->SetSolverType(ChSolver::Type::APGD);
                            break;
                        case 8:
                            app->GetSystem()->SetSolverType(ChSolver::Type::MINRES);
                            break;
                        case 9:
                            GetLog()
                                << "WARNING.\nYou cannot change to a custom solver using the GUI. Use C++ instead.\n";
                            break;
                    }
                    break;
                }

                if (id == 9908) {
                    int sel = ((irr::gui::IGUIComboBox*)event.GUIEvent.Caller)->getSelected();
                    switch (sel) {
                        case 0:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT);
                            break;
                        case 1:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_LINEARIZED);
                            break;
                        case 2:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_PROJECTED);
                            break;
                        case 3:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::TRAPEZOIDAL);
                            break;
                        case 4:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::TRAPEZOIDAL_LINEARIZED);
                            break;
                        case 5:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::HHT);
                            break;
                        case 6:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::HEUN);
                            break;
                        case 7:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::RUNGEKUTTA45);
                            break;
                        case 8:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::EULER_EXPLICIT);
                            break;
                        case 9:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::LEAPFROG);
                            break;
                        case 10:
                            app->GetSystem()->SetTimestepperType(ChTimestepper::Type::NEWMARK);
                            break;
                        case 11:
                            GetLog() << "WARNING.\nYou cannot change to a custom timestepper using the GUI. Use C++ "
                                        "instead.\n";
                            break;
                    }
                    break;
                }

            case irr::gui::EGET_CHECKBOX_CHANGED:
                switch (id) {
                    case 9906:
                        app->GetSystem()->SetSolverWarmStarting(
                            ((irr::gui::IGUICheckBox*)event.GUIEvent.Caller)->isChecked());
                        break;
                    case 9913:
                        app->GetSystem()->SetUseSleeping(((irr::gui::IGUICheckBox*)event.GUIEvent.Caller)->isChecked());
                        break;
                    case 9916:
                        app->SetTryRealtime(((irr::gui::IGUICheckBox*)event.GUIEvent.Caller)->isChecked());
                        break;
                    case 9917:
                        app->pause_step = ((irr::gui::IGUICheckBox*)event.GUIEvent.Caller)->isChecked();
                        break;
                }
                break;

            case irr::gui::EGET_EDITBOX_ENTER:
                if (id == 9918) {
                    double dt = 0.01;
                    dt = atof(irr::core::stringc(((irr::gui::IGUIEditBox*)event.GUIEvent.Caller)->getText()).c_str());
                    app->SetTimestep(dt);
                    break;
                }

                if (id == 9921) {
                    double scale = 0.01;
                    scale =
                        atof(irr::core::stringc(((irr::gui::IGUIEditBox*)event.GUIEvent.Caller)->getText()).c_str());
                    app->SetSymbolscale(scale);
                    break;
                }

            default:
                break;
        }
    }

    return false;
}

// -----------------------------------------------------------------------------
// Implementation of ChIrrAppInterface methods
// -----------------------------------------------------------------------------

// Create the IRRLICHT context (device, etc.)
ChIrrAppInterface::ChIrrAppInterface(ChSystem* psystem,
                                     const wchar_t* title,
                                     irr::core::dimension2d<irr::u32> dimens,
                                     bool do_fullscreen,
                                     bool do_shadows,
                                     bool do_antialias,
                                     irr::video::E_DRIVER_TYPE mydriver)
    : step_manage(true),
      try_realtime(false),
      pause_step(false),
      timestep(0.01),
      do_single_step(false),
      videoframe_save(false),
      videoframe_num(0),
      videoframe_each(1),
      symbolscale(1.0),
      camera_auto_rotate_speed(0.0),
      selectedtruss(0),
      selectedspring(0),
      selectedmover(0) {
    irr::SIrrlichtCreationParameters params = irr::SIrrlichtCreationParameters();
    params.AntiAlias = do_antialias;
    params.Bits = 32;
    params.Fullscreen = do_fullscreen;
    params.DriverType = mydriver;
    params.WindowSize = dimens;
    params.Stencilbuffer = do_shadows;

    device = irr::createDeviceEx(params);

    if (device == 0) {
        GetLog() << "Cannot use default video driver - fall back to OpenGL \n";
        params.DriverType = irr::video::EDT_OPENGL;

        device = irr::createDeviceEx(params);

        if (!device)
            return;
    }

    // Xeffects for shadow maps!
    if (do_antialias)
        effect = new EffectHandler(device, device->getVideoDriver()->getScreenSize() * 2, true, false, true);
    else
        effect = new EffectHandler(device, device->getVideoDriver()->getScreenSize(), true, false, true);
    // note: Irrlicht antialiasing does not work with Xeffects, but we could fake AA in Xeffects
    // by doubling the size of its buffer:  EffectHandler(device, device->getVideoDriver()->getScreenSize()*2
    effect->setAmbientColor(irr::video::SColor(255, 122, 122, 122));
    use_effects = false;  // will be true as sson as a lightwith shadow is added.

    if (title)
        device->setWindowCaption(title);
    else
        device->setWindowCaption(L"Chrono::Engine");

    irr::gui::IGUISkin* skin = GetIGUIEnvironment()->getSkin();
    irr::gui::IGUIFont* font = GetIGUIEnvironment()->getFont(GetChronoDataFile("fonts/arial8.xml").c_str());
    if (font)
        skin->setFont(font);
    skin->setColor(irr::gui::EGDC_BUTTON_TEXT, irr::video::SColor(255, 40, 50, 50));
    skin->setColor(irr::gui::EGDC_HIGH_LIGHT, irr::video::SColor(255, 40, 70, 250));
    skin->setColor(irr::gui::EGDC_FOCUSED_EDITABLE, irr::video::SColor(255, 0, 255, 255));
    skin->setColor(irr::gui::EGDC_3D_HIGH_LIGHT, irr::video::SColor(200, 210, 210, 210));

    gad_tabbed = GetIGUIEnvironment()->addTabControl(irr::core::rect<irr::s32>(2, 70, 220, 496), 0, true, true);
    gad_tab1 = gad_tabbed->addTab(L"Stats");
    gad_tab2 = gad_tabbed->addTab(L"System");
    gad_tab3 = gad_tabbed->addTab(L"Help");

    // create GUI gadgets
    gad_textFPS =
        GetIGUIEnvironment()->addStaticText(L"FPS", irr::core::rect<irr::s32>(10, 10, 200, 230), true, true, gad_tab1);

    gad_labelcontacts =
        GetIGUIEnvironment()->addComboBox(irr::core::rect<irr::s32>(10, 240, 200, 240 + 20), gad_tab1, 9901);
    gad_labelcontacts->addItem(L"Contact distances");
    gad_labelcontacts->addItem(L"Contact force modulus");
    gad_labelcontacts->addItem(L"Contact force (normal)");
    gad_labelcontacts->addItem(L"Contact force (tangent)");
    gad_labelcontacts->addItem(L"Contact torque modulus");
    gad_labelcontacts->addItem(L"Contact torque (spinning)");
    gad_labelcontacts->addItem(L"Contact torque (rolling)");
    gad_labelcontacts->addItem(L"Don't print contact values");
    gad_labelcontacts->setSelected(7);

    gad_drawcontacts =
        GetIGUIEnvironment()->addComboBox(irr::core::rect<irr::s32>(10, 260, 200, 260 + 20), gad_tab1, 9901);
    gad_drawcontacts->addItem(L"Contact normals");
    gad_drawcontacts->addItem(L"Contact distances");
    gad_drawcontacts->addItem(L"Contact N forces");
    gad_drawcontacts->addItem(L"Contact forces");
    gad_drawcontacts->addItem(L"Don't draw contacts");
    gad_drawcontacts->setSelected(4);

    gad_labellinks =
        GetIGUIEnvironment()->addComboBox(irr::core::rect<irr::s32>(10, 280, 200, 280 + 20), gad_tab1, 9923);
    gad_labellinks->addItem(L"Link react.force modulus");
    gad_labellinks->addItem(L"Link react.force X");
    gad_labellinks->addItem(L"Link react.force Y");
    gad_labellinks->addItem(L"Link react.force Z");
    gad_labellinks->addItem(L"Link react.torque modulus");
    gad_labellinks->addItem(L"Link react.torque X");
    gad_labellinks->addItem(L"Link react.torque Y");
    gad_labellinks->addItem(L"Link react.torque Z");
    gad_labellinks->addItem(L"Don't print link values");
    gad_labellinks->setSelected(8);

    gad_drawlinks =
        GetIGUIEnvironment()->addComboBox(irr::core::rect<irr::s32>(10, 300, 200, 300 + 20), gad_tab1, 9924);
    gad_drawlinks->addItem(L"Link reaction forces");
    gad_drawlinks->addItem(L"Link reaction torques");
    gad_drawlinks->addItem(L"Don't draw link vectors");
    gad_drawlinks->setSelected(2);

    gad_plot_aabb = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 330, 200, 330 + 15),
                                                      gad_tab1, 9914, L"Draw AABB");

    gad_plot_cogs = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 345, 200, 345 + 15),
                                                      gad_tab1, 9915, L"Draw COGs");

    gad_plot_linkframes = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 360, 200, 360 + 15),
                                                            gad_tab1, 9920, L"Draw link frames");

    gad_symbolscale =
        GetIGUIEnvironment()->addEditBox(L"", irr::core::rect<irr::s32>(170, 330, 200, 330 + 15), true, gad_tab1, 9921);
    gad_symbolscale_info = GetIGUIEnvironment()->addStaticText(
        L"Symbols scale", irr::core::rect<irr::s32>(110, 330, 170, 330 + 15), false, false, gad_tab1);
    SetSymbolscale(symbolscale);

    gad_plot_convergence = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 375, 200, 375 + 15),
                                                             gad_tab1, 9902, L"Plot convergence");

    // --

    gad_speed_iternumber =
        GetIGUIEnvironment()->addScrollBar(true, irr::core::rect<irr::s32>(10, 10, 150, 10 + 20), gad_tab2, 9904);
    gad_speed_iternumber->setMax(120);
    gad_speed_iternumber_info = GetIGUIEnvironment()->addStaticText(
        L"", irr::core::rect<irr::s32>(155, 10, 220, 10 + 20), false, false, gad_tab2);

    gad_pos_iternumber =
        GetIGUIEnvironment()->addScrollBar(true, irr::core::rect<irr::s32>(10, 40, 150, 40 + 20), gad_tab2, 9905);
    gad_pos_iternumber->setMax(120);
    gad_pos_iternumber_info = GetIGUIEnvironment()->addStaticText(L"", irr::core::rect<irr::s32>(155, 40, 220, 40 + 20),
                                                                  false, false, gad_tab2);

    gad_warmstart = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 70, 200, 70 + 20), gad_tab2,
                                                      9906, L"Warm starting");

    gad_usesleep = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 100, 200, 100 + 20), gad_tab2,
                                                     9913, L"Enable sleeping");

    gad_ccpsolver =
        GetIGUIEnvironment()->addComboBox(irr::core::rect<irr::s32>(10, 130, 200, 130 + 20), gad_tab2, 9907);
    gad_ccpsolver->addItem(L"Projected SOR");
    gad_ccpsolver->addItem(L"Projected SSOR");
    gad_ccpsolver->addItem(L"Projected Jacobi");
    gad_ccpsolver->addItem(L"Multithreaded SOR");
    gad_ccpsolver->addItem(L"Projected BB");
    gad_ccpsolver->addItem(L"Projected PCG");
    gad_ccpsolver->addItem(L"Projected MINRES");
    gad_ccpsolver->addItem(L"APGD");
    gad_ccpsolver->addItem(L"MINRES");
    gad_ccpsolver->addItem(L"(custom)");
    gad_ccpsolver->setSelected(5);

    gad_stepper = GetIGUIEnvironment()->addComboBox(irr::core::rect<irr::s32>(10, 160, 200, 160 + 20), gad_tab2, 9908);
    gad_stepper->addItem(L"Euler implicit");
    gad_stepper->addItem(L"Euler semimplicit (linearized)");
    gad_stepper->addItem(L"Euler semimplicit projected");
    gad_stepper->addItem(L"Trapezoidal");
    gad_stepper->addItem(L"Trapezoidal (linearized)");
    gad_stepper->addItem(L"HHT");
    gad_stepper->addItem(L"Heun explicit");
    gad_stepper->addItem(L"RungeKutta45 explicit");
    gad_stepper->addItem(L"Euler explicit");
    gad_stepper->addItem(L"Leapfrog");
    gad_stepper->addItem(L"Newmark");
    gad_stepper->addItem(L"(custom)");

    gad_stepper->setSelected(0);

    gad_omega =
        GetIGUIEnvironment()->addScrollBar(true, irr::core::rect<irr::s32>(10, 190, 150, 190 + 20), gad_tab2, 9909);
    gad_omega->setMax(100);
    gad_omega_info = GetIGUIEnvironment()->addStaticText(L"", irr::core::rect<irr::s32>(155, 190, 220, 190 + 20), false,
                                                         false, gad_tab2);

    gad_lambda =
        GetIGUIEnvironment()->addScrollBar(true, irr::core::rect<irr::s32>(10, 220, 150, 220 + 20), gad_tab2, 9910);
    gad_lambda->setMax(100);
    gad_lambda_info = GetIGUIEnvironment()->addStaticText(L"", irr::core::rect<irr::s32>(155, 220, 220, 220 + 20),
                                                          false, false, gad_tab2);

    gad_clamping =
        GetIGUIEnvironment()->addScrollBar(true, irr::core::rect<irr::s32>(10, 250, 150, 250 + 20), gad_tab2, 9911);
    gad_clamping->setMax(100);
    gad_clamping_info = GetIGUIEnvironment()->addStaticText(L"", irr::core::rect<irr::s32>(155, 250, 220, 250 + 20),
                                                            false, false, gad_tab2);

    gad_minbounce =
        GetIGUIEnvironment()->addScrollBar(true, irr::core::rect<irr::s32>(10, 280, 150, 280 + 20), gad_tab2, 9912);
    gad_minbounce->setMax(100);
    gad_minbounce_info = GetIGUIEnvironment()->addStaticText(L"", irr::core::rect<irr::s32>(155, 280, 220, 280 + 20),
                                                             false, false, gad_tab2);

    gad_timestep =
        GetIGUIEnvironment()->addEditBox(L"", irr::core::rect<irr::s32>(140, 320, 200, 320 + 15), true, gad_tab2, 9918);
    gad_timestep_info = GetIGUIEnvironment()->addStaticText(
        L"Time step", irr::core::rect<irr::s32>(10, 320, 130, 320 + 15), false, false, gad_tab2);

    gad_try_realtime = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 340, 200, 340 + 15),
                                                         gad_tab2, 9916, L"Realtime step");
    gad_pause_step = GetIGUIEnvironment()->addCheckBox(false, irr::core::rect<irr::s32>(10, 355, 200, 355 + 15),
                                                       gad_tab2, 9917, L"Pause physics");

    gad_textHelp =
        GetIGUIEnvironment()->addStaticText(L"FPS", irr::core::rect<irr::s32>(10, 10, 200, 350), true, true, gad_tab3);
    irr::core::stringw hstr = "Instructions for interface.\n\n";
    hstr += "MOUSE \n\n";
    hstr += " left button: camera rotation \n";
    hstr += " righ button: camera translate \n";
    hstr += " wheel rotation: camera forward \n";
    hstr += " wheel button: drag collision shapes\n";
    hstr += "\nKEYBOARD\n\n";
    hstr += " 'i' key: show/hide settings\n";
    hstr += " arrows keys: camera X/Z translate\n";
    hstr += " Pg Up/Dw keys: camera Y translate\n";
    hstr += " 'spacebar' key: stop/start simul.\n";
    hstr += " 'p' key: advance single step\n";
    hstr += " 'Print Scr' key: video capture to .bmp's\n";
    hstr += " 'F6' key: single dump sys. matrices.\n";
    hstr += " 'F7' key: continuous dump sys. matrices.\n";
    hstr += " 'F8' key: dump a .json file.\n";
    hstr += " 'F10' key: non-linear statics.\n";
    hstr += " 'F11' key: linear statics.\n";
    hstr += " 'F2-F3-F4' key: auto rotate camera.\n";
    gad_textHelp->setText(hstr.c_str());

    ///

    system = psystem;

    show_infos = false;

    // the container, a level that contains all chrono nodes
    container = device->getSceneManager()->addEmptySceneNode();

    // the event receiver, taking care of user interaction
    ChIrrAppEventReceiver* receiver = new ChIrrAppEventReceiver(this);
    device->setEventReceiver(receiver);
}

// ChIrrAppInterface destructor. This safely delete every Irrlicht item
// (including the Irrlicht scene nodes)
ChIrrAppInterface::~ChIrrAppInterface() {
    device->drop();
    // delete (receiver);
}

// Set integration time step.
void ChIrrAppInterface::SetTimestep(double val) {
    timestep = ChMax(10e-9, val);
    char message[50];
    sprintf(message, "%g", timestep);
    gad_timestep->setText(irr::core::stringw(message).c_str());
}

// Set the scale for drawing symbols.
void ChIrrAppInterface::SetSymbolscale(double val) {
    symbolscale = ChMax(10e-12, val);
    char message[50];
    sprintf(message, "%g", symbolscale);
    gad_symbolscale->setText(irr::core::stringw(message).c_str());
}

// Set the fonts to be used from now on.
void ChIrrAppInterface::SetFonts(const std::string& mfontdir) {
    irr::gui::IGUISkin* skin = GetIGUIEnvironment()->getSkin();
    irr::gui::IGUIFont* font = GetIGUIEnvironment()->getFont(mfontdir.c_str());
    if (font)
        skin->setFont(font);
}

// Clean canvas at beginning of scene.
void ChIrrAppInterface::BeginScene(bool backBuffer, bool zBuffer, irr::video::SColor color) {
    GetVideoDriver()->beginScene(backBuffer, zBuffer, color);

    if (camera_auto_rotate_speed) {
        irr::core::vector3df pos = GetSceneManager()->getActiveCamera()->getPosition();
        irr::core::vector3df target = GetSceneManager()->getActiveCamera()->getTarget();
        pos.rotateXZBy(camera_auto_rotate_speed, target);
        GetSceneManager()->getActiveCamera()->setPosition(pos);
        GetSceneManager()->getActiveCamera()->setTarget(target);
    }
}

// Call this to end the scene draw at the end of each animation frame.
void ChIrrAppInterface::EndScene() {
    GetVideoDriver()->endScene();
}

// Advance physics by one time step.
void ChIrrAppInterface::DoStep() {
    if (!step_manage)
        return;

    if (pause_step) {
        if (do_single_step)
            do_single_step = false;
        else
            return;
    }

    if (videoframe_save) {
        if (videoframe_num % videoframe_each == 0) {
            ChFileutils::MakeDirectory("video_capture");
            irr::video::IImage* image = GetVideoDriver()->createScreenShot();
            char filename[100];
            sprintf(filename, "video_capture/screenshot%05d.bmp", (videoframe_num + 1) / videoframe_each);
            if (image)
                device->getVideoDriver()->writeImageToFile(image, filename);
            image->drop();
        }
        videoframe_num++;
    }

    double dt;
    if (try_realtime)
        dt = m_realtime_timer.SuggestSimulationStep(timestep);
    else
        dt = timestep;

    try {
        system->DoStepDynamics(dt);
    } catch (ChException my_exception) {
        GetLog() << my_exception.what() << "\n";
    }
}

// Redraw all 3D shapes and GUI elements
void ChIrrAppInterface::DrawAll() {
    irr::core::stringw str = "World time   =";
    str += (int)(1000 * system->GetChTime());
    str += " ms  \n\nCPU step (total)      =";
    str += (int)(1000 * system->GetTimerStep());
    str += " ms \n  CPU Collision time =";
    str += (int)(1000 * system->GetTimerCollisionBroad());
    str += " ms \n  CPU Solver time         =";
    str += (int)(1000 * system->GetTimerSolver());
    str += " ms \n  CPU Update time      =";
    str += (int)(1000 * system->GetTimerUpdate());
    str += " ms \n\nSolver vel.iters : ";
    str += system->GetMaxItersSolverSpeed();
    str += "\nSolver pos.iters : ";
    str += system->GetMaxItersSolverStab();
    str += "\n\nN.of active bodies  : ";
    str += system->GetNbodies();
    str += "\nN.of sleeping bodies  : ";
    str += system->GetNbodiesSleeping();
    str += "\nN.of contacts  : ";
    str += system->GetNcontacts();
    str += "\nN.of coords    : ";
    str += system->GetNcoords_w();
    str += "\nN.of constr.   : ";
    str += system->GetNdoc_w();
    str += "\nN.of variables : ";
    str += system->GetNsysvars_w();
    gad_textFPS->setText(str.c_str());

    if (use_effects)
        effect->update();  // DRAW 3D SCENE using Xeffects for shadow maps, if used!
    else
        GetSceneManager()->drawAll();  // DRAW 3D SCENE the usual way, if no shadow maps

    int dmode = gad_drawcontacts->getSelected();
    ChIrrTools::drawAllContactPoints(*system, GetVideoDriver(), symbolscale, (ChIrrTools::eCh_ContactsDrawMode)dmode);

    int lmode = gad_labelcontacts->getSelected();
    ChIrrTools::drawAllContactLabels(*system, GetDevice(), (ChIrrTools::eCh_ContactsLabelMode)lmode);

    int dmodeli = gad_drawlinks->getSelected();
    ChIrrTools::drawAllLinks(*system, GetVideoDriver(), symbolscale, (ChIrrTools::eCh_LinkDrawMode)dmodeli);

    int lmodeli = gad_labellinks->getSelected();
    ChIrrTools::drawAllLinkLabels(*system, GetDevice(), (ChIrrTools::eCh_LinkLabelMode)lmodeli);

    if (gad_plot_aabb->isChecked())
        ChIrrTools::drawAllBoundingBoxes(*system, GetVideoDriver());

    if (gad_plot_cogs->isChecked())
        ChIrrTools::drawAllCOGs(*system, GetVideoDriver(), symbolscale);

    if (gad_plot_linkframes->isChecked())
        ChIrrTools::drawAllLinkframes(*system, GetVideoDriver(), symbolscale);

    if (gad_plot_convergence->isChecked())
        ChIrrTools::drawHUDviolation(GetVideoDriver(), GetDevice(), *system, 240, 370, 300, 100, 100.0, 500.0);

    gad_tabbed->setVisible(show_infos);

    if (gad_speed_iternumber_info->isVisible()) {
        gad_warmstart->setChecked(GetSystem()->GetSolverWarmStarting());
        gad_usesleep->setChecked(GetSystem()->GetUseSleeping());

        char message[50];

        gad_speed_iternumber->setPos(GetSystem()->GetMaxItersSolverSpeed());
        sprintf(message, "%i vel.iters", GetSystem()->GetMaxItersSolverSpeed());
        gad_speed_iternumber_info->setText(irr::core::stringw(message).c_str());

        gad_pos_iternumber->setPos(GetSystem()->GetMaxItersSolverStab());
        sprintf(message, "%i pos.iters", GetSystem()->GetMaxItersSolverStab());
        gad_pos_iternumber_info->setText(irr::core::stringw(message).c_str());

        gad_omega->setPos((irr::s32)(50.0 * (GetSystem()->GetSolverOverrelaxationParam())));
        sprintf(message, "%g omega", GetSystem()->GetSolverOverrelaxationParam());
        gad_omega_info->setText(irr::core::stringw(message).c_str());

        gad_lambda->setPos((irr::s32)(50.0 * (GetSystem()->GetSolverSharpnessParam())));
        sprintf(message, "%g lambda", GetSystem()->GetSolverSharpnessParam());
        gad_lambda_info->setText(irr::core::stringw(message).c_str());

        gad_clamping->setPos((irr::s32)((50.0 / 3.0) * (GetSystem()->GetMaxPenetrationRecoverySpeed())));
        sprintf(message, "%g stab.clamp", GetSystem()->GetMaxPenetrationRecoverySpeed());
        gad_clamping_info->setText(irr::core::stringw(message).c_str());

        gad_minbounce->setPos((irr::s32)(200.0 * (GetSystem()->GetMinBounceSpeed())));
        sprintf(message, "%g min.bounce v", GetSystem()->GetMinBounceSpeed());
        gad_minbounce_info->setText(irr::core::stringw(message).c_str());

        switch (GetSystem()->GetSolverType()) {
            case ChSolver::Type::SOR:
                gad_ccpsolver->setSelected(0);
                break;
            case ChSolver::Type::SYMMSOR:
                gad_ccpsolver->setSelected(1);
                break;
            case ChSolver::Type::JACOBI:
                gad_ccpsolver->setSelected(2);
                break;
            case ChSolver::Type::SOR_MULTITHREAD:
                gad_ccpsolver->setSelected(3);
                break;
            case ChSolver::Type::BARZILAIBORWEIN:
                gad_ccpsolver->setSelected(4);
                break;
            case ChSolver::Type::PCG:
                gad_ccpsolver->setSelected(5);
                break;
            case ChSolver::Type::PMINRES:
                gad_ccpsolver->setSelected(6);
                break;
            case ChSolver::Type::APGD:
                gad_ccpsolver->setSelected(7);
                break;
            case ChSolver::Type::MINRES:
                gad_ccpsolver->setSelected(8);
                break;
            default:
                gad_ccpsolver->setSelected(9);
                break;
        }

        switch (GetSystem()->GetTimestepperType()) {
            case ChTimestepper::Type::EULER_IMPLICIT:
                gad_stepper->setSelected(0);
                break;
            case ChTimestepper::Type::EULER_IMPLICIT_LINEARIZED:
                gad_stepper->setSelected(1);
                break;
            case ChTimestepper::Type::EULER_IMPLICIT_PROJECTED:
                gad_stepper->setSelected(2);
                break;
            case ChTimestepper::Type::TRAPEZOIDAL:
                gad_stepper->setSelected(3);
                break;
            case ChTimestepper::Type::TRAPEZOIDAL_LINEARIZED:
                gad_stepper->setSelected(4);
                break;
            case ChTimestepper::Type::HHT:
                gad_stepper->setSelected(5);
                break;
            case ChTimestepper::Type::HEUN:
                gad_stepper->setSelected(6);
                break;
            case ChTimestepper::Type::RUNGEKUTTA45:
                gad_stepper->setSelected(7);
                break;
            case ChTimestepper::Type::EULER_EXPLICIT:
                gad_stepper->setSelected(8);
                break;
            case ChTimestepper::Type::LEAPFROG:
                gad_stepper->setSelected(9);
                break;
            case ChTimestepper::Type::NEWMARK:
                gad_stepper->setSelected(10);
                break;
            default:
                gad_stepper->setSelected(11);
                break;
        }

        gad_try_realtime->setChecked(GetTryRealtime());
        gad_pause_step->setChecked(pause_step);

        if (!GetStepManage()) {
            sprintf(message, "%g", GetSystem()->GetStep());
            gad_timestep->setText(irr::core::stringw(message).c_str());
        }

        // disable timestep-related gadgets if dt not handled by application object
        gad_try_realtime->setEnabled(GetStepManage());
        gad_pause_step->setEnabled(GetStepManage());
        gad_timestep->setEnabled(GetStepManage());
    }

    // if(show_infos)
    GetIGUIEnvironment()->drawAll();
}

// Dump the last used system matrices and vectors in the current directory,
void ChIrrAppInterface::DumpSystemMatrices() {
    // For safety
    GetSystem()->Setup();
    GetSystem()->Update();

    try {
        // Save M mass matrix, K stiffness matrix, R damping matrix, Cq jacobians:
        GetSystem()->DumpSystemMatrices(true, true, true, true, "dump_");

    } catch (ChException myexc) {
        GetLog() << myexc.what();
    }
}

}  // end namespace irrlicht
}  // end namespace chrono


text:
import logging
import yaml
import io

from redash.utils.requests_session import requests_or_advocate, UnacceptableAddressException

from redash.query_runner import *
from redash.utils import json_dumps

logger = logging.getLogger(__name__)

try:
    import pandas as pd
    import numpy as np
    enabled = True
except ImportError:
    enabled = False

class CSV(BaseQueryRunner):
    should_annotate_query = False

    @classmethod
    def name(cls):
        return "CSV"

    @classmethod
    def enabled(cls):
        return enabled

    @classmethod
    def configuration_schema(cls):
        return {
            'type': 'object',
            'properties': {},
        }

    def __init__(self, configuration):
        super(CSV, self).__init__(configuration)
        self.syntax = "yaml"

    def test_connection(self):
        pass

    def run_query(self, query, user):
        path = ""
        ua = ""
        args = {}
        try:
            args = yaml.safe_load(query)
            path = args['url']
            args.pop('url', None)
            ua = args['user-agent']
            args.pop('user-agent', None)
        except:
            pass

        try:
            response = requests_or_advocate.get(url=path, headers={"User-agent": ua})
            workbook = pd.read_csv(io.BytesIO(response.content),sep=",", **args)

            df = workbook.copy()
            data = {'columns': [], 'rows': []}
            conversions = [
                {'pandas_type': np.integer, 'redash_type': 'integer',},
                {'pandas_type': np.inexact, 'redash_type': 'float',},
                {'pandas_type': np.datetime64, 'redash_type': 'datetime', 'to_redash': lambda x: x.strftime('%Y-%m-%d %H:%M:%S')},
                {'pandas_type': np.bool_, 'redash_type': 'boolean'},
                {'pandas_type': np.object, 'redash_type': 'string'}
            ]
            labels = []
            for dtype, label in zip(df.dtypes, df.columns):
                for conversion in conversions:
                    if issubclass(dtype.type, conversion['pandas_type']):
                        data['columns'].append({'name': label, 'friendly_name': label, 'type': conversion['redash_type']})
                        labels.append(label)
                        func = conversion.get('to_redash')
                        if func:
                            df[label] = df[label].apply(func)
                        break
            data['rows'] = df[labels].replace({np.nan: None}).to_dict(orient='records')

            json_data = json_dumps(data)
            error = None
        except KeyboardInterrupt:
            error = "Query cancelled by user."
            json_data = None
        except UnacceptableAddressException:
            error = "Can't query private addresses."
            json_data = None
        except Exception as e:
            error = "Error reading {0}. {1}".format(path, str(e))
            json_data = None

        return json_data, error

    def get_schema(self):
        raise NotSupported()

register(CSV)

redpajama_set_name: RedPajamaGithub


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM ../../../dist/idl\nsISHTransaction.idl
 */

#ifndef __gen_nsISHTransaction_h__
#define __gen_nsISHTransaction_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsISHEntry; /* forward declaration */

/* starting interface:    nsISHTransaction */
#define NS_ISHTRANSACTION_IID_STR "2edf705f-d252-4971-9f09-71dd0f760dc6"

#define NS_ISHTRANSACTION_IID \
  {0x2edf705f, 0xd252, 0x4971, \
    { 0x9f, 0x09, 0x71, 0xdd, 0x0f, 0x76, 0x0d, 0xc6 }}

class NS_NO_VTABLE nsISHTransaction : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISHTRANSACTION_IID)

  /* attribute nsISHEntry sHEntry; */
  NS_IMETHOD GetSHEntry(nsISHEntry * *aSHEntry) = 0;
  NS_IMETHOD SetSHEntry(nsISHEntry *aSHEntry) = 0;

  /* attribute nsISHTransaction prev; */
  NS_IMETHOD GetPrev(nsISHTransaction * *aPrev) = 0;
  NS_IMETHOD SetPrev(nsISHTransaction *aPrev) = 0;

  /* attribute nsISHTransaction next; */
  NS_IMETHOD GetNext(nsISHTransaction * *aNext) = 0;
  NS_IMETHOD SetNext(nsISHTransaction *aNext) = 0;

  /* attribute boolean persist; */
  NS_IMETHOD GetPersist(bool *aPersist) = 0;
  NS_IMETHOD SetPersist(bool aPersist) = 0;

  /* void create (in nsISHEntry aSHEntry, in nsISHTransaction aPrev); */
  NS_IMETHOD Create(nsISHEntry *aSHEntry, nsISHTransaction *aPrev) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsISHTransaction, NS_ISHTRANSACTION_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISHTRANSACTION \
  NS_IMETHOD GetSHEntry(nsISHEntry * *aSHEntry) override; \
  NS_IMETHOD SetSHEntry(nsISHEntry *aSHEntry) override; \
  NS_IMETHOD GetPrev(nsISHTransaction * *aPrev) override; \
  NS_IMETHOD SetPrev(nsISHTransaction *aPrev) override; \
  NS_IMETHOD GetNext(nsISHTransaction * *aNext) override; \
  NS_IMETHOD SetNext(nsISHTransaction *aNext) override; \
  NS_IMETHOD GetPersist(bool *aPersist) override; \
  NS_IMETHOD SetPersist(bool aPersist) override; \
  NS_IMETHOD Create(nsISHEntry *aSHEntry, nsISHTransaction *aPrev) override;

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISHTRANSACTION(_to) \
  NS_IMETHOD GetSHEntry(nsISHEntry * *aSHEntry) override { return _to GetSHEntry(aSHEntry); } \
  NS_IMETHOD SetSHEntry(nsISHEntry *aSHEntry) override { return _to SetSHEntry(aSHEntry); } \
  NS_IMETHOD GetPrev(nsISHTransaction * *aPrev) override { return _to GetPrev(aPrev); } \
  NS_IMETHOD SetPrev(nsISHTransaction *aPrev) override { return _to SetPrev(aPrev); } \
  NS_IMETHOD GetNext(nsISHTransaction * *aNext) override { return _to GetNext(aNext); } \
  NS_IMETHOD SetNext(nsISHTransaction *aNext) override { return _to SetNext(aNext); } \
  NS_IMETHOD GetPersist(bool *aPersist) override { return _to GetPersist(aPersist); } \
  NS_IMETHOD SetPersist(bool aPersist) override { return _to SetPersist(aPersist); } \
  NS_IMETHOD Create(nsISHEntry *aSHEntry, nsISHTransaction *aPrev) override { return _to Create(aSHEntry, aPrev); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISHTRANSACTION(_to) \
  NS_IMETHOD GetSHEntry(nsISHEntry * *aSHEntry) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSHEntry(aSHEntry); } \
  NS_IMETHOD SetSHEntry(nsISHEntry *aSHEntry) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetSHEntry(aSHEntry); } \
  NS_IMETHOD GetPrev(nsISHTransaction * *aPrev) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrev(aPrev); } \
  NS_IMETHOD SetPrev(nsISHTransaction *aPrev) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetPrev(aPrev); } \
  NS_IMETHOD GetNext(nsISHTransaction * *aNext) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNext(aNext); } \
  NS_IMETHOD SetNext(nsISHTransaction *aNext) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetNext(aNext); } \
  NS_IMETHOD GetPersist(bool *aPersist) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPersist(aPersist); } \
  NS_IMETHOD SetPersist(bool aPersist) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetPersist(aPersist); } \
  NS_IMETHOD Create(nsISHEntry *aSHEntry, nsISHTransaction *aPrev) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Create(aSHEntry, aPrev); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsSHTransaction : public nsISHTransaction
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSISHTRANSACTION

  nsSHTransaction();

private:
  ~nsSHTransaction();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS(nsSHTransaction, nsISHTransaction)

nsSHTransaction::nsSHTransaction()
{
  /* member initializers and constructor code */
}

nsSHTransaction::~nsSHTransaction()
{
  /* destructor code */
}

/* attribute nsISHEntry sHEntry; */
NS_IMETHODIMP nsSHTransaction::GetSHEntry(nsISHEntry * *aSHEntry)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsSHTransaction::SetSHEntry(nsISHEntry *aSHEntry)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute nsISHTransaction prev; */
NS_IMETHODIMP nsSHTransaction::GetPrev(nsISHTransaction * *aPrev)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsSHTransaction::SetPrev(nsISHTransaction *aPrev)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute nsISHTransaction next; */
NS_IMETHODIMP nsSHTransaction::GetNext(nsISHTransaction * *aNext)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsSHTransaction::SetNext(nsISHTransaction *aNext)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute boolean persist; */
NS_IMETHODIMP nsSHTransaction::GetPersist(bool *aPersist)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsSHTransaction::SetPersist(bool aPersist)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void create (in nsISHEntry aSHEntry, in nsISHTransaction aPrev); */
NS_IMETHODIMP nsSHTransaction::Create(nsISHEntry *aSHEntry, nsISHTransaction *aPrev)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

// {BFD1A792-AD9F-11d3-BDC7-0050040A9B44}
#define NS_SHTRANSACTION_CID \
{0xbfd1a792, 0xad9f, 0x11d3, {0xbd, 0xc7, 0x0, 0x50, 0x4, 0xa, 0x9b, 0x44}}
#define NS_SHTRANSACTION_CONTRACTID \
    "@mozilla.org/browser/session-history-transaction;1"

#endif /* __gen_nsISHTransaction_h__ */


text:
class Image < ActiveRecord::Base
  self.table_name = "AnnotationBase"
  self.primary_key = "AnnotationId"

  belongs_to :project, foreign_key: "ObjectId"

  default_scope {
    where("IsDocument" => true)        # Is an image
    .where("ObjectTypeCode" => 10056)  # Associated to a project
    .order("ModifiedOn").reverse_order # Most recent image last
  }

  alias_attribute :filename,  "FileName"
  alias_attribute :mime_type, "MimeType"
  alias_attribute :body, "DocumentBody"

  # TODO This shouldn't be in the model because it's
  # routing logic, not model logic. Perhaps a mixin
  # of some sort. Maybe look at Paperclip's design.
  def url(style=nil)
    base_path = "/images/#{filename}"
    style ? base_path << "?style=#{style}" : base_path
  end

  def content(style=nil)
    ImageCacher.new(self, hash_key: hash_key(style), style: style).value
  end

  def hash_key(style)
    style || "nil"
  end

  def binary(style=nil)
    Base64.decode64 content(style)
  end

  def data(style=nil)
    "data:#{ mime_type };base64,#{ content(style) }"
  end

  def raw_data
    "data:#{ mime_type };base64,#{ body }"
  end

  def styles
    {
      small:  [ 300, 200],
      medium: [ 600, 400],
      large:  [1200, 800]
    }
  end

  def to_param
    filename
  end

  def resize(style)
    if style
      dimensions = styles[style.to_sym]
      base64 = Magick::Image.read_inline(raw_data).first
      resized_image = base64.resize_to_fill(dimensions.first, dimensions.last)
      Base64.encode64 resized_image.to_blob
    else
      body
    end
  end

end


text:
using Cauldron.Interception.Cecilator;

namespace Cauldron.Interception.Fody.HelperTypes
{
    public sealed class __Extensions : HelperTypeBase
    {
        public __Extensions(Builder builder) : base(builder, "Cauldron.Interception.Extensions")
        {
            this.TryDisposeInternal = this.type.GetMethod("TryDisposeInternal", 1);
        }

        public Method TryDisposeInternal { get; private set; }
    }
}


text:
function bitlyff_hello() {
    alter('Hello from bitlyff! Sorry, but the function you triggered is not yet implemented.');
}

function bitlyff_gotoUrl(str){
	opener.focus();
	self.focus();
	if(opener.gBrowser.addTab) {
		opener.gBrowser.selectedTab = opener.gBrowser.addTab(str);
	} else {
		window.open(str);
	}
}

function bitlyff_overlayInit(){
    try{
        var oContext = document.getElementById("contentAreaContextMenu");
	oContext.setAttribute("onpopupshowing", "bitlyff_contextShowing(event); "+ oContext.getAttribute("onpopupshowing"));
    } catch(err) { alert(err); }
}

function bitlyff_copyCurrentPage() {
    bitlyff_copyShortUrl(gBrowser.currentURI.spec);
}

function bitlyff_getPageInfo(){
    window.openDialog('chrome://bitlyff/content/pageinfo.xul','bitlyffPageInfo','chrome, centerscreen, resizable');
}

function bitlyff_PageInfoLoad() {
    var titleField 	= document.getElementById("title-field");
    var visThumbnailField = document.getElementById("visthumbnail-field");

    var longField 	= document.getElementById("long-field");
    var shortField 	= document.getElementById("short-field");
    var mirrorField 	= document.getElementById("mirror-field");

    var smallThumbnailField = document.getElementById("thumbnail-small-field");
    var mediumThumbnailField = document.getElementById("thumbnail-medium-field");
    var largeThumbnailField = document.getElementById("thumbnail-large-field");

    var clicksField = document.getElementById("clicks-field");

    var refGrid = document.getElementById("refgrid");
    var refGridRows = document.getElementById("refgridrows");

    if(opener.gBrowser && opener.gBrowser.currentURI){
	var url = bitlyff_getShortUrl(opener.gBrowser.currentURI.spec);
        eval('var bitlyresult = ' + bitlyff_getInfo(url));

        bitlyff_AddUrlLabel(longField, bitlyresult.shortenedUrl.long);
        bitlyff_AddUrlLabel(shortField, bitlyresult.shortenedUrl.short);
        if (bitlyresult.shortenedUrl.mirror) {
            bitlyff_AddUrlLabel(mirrorField, bitlyresult.shortenedUrl.mirror);
        }

        /** if (bitlyresult.shortenedUrl.thumbnails.small) {
           visThumbnailField.onload = function() {
                if (visThumbnailField && visThumbnailField.src != "")  {
                    visThumbnailField.setAttribute("width", visThumbnailField.naturalWidth);
                    visThumbnailField.setAttribute("height", visThumbnailField.naturalHeight);
                    window.resizeBy(0, visThumbnailField.naturalHeight)
                }
            }
            visThumbnailField.src = bitlyresult.shortenedUrl.thumbnails.small;
        } else {
            visThumbnailField.setAttribute("collapsed", true);
        } **/

        if (bitlyresult.shortenedUrl.thumbnails.small) {
            bitlyff_AddUrlLabel(smallThumbnailField, bitlyresult.shortenedUrl.thumbnails.small);
        }
        if(bitlyresult.shortenedUrl.thumbnails.medium) {
            bitlyff_AddUrlLabel(mediumThumbnailField, bitlyresult.shortenedUrl.thumbnails.medium);
        }
        if(bitlyresult.shortenedUrl.thumbnails.large) {
            bitlyff_AddUrlLabel(largeThumbnailField, bitlyresult.shortenedUrl.thumbnails.large);
        }

        if (bitlyresult.shortenedUrl.clicks) {
            clicksField.value = bitlyresult.shortenedUrl.clicks;
        }

        if (bitlyresult.shortenedUrl.referrers && bitlyresult.shortenedUrl.referrers.length > 0) {
            for (var i=0; i < bitlyresult.shortenedUrl.referrers.length; i++) {
                var newRow = document.createElement("row");

                var sourceLabel = document.createElement("label");
                bitlyff_AddUrlLabel(sourceLabel, bitlyresult.shortenedUrl.referrers[i].referrer.source);

                var clicksLabel = document.createElement("label");
                clicksLabel.setAttribute("value", bitlyresult.shortenedUrl.referrers[i].referrer.clicks);

                newRow.appendChild(sourceLabel);
                newRow.appendChild(clicksLabel);

                refGridRows.appendChild(newRow);
            }
        } else {
             refGrid.setAttribute("collapsed", true);
        }

    }
}

function bitlyff_AddUrlLabel(field, str){
    field.setAttribute("value", str);
    field.setAttribute("style", "color: #00F; text-decoration: underline; cursor: pointer;");
    field.setAttribute("onclick", "bitlyff_gotoUrl('" + str + "');");
}

function bitlyff_copyCurrentAnchor() {
    	if(gContextMenu != null && (gContextMenu.getLinkURL || gContextMenu.linkURL)){
		var url = (gContextMenu.getLinkURL) ? gContextMenu.getLinkURL() : gContextMenu.linkURL
		bitlyff_copyShortUrl(url);
	}
}

function bitlyff_copyShortUrl(str) {
    var bitlyUrl = bitlyff_getShortUrl(str);
    bitlyff_copyText(bitlyUrl);
}

function bitlyff_getShortUrl(str) {
    var request	= new XMLHttpRequest();
    request.open( "GET", "http://bit.ly/api?url=" + str, false);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(null);

    return request.responseText;
}

function bitlyff_getInfo(str) {
    var request	= new XMLHttpRequest();
    request.open( "GET", "http://bit.ly/feed.php?url=" + str + "&format=json", false);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(null);

    return request.responseText;
}

function bitlyff_contextShowing(event){
	try{
		if(document.popupNode.nodeName.toUpperCase() == "A"){
			document.getElementById("bitlyff-context-anchor-menu").setAttribute("collapsed", false);
		} else {
			document.getElementById("bitlyff-context-anchor-menu").setAttribute("collapsed", true);
		}
	} catch(err) {alert(err);}
}

function bitlyff_copyfieldvalue(str) {
    var element = document.getElementById(str);
    bitlyff_copyText(element.value);
}

function bitlyff_copyText(str){
	try {
            var clipboard = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
            clipboard.copyString(str);
	} catch(err) {alert(err);}
}


text:
import ast
import imp
import logging
import pkgutil

class ModuleDependencyAnalyzer(object):
    _IMP_TYPE_NAMES = {
        imp.PY_FROZEN: 'frozen',
        imp.PY_SOURCE: 'source',
        imp.PY_COMPILED: 'compiled',
        imp.C_EXTENSION: 'c-extension',
        imp.C_BUILTIN: 'built-in',
    }

    def __init__(self):
        """Creates new ModuleDependencyAnalyzer"""
        self._logger = logging.getLogger('multyvac.dependency-analyzer')
        # Root modules that have been or are being inspected
        self._inspected_modules = set()
        # Root modules that have yet to be inspected
        self._modules_to_inspect = set()
        # Root modules that should be ignored by this (Not sent or traversed)
        self._modules_to_ignore = set()
        # Root module paths to transmit. Will never include path to modules
        # that contain c-extensions, and are thus untransmittable.
        self._paths_to_transmit = set()
        self.has_module_dependencies = False

    def add(self, module_name):
        """
        Adds a module to be analyzed.
        :param module_name: String of module name.
        """
        self._logger.debug('Queuing module %r', module_name)
        root_module_name = self._extract_root_module(module_name)
        self._modules_to_inspect.add(root_module_name)
        while self._modules_to_inspect:
            self._inspect(self._modules_to_inspect.pop())

    def ignore(self, module_name):
        """
        Ignores modules in dependency analysis so that they are neither
        transmitted nor traversed. Should be called before dependencies
        are sent the first time.
        """
        # what if module is already part of paths to transmit?
        if hasattr(module_name, '__iter__'):
            self._modules_to_ignore.update(module_name)
        elif isinstance(module_name, str):
            self._modules_to_ignore.add(module_name)
        else:
            raise TypeError('module_name must be string')

    def get_and_clear_paths(self):
        # might be nice if this returned module names as well
        paths = self._paths_to_transmit
        if paths:
            self.has_module_dependencies = True
        self._paths_to_transmit = set()
        return paths

    def _inspect(self, root_module_name):
        """
        Determines what resources to send over (if any) for a given module.
        """
        if root_module_name in self._inspected_modules:
            self._logger.debug('Already inspected module %r, skipping',
                               root_module_name)
            return
        elif root_module_name in self._modules_to_ignore:
            self._logger.debug('Module %r is to be ignored, skipping',
                               root_module_name)
            return
        else:
            # Add module to set of scanned modules, before we've analyzed it
            self._inspected_modules.add(root_module_name)

        self._logger.debug('Inspecting module %r', root_module_name)
        try:
            fp, pathname, description = imp.find_module(root_module_name)
        except ImportError:
            self._logger.debug('Could not find module %r, skipping',
                               root_module_name)
            return
        _, _, mod_type = description
        if mod_type == imp.PY_SOURCE:
            self._paths_to_transmit.add(pathname)
            self._logger.debug('Module %r is source/compiled. Added path %r',
                               root_module_name, pathname)
            # TODO: Does this work with compiled sources?
            try:
                source_imps = self._find_imports(ast.parse(fp.read(),
                                                           root_module_name))
            except SyntaxError:
                self._logger.debug('Module %r has a syntax error. '
                                   'Skipping source analysis',
                                   root_module_name)
                # For malformed source code
                source_imps = []
            # Close the file handle that's been opened for us by find_module
            fp.close()
            self._logger.debug('Module %r had these imports %r',
                               root_module_name, source_imps)
            for source_imp in source_imps:
                if source_imp in self._inspected_modules:
                    self._logger.debug('Module %r Source import %r '
                                       'already inspected', root_module_name,
                                       source_imp)
                elif source_imp in self._modules_to_inspect:
                    self._logger.debug('Module %r Source import %r '
                                       'already queued', root_module_name,
                                       source_imp)
                elif source_imp in self._modules_to_ignore:
                    self._logger.debug('Module %r Source import %r '
                                       'to be ignored', root_module_name,
                                       source_imp)
                else:
                    # Cannot be relative import since this is top-level
                    self._modules_to_inspect.add(source_imp)
                    self._logger.debug('Module %r Source import %r added '
                                       'to queue', root_module_name, source_imp)
        elif mod_type == imp.PKG_DIRECTORY:
            self._logger.debug('Module %r is package. Recursing...',
                               root_module_name)
            if self._deep_inspect_path(pathname, root_module_name):
                self._paths_to_transmit.add(pathname)
                self._logger.debug('Module %r has no c-extensions. Added path %r',
                                   root_module_name, pathname)
        elif mod_type in (imp.C_EXTENSION, imp.C_BUILTIN, imp.PY_FROZEN,
                          imp.PY_COMPILED):
            self._logger.debug('Module %r is %s. Skipping.',
                               root_module_name,
                               self._IMP_TYPE_NAMES[mod_type])
        else:
            raise Exception('Unrecognized module %r type %s'
                            % (root_module_name, mod_type))

    def _deep_inspect_path(self, path, package_name):
        """
        Traverses :param path: analyzing all valid Python modules.
        Returns True if this path is eligible to be sent (No c-extensions).
        Adds module references to list of modules to be inspected.
        """
        ret = True
        for _, submodule_name, _ in pkgutil.iter_modules([path]):
            self._logger.debug('Inspecting submodule %r', submodule_name)
            fp, pathname, description = imp.find_module(submodule_name, [path])
            _, _, mod_type = description
            if mod_type == imp.PY_SOURCE:
                self._logger.debug('%r -> %r is source/compiled. '
                                   'Scanning imports.',
                                   package_name,
                                   submodule_name)
                # TODO: Does this work with compiled sources?
                try:
                    source_imps = self._find_imports(ast.parse(fp.read(),
                                                               submodule_name))
                except SyntaxError:
                    self._logger.debug('%r -> %r has a syntax error. '
                                       'Skipping source analysis',
                                       package_name,
                                       submodule_name)
                    source_imps = []
                # Close the file handle that's been opened for us by find_module
                fp.close()
                self._logger.debug('%r -> %r had these imports %r',
                                   package_name, submodule_name, source_imps)
                for source_imp in source_imps:
                    if source_imp in self._inspected_modules:
                        self._logger.debug('%r -> %r -> %r already inspected',
                                           package_name,
                                           submodule_name,
                                           source_imp)
                    elif source_imp in self._modules_to_inspect:
                        self._logger.debug('%r -> %r -> %r already queued',
                                           package_name,
                                           submodule_name,
                                           source_imp)
                    elif source_imp in self._modules_to_ignore:
                        self._logger.debug('%r -> %r -> %r to be ignored',
                                           package_name,
                                           submodule_name,
                                           source_imp)
                    elif self._is_relative_import(source_imp, path):
                        self._logger.debug('%r -> %r -> %r is relative.',
                                           package_name,
                                           submodule_name,
                                           source_imp)
                    else:
                        self._modules_to_inspect.add(source_imp)
                        self._logger.debug('%r -> %r -> %r added to queue',
                                           package_name,
                                           submodule_name,
                                           source_imp)
            elif mod_type == imp.PKG_DIRECTORY:
                self._logger.debug('%r -> %r is package. Recursing...',
                                   package_name, submodule_name)
                ret = ret and self._deep_inspect_path(pathname, package_name)
            elif mod_type in (imp.C_EXTENSION, imp.C_BUILTIN, imp.PY_FROZEN,
                              imp.PY_COMPILED):

                self._logger.debug('%r -> %r is %s.',
                                   package_name,
                                   submodule_name,
                                   self._IMP_TYPE_NAMES[mod_type])

                # Close the file handle that's been opened for us by find_module
                fp.close()

                # TODO: Can we go from compiled Python to an AST to identify
                # imports?
                # Since this is a common case, we assume that the PY will be
                # alongside the PYC for now, and ignore any issues that may
                # arise.
                if mod_type != imp.PY_COMPILED:
                    ret = False
            else:
                raise Exception('Unrecognized module type %s' % submodule_name)

        return ret

    @staticmethod
    def _is_relative_import(module_name, path):
        """Checks if import is relative. Returns True if relative, False if
        absolute, and None if import could not be found."""
        try:
            # Check within the restricted path of a (sub-)package
            imp.find_module(module_name, [path])
        except ImportError:
            pass
        else:
            return True

        try:
            # Check across all of sys.path
            imp.find_module(module_name)
        except ImportError:
            pass
        else:
            return False

        # Module could not be found on system due to:
        # 1. Import that doesn't exist. "Bad import".
        # 2. Since we're only scanning the AST, there's a good chance the
        #    import's inclusion is conditional, and would never be triggered.
        #    For example, an import specific to an OS.
        return None

    @staticmethod
    def _extract_root_module(module_name):
        """Given a module name, returns only the root module by ignoring
        everything including and after the leftmost "." if one exists."""
        return module_name.split('.')[0]

    def _find_imports(self, node):
        """Recurses through AST collecting the targets of all import
        statements."""
        if isinstance(node, ast.Import):
            return {self._extract_root_module(alias.name) for alias in node.names}
        elif isinstance(node, ast.ImportFrom):
            # We ignore all imports with levels other than 0. That's because if
            # if level > 0, we know that it's a relative import, and we only
            # care about root modules.
            if node.level == 0:
                return {self._extract_root_module(node.module)}
            else:
                return set()
        elif hasattr(node, 'body') and hasattr(node.body, '__iter__'):
            # Not all bodies are lists (for ex. exec)
            imps = set()
            for child_node in node.body:
                imps.update(self._find_imports(child_node))
            return imps
        else:
            return set()


text:
package com.amazonaws.blox.dataservicemodel.v1.model;

public enum EnvironmentType {
  // TODO Temporary deployment type for steel thread, remove once Daemon is implemented:
  SingleTask,
  Daemon
}


text:
package com.intellij.util.xml;

import com.intellij.openapi.util.Pair;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ConcurrentFactoryMap;
import com.intellij.util.containers.FactoryMap;
import com.intellij.util.xml.impl.DomInvocationHandler;
import com.intellij.util.xml.impl.DomManagerImpl;
import com.intellij.util.xml.reflect.AbstractDomChildrenDescription;
import gnu.trove.THashSet;
import net.sf.cglib.proxy.AdvancedProxy;
import net.sf.cglib.proxy.InvocationHandler;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.ConcurrentMap;

/**
 * @author peter
 */
public class ModelMergerImpl implements ModelMerger {
  private final List<Pair<InvocationStrategy,Class>> myInvocationStrategies = new ArrayList<>();
  private final List<MergingStrategy> myMergingStrategies = new ArrayList<>();
  private final List<Class> myMergingStrategyClasses = new ArrayList<>();
  private static final Class<MergedObject> MERGED_OBJECT_CLASS = MergedObject.class;

  private final ConcurrentMap<Method,List<Pair<InvocationStrategy,Class>>> myAcceptsCache = ConcurrentFactoryMap.createMap(method-> {
      List<Pair<InvocationStrategy,Class>> result = new ArrayList<>();
      for (int i = myInvocationStrategies.size() - 1; i >= 0; i--) {
        final Pair<InvocationStrategy, Class> pair = myInvocationStrategies.get(i);
        if (pair.first.accepts(method)) {
          result.add(pair);
        }
      }
      return result;
    }
  );

  public ModelMergerImpl() {
    addInvocationStrategy(Object.class, new InvocationStrategy<Object>() {
      @Override
      public boolean accepts(final Method method) {
        return true;
      }

      @Override
      public Object invokeMethod(final JavaMethod javaMethod, final Object proxy, final Object[] args, final List<?> implementations)
        throws IllegalAccessException, InvocationTargetException {
        final Method method = javaMethod.getMethod();
        List<Object> results = getMergedImplementations(method, args, method.getReturnType(), implementations, isIntersectionMethod(javaMethod));
        return results.isEmpty() ? null : results.get(0);
      }
    });

    addInvocationStrategy(Object.class, new InvocationStrategy<Object>() {
      @Override
      public boolean accepts(final Method method) {
        return Collection.class.isAssignableFrom(method.getReturnType());
      }

      @Override
      public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations)
        throws IllegalAccessException, InvocationTargetException {

        final Type type = DomReflectionUtil.extractCollectionElementType(method.getGenericReturnType());
        assert type != null : "No generic return type in method " + method;
        return getMergedImplementations(method.getMethod(), args, ReflectionUtil.getRawType(type), implementations, isIntersectionMethod(method));
      }
    });

    addInvocationStrategy(Object.class, new InvocationStrategy<Object>() {
      @Override
      public boolean accepts(final Method method) {
        return Object.class.equals(method.getDeclaringClass());
      }

      @Override
      public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations) {
        @NonNls String methodName = method.getName();
        if ("toString".equals(methodName)) {
          return "Merger: " + implementations;
        }
        if ("hashCode".equals(methodName)) {
          int result = 1;

          for (Object element : implementations)
            result = 31 * result + element.hashCode();

          return result;
        }
        if ("equals".equals(methodName)) {
          final Object arg = args[0];
          return arg instanceof MergedObject && implementations.equals(((MergedObject)arg).getImplementations());

        }
        return null;
      }
    });

    addInvocationStrategy(Object.class, new InvocationStrategy<Object>() {
      @Override
      public boolean accepts(final Method method) {
        return "isValid".equals(method.getName());
      }

      @Override
      public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations)
        throws IllegalAccessException, InvocationTargetException {
        for (final Object implementation : implementations) {
          if (!((Boolean)method.invoke(implementation, args))) {
            return Boolean.FALSE;
          }
        }
        return Boolean.TRUE;
      }
    });

    addInvocationStrategy(Object.class, new InvocationStrategy<Object>() {
      @Override
      public boolean accepts(final Method method) {
        return void.class.equals(method.getReturnType());
      }

      @Override
      public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations)
        throws IllegalAccessException, InvocationTargetException {
        for (final Object t : implementations) {
          method.invoke(t, args);
        }
        return null;
      }
    });

    addInvocationStrategy(Object.class, new InvocationStrategy<Object>() {
      @Override
      public boolean accepts(final Method method) {
        return MERGED_OBJECT_CLASS.equals(method.getDeclaringClass());
      }

      @Override
      public Object invokeMethod(final JavaMethod method, final Object proxy, final Object[] args, final List<?> implementations)
        throws IllegalAccessException, InvocationTargetException {
        assert "getImplementations".equals(method.getName());
        return implementations;
      }
    });

    addInvocationStrategy(DomElement.class, new InvocationStrategy<DomElement>() {
      @Override
      public boolean accepts(final Method method) {
        return DomInvocationHandler.ACCEPT_METHOD.equals(method);
      }

      @Override
      public Object invokeMethod(final JavaMethod method, final DomElement proxy, final Object[] args, final List<? extends DomElement> implementations)
        throws IllegalAccessException, InvocationTargetException {
        final DomElementVisitor visitor = (DomElementVisitor)args[0];
        ((DomManagerImpl)implementations.get(0).getManager()).getApplicationComponent().getVisitorDescription(visitor.getClass()).acceptElement(visitor, proxy);
        return null;
      }
    });

    addInvocationStrategy(DomElement.class, new InvocationStrategy<DomElement>() {
      @Override
      public boolean accepts(final Method method) {
        return DomInvocationHandler.ACCEPT_CHILDREN_METHOD.equals(method);
      }

      @Override
      public Object invokeMethod(final JavaMethod method, final DomElement proxy, final Object[] args, final List<? extends DomElement> implementations)
        throws IllegalAccessException, InvocationTargetException {
        final DomElementVisitor visitor = (DomElementVisitor)args[0];
        for (final AbstractDomChildrenDescription description : implementations.get(0).getGenericInfo().getChildrenDescriptions()) {
          for (final DomElement value : description.getValues(proxy)) {
            value.accept(visitor);
          }
        }
        return null;
      }
    });

  }

  private boolean isIntersectionMethod(final JavaMethod javaMethod) {
    return javaMethod.getMethod().getAnnotation(Intersect.class) != null;
  }

  @Override
  public final <T> void addInvocationStrategy(Class<T> aClass, InvocationStrategy<T> strategy) {
    myInvocationStrategies.add(Pair.create(strategy, aClass));
  }

  @Override
  public final <T> void addMergingStrategy(Class<T> aClass, MergingStrategy<T> strategy) {
    myMergingStrategies.add(strategy);
    myMergingStrategyClasses.add(aClass);
  }

  @Override
  public <T> T mergeModels(final Class<T> aClass, final T... implementations) {
    if (implementations.length == 1) return implementations[0];
    final MergingInvocationHandler<T> handler = new MergingInvocationHandler<>(aClass, Arrays.asList(implementations));
    return _mergeModels(aClass, handler, implementations);
  }

  @Override
  public <T> T mergeModels(final Class<T> aClass, final Collection<? extends T> implementations) {
    return (T)mergeModels((Class)aClass, implementations.toArray());
  }

  private <T> T _mergeModels(final Class<? super T> aClass, final MergingInvocationHandler<T> handler, final T... implementations) {
    final Set<Class> commonClasses = getCommonClasses(new THashSet<>(), (Object[])implementations);
    commonClasses.add(MERGED_OBJECT_CLASS);
    commonClasses.add(aClass);
    return AdvancedProxy.createProxy(handler, null, commonClasses.toArray(ArrayUtil.EMPTY_CLASS_ARRAY));
  }

  private static <T extends Collection<Class>> T getCommonClasses(final T result, final Object... implementations) {
    if (implementations.length > 0) {
      DomUtil.getAllInterfaces(implementations[0].getClass(), result);
      for (int i = 1; i < implementations.length; i++) {
        final ArrayList<Class> list1 = new ArrayList<>();
        DomUtil.getAllInterfaces(implementations[i].getClass(), list1);
        result.retainAll(list1);
      }
    }
    return result;
  }

  private static final Map<Class<?>, Method> ourPrimaryKeyMethods = new HashMap<>();

  public class MergingInvocationHandler<T> implements InvocationHandler {
    private final Class<? super T> myClass;
    private List<? extends T> myImplementations;

    public MergingInvocationHandler(final Class<T> aClass, final List<? extends T> implementations) {
      this(aClass);
      for (final T implementation : implementations) {
        if (implementation instanceof StableElement) {
          throw new AssertionError("Stable values merging is prohibited: " + implementation);
        }
      }
      myImplementations = implementations;
    }

    public MergingInvocationHandler(final Class<T> aClass) {
      myClass = aClass;
    }

    @NotNull
    private InvocationStrategy findStrategy(final Object proxy, final Method method) {
      for (final Pair<InvocationStrategy, Class> pair : myAcceptsCache.get(method)) {
        if (Object.class.equals(pair.second) || pair.second.isInstance(proxy)) {
          return pair.first;
        }
      }
      throw new AssertionError("impossible");
    }

    @Override
    public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
      try {
        return findStrategy(proxy, method).invokeMethod(getJavaMethod(method), proxy, args, myImplementations);
      }
      catch (InvocationTargetException e) {
        throw e.getCause();
      }
    }

    private JavaMethod getJavaMethod(final Method method) {
      if (ReflectionUtil.isAssignable(MERGED_OBJECT_CLASS, method.getDeclaringClass())) {
        return JavaMethod.getMethod(MERGED_OBJECT_CLASS, method);
      }
      if (ReflectionUtil.isAssignable(method.getDeclaringClass(), myClass)) {
        return JavaMethod.getMethod(myClass, method);
      }
      return JavaMethod.getMethod(method.getDeclaringClass(), method);
    }
  }

  @Nullable
  private static Object getPrimaryKey(Object implementation, final boolean singleValuedInvocation) {
    final Method method = getPrimaryKeyMethod(implementation.getClass());
    if (method != null) {
      final Object o = DomReflectionUtil.invokeMethod(method, implementation);
      return ReflectionUtil.isAssignable(GenericValue.class, method.getReturnType()) ? ((GenericValue)o).getValue() : o;
    }
    else {
      if (implementation instanceof GenericValue) {
        return singleValuedInvocation? Boolean.TRUE : ((GenericValue)implementation).getValue();
      }
      else {
        return null;
      }
    }
  }

  @Nullable
  private static Method getPrimaryKeyMethod(final Class<?> aClass) {
    Method method = ourPrimaryKeyMethods.get(aClass);
    if (method == null) {
      if (ourPrimaryKeyMethods.containsKey(aClass)) return null;

      for (final Method method1 : ReflectionUtil.getClassPublicMethods(aClass)) {
        if ((method = findPrimaryKeyAnnotatedMethod(method1, aClass)) != null) {
          break;
        }
      }
      ourPrimaryKeyMethods.put(aClass, method);
    }
    return method;
  }

  @Nullable
  private static Method findPrimaryKeyAnnotatedMethod(final Method method, final Class aClass) {
    return method.getReturnType() != void.class && method.getParameterTypes().length == 0 ? new JavaMethodSignature(method)
      .findAnnotatedMethod(PrimaryKey.class, aClass) : null;
  }

  private List<Object> getMergedImplementations(final Method method,
                                                final Object[] args,
                                                final Class returnType,
                                                final List<?> implementations,
                                                final boolean intersect) throws IllegalAccessException, InvocationTargetException {

    final List<Object> results = new ArrayList<>();

    if (returnType.isInterface()) {
      final List<Object> orderedPrimaryKeys = new SmartList<>();
      final Map<Object, List<Set<Object>>> map = FactoryMap.create(key -> {
        orderedPrimaryKeys.add(key);
        return new SmartList<>();
      });
      final Map<Object, int[]> counts = FactoryMap.create(key -> new int[implementations.size()]);
      for (int i = 0; i < implementations.size(); i++) {
        Object t = implementations.get(i);
        final Object o = method.invoke(t, args);
        if (o instanceof Collection) {
          for (final Object o1 : (Collection)o) {
            addToMaps(o1, counts, map, i, results, false, intersect);
          }
        }
        else if (o != null) {
          addToMaps(o, counts, map, i, results, true, intersect);
        }

      }

      for (final Object primaryKey : orderedPrimaryKeys) {
        for (final Set<Object> objects : map.get(primaryKey)) {
          results.add(mergeImplementations(returnType, new ArrayList<>(objects)));
        }
      }
    }
    else {
      HashSet<Object> map = new HashSet<>();
      for (final Object t : implementations) {
        final Object o = method.invoke(t, args);
        if (o instanceof Collection) {
          map.addAll((Collection<Object>)o);
        }
        else if (o != null) {
          map.add(o);
          break;
        }
      }
      results.addAll(map);
    }
    return results;
  }

  protected final Object mergeImplementations(final Class returnType, final List<Object> implementations) {
    for (int i = myMergingStrategies.size() - 1; i >= 0; i--) {
      if (ReflectionUtil.isAssignable(myMergingStrategyClasses.get(i), returnType)) {
        final Object o = myMergingStrategies.get(i).mergeChildren(returnType, implementations);
        if (o != null) {
          return o;
        }
      }
    }
    if (implementations.size() == 1) {
      return implementations.get(0);
    }
    return mergeModels(returnType, implementations);
  }

  private boolean addToMaps(final Object o,
                            final Map<Object, int[]> counts,
                            final Map<Object, List<Set<Object>>> map,
                            final int index,
                            final List<Object> results,
                            final boolean singleValuedInvocation,
                            final boolean intersect) {
    final Object primaryKey = getPrimaryKey(o, singleValuedInvocation);
    if (primaryKey != null || singleValuedInvocation) {
      final List<Set<Object>> list = map.get(primaryKey);
      final int[] indices = counts.get(primaryKey);
      int objIndex = intersect? indices[index] : indices[index]++;
      if (list.size() <= objIndex) {
        list.add(new LinkedHashSet<>());
      }
      list.get(objIndex).add(o);
      return false;
    }

    results.add(o);
    return true;
  }

}


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

import io.prestosql.orc.OrcCorruptionException;
import io.prestosql.orc.StreamDescriptor;
import io.prestosql.spi.type.Type;

import java.util.function.Predicate;

import static java.lang.Math.max;

final class ReaderUtils
{
    private ReaderUtils() {}

    public static void verifyStreamType(StreamDescriptor streamDescriptor, Type actual, Predicate<Type> validTypes)
            throws OrcCorruptionException
    {
        if (validTypes.test(actual)) {
            return;
        }

        throw new OrcCorruptionException(
                streamDescriptor.getOrcDataSourceId(),
                "Can not read SQL type %s from ORC stream %s of type %s",
                actual,
                streamDescriptor.getStreamName(),
                streamDescriptor.getStreamType());
    }

    public static int minNonNullValueSize(int nonNullCount)
    {
        return max(nonNullCount + 1, 1025);
    }

    public static byte[] unpackByteNulls(byte[] values, boolean[] isNull)
    {
        byte[] result = new byte[isNull.length];

        int position = 0;
        for (int i = 0; i < isNull.length; i++) {
            result[i] = values[position];
            if (!isNull[i]) {
                position++;
            }
        }
        return result;
    }

    public static short[] unpackShortNulls(short[] values, boolean[] isNull)
    {
        short[] result = new short[isNull.length];

        int position = 0;
        for (int i = 0; i < isNull.length; i++) {
            result[i] = values[position];
            if (!isNull[i]) {
                position++;
            }
        }
        return result;
    }

    public static int[] unpackIntNulls(int[] values, boolean[] isNull)
    {
        int[] result = new int[isNull.length];

        int position = 0;
        for (int i = 0; i < isNull.length; i++) {
            result[i] = values[position];
            if (!isNull[i]) {
                position++;
            }
        }
        return result;
    }

    public static long[] unpackLongNulls(long[] values, boolean[] isNull)
    {
        long[] result = new long[isNull.length];

        int position = 0;
        for (int i = 0; i < isNull.length; i++) {
            result[i] = values[position];
            if (!isNull[i]) {
                position++;
            }
        }
        return result;
    }

    public static long[] unpackInt128Nulls(long[] values, boolean[] isNull)
    {
        long[] result = new long[isNull.length * 2];

        int position = 0;
        int outputPosition = 0;
        for (int i = 0; i < isNull.length; i++) {
            result[outputPosition] = values[position];
            result[outputPosition + 1] = values[position + 1];
            if (!isNull[i]) {
                position += 2;
            }
            outputPosition += 2;
        }
        return result;
    }

    public static void unpackLengthNulls(int[] values, boolean[] isNull, int nonNullCount)
    {
        int nullSuppressedPosition = nonNullCount - 1;
        for (int outputPosition = isNull.length - 1; outputPosition >= 0; outputPosition--) {
            if (isNull[outputPosition]) {
                values[outputPosition] = 0;
            }
            else {
                values[outputPosition] = values[nullSuppressedPosition];
                nullSuppressedPosition--;
            }
        }
    }

    public static void convertLengthVectorToOffsetVector(int[] vector)
    {
        int currentLength = vector[0];
        vector[0] = 0;
        for (int i = 1; i < vector.length; i++) {
            int nextLength = vector[i];
            vector[i] = vector[i - 1] + currentLength;
            currentLength = nextLength;
        }
    }
}