text:
#include "CSamusDoll.hpp"
#include "GameGlobalObjects.hpp"
#include "CSimplePool.hpp"
#include "CDependencyGroup.hpp"
#include "zeus/CEulerAngles.hpp"
#include "Collision/CollisionUtil.hpp"
#include "Graphics/CBooRenderer.hpp"
#include "World/CMorphBall.hpp"

namespace urde::MP1 {

const zeus::CVector3f CSamusDoll::skInitialOffset = {0.f, 0.f, 0.8f};

static const std::pair<const char*, u32> SpiderBallGlassModels[] = {
    {"SamusSpiderBallGlassCMDL", 0}, {"SamusSpiderBallGlassCMDL", 0}, {"SamusSpiderBallGlassCMDL", 1},
    {"SamusPhazonBallGlassCMDL", 0}, {"SamusSpiderBallGlassCMDL", 0}, {"SamusSpiderBallGlassCMDL", 0},
    {"SamusSpiderBallGlassCMDL", 1}, {"SamusPhazonBallGlassCMDL", 0},
};

static const std::pair<const char*, u32> SpiderBallCharacters[] = {
    {"SamusSpiderBallANCS", 0}, {"SamusSpiderBallANCS", 0}, {"SamusSpiderBallANCS", 1}, {"SamusPhazonBallANCS", 0},
    {"SamusFusionBallANCS", 0}, {"SamusFusionBallANCS", 2}, {"SamusFusionBallANCS", 1}, {"SamusFusionBallANCS", 3},
};

static const std::pair<const char*, u32> BallCharacters[] = {
    {"SamusBallANCS", 0},       {"SamusBallANCS", 0},       {"SamusBallANCS", 1},       {"SamusBallANCS", 0},
    {"SamusFusionBallANCS", 0}, {"SamusFusionBallANCS", 2}, {"SamusFusionBallANCS", 1}, {"SamusFusionBallANCS", 3},
};

static const u32 SpiderBallGlowColorIdxs[] = {3, 3, 2, 4, 5, 7, 6, 8};

static const u32 BallGlowColorIdxs[] = {0, 0, 1, 0, 5, 7, 6, 8};

static const char* BeamModels[] = {"CMDL_InvPowerBeam", "CMDL_InvIceBeam", "CMDL_InvWaveBeam", "CMDL_InvPlasmaBeam",
                                   "CMDL_InvPowerBeam"};

static const char* VisorModels[] = {"CMDL_InvVisor",       "CMDL_InvGravityVisor", "CMDL_InvVisor",
                                    "CMDL_InvPhazonVisor", "CMDL_InvFusionVisor",  "CMDL_InvFusionVisor",
                                    "CMDL_InvFusionVisor", "CMDL_InvFusionVisor"};

static const char* FinModels[] = {"CMDL_InvPowerFins",   "CMDL_InvPowerFins", "CMDL_InvPowerFins",
                                  "CMDL_InvPowerFins",   "CMDL_InvPowerFins", "CMDL_InvVariaFins",
                                  "CMDL_InvGravityFins", "CMDL_InvPhazonFins"};

static const u32 Character1Idxs[8] = {0, 6, 2, 10, 16, 24, 20, 28};

static const u32 CharacterBootsIdxs[8] = {1, 7, 3, 11, 17, 25, 21, 29};

static const u32 Character2and3Idxs[8][2] = {{14, 15}, {8, 9},   {4, 5},   {12, 13},
                                             {18, 19}, {26, 27}, {22, 23}, {30, 31}};

CSamusDoll::CSamusDoll(const CDependencyGroup& suitDgrp, const CDependencyGroup& ballDgrp,
                       CPlayerState::EPlayerSuit suit, CPlayerState::EBeamId beam, bool hasSpiderBall,
                       bool hasGrappleBeam)
: x10_ballXf(zeus::CTransform::Translate(0.f, 0.f, 0.625f * g_tweakPlayer->GetPlayerBallHalfExtent()))
, x44_suit(suit)
, x48_beam(beam) {
  x70_fixedRot.rotateZ(M_PIF);
  x90_userInterpRot = xb0_userRot = x70_fixedRot;
  x1d4_spiderBallGlass = g_SimplePool->GetObj(SpiderBallGlassModels[int(suit)].first);
  x1e0_ballMatIdx = hasSpiderBall ? SpiderBallCharacters[int(suit)].second : BallCharacters[int(suit)].second;
  x1e4_glassMatIdx = SpiderBallGlassModels[int(suit)].second;
  x1e8_ballGlowColorIdx = hasSpiderBall ? SpiderBallGlowColorIdxs[int(suit)] : BallGlowColorIdxs[int(suit)];
  x1ec_itemScreenSamus = g_SimplePool->GetObj("ANCS_ItemScreenSamus");
  x1f4_invBeam = g_SimplePool->GetObj(BeamModels[int(beam)]);
  x200_invVisor = g_SimplePool->GetObj(VisorModels[int(suit)]);
  x20c_invGrappleBeam = g_SimplePool->GetObj("CMDL_InvGrappleBeam");
  x218_invFins = g_SimplePool->GetObj(FinModels[int(suit)]);
  x224_ballInnerGlow = g_SimplePool->GetObj("BallInnerGlow");
  x22c_ballInnerGlowGen = std::make_unique<CElementGen>(x224_ballInnerGlow);
  x230_ballTransitionFlash = g_SimplePool->GetObj("MorphBallTransitionFlash");
  x23c_lights.push_back(CLight::BuildDirectional(zeus::skForward, zeus::skWhite));
  x24c_actorLights = std::make_unique<CActorLights>(8, zeus::skZero3f, 4, 4, false, false, false, 0.1f);
  x270_24_hasSpiderBall = hasSpiderBall;
  x270_25_hasGrappleBeam = hasGrappleBeam;
  x22c_ballInnerGlowGen->SetGlobalScale(zeus::CVector3f(0.625f));
  x0_depToks.reserve(suitDgrp.GetObjectTagVector().size() + ballDgrp.GetObjectTagVector().size());
  for (const SObjectTag& tag : suitDgrp.GetObjectTagVector()) {
    x0_depToks.push_back(g_SimplePool->GetObj(tag));
    x0_depToks.back().Lock();
  }
  for (const SObjectTag& tag : ballDgrp.GetObjectTagVector()) {
    x0_depToks.push_back(g_SimplePool->GetObj(tag));
    x0_depToks.back().Lock();
  }
}

bool CSamusDoll::IsLoaded() const {
  if (x270_31_loaded)
    return true;
  if (!x1ec_itemScreenSamus.IsLoaded())
    return false;
  if (!x1f4_invBeam.IsLoaded())
    return false;
  if (!x200_invVisor.IsLoaded())
    return false;
  if (!x20c_invGrappleBeam.IsLoaded())
    return false;
  if (!x1d4_spiderBallGlass.IsLoaded())
    return false;
  if (x218_invFins && !x218_invFins.IsLoaded())
    return false;
  return xc8_suitModel0.operator bool();
}

CModelData CSamusDoll::BuildSuitModelData1(CPlayerState::EPlayerSuit suit) {
  CModelData ret(CAnimRes(g_ResFactory->GetResourceIdByName("ANCS_ItemScreenSamus")->id, Character1Idxs[int(suit)],
                          zeus::skOne3f, 2, true));
  CAnimPlaybackParms parms(2, -1, 1.f, true);
  ret.GetAnimationData()->SetAnimation(parms, false);
  return ret;
}

CModelData CSamusDoll::BuildSuitModelDataBoots(CPlayerState::EPlayerSuit suit) {
  CModelData ret(CAnimRes(g_ResFactory->GetResourceIdByName("ANCS_ItemScreenSamus")->id, CharacterBootsIdxs[int(suit)],
                          zeus::skOne3f, 2, true));
  CAnimPlaybackParms parms(2, -1, 1.f, true);
  ret.GetAnimationData()->SetAnimation(parms, false);
  return ret;
}

bool CSamusDoll::CheckLoadComplete() {
  if (IsLoaded())
    return true;

  for (const CToken& tok : x0_depToks)
    if (!tok.IsLoaded())
      return false;

  xc8_suitModel0.emplace(BuildSuitModelData1(x44_suit));
  for (int i = 0; i < 2; ++i) {
    CAnimRes res(g_ResFactory->GetResourceIdByName("ANCS_ItemScreenSamus")->id, Character2and3Idxs[int(x44_suit)][i],
                 zeus::skOne3f, 2, true);
    CModelData mData(res);
    x118_suitModel1and2.push_back(mData.GetAnimationData()->GetModelData());
    x118_suitModel1and2.back().Lock();
  }
  x134_suitModelBoots.emplace(BuildSuitModelDataBoots(x44_suit));

  CAnimRes res(g_ResFactory
                   ->GetResourceIdByName(x270_24_hasSpiderBall ? SpiderBallCharacters[int(x44_suit)].first
                                                               : BallCharacters[int(x44_suit)].first)
                   ->id,
               0, zeus::skOne3f, 0, true);
  x184_ballModelData.emplace(res);
  x1e0_ballMatIdx =
      x270_24_hasSpiderBall ? SpiderBallCharacters[int(x44_suit)].second : BallCharacters[int(x44_suit)].second;
  x270_31_loaded = true;
  return true;
}

void CSamusDoll::Update(float dt, CRandom16& rand) {
  if (x1f4_invBeam.IsLoaded())
    x1f4_invBeam->Touch(0);
  if (x200_invVisor.IsLoaded())
    x200_invVisor->Touch(0);
  if (x20c_invGrappleBeam.IsLoaded())
    x20c_invGrappleBeam->Touch(0);
  if (x1d4_spiderBallGlass.IsLoaded())
    x1d4_spiderBallGlass->Touch(0);
  if (x218_invFins.IsLoaded())
    x218_invFins->Touch(0);

  if (!CheckLoadComplete())
    return;

  x40_alphaIn = std::min(x40_alphaIn + 2.f * dt, 1.f);
  if (x54_remTransitionTime > 0.f) {
    float oldRemTransTime = x54_remTransitionTime;
    x54_remTransitionTime = std::max(0.f, x54_remTransitionTime - dt);
    if (!x4c_completedMorphball && x4d_selectedMorphball && oldRemTransTime >= x50_totalTransitionTime - 0.5f &&
        x54_remTransitionTime < x50_totalTransitionTime - 0.5f) {
      x238_ballTransitionFlashGen = std::make_unique<CElementGen>(x230_ballTransitionFlash);
      x238_ballTransitionFlashGen->SetGlobalScale(zeus::CVector3f(0.625f));
    }

    if (x54_remTransitionTime == 0.f) {
      x4c_completedMorphball = x4d_selectedMorphball;
      if (!x4d_selectedMorphball) {
        xc8_suitModel0->GetAnimationData()->SetAnimation(CAnimPlaybackParms(2, -1, 1.f, true), false);
        x134_suitModelBoots->GetAnimationData()->SetAnimation(CAnimPlaybackParms(2, -1, 1.f, true), false);
      }
    }
  }

  if (x270_26_pulseSuit)
    x58_suitPulseFactor = std::min(x58_suitPulseFactor + 2.f * dt, 1.f);
  else
    x58_suitPulseFactor = std::max(x58_suitPulseFactor - 2.f * dt, 0.f);

  if (x270_27_pulseBeam)
    x5c_beamPulseFactor = std::min(x5c_beamPulseFactor + 2.f * dt, 1.f);
  else
    x5c_beamPulseFactor = std::max(x5c_beamPulseFactor - 2.f * dt, 0.f);

  if (x270_28_pulseGrapple)
    x60_grapplePulseFactor = std::min(x60_grapplePulseFactor + 2.f * dt, 1.f);
  else
    x60_grapplePulseFactor = std::max(x60_grapplePulseFactor - 2.f * dt, 0.f);

  if (x270_29_pulseBoots)
    x64_bootsPulseFactor = std::min(x64_bootsPulseFactor + 2.f * dt, 1.f);
  else
    x64_bootsPulseFactor = std::max(x64_bootsPulseFactor - 2.f * dt, 0.f);

  if (x270_30_pulseVisor)
    x68_visorPulseFactor = std::min(x68_visorPulseFactor + 2.f * dt, 1.f);
  else
    x68_visorPulseFactor = std::max(x68_visorPulseFactor - 2.f * dt, 0.f);

  if (x4c_completedMorphball)
    x6c_ballPulseFactor = std::min(x6c_ballPulseFactor + 2.f * dt, 1.f);
  else
    x6c_ballPulseFactor = std::max(x6c_ballPulseFactor - 2.f * dt, 0.f);

  if (x44_suit == CPlayerState::EPlayerSuit::Phazon) {
    if (!x250_phazonIndirectTexture)
      x250_phazonIndirectTexture = g_SimplePool->GetObj("PhazonIndirectTexture");
  } else {
    if (x250_phazonIndirectTexture)
      x250_phazonIndirectTexture = TLockedToken<CTexture>();
  }

  if (x250_phazonIndirectTexture) {
    x260_phazonOffsetAngle += 0.03f;
    x260_phazonOffsetAngle.makeRel();
    g_Renderer->AllocatePhazonSuitMaskTexture();
  }

  xc8_suitModel0->AdvanceAnimationIgnoreParticles(dt, rand, true);
  x134_suitModelBoots->AdvanceAnimationIgnoreParticles(dt, rand, true);
  x184_ballModelData->AdvanceAnimationIgnoreParticles(dt, rand, true);

  SetupLights();

  x22c_ballInnerGlowGen->SetGlobalTranslation(x10_ballXf.origin);
  x22c_ballInnerGlowGen->Update(dt);

  if (x238_ballTransitionFlashGen) {
    if (x238_ballTransitionFlashGen->IsSystemDeletable())
      x238_ballTransitionFlashGen.reset();
    if (x238_ballTransitionFlashGen) {
      x22c_ballInnerGlowGen->SetGlobalTranslation(x10_ballXf.origin);
      x22c_ballInnerGlowGen->Update(dt);
    }
  }

  if (xc4_viewInterp != 0.f && xc4_viewInterp != 1.f) {
    if (xc4_viewInterp < 0.f)
      xc4_viewInterp = std::min(xc4_viewInterp + 3.f * dt, 0.f);
    else
      xc4_viewInterp = std::min(xc4_viewInterp + 3.f * dt, 1.f);

    float interp = std::fabs(xc4_viewInterp);
    float oneMinusInterp = 1.f - interp;
    xa4_offset = x84_interpStartOffset * interp + skInitialOffset * oneMinusInterp;

    xb0_userRot = zeus::CQuaternion::slerpShort(x70_fixedRot, x90_userInterpRot, interp);

    if (xc4_viewInterp <= 0.f) // Zoom out
      xc0_userZoom = x80_fixedZoom * oneMinusInterp + xa0_userInterpZoom * interp;
    else // Zoom in
      xc0_userZoom = x80_fixedZoom * interp + xa0_userInterpZoom * oneMinusInterp;
  }
}

void CSamusDoll::Draw(const CStateManager& mgr, float alpha) {
  if (!IsLoaded())
    return;
  SCOPED_GRAPHICS_DEBUG_GROUP("CSamusDoll::Draw", zeus::skPurple);

  alpha *= x40_alphaIn;

  float itemPulse = zeus::clamp(0.f, (std::sin(5.f * CGraphics::GetSecondsMod900()) + 1.f) * 0.5f, 1.f) *
                    (1.f - std::fabs(xc4_viewInterp));

  g_Renderer->SetPerspective(55.f, g_Viewport.x8_width, g_Viewport.xc_height, 0.2f, 4096.f);

  CGraphics::SetViewPointMatrix(zeus::CTransform(xb0_userRot, xa4_offset) *
                                zeus::CTransform::Translate(0.f, xc0_userZoom, 0.f));

  zeus::CTransform gunXf = xc8_suitModel0->GetScaledLocatorTransform("GUN_LCTR");
  zeus::CTransform visorXf = xc8_suitModel0->GetScaledLocatorTransform("VISOR_LCTR");
  zeus::CTransform grappleXf = xc8_suitModel0->GetScaledLocatorTransform("GRAPPLE_LCTR");

  if (!x4c_completedMorphball || !x4d_selectedMorphball) {
    float suitPulse = itemPulse * x58_suitPulseFactor;
    float bootsPulse = std::max(suitPulse, itemPulse * x64_bootsPulseFactor);

    bool phazonSuit = x44_suit == CPlayerState::EPlayerSuit::Phazon;
    // Enable dst alpha 1.0

    for (size_t i = 0; i <= x118_suitModel1and2.size(); ++i) {
      TCachedToken<CSkinnedModel> backupModelData = xc8_suitModel0->GetAnimationData()->GetModelData();
      if (i < x118_suitModel1and2.size())
        xc8_suitModel0->GetAnimationData()->SubstituteModelData(x118_suitModel1and2[i]);
      xc8_suitModel0->InvSuitDraw(CModelData::EWhichModel::Normal, zeus::CTransform(), x24c_actorLights.get(),
                                  zeus::CColor(1.f, alpha), zeus::CColor(1.f, alpha * suitPulse));
      xc8_suitModel0->GetAnimationData()->SubstituteModelData(backupModelData);
    }

    x134_suitModelBoots->InvSuitDraw(CModelData::EWhichModel::Normal, zeus::CTransform(),
                                     x24c_actorLights.get(), zeus::CColor(1.f, alpha),
                                     zeus::CColor(1.f, alpha * bootsPulse));

    {
      CGraphics::SetModelMatrix(gunXf);
      x1f4_invBeam->GetInstance().ActivateLights(x23c_lights);
      CModelFlags flags = {};

      flags.m_extendedShader = EExtendedShader::SolidColorBackfaceCullLEqualAlphaOnly;
      flags.x4_color = zeus::skWhite;
      x1f4_invBeam->Draw(flags);

      flags.m_extendedShader = EExtendedShader::ForcedAlpha;
      flags.x4_color = zeus::CColor(1.f, alpha);
      x1f4_invBeam->Draw(flags);

      flags.m_extendedShader = EExtendedShader::ForcedAdditive;
      flags.x4_color = zeus::CColor(1.f, alpha * itemPulse * x5c_beamPulseFactor);
      x1f4_invBeam->Draw(flags);
    }

    {
      CGraphics::SetModelMatrix(visorXf);

      float visorT = std::fmod(CGraphics::GetSecondsMod900(), 1.f) * (1.f - std::fabs(xc4_viewInterp));
      float alphaBlend = (visorT < 0.25f) ? 1.f - 2.f * visorT : (visorT < 0.5f) ? 2.f * (visorT - 0.25f) + 0.5f : 1.f;
      float addBlend = (visorT > 0.75f) ? 1.f - 4.f * (visorT - 0.75f) : (visorT > 0.5f) ? 4.f * (visorT - 0.5f) : 0.f;

      x200_invVisor->GetInstance().ActivateLights(x23c_lights);
      CModelFlags flags = {};
      flags.m_extendedShader = EExtendedShader::Lighting;
      flags.x4_color =
          zeus::CColor::lerp(zeus::CColor(1.f, alpha), zeus::CColor(alphaBlend, alpha), x68_visorPulseFactor);
      x200_invVisor->Draw(flags);

      flags.m_extendedShader = EExtendedShader::ForcedAdditive;
      flags.x4_color = zeus::CColor(1.f, alpha * addBlend * x68_visorPulseFactor);
      x200_invVisor->Draw(flags);
    }

    if (x270_25_hasGrappleBeam) {
      CGraphics::SetModelMatrix(grappleXf);

      x20c_invGrappleBeam->GetInstance().ActivateLights(x23c_lights);
      CModelFlags flags = {};
      flags.m_extendedShader = EExtendedShader::ForcedAlpha;
      flags.x4_color = zeus::CColor(1.f, alpha);
      x20c_invGrappleBeam->Draw(flags);

      flags.m_extendedShader = EExtendedShader::ForcedAdditive;
      flags.x4_color = zeus::CColor(1.f, alpha * itemPulse * x60_grapplePulseFactor);
      x20c_invGrappleBeam->Draw(flags);
    } else if (x44_suit >= CPlayerState::EPlayerSuit::FusionPower) {
      CGraphics::SetModelMatrix(grappleXf);

      x218_invFins->GetInstance().ActivateLights(x23c_lights);
      CModelFlags flags = {};
      flags.m_extendedShader = EExtendedShader::ForcedAlpha;
      flags.x4_color = zeus::CColor(1.f, alpha);
      x218_invFins->Draw(flags);

      flags.m_extendedShader = EExtendedShader::ForcedAdditive;
      flags.x4_color = zeus::CColor(1.f, alpha * suitPulse);
      x218_invFins->Draw(flags);
    }

    if (x54_remTransitionTime > 0.f) {
      float ballT = 1.f - x54_remTransitionTime / x50_totalTransitionTime;

      float ballAlpha = 0.f;
      if (x4d_selectedMorphball)
        ballAlpha = 1.f - std::min(x54_remTransitionTime / 0.25f, 1.f);
      else if (x4c_completedMorphball)
        ballAlpha = std::max(0.f, (x54_remTransitionTime - (x50_totalTransitionTime - 0.25f)) / 0.25f);

      if (ballAlpha > 0.f) {
        CModelFlags flags = {};
        flags.x1_matSetIdx = x1e0_ballMatIdx;
        flags.m_extendedShader = EExtendedShader::SolidColorBackfaceCullLEqualAlphaOnly;
        flags.x4_color = zeus::skWhite;
        x184_ballModelData->Render(mgr, x10_ballXf, x24c_actorLights.get(), flags);

        flags.m_extendedShader = EExtendedShader::ForcedAlpha;
        flags.x4_color = zeus::skWhite;
        flags.x4_color.a() = alpha * ballAlpha;
        x184_ballModelData->Render(mgr, x10_ballXf, x24c_actorLights.get(), flags);

        flags.m_extendedShader = EExtendedShader::ForcedAdditive;
        flags.x4_color = zeus::skWhite;
        flags.x4_color.a() = x6c_ballPulseFactor * alpha * ballAlpha * itemPulse;
        x184_ballModelData->Render(mgr, x10_ballXf, x24c_actorLights.get(), flags);
      }

      if (x4d_selectedMorphball && ballT > 0.5f) {
        float ballEndT = (ballT - 0.5f) / 0.5f;
        float oneMinusBallEndT = 1.f - ballEndT;

        float spinScale = 0.75f * oneMinusBallEndT + 1.f;
        float spinAlpha;
        if (ballEndT < 0.1f)
          spinAlpha = 0.f;
        else if (ballEndT < 0.2f)
          spinAlpha = (ballEndT - 0.1f) / 0.1f;
        else if (ballEndT < 0.9f)
          spinAlpha = 1.f;
        else
          spinAlpha = 1.f - (ballT - 0.9f) / 0.1f;

        zeus::CRelAngle spinAngle = zeus::degToRad(360.f * oneMinusBallEndT);
        spinAlpha *= 0.5f;
        if (spinAlpha > 0.f) {
          CModelFlags flags = {};
          flags.m_extendedShader = EExtendedShader::ForcedAdditive;
          flags.x1_matSetIdx = x1e0_ballMatIdx;
          flags.x4_color = zeus::CColor(1.f, spinAlpha * alpha);
          x184_ballModelData->Render(
              mgr, x10_ballXf * zeus::CTransform::RotateZ(spinAngle) * zeus::CTransform::Scale(spinScale),
              x24c_actorLights.get(), flags);
        }
      }

      if (x270_24_hasSpiderBall) {
        CGraphics::SetModelMatrix(x10_ballXf);
        CModelFlags flags = {};
        flags.x1_matSetIdx = x1e4_glassMatIdx;
        x1d4_spiderBallGlass->GetInstance().ActivateLights(x23c_lights);

        flags.m_extendedShader = EExtendedShader::SolidColorBackfaceCullLEqualAlphaOnly;
        flags.x4_color = zeus::skWhite;
        x1d4_spiderBallGlass->Draw(flags);

        flags.m_extendedShader = EExtendedShader::ForcedAlpha;
        flags.x4_color = zeus::skWhite;
        flags.x4_color.a() = alpha;
        x1d4_spiderBallGlass->Draw(flags);

        flags.m_extendedShader = EExtendedShader::ForcedAdditive;
        flags.x4_color = zeus::skWhite;
        flags.x4_color.a() = x6c_ballPulseFactor * alpha * itemPulse;
        x1d4_spiderBallGlass->Draw(flags);
      }
    }

    if (phazonSuit && alpha > 0.1f) {
      float radius = zeus::clamp(0.2f, (10.f - (xc0_userZoom >= 0.f ? xc0_userZoom : -xc0_userZoom)) / 20.f, 1.f);
      float offset = std::sin(x260_phazonOffsetAngle);
      zeus::CColor color = g_tweakGuiColors->GetPauseBlurFilterColor();
      color.a() = alpha;
      g_Renderer->DrawPhazonSuitIndirectEffect(zeus::CColor(0.1f, alpha), x250_phazonIndirectTexture, color, radius,
                                               0.1f, offset, offset);
    }
  } else {
    CModelFlags flags = {};
    flags.x1_matSetIdx = x1e0_ballMatIdx;
    flags.m_extendedShader = EExtendedShader::SolidColorBackfaceCullLEqualAlphaOnly;
    flags.x4_color = zeus::skWhite;
    x184_ballModelData->Render(mgr, x10_ballXf, x24c_actorLights.get(), flags);

    flags.m_extendedShader = EExtendedShader::ForcedAlpha;
    flags.x4_color = zeus::skWhite;
    flags.x4_color.a() = alpha;
    x184_ballModelData->Render(mgr, x10_ballXf, x24c_actorLights.get(), flags);

    flags.m_extendedShader = EExtendedShader::ForcedAdditive;
    flags.x4_color = zeus::skWhite;
    flags.x4_color.a() = x6c_ballPulseFactor * alpha * itemPulse;
    x184_ballModelData->Render(mgr, x10_ballXf, x24c_actorLights.get(), flags);

    const u8* c = CMorphBall::BallGlowColors[x1e8_ballGlowColorIdx];
    zeus::CColor color = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, alpha};
    x22c_ballInnerGlowGen->SetModulationColor(color);

    if (alpha > 0.f) {
      if (x22c_ballInnerGlowGen->GetNumActiveChildParticles() > 0) {
        const u8* c = CMorphBall::BallTransFlashColors[x1e8_ballGlowColorIdx];
        zeus::CColor color = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, alpha};
        x22c_ballInnerGlowGen->GetActiveChildParticle(0).SetModulationColor(color);

        if (x22c_ballInnerGlowGen->GetNumActiveChildParticles() > 1) {
          const u8* c = CMorphBall::BallAuxGlowColors[x1e8_ballGlowColorIdx];
          zeus::CColor color = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, alpha};
          x22c_ballInnerGlowGen->GetActiveChildParticle(1).SetModulationColor(color);
        }
      }
      x22c_ballInnerGlowGen->Render();
    }

    if (x270_24_hasSpiderBall) {
      CGraphics::SetModelMatrix(x10_ballXf);
      CModelFlags flags = {};
      flags.x1_matSetIdx = x1e4_glassMatIdx;
      x1d4_spiderBallGlass->GetInstance().ActivateLights(x23c_lights);

      flags.m_extendedShader = EExtendedShader::SolidColorBackfaceCullLEqualAlphaOnly;
      flags.x4_color = zeus::skWhite;
      x1d4_spiderBallGlass->Draw(flags);

      flags.m_extendedShader = EExtendedShader::ForcedAlpha;
      flags.x4_color = zeus::skWhite;
      flags.x4_color.a() = alpha;
      x1d4_spiderBallGlass->Draw(flags);

      flags.m_extendedShader = EExtendedShader::ForcedAdditive;
      flags.x4_color = zeus::skWhite;
      flags.x4_color.a() = x6c_ballPulseFactor * alpha * itemPulse;
      x1d4_spiderBallGlass->Draw(flags);
    }
  }

  if (x238_ballTransitionFlashGen) {
    const u8* c = CMorphBall::BallTransFlashColors[x1e8_ballGlowColorIdx];
    zeus::CColor color = {c[0] / 255.f, c[1] / 255.f, c[2] / 255.f, 1.f};
    x238_ballTransitionFlashGen->SetModulationColor(color);
    x238_ballTransitionFlashGen->Render();
  }

  CGraphics::DisableAllLights();
}

void CSamusDoll::Touch() {
  if (!CheckLoadComplete())
    return;
  xc8_suitModel0->GetAnimationData()->PreRender();
  x134_suitModelBoots->GetAnimationData()->PreRender();
  x184_ballModelData->GetAnimationData()->PreRender();
  xc8_suitModel0->Touch(CModelData::EWhichModel::Normal, 0);
  x134_suitModelBoots->Touch(CModelData::EWhichModel::Normal, 0);
  x184_ballModelData->Touch(CModelData::EWhichModel::Normal, 0);
}

void CSamusDoll::SetupLights() {
  x23c_lights[0] = CLight::BuildDirectional(xb0_userRot.toTransform().basis[1], zeus::CColor(0.75f, 1.f));
  x24c_actorLights->BuildFakeLightList(x23c_lights, zeus::skBlack);
}

void CSamusDoll::SetInMorphball(bool morphball) {
  if (x54_remTransitionTime > 0.f)
    return;
  if (x4d_selectedMorphball == morphball)
    return;
  x4d_selectedMorphball = morphball;
  SetTransitionAnimation();
}

void CSamusDoll::SetTransitionAnimation() {
  if (!x4c_completedMorphball) {
    /* Into morphball */
    xc8_suitModel0->GetAnimationData()->SetAnimation(CAnimPlaybackParms{0, -1, 1.f, true}, false);
    x134_suitModelBoots->GetAnimationData()->SetAnimation(CAnimPlaybackParms{0, -1, 1.f, true}, false);
    x50_totalTransitionTime = x54_remTransitionTime = xc8_suitModel0->GetAnimationData()->GetAnimationDuration(0);
  } else if (!x4d_selectedMorphball) {
    /* Outta morphball */
    xc8_suitModel0->GetAnimationData()->SetAnimation(CAnimPlaybackParms{1, -1, 1.f, true}, false);
    x134_suitModelBoots->GetAnimationData()->SetAnimation(CAnimPlaybackParms{1, -1, 1.f, true}, false);
    x50_totalTransitionTime = x54_remTransitionTime = xc8_suitModel0->GetAnimationData()->GetAnimationDuration(1);
  }
}

void CSamusDoll::SetRotationSfxPlaying(bool playing) {
  if (playing) {
    if (x268_rotateSfx)
      return;
    x268_rotateSfx = CSfxManager::SfxStart(SFXui_map_rotate, 1.f, 0.f, false, 0x7f, true, kInvalidAreaId);
  } else {
    CSfxManager::SfxStop(x268_rotateSfx);
    x268_rotateSfx.reset();
  }
}

void CSamusDoll::SetOffsetSfxPlaying(bool playing) {
  if (playing) {
    if (x264_offsetSfx)
      return;
    x264_offsetSfx = CSfxManager::SfxStart(SFXui_map_pan, 1.f, 0.f, false, 0x7f, true, kInvalidAreaId);
  } else {
    CSfxManager::SfxStop(x264_offsetSfx);
    x264_offsetSfx.reset();
  }
}

void CSamusDoll::SetZoomSfxPlaying(bool playing) {
  if (playing) {
    if (x26c_zoomSfx)
      return;
    x26c_zoomSfx = CSfxManager::SfxStart(SFXui_map_zoom, 1.f, 0.f, false, 0x7f, true, kInvalidAreaId);
  } else {
    CSfxManager::SfxStop(x26c_zoomSfx);
    x26c_zoomSfx.reset();
  }
}

void CSamusDoll::SetRotation(float xDelta, float zDelta, float dt) {
  if (xc4_viewInterp != 0.f && xc4_viewInterp != 1.f)
    return;
  SetRotationSfxPlaying(xDelta != 0.f || zDelta != 0.f);
  zeus::CEulerAngles angles(xb0_userRot);

  zeus::CRelAngle angX(angles.x());
  angX.makeRel();
  zeus::CRelAngle angZ(angles.z());
  angZ.makeRel();

  angX += xDelta;
  angX.makeRel();
  angZ += zDelta;
  angZ.makeRel();

  float angXCenter = angX;
  if (angXCenter > M_PIF)
    angXCenter -= 2.f * M_PIF;
  angXCenter = zeus::clamp(-1.555f, angXCenter, 1.555f);

  zeus::CQuaternion quat;
  quat.rotateZ(angZ);
  quat.rotateX(zeus::CRelAngle(angXCenter).asRel());
  xb0_userRot = quat;
}

void CSamusDoll::SetOffset(const zeus::CVector3f& offset, float dt) {
  if (xc4_viewInterp != 0.f && xc4_viewInterp != 1.f)
    return;
  zeus::CVector3f oldOffset = xa4_offset;
  zeus::CMatrix3f rotMtx = xb0_userRot.toTransform().basis;
  xa4_offset += rotMtx * zeus::CVector3f(offset.x(), 0.f, offset.z());
  SetOffsetSfxPlaying((oldOffset - xa4_offset).magnitude() > dt);
  float oldZoom = xc0_userZoom;
  xc0_userZoom = zeus::clamp(-4.f, xc0_userZoom + offset.y(), -2.2f);
  bool zoomSfx = std::fabs(xc0_userZoom - oldZoom) > dt;
  float zoomDelta = offset.y() - (xc0_userZoom - oldZoom);
  zeus::CVector3f newOffset = rotMtx[1] * zoomDelta + xa4_offset;
  zeus::CVector3f delta = newOffset - xa4_offset;
  oldOffset = xa4_offset;
  if (!delta.isZero()) {
    zeus::CSphere sphere(skInitialOffset, 1.f);
    float T;
    zeus::CVector3f point;
    if (CollisionUtil::RaySphereIntersection(sphere, xa4_offset, delta.normalized(), 0.f, T, point)) {
      if ((point - xa4_offset).magnitude() < std::fabs(zoomDelta))
        xa4_offset = point;
      else
        xa4_offset = newOffset;
    } else {
      xa4_offset = newOffset;
    }
  }
  if ((oldOffset - xa4_offset).magnitude() > dt)
    zoomSfx = true;
  SetZoomSfxPlaying(zoomSfx);
  delta = xa4_offset - skInitialOffset;
  if (delta.magnitude() > 1.f)
    xa4_offset = delta.normalized() + skInitialOffset;
}

void CSamusDoll::BeginViewInterpolate(bool zoomIn) {
  if (xc4_viewInterp == 0.f) {
    CSfxManager::SfxStart(SFXui_samus_doll_enter, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId);
  } else {
    SetOffsetSfxPlaying(false);
    SetZoomSfxPlaying(false);
    SetRotationSfxPlaying(false);
    CSfxManager::SfxStart(SFXui_samus_doll_exit, 1.f, 0.f, false, 0x7f, false, kInvalidAreaId);
  }

  xc4_viewInterp = zoomIn ? FLT_EPSILON : (-1.f + FLT_EPSILON);
  x84_interpStartOffset = xa4_offset;
  x90_userInterpRot = xb0_userRot;
  xa0_userInterpZoom = xc0_userZoom;
  x80_fixedZoom = zoomIn ? -2.2f : -3.6f;
}

} // namespace urde::MP1


text:
<!-- app/templates/home/_header.html -->

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>{{ title }} </title>

  <!-- Custom fonts for this template-->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.7.2/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
    rel="stylesheet">

  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet" type="text/css">
  <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css">
  <link href="https://cdn.datatables.net/select/1.3.0/css/select.bootstrap4.min.css" rel="stylesheet" type="text/css">
  <link href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.dataTables.min.css" rel="stylesheet" type="text/css">

  <link rel="shortcut icon" href="{{ url_for('static', filename='img/favicon.ico', _external=True) }}">

  <!-- Custom styles for this template-->
  <link href="{{ url_for('static', filename='css/sb-admin-2.min.css', _external=True) }}" rel="stylesheet">

  {# incluir js scripts #}
{% include "home/_jsincludes_top.html" %}

</head>

redpajama_set_name: RedPajamaGithub


text:
package com.mongodb;

interface Connection {
    int getGeneration();

    long getOpenedAt();

    long getLastUsedAt();

    boolean isClosed();

    void close();
}


text:
/** @file
 *  @brief Implements LU decomposition for square matrix expressions.
 *
 * @todo The LU implementation does not check for a zero diagonal entry
 * (implying that the input has no LU factorization).
 *
 * @todo Should also have a pivoting implementation.
 *
 * @todo need to throw a numeric error if the determinant of the matrix
 * given to lu(), lu_solve(), or inverse() is 0.
 *
 * @internal The implementation is the same for fixed- and dynamic-size
 * matrices.  It can be sped up for small matrices later.
 */

#ifndef lu_h
#define lu_h

#include <cml/et/size_checking.h>
#include <cml/matrix/matrix_expr.h>
#include <cml/matvec/matvec_promotions.h>

/* This is used below to create a more meaningful compile-time error when
 * lu is not provided with a matrix or MatrixExpr argument:
 */
struct lu_expects_a_matrix_arg_error;

/* This is used below to create a more meaningful compile-time error when
 * lu_inplace is not provided with an assignable matrix argument:
 */
struct lu_inplace_expects_an_assignable_matrix_arg_error;

namespace cml {
namespace detail {

/** Compute the LU decomposition in-place, with L a unit triangular matrix
 * (1's in the diagonal), using Doolittle's method without pivoting.
 *
 * @warning Without pivoting, this is numerically stable only for
 * diagonally dominant matrices.
 */
template<class MatT> inline
void lu_inplace(MatT& A)
{
  /* Shorthand: */
  typedef et::ExprTraits<MatT> arg_traits;
  typedef typename arg_traits::result_tag arg_result;
  typedef typename arg_traits::assignable_tag arg_assignment;
  typedef typename arg_traits::size_tag size_tag;
  typedef typename arg_traits::value_type value_type;

  /* lu_inplace() requires an assignable matrix expression: */
  CML_STATIC_REQUIRE_M(
    (same_type<arg_result, et::matrix_result_tag>::is_true
     && same_type<arg_assignment, et::assignable_tag>::is_true),
    lu_inplace_expects_an_assignable_matrix_arg_error);
  /* Note: parens are required here so that the preprocessor ignores the
   * commas.
   */

  /* Verify that the matrix is square, and get the size: */
  ssize_t N = (ssize_t) cml::et::CheckedSquare(A, size_tag());
  for(ssize_t k = 0; k < N; ++k) {

    /* Compute the upper triangle: */
    for(ssize_t j = k; j < N; ++j) {
      value_type sum(0);
      for(ssize_t p = 0; p < k; ++ p) sum += A(k,p)*A(p,j);
      A(k,j) -= sum;
    }

    /* Compute the lower triangle: */
    for(ssize_t i = k+1; i < N; ++i) {
      value_type sum(0);
      for(ssize_t p = 0; p < k; ++p) sum += A(i,p)*A(p,k);
      A(i,k) = (A(i,k) - sum) / A(k,k);
    }
  }
}

/** Compute the LU decomposition by Doolittle's method, and return a copy
 * of the result.
 *
 * @sa detail::lu_inplace
 */
template<class MatT>
inline typename MatT::temporary_type
lu_copy(const MatT& M)
{
    /* Shorthand: */
    typedef et::ExprTraits<MatT> arg_traits;
    typedef typename arg_traits::result_tag arg_result;

    /* lu_with_copy() requires a matrix expression: */
    CML_STATIC_REQUIRE_M(
        (same_type<arg_result, et::matrix_result_tag>::is_true),
        lu_expects_a_matrix_arg_error);
    /* Note: parens are required here so that the preprocessor ignores the
     * commas.
     */

    /* Use the in-place LU function, and return the result: */
    typename MatT::temporary_type A;
    cml::et::detail::Resize(A,M.rows(),M.cols());
    A = M;
    lu_inplace(A);
    return A;
}

} // namespace detail

/** LU factorization for a matrix, with L a unit lower triangular matrix.
 *
 * @sa detail::lu_copy
 */
template<typename E, class AT, typename BO, class L>
inline typename matrix<E,AT,BO,L>::temporary_type
lu(const matrix<E,AT,BO,L>& m)
{
    return detail::lu_copy(m);
}

/** LU factorization for a matrix expression, with L a unit lower
 * triangular matrix.
 *
 * @sa detail::lu_copy
 */
template<typename XprT>
inline typename et::MatrixXpr<XprT>::temporary_type
lu(const et::MatrixXpr<XprT>& e)
{
    return detail::lu_copy(e);
}

/** Solve y = LUx for x.
 *
 * This solves Lb = y for b by forward substitution, then Ux = b for x by
 * backward substitution.  L is assumed to be a unit lower triangular
 * matrix embedded into LU.
 *
 * @sa lu
 */
template<typename MatT, typename VecT> inline
typename et::MatVecPromote<MatT,VecT>::temporary_type
lu_solve(const MatT& LU, const VecT& b)
{
  /* Shorthand. */
  typedef et::ExprTraits<MatT> lu_traits;
  typedef typename et::MatVecPromote<MatT,VecT>::temporary_type vector_type;
  typedef typename vector_type::value_type value_type;

  /* Verify that the matrix is square, and get the size: */
  ssize_t N = (ssize_t) cml::et::CheckedSquare(
    LU, typename lu_traits::size_tag());

  /* Verify that the matrix and vector have compatible sizes: */
  et::CheckedSize(LU, b, typename vector_type::size_tag());

  /* Solve Ly = b for y by forward substitution.  The entries below the
   * diagonal of LU correspond to L, understood to be below a diagonal of
   * 1's:
   */
  vector_type y; cml::et::detail::Resize(y,N);
  for(ssize_t i = 0; i < N; ++i) {
    value_type yi = b[i];
    for(ssize_t j = 0; j < i; ++j) yi -= LU(i,j)*y[j];
    y[i] = yi;
  }

  /* Solve Ux = y for x by backward substitution.  The entries at and above
   * the diagonal of LU correspond to U:
   */
  vector_type x; cml::et::detail::Resize(x,N);
  for(ssize_t i = N-1; i >= 0; --i) {
    value_type xi = y[i];
    for(ssize_t j = i+1; j < N; ++j) xi -= LU(i,j)*x[j];
    x[i] = xi/LU(i,i);
  }

  /* Return x: */
  return x;
}

} // namespace cml

#endif

// -------------------------------------------------------------------------
// vim:ft=cpp


text:
/**
 * Created by rossbille on 22/05/2015.
 */
import io from 'socket.io-client'

export default class SignallingClient {
    constructor(path) {
        this.path = path;
        this.onId = null;
        this.onClients = null;
        this.onNewClient = null;
        this.onRemove = null;
        this.onMessage = null;

        this.socket = null;
    }

    connect() {
        if (this.onId === null ||
            this.onClients === null ||
            this.onNewClient === null ||
            this.onRemove === null ||
            this.onMessage === null) {
            throw new Error("Please setup all callbacks before trying to connect.");
        }

        this.socket = io.connect(this.path, {reconnection: false});

        this.socket.on('id', (id) => { this.onId(id); });

        this.socket.on('clients', (clients) => { this.onClients(clients); });

        this.socket.on('new client', (client) => { this.onNewClient(client); });

        this.socket.on('remove', (client) => { this.onRemove(client); });

        this.socket.on('message', (message) => { this.onMessage(message); });
    }

    sendMessage(message) {
        this.socket.emit('message', message);
    }
}


text:
package com.scut.vsp.code.codemodule.entity;

import com.scut.vsp.exception.ProgramInvalidException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

/**
 * Created by sosoo on 2016/11/28.
 */

public class OPERATOR extends procedureModule {
    private String op;
    private String moduleType = "OPERATOR";
    private ArrayList<OperandInfo> Operands = new ArrayList<>();
    private String assgin;
    private String assignIndex;

    public OPERATOR() {
    }

    public String getOp() {
        return op;
    }

    public String getModuleType() {
        return moduleType;
    }

    public String getAssgin() {
        return assgin;
    }

    public void setAssgin(String assgin) {
        this.assgin = assgin;
    }

    @Override
    public void init(Map<String, Object> jsonMap) throws ProgramInvalidException {
        try {
            super.init(jsonMap);
            this.op = (String) jsonMap.get("op");
            if (jsonMap.containsKey("assignValue")) {
                this.assgin = (String) jsonMap.get("assignValue");
            }
            if (jsonMap.containsKey("assignIndex")) {
                this.assignIndex = (String) jsonMap.get("assignIndex");
            }
            if (jsonMap.containsKey("first")) {
                OperandInfo first = new OperandInfo((String) jsonMap.get("firstType"), null, (String) jsonMap.get("first"), jsonMap.get("firstIndex"));
                Operands.add(first);
            }
            if (jsonMap.containsKey("second")) {
                OperandInfo second = new OperandInfo((String) jsonMap.get("secondType"), null, (String) jsonMap.get("second"), jsonMap.get("secondIndex"));
                Operands.add(second);
            }
        }
        catch (Exception e){
            throw new ProgramInvalidException("Something in your code maybe wrong");
        }
    }

    @Override
    public String generateJavascript() {
        try {
            String javascriptCode = "";
            if (assgin != null) {
                if (assignIndex!=null){
                    javascriptCode += assgin+"["+assignIndex +"]"+ " = ";
                }
                else
                    javascriptCode += assgin + " = ";
            }
//            File operationXml = new File(System.getProperty("user.dir") + File.separator + "out" + File.separator
//                    + "production" + File.separator + "CodeGenera" + File.separator + "configs" + File.separator + "Operation.xml");
            File operationXml = new File(this.getClass().getClassLoader().getResource("configs/Operation.xml").toURI());
            Document operationsNode = Jsoup.parse(operationXml, "UTF-8");
            Element operationNode = operationsNode.getElementById(getOp());
            assert (operationNode != null);
            for (Element node :
                    operationNode.children()) {
                if (node.tagName().equals("operand")) {
                    int index = Integer.parseInt(node.html());
                    switch (Operands.get(index).getVarType()) {
                        case immediate:
                            javascriptCode += Operands.get(index).getValue() + " ";
                            break;
                        case VAR:
                            if (Operands.get(index).getIndex().equals(""))
                                javascriptCode += Operands.get(index).getValue() + " ";
                            else{
                                javascriptCode+=Operands.get(index).getValue()+"["+Operands.get(index).getIndex()+"] ";
                            }
                            break;
                    }
                } else if (node.tagName().equals("symbol")) {
                    javascriptCode += node.html() + " ";
                }
            }
            javascriptCode += ";\n";
            return javascriptCode;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>F-Index</title>
<meta name="date" content="2015-07-25">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L N O P R S T U V W

F

FILE_SEPARATOR - Static variable in class Utilities.FileFinder

FileFinder - Class in Utilities

This class helps find files in the file system on both Linux and Windows.

FileFinder() - Constructor for class Utilities.FileFinder

A B C D E F G H I K L N O P R S T U V W

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
function removeCurrentUser(clients, currentUser) {
  peers = []
  for (var i=0; i < clients.length; i++){
    if (clients[i] !== currentUser) {
      peers.push(clients[i])
    }
  }
  return peers;
}


text:
using System;
using System.Threading;

public class Alpha {

   // This method that will be called when the thread is started
   public void Beta()
   {
      while (true)
      {
         Console.WriteLine("Alpha.Beta is running in its own thread.");
      }
   }
};

public class Simple
{
   public static int Main()
   {
      Console.WriteLine("Thread Start/Stop/Join Sample");

      Alpha oAlpha = new Alpha();

      // Create the thread object, passing in the Alpha.Beta method
      // via a ThreadStart delegate. This does not start the thread.
      Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

      // Start the thread
      oThread.Start();

      // Spin for a while waiting for the started thread to become
      // alive:
      while (!oThread.IsAlive);

      // Put the Main thread to sleep for 1 millisecond to allow oThread
      // to do some work:
      Thread.Sleep(1);

      // Request that oThread be stopped
      oThread.Abort();

      // Wait until oThread finishes. Join also has overloads
      // that take a millisecond interval or a TimeSpan object.
      oThread.Join();

      Console.WriteLine();
      Console.WriteLine("Alpha.Beta has finished");

      try
      {
         Console.WriteLine("Try to restart the Alpha.Beta thread");
         oThread.Start();
      }
      catch (ThreadStateException)
      {
         Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
         Console.WriteLine("Expected since aborted threads cannot be restarted.");
      }
      return 0;
   }
}


text:
/* globals Pash, Module, importScripts, self, Util, Cipher, Breadcrumbs */
'use strict'

// Import and bind pbkdf
importScripts('pbkdf_min.js', 'Util.js', 'Cipher.js', 'Breadcrumbs.js')

/**
 * Implemented by https://github.com/sitegui/pbkdf-sha256-asm/
 * @function
 * @param {string} password
 * @param {string} salt
 * @param {number} blockIndex
 * @param {number} rounds
 * @returns {string} 64-char hex-encoded string
 */
let pbkdf = Module.cwrap('pbkdf_simple', 'string', ['string', 'string', 'number', 'number'])

/**
 * Alphabet type constants
 */
let alphabets = {
	a: 'abcdefghijklmnopqrstuvwxyz',
	A: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
	'0': '0123456789',
	$: '!#$%&()*+,-./:;<=>?@[]_{|}'
}

/**
 * Treat an incoming message to apply the PASH algorithm
 * @param {Event} event
 */
self.onmessage = function (event) {
	let data = event.data,
		result = '',
		pash, key

	if (data.action === 'password') {
		pash = new Pash(data.masterPassword, data.userName, data.serviceName, data.color)
		if (data.format === Pash.FORMAT.NUMERIC) {
			result = pash.getNumericPassword(data.length)
		} else if (data.format === Pash.FORMAT.STANDARD) {
			result = pash.getStandardPassword(data.length)
		} else if (data.format === Pash.FORMAT.STRONG) {
			result = pash.getStrongPassword(data.length)
		} else if (data.format === Pash.FORMAT.RAW) {
			result = pash.getRawPassword()
		}
	} else if (data.action === 'encrypt') {
		key = new Pash(data.masterPassword, data.userName, 'pash', 'red').getRawPassword()
		result = Cipher.encrypt(key, data.plaintext)
	} else if (data.action === 'decrypt') {
		key = new Pash(data.masterPassword, data.userName, 'pash', 'red').getRawPassword()
		result = Cipher.decrypt(key, data.ciphertext)
	} else if (data.action === 'breadcrumbs') {
		result = Breadcrumbs.generate(data.masterPassword, 3, 1)
	}

	self.postMessage({
		result,
		tag: data.tag
	})
}

/**
 * Create a PASH object from normalized inputs
 * @class
 * @param {string} masterPassword
 * @param {string} userName
 * @param {string} serviceName
 * @param {string} color
 */
self.Pash = function Pash(masterPassword, userName, serviceName, color) {
	/** @member {string} */
	this.masterPassword = masterPassword

	/** @member {string} */
	this.salt = userName + '\n' + serviceName + '\n' + color

	/** @member {Uint8Array} */
	this.block = null

	/**
	 * Bit position (8 bit = 1 Byte)
	 * @member {number}
	 */
	this.streamPos = 0
}

/**
 * Output format type constants
 * @enum {number}
 */
Pash.FORMAT = {
	STANDARD: 0,
	NUMERIC: 1,
	STRONG: 2,
	RAW: 3
}

/**
 * Return a string with at least 1 upper-case letter, 1 lower-case letter and 1 digit
 * @param {number} length one of Pash.LENGTH.* constants
 * @returns {string}
 */
Pash.prototype.getStandardPassword = function (length) {
	let alphabet, str, i, hasa, has0, c

	alphabet = alphabets.a + alphabets['0']
	length *= 5
	do {
		// The first char is an upper-case letter
		str = this.chooseRandom(alphabets.A)

		// Pick random from a0
		hasa = has0 = false
		for (i = 1; i < length; i++) {
			c = this.chooseRandom(alphabet)
			str += c
			hasa = hasa || alphabets.a.indexOf(c) !== -1
			has0 = has0 || alphabets['0'].indexOf(c) !== -1
		}
	} while (!hasa || !has0) // Try again

	return str
}

/**
 * Return a string composed only of numbers
 * @param {number} length one of Pash.LENGTH.* constants
 * @returns {string}
 */
Pash.prototype.getNumericPassword = function (length) {
	let i, str = ''

	// Pick random digits
	length *= 4
	for (i = 0; i < length; i++) {
		str += this.chooseRandom(alphabets['0'])
	}

	return str
}

/**
 * Return a string with at least 1 upper-case letter, 1 lower-case letter, 1 digit and 1 symbol
 * @param {number} length one of Pash.LENGTH.* constants
 * @returns {string}
 */
Pash.prototype.getStrongPassword = function (length) {
	let alphabet, str, i, hasA, hasa, has0, has$, c

	alphabet = alphabets.A + alphabets.a + alphabets['0'] + alphabets.$
	length *= 7
	do {
		str = ''

		// Pick random from Aa0$
		hasA = hasa = has0 = has$ = false
		for (i = 0; i < length; i++) {
			c = this.chooseRandom(alphabet)
			str += c
			hasA = hasA || alphabets.A.indexOf(c) !== -1
			hasa = hasa || alphabets.a.indexOf(c) !== -1
			has0 = has0 || alphabets['0'].indexOf(c) !== -1
			has$ = has$ || alphabets.$.indexOf(c) !== -1
		}
	} while (!hasA || !hasa || !has0 || !has$) // Try again

	return str
}

/**
 * Return a string with 64 hex chars
 * @returns {string}
 */
Pash.prototype.getRawPassword = function () {
	return this.getKeyBlock(0, true)
}

/**
 * Return the next n bits from the key stream
 * If needed, a new key block will be generated
 * @param {number} n 1<=n<=32
 * @returns {number} the first bit is the most significant
 */
Pash.prototype.getNextBits = function (n) {
	let result = 0,
		bitPosInBlock, i, bytePosInBlock, bitPosInByte, byte, bit

	// Extract each bit
	for (i = 0; i < n; i++) {
		bitPosInBlock = this.streamPos & 0xFF
		if (bitPosInBlock === 0) {
			// Load this block
			this.block = this.getKeyBlock(this.streamPos >>> 8)
		}

		// Get the bit
		bytePosInBlock = bitPosInBlock >>> 3
		bitPosInByte = bitPosInBlock & 0x7
		byte = this.block[bytePosInBlock]
		bit = (byte >>> (7 - bitPosInByte)) & 0x1

		// Add to result
		result <<= 1
		result |= bit

		// Increment
		this.streamPos++
	}

	return result
}

/**
 * Return a integer random value 0 <= r < max
 * The random value is derived from the key stream and is close to a uniform distribuition
 * @param {number} max must be greater than 1 and smaller than 2^32
 * @returns {number}
 */
Pash.prototype.getNextRandom = function (max) {
	// Take ceil(log2(max))
	let nBits = 0,
		temp = max - 1
	while (temp) {
		temp >>>= 1
		nBits++
	}

	// Find the next valid value
	let r
	do {
		r = this.getNextBits(nBits)
	} while (r >= max)

	return r
}

/**
 * Return a random element from the given array
 * @param {Array} array
 * @returns {*}
 */
Pash.prototype.chooseRandom = function (array) {
	return array[this.getNextRandom(array.length)]
}

/**
 * Generate the n-th key block
 * @param {number} index block index (0=first block)
 * @param {boolean} [returnAsString=false]
 * @returns {Uint8Array|string} with 256 bits (32 bytes)
 */
Pash.prototype.getKeyBlock = function (index, returnAsString) {
	let hexStr = pbkdf(this.masterPassword, this.salt, index, 1e4)
	if (returnAsString) {
		return hexStr
	}
	return Util.i8ArrFromHex(hexStr)
}


text:
package org.verdictdb.core.sqlobject;

public class DropTableQuery implements SqlConvertible {

  private static final long serialVersionUID = -3481351240470800158L;

  String schemaName;

  String tableName;

  boolean isIfExists;

  public DropTableQuery(String schemaName, String tableName) {
    this.schemaName = schemaName;
    this.tableName = tableName;
  }

  public static DropTableQuery create(String schemaName, String tableName) {
    return new DropTableQuery(schemaName, tableName);
  }

  public String getSchemaName() {
    return schemaName;
  }

  public String getTableName() {
    return tableName;
  }

  public boolean isIfExists() {
    return isIfExists;
  }

  public void setIfExists(boolean ifExists) {
    isIfExists = ifExists;
  }
}


text:
<html>
    <head>
        <title>JQuery Animation</title>
        <link rel="stylesheet" href="style.css">
    </head>

    <body>
    </body>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script type="text/javascript">
    $(document).ready(function(){

    });

    </script>
</html>


text:
from django.template import Library
register = Library()
from .tags import Edit, EditLoader


text:
// Copyright (c) 2012 Nezametdinov E. Ildus
// Licensed under the MIT License (see LICENSE.txt for details)

#ifndef RAY_H
#define RAY_H

#include "Vector.h"

namespace selene
{

        /**
         * \addtogroup Math
         * @{
         */

        // Forward declaration of classes
        class LineSegment2d;
        class Line2d;
        class Circle;
        class Sphere;

        /**
         * Represents ray in 2D space.
         */
        class Ray2d
        {
        public:
                /**
                 * \brief Constructs ray with given origin and direction.
                 * \param[in] origin origin of the ray
                 * \param[in] direction direction of the ray
                 */
                Ray2d(const Vector2d& origin, const Vector2d& direction);
                Ray2d(const Ray2d&) = default;
                ~Ray2d();
                Ray2d& operator =(const Ray2d&) = default;

                /**
                 * \brief Defines ray with given origin and direction (direction must be already normalized).
                 * \param[in] origin origin of the ray
                 * \param[in] direction direction of the ray
                 */
                void define(const Vector2d& origin, const Vector2d& direction);

                /**
                 * \brief Sets origin.
                 * \param[in] origin origin of the ray
                 */
                void setOrigin(const Vector2d& origin);

                /**
                 * \brief Returns origin.
                 * \return origin of the ray
                 */
                const Vector2d& getOrigin() const;

                /**
                 * \brief Sets direction.
                 * \param[in] direction direction of the ray
                 */
                void setDirection(const Vector2d& direction);

                /**
                 * \brief Returns direction.
                 * \return direction of the ray
                 */
                const Vector2d& getDirection() const;

                /**
                 * \brief Determines intersection with line.
                 * \param[in] line line
                 * \param[out] distanceToIntersection distance to intersection point
                 * \return true if ray intersects the line
                 */
                bool intersects(const Line2d& line, float& distanceToIntersection) const;

                /**
                 * \brief Determines intersection with line segment.
                 * \param[in] lineSegment line segment
                 * \param[out] distanceToIntersection distance to intersection point
                 * \return true if ray intersects the line segment
                 */
                bool intersects(const LineSegment2d& lineSegment, float& distanceToIntersection) const;

                /**
                 * \brief Determines intersection with circle.
                 * \param[in] circle circle
                 * \param[out] distanceToIntersection distance to intersection point (closest one)
                 * \return true if ray intersects the circle
                 */
                bool intersects(const Circle& circle, float& distanceToIntersection) const;

        private:
                Vector2d origin_, direction_;

        };

        /**
         * Represents ray in 3D space.
         */
        class Ray3d
        {
        public:
                /**
                 * \brief Constructs ray with given origin and direction.
                 * \param[in] origin origin of the ray
                 * \param[in] direction direction of the ray
                 */
                Ray3d(const Vector3d& origin, const Vector3d& direction);
                Ray3d(const Ray3d&) = default;
                ~Ray3d();
                Ray3d& operator =(const Ray3d&) = default;

                /**
                 * \brief Defines ray with given origin and direction (direction must be already normalized).
                 * \param[in] origin origin of the ray
                 * \param[in] direction direction of the ray
                 */
                void define(const Vector3d& origin, const Vector3d& direction);

                /**
                 * \brief Sets origin.
                 * \param[in] origin origin of the ray
                 */
                void setOrigin(const Vector3d& origin);

                /**
                 * \brief Returns origin.
                 * \return origin of the ray
                 */
                const Vector3d& getOrigin() const;

                /**
                 * \brief Sets direction.
                 * \param[in] direction direction of the ray
                 */
                void setDirection(const Vector3d& direction);

                /**
                 * \brief Returns direction.
                 * \return direction of the ray
                 */
                const Vector3d& getDirection() const;

                /**
                 * \brief Determines intersection with sphere.
                 * \param[in] sphere sphere
                 * \param[out] distanceToIntersection distance to intersection point (closest one)
                 * \return true if ray intersects the sphere
                 */
                bool intersects(const Sphere& sphere, float& distanceToIntersection) const;

        private:
                Vector3d origin_, direction_;

        };

        /**
         * @}
         */

}

#endif


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Context\Api\Admin;

use ApiPlatform\Core\Api\IriConverterInterface;
use Behat\Behat\Context\Context;
use Sylius\Behat\Client\ApiClientInterface;
use Sylius\Behat\Client\ResponseCheckerInterface;
use Sylius\Behat\Service\SharedStorageInterface;
use Sylius\Component\Addressing\Model\CountryInterface;
use Sylius\Component\Addressing\Model\ProvinceInterface;
use Symfony\Component\Intl\Countries;
use Webmozart\Assert\Assert;

final class ManagingCountriesContext implements Context
{
    /** @var ApiClientInterface */
    private $client;

    /** @var ApiClientInterface */
    private $provincesClient;

    /** @var ResponseCheckerInterface */
    private $responseChecker;

    /** @var SharedStorageInterface */
    private $sharedStorage;

    /** @var IriConverterInterface */
    private $iriConverter;

    public function __construct(
        ApiClientInterface $client,
        ApiClientInterface $provincesClient,
        ResponseCheckerInterface $responseChecker,
        SharedStorageInterface $sharedStorage,
        IriConverterInterface $iriConverter
    ) {
        $this->client = $client;
        $this->provincesClient = $provincesClient;
        $this->responseChecker = $responseChecker;
        $this->sharedStorage = $sharedStorage;
        $this->iriConverter = $iriConverter;
    }

    /**
     * @When I want to add a new country
     */
    public function iWantToAddANewCountry(): void
    {
        $this->client->buildCreateRequest();
    }

    /**
     * @When I choose :countryName
     */
    public function iChoose(string $countryName): void
    {
        $this->client->addRequestData('code', $this->getCountryCodeByName($countryName));
    }

    /**
     * @When I add it
     */
    public function iAddIt(): void
    {
        $this->client->create();
    }

    /**
     * @When /^I want to edit (this country)$/
     * @When /^I want to create a new province in (country "([^"]+)")$/
     */
    public function iWantToEditThisCountry(CountryInterface $country): void
    {
        $this->client->buildUpdateRequest($country->getCode());
    }

    /**
     * @When I enable it
     */
    public function iEnableIt(): void
    {
        $this->client->addRequestData('enabled', true);
    }

    /**
     * @When I disable it
     */
    public function iDisableIt(): void
    {
        $this->client->addRequestData('enabled', false);
    }

    /**
     * @When I save my changes
     * @When I try to save changes
     */
    public function iSaveMyChanges(): void
    {
        $this->client->update();
    }

    /**
     * @When I name the province :provinceName
     */
    public function iNameTheProvince(string $provinceName): void
    {
        $this->client->addSubResourceData(
            'provinces',
            ['name' => $provinceName]
        );
    }

    /**
     * @When I specify the province code as :provinceCode
     */
    public function iSpecifyTheProvinceCodeAs(string $provinceCode): void
    {
        $this->client->addSubResourceData(
            'provinces',
            ['code' => $provinceCode]
        );
    }

    /**
     * @When I add the :provinceName province with :provinceCode code
     */
    public function iAddTheProvinceWithCode(string $provinceName, string $provinceCode): void
    {
        $this->client->addSubResourceData(
            'provinces',
            ['code' => $provinceCode, 'name' => $provinceName]
        );
    }

    /**
     * @When I add the :name province with :code code and :abbreviation abbreviation
     */
    public function iAddTheProvinceWithCodeAndAbbreviation(string $name, string $code, string $abbreviation): void
    {
        $this->client->addSubResourceData(
            'provinces',
            ['code' => $code, 'name' => $name, 'abbreviation' => $abbreviation]
        );
    }

    /**
     * @When /^I delete the ("[^"]+" province) of (this country)$/
     */
    public function iDeleteTheProvinceOfThisCountry(ProvinceInterface $province, CountryInterface $country): void
    {
        $iri = $this->iriConverter->getItemIriFromResourceClass(get_class($province), ['code' => $province->getCode()]);

        $provinces = $this->responseChecker->getValue($this->client->show($country->getCode()), 'provinces');
        foreach ($provinces as $countryProvince) {
            if ($iri === $countryProvince) {
                $this->client->removeSubResource('provinces', $countryProvince);
            }
        }
    }

    /**
     * @When I do not specify the province code
     * @When I do not name the province
     */
    public function iDoNotSpecifyTheProvince(): void
    {
        // Intentionally left blank
    }

    /**
     * @When I remove :province province name
     */
    public function iRemoveProvinceName(ProvinceInterface $province): void
    {
        $this->provincesClient->buildUpdateRequest($province->getCode());
        $this->provincesClient->addRequestData('name', '');
        $this->provincesClient->update();
    }

    /**
     * @Then I should be notified that it has been successfully created
     */
    public function iShouldBeNotifiedThatItHasBeenSuccessfullyCreated(): void
    {
        Assert::true(
            $this->responseChecker->isCreationSuccessful($this->client->getLastResponse()),
            'Country could not be created'
        );
    }

    /**
     * @Then the country :country should appear in the store
     */
    public function theCountryShouldAppearInTheStore(CountryInterface $country): void
    {
        Assert::true(
            $this->responseChecker->hasItemWithValue($this->client->index(), 'code', $country->getCode()),
            sprintf('There is no country with name "%s"', $country->getName())
        );
    }

    /**
     * @Then the country :country should have the :province province
     * @Then /^(this country) should have the ("[^"]*" province)$/
     */
    public function theCountryShouldHaveTheProvince(CountryInterface $country, ProvinceInterface $province): void
    {
        Assert::true($this->responseChecker->hasItemWithValue(
            $this->client->subResourceIndex('provinces', $country->getCode()),
            'code',
            $province->getCode()
        ));
    }

    /**
     * @Then the province should still be named :province in this country
     */
    public function theProvinceShouldStillBeNamedInThisCountry(ProvinceInterface $province): void
    {
        /** @var CountryInterface $country */
        $country = $this->sharedStorage->get('country');
        Assert::true($this->responseChecker->hasItemWithValue(
            $this->client->subResourceIndex('provinces', $country->getCode()),
            'code',
            $province->getCode()
        ));
    }

    /**
     * @Then I should not be able to choose :countryName
     */
    public function iShouldNotBeAbleToChoose(string $countryName): void
    {
        $this->client->addRequestData('code', $this->getCountryCodeByName($countryName));
        $response = $this->client->create();
        Assert::false(
            $this->responseChecker->isCreationSuccessful($response),
            'Country has been created successfully, but it should not'
        );
        Assert::same($this->responseChecker->getError($response), 'code: Country ISO code must be unique.');
    }

    /**
     * @Then I should be notified that it has been successfully edited
     */
    public function iShouldBeNotifiedThatItHasBeenSuccessfullyEdited(): void
    {
        Assert::true(
            $this->responseChecker->isUpdateSuccessful($this->client->getLastResponse()),
            'Country could not be edited'
        );
    }

    /**
     * @Then /^(this country) should be (enabled|disabled)$/
     */
    public function thisCountryShouldBeDisabled(CountryInterface $country, string $enabled): void
    {
        Assert::true(
            $this->responseChecker->hasValue(
                $this->client->show($country->getCode()),
                'enabled',
                $enabled === 'enabled'
            ),
            'Country is not disabled'
        );
    }

    /**
     * @Then I should not be able to edit its code
     */
    public function theCodeFieldShouldBeDisabled(): void
    {
        $this->client->updateRequestData(['code' => 'NEW_CODE']);

        Assert::false($this->responseChecker->hasValue($this->client->update(), 'code', 'NEW_CODE'));
    }

    /**
     * @Then /^province with code ("[^"]*") should not be added in (this country)$/
     */
    public function provinceWithCodeShouldNotBeAddedInThisCountry(string $provinceCode, CountryInterface $country): void
    {
        /** @var ProvinceInterface $province */
        foreach ($this->getProvincesOfCountry($country) as $province) {
            Assert::false(
                $province->getCode() === $provinceCode,
                sprintf('The country "%s" should not have the "%s" province', $country->getName(), $province->getName())
            );
        }
    }

    /**
     * @Then this country should not have the :provinceName province
     * @Then province with name :provinceName should not be added in this country
     */
    public function thisCountryShouldNotHaveTheProvince(string $provinceName): void
    {
        /** @var CountryInterface $country */
        $country = $this->sharedStorage->get('country');
        /** @var ProvinceInterface $province */
        foreach ($this->getProvincesOfCountry($country) as $province) {
            Assert::false(
                $province->getName() === $provinceName,
                sprintf('The country "%s" should not have the "%s" province', $country->getName(), $province->getName())
            );
        }
    }

    /**
     * @Then I should be notified that province code must be unique
     */
    public function iShouldBeNotifiedThatProvinceCodeMustBeUnique(): void
    {
        Assert::same(
            $this->responseChecker->getError($this->client->getLastResponse()),
            'provinces[1].code: Province code must be unique.'
        );
    }

    /**
     * @Then I should be notified that :field is required
     */
    public function iShouldBeNotifiedThatFieldIsRequired(string $field): void
    {
        Assert::contains(
            $this->responseChecker->getError($this->client->getLastResponse()),
            \sprintf('Please enter province %s.', $field)
        );
    }

    /**
     * @Then I should be notified that name of the province is required
     */
    public function iShouldBeNotifiedThatNameOfTheProvinceIsRequired(): void
    {
        Assert::contains(
            $this->responseChecker->getError($this->provincesClient->getLastResponse()),
            'Please enter province name.'
        );
    }

    private function getCountryCodeByName(string $countryName): string
    {
        $countryList = array_flip(Countries::getNames());
        Assert::keyExists(
            $countryList,
            $countryName,
            sprintf('The country with name "%s" not found', $countryName)
        );

        return $countryList[$countryName];
    }

    private function getProvincesOfCountry(CountryInterface $country): iterable
    {
        $response = $this->client->show($country->getCode());
        $countryFromResponse = $this->responseChecker->getResponseContent($response);

        foreach ($countryFromResponse['provinces'] as $provinceFromResponse) {
            yield $this->iriConverter->getItemFromIri($provinceFromResponse);
        }
    }
}


text:
This is a boilerplate project for static site builds and single page apps. It is heavily opinionated and designed to rapidly build front-end templates in isolation, typically before they are integrated with a CMS or back-end system.

Based on Gulp, it performs the following tasks;

* Compiling CSS with SASS and PostCSS (autoprefixer + cssnano)
* Compiling HTML templates from Twig partials
* Minifying and concatenating Javascript using Uglify
* Compressing images using imagemin and svgmin
* Linting SASS and Javascript
* Provides a simple livereload web server for development

### Getting started

1.  Clone the project

    `git clone git@github.com:andrewjoll/static-boilerplate.git .`

2.  Install the dependencies.

    `npm install`

3.  Start the server

    `gulp serve`

4.  Navigate to the site

    `http://localhost:8080/`

If you'd prefer to use your own web server, you can use `gulp watch` instead.

### Configuration

When building manually you can specify a config environment. This is done with the `env` parameter.

E.g; `gulp build --env=prod`

Configuration is defined per-task in `config.js` and additional environments can be created if required.

```js
dev: {
    js: {
        mangle: false,
        output: {
            beautify: true
        },
        compress: {}
    }
},
prod: {
    js: {
        mangle: true,
        beautify: false,
        compress: {
            drop_console:  true
        }
    }
}
```


text:
using UnityEngine;
using System.Collections;

/// Cardboard audio source component that enhances AudioSource to provide advanced spatial audio
/// features.
[AddComponentMenu("Cardboard/Audio/CardboardAudioSource")]
public class CardboardAudioSource : MonoBehaviour {
  /// Directivity pattern shaping factor.
  public float directivityAlpha = 0.0f;

  /// Directivity pattern order.
  public float directivitySharpness = 1.0f;

  /// Input gain in decibels.
  public float gainDb = 0.0f;

  /// Occlusion effect toggle.
  public bool occlusionEnabled = false;

  /// Play source on awake.
  public bool playOnAwake = true;

  /// Volume rolloff model with respect to the distance.
  public AudioRolloffMode rolloffMode = AudioRolloffMode.Logarithmic;

  /// The default AudioClip to play.
  public AudioClip clip {
    get { return clip; }
    set {
      sourceClip = value;
      if (audioSource != null) {
        audioSource.clip = sourceClip;
      }
    }
  }
  [SerializeField]
  private AudioClip sourceClip = null;

  /// Is the clip playing right now (Read Only)?
  public bool isPlaying {
    get {
      if (audioSource != null) {
        return audioSource.isPlaying;
      }
      return false;
    }
  }

  /// Is the audio clip looping?
  public bool loop {
    get { return sourceLoop; }
    set {
      sourceLoop = value;
      if (audioSource != null) {
        audioSource.loop = sourceLoop;
      }
    }
  }
  [SerializeField]
  private bool sourceLoop = false;

  /// Un- / Mutes the source. Mute sets the volume=0, Un-Mute restore the original volume.
  public bool mute {
    get { return sourceMute; }
    set {
      sourceMute = value;
      if (audioSource != null) {
        audioSource.mute = sourceMute;
      }
    }
  }
  [SerializeField]
  private bool sourceMute = false;

  /// The pitch of the audio source.
  public float pitch {
    get { return sourcePitch; }
    set {
      sourcePitch = value;
      if (audioSource != null) {
        audioSource.pitch = sourcePitch;
      }
    }
  }
  [SerializeField]
  [Range(-3.0f, 3.0f)]
  private float sourcePitch = 1.0f;

  /// The volume of the audio source (0.0 to 1.0).
  public float volume {
    get { return sourceVolume; }
    set {
      sourceVolume = value;
      if (audioSource != null) {
        audioSource.volume = sourceVolume;
      }
    }
  }
  [SerializeField]
  [Range(0.0f, 1.0f)]
  private float sourceVolume = 1.0f;

  /// MaxDistance is the distance a sound stops attenuating at.
  public float maxDistance {
    get { return sourceMaxDistance; }
    set {
      sourceMaxDistance = Mathf.Clamp(sourceMaxDistance,
                                      sourceMinDistance + CardboardAudio.distanceEpsilon,
                                      CardboardAudio.maxDistanceLimit);
    }
  }
  [SerializeField]
  private float sourceMaxDistance = 500.0f;

  /// Within the Min distance the CardboardAudioSource will cease to grow louder in volume.
  public float minDistance {
    get { return sourceMinDistance; }
    set {
      sourceMinDistance = Mathf.Clamp(value, 0.0f, CardboardAudio.minDistanceLimit);
    }
  }
  [SerializeField]
  private float sourceMinDistance = 0.0f;

  /// Binaural (HRTF) rendering toggle.
  [SerializeField]
  private bool hrtfEnabled = true;

  // Unique source id.
  private int id = -1;

  // Current occlusion value;
  private float currentOcclusion = 0.0f;

  // Target occlusion value.
  private float targetOcclusion = 0.0f;

  // Next occlusion update time in seconds.
  private float nextOcclusionUpdate = 0.0f;

  // Unity audio source attached to the game object.
  private AudioSource audioSource = null;

  // Denotes whether the source is currently paused or not.
  private bool isPaused = false;

  void Awake () {
    audioSource = gameObject.AddComponent<AudioSource>();
    audioSource.hideFlags = HideFlags.HideInInspector;
    audioSource.playOnAwake = false;
    audioSource.bypassReverbZones = true;
#if UNITY_4_5 || UNITY_4_6 || UNITY_4_7
    audioSource.panLevel = 0.0f;
#else
    audioSource.spatialBlend = 0.0f;
#endif
    OnValidate();
  }

  void OnEnable () {
    audioSource.enabled = true;
    if (playOnAwake && !isPlaying) {
      Play();
    }
  }

  void Start () {
    if (playOnAwake && !isPlaying) {
      Play();
    }
  }

  void OnDisable () {
    Stop();
    audioSource.enabled = false;
  }

  void OnDestroy () {
    Destroy(audioSource);
  }

  void Update () {
    // Update occlusion state.
    if (!occlusionEnabled) {
      targetOcclusion = 0.0f;
    } else if (Time.time >= nextOcclusionUpdate) {
      nextOcclusionUpdate = Time.time + CardboardAudio.occlusionDetectionInterval;
      targetOcclusion = CardboardAudio.ComputeOcclusion(transform);
    }
    currentOcclusion = Mathf.Lerp(currentOcclusion, targetOcclusion,
                                  CardboardAudio.occlusionLerpSpeed * Time.deltaTime);
    // Update source.
    if (!isPlaying && !isPaused) {
      Stop();
    } else {
      CardboardAudio.UpdateAudioSource(id, transform, gainDb, rolloffMode, sourceMinDistance,
                                       sourceMaxDistance, directivityAlpha, directivitySharpness,
                                       currentOcclusion);
    }
  }

#if !USE_SPATIALIZER_PLUGIN
  void OnAudioFilterRead (float[] data, int channels) {
    if (id >= 0) {
      // Pass the next buffer to the audio system.
      CardboardAudio.ProcessAudioSource(id, data, data.Length);
    } else {
      // Fill the buffer with zeros if the source has not been initialized yet.
      for (int i = 0; i < data.Length; ++i) {
        data[i] = 0.0f;
      }
    }
  }
#endif

  /// Pauses playing the clip.
  public void Pause () {
    if (audioSource != null) {
      isPaused = true;
      audioSource.Pause();
    }
  }

  /// Plays the clip.
  public void Play () {
    if (audioSource != null && InitializeSource()) {
      audioSource.Play();
      isPaused = false;
    }
  }

  /// Plays the clip with a delay specified in seconds.
  public void PlayDelayed (float delay) {
    if (audioSource != null && InitializeSource()) {
      audioSource.PlayDelayed(delay);
      isPaused = false;
    }
  }

  /// Plays an AudioClip.
  public void PlayOneShot (AudioClip clip) {
    PlayOneShot(clip, 1.0f);
  }

  /// Plays an AudioClip, and scales its volume.
  public void PlayOneShot (AudioClip clip, float volume) {
    if (audioSource != null && InitializeSource()) {
      audioSource.PlayOneShot(clip, volume);
      isPaused = false;
    }
  }

  /// Stops playing the clip.
  public void Stop () {
    if (audioSource != null) {
      audioSource.Stop();
      ShutdownSource();
      isPaused = false;
    }
  }

#if !(UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
  /// Unpauses the paused playback.
  public void UnPause () {
    if (audioSource != null) {
      audioSource.UnPause();
      isPaused = false;
    }
  }
#endif

  // Initializes the source.
  private bool InitializeSource () {
    if (id < 0) {
      id = CardboardAudio.CreateAudioSource(hrtfEnabled);
      if (id >= 0) {
        CardboardAudio.UpdateAudioSource(id, transform, gainDb, rolloffMode, sourceMinDistance,
                                         sourceMaxDistance, directivityAlpha, directivitySharpness,
                                         currentOcclusion);
#if USE_SPATIALIZER_PLUGIN
        audioSource.spatialize = true;
        audioSource.SetSpatializerFloat(0, id);
#endif
      }
    }
    return id >= 0;
  }

  // Shuts down the source.
  private void ShutdownSource () {
    if (id >= 0) {
#if USE_SPATIALIZER_PLUGIN
      audioSource.SetSpatializerFloat(0, -1.0f);
      audioSource.spatialize = false;
#endif
      CardboardAudio.DestroyAudioSource(id);
      id = -1;
    }
  }

  void OnValidate () {
    clip = sourceClip;
    loop = sourceLoop;
    mute = sourceMute;
    pitch = sourcePitch;
    volume = sourceVolume;
    minDistance = sourceMinDistance;
    maxDistance = sourceMaxDistance;
  }

#if !(UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
  void OnDrawGizmosSelected () {
    Gizmos.color = new Color(0.75f, 0.75f, 1.0f, 0.5f);
    DrawDirectivityGizmo(180);
  }

  // Draws a 3D gizmo in the Scene View that shows the selected directivity pattern.
  private void DrawDirectivityGizmo (int resolution) {
    Vector2[] points = CardboardAudio.Generate2dPolarPattern(directivityAlpha, directivitySharpness,
                                                             resolution);
    // Compute |vertices| from the polar pattern |points|.
    int numVertices = resolution + 1;
    Vector3[] vertices = new Vector3[numVertices];
    vertices[0] = Vector3.zero;
    for (int i = 0; i < points.Length; ++i) {
      vertices[i + 1] = new Vector3(points[i].x, 0.0f, points[i].y);
    }
    // Generate |triangles| from |vertices|. Two triangles per each sweep to avoid backface culling.
    int[] triangles = new int[6 * numVertices];
    for (int i = 0; i < numVertices - 1; ++i) {
      int index = 6 * i;
      if (i < numVertices - 2) {
        triangles[index] = 0;
        triangles[index + 1] = i + 1;
        triangles[index + 2] = i + 2;
      } else {
        // Last vertex is connected back to the first for the last triangle.
        triangles[index] = 0;
        triangles[index + 1] = numVertices - 1;
        triangles[index + 2] = 1;
      }
      // The second triangle facing the opposite direction.
      triangles[index + 3] = triangles[index];
      triangles[index + 4] = triangles[index + 2];
      triangles[index + 5] = triangles[index + 1];
    }
    // Construct a new mesh for the gizmo.
    Mesh directivityGizmoMesh = new Mesh();
    directivityGizmoMesh.hideFlags = HideFlags.DontSaveInEditor;
    directivityGizmoMesh.vertices = vertices;
    directivityGizmoMesh.triangles = triangles;
    directivityGizmoMesh.RecalculateNormals();
    // Draw the mesh.
    Vector3 scale = 2.0f * Mathf.Max(transform.lossyScale.x, transform.lossyScale.z) * Vector3.one;
    Gizmos.DrawMesh(directivityGizmoMesh, transform.position, transform.rotation, scale);
  }
#endif
}


text:
package com.digitalfingertip.mobisevera;

import com.digitalfingertip.mobisevera.activity.MobiseveraClaimActivity;
import com.digitalfingertip.mobisevera.activity.MobiseveraFrontpageActivity;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MobiseveraNaviAdapter extends ArrayAdapter<String> {

	private static final String TAG = "Sevedroid";
	private Activity context = null;
	private LayoutInflater lInflater = null;
	private float currentRotation = 0;
	private String [] strings = null;
	private int mSelectedEventID = 0;
	public MobiseveraNaviAdapter(Activity context, int textViewResourceId) {
		super(context, textViewResourceId);
		this.context = context;
	}

	public MobiseveraNaviAdapter(
			Activity parent,
			int listItemResourceId,
			String[] strings,
			int ... eventId
			) {
		super(parent, listItemResourceId, strings);
		//this.mSelectedPosition;
		this.context = parent;
		this.strings = strings;
		if(eventId != null && eventId.length != 0) {
			mSelectedEventID = eventId[0];
		}
	}

	public void turn(ImageView turnImg)
	{
	    RotateAnimation anim = new RotateAnimation(currentRotation, currentRotation + 30,
	            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,0.5f);
	    currentRotation = (currentRotation + 90) % 360;

	    anim.setInterpolator(new LinearInterpolator());
	    anim.setDuration(1000);
	    anim.setFillEnabled(true);

	    anim.setFillAfter(true);
	    turnImg.startAnimation(anim);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View res = null;
		if(convertView == null) {
			if(context != null) {
				lInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			}
			if(lInflater != null) {
				res = (View)lInflater.inflate(R.layout.mobisevera_list_item, parent, false);
			}
		} else {
			res = (View)convertView;
		}
		ImageView rightIconView = (ImageView)res.findViewById(R.id.list_item_icon_right);
		//This tests whether the class using the adapter wants to show some item as "expanded". For now
		//only means that it has a downward arrow instead of the right-pointing arrow.
		//we now a bit awkwardly need to list all of the combinations here, but TODO: find a better way
		if((context instanceof MobiseveraFrontpageActivity &&
				MobiseveraNaviContainer.isInExpandedState(MobiseveraNaviContainer.NAVI_FRONT_ACTIVITY, position)) ||
		(context instanceof MobiseveraClaimActivity &&
				MobiseveraNaviContainer.isInExpandedState(MobiseveraNaviContainer.MAIN_CLAIM_ACTIVITY, position)))
		{
			Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down);
			rightIconView.setImageBitmap(bm);
		} else {
			Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_right);
			rightIconView.setImageBitmap(bm);
		}
		TextView textContent = ((TextView)res.findViewById(R.id.list_item_content));
		Log.d(TAG,"Added string:"+strings[position]+" to position "+position);
		textContent.setText(strings[position]);
		return res;
	}

}


text:
HOVERBOARD.ServiceWorkerRegistration = (function () {
  'use strict';

  // Ensure we only attempt to register the SW once.
  var isAlreadyRegistered = false;

  var URL = 'service-worker.js';
  var SCOPE = './';

  var register = function () {
    if (!isAlreadyRegistered) {
      isAlreadyRegistered = true;

      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register(URL, {
          scope: SCOPE
        }).then(function (registration) {
          registration.onupdatefound = function () {
            // The updatefound event implies that registration.installing is set; see
            // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
            var installingWorker = registration.installing;

            installingWorker.onstatechange = function () {
              switch (installingWorker.state) {
                case 'installed':
                  if (!navigator.serviceWorker.controller) {
                    HOVERBOARD.Elements.Template.$.toast.showMessage(
                      'Caching complete! Future visits will work offline.');
                  }
                  break;

                case 'redundant':
                  throw Error('The installing service worker became redundant.');
              }
            };
          };
        }).catch(function (e) {
          HOVERBOARD.Analytics.trackError('navigator.serviceWorker.register() error', e);
          console.error('Service worker registration failed:', e);
        });
      }
    }
  };

  // Check to see if the service worker controlling the page at initial load
  // has become redundant, since this implies there's a new service worker with fresh content.
  if (navigator.serviceWorker && navigator.serviceWorker.controller) {
    navigator.serviceWorker.controller.onstatechange = function (event) {
      if (event.target.state === 'redundant') {
        // Define a handler that will be used for the next io-toast tap, at which point it
        // be automatically removed.
        var tapHandler = function () {
          window.location.reload();
        };

        if (HOVERBOARD.Elements && HOVERBOARD.Elements.Template &&
          HOVERBOARD.Elements.Template.$.toast.showMessage) {
          HOVERBOARD.Elements.Template.$.toast.showMessage(
            'A new version of this app is available.', tapHandler, 'Refresh',
            null, 0); // duration 0 indications shows the toast indefinitely.
        } else {
          tapHandler(); // Force reload if user never was shown the toast.
        }
      }
    };
  }

  return {
    register: register,
    URL: URL,
    SCOPE: SCOPE
  };
})();


text:
<?php

namespace PhpAbac\Manager;

use PhpAbac\Model\AbstractAttribute;

interface AttributeManagerInterface
{
    public function getAttribute(string $attributeId): AbstractAttribute;

    public function retrieveAttribute(AbstractAttribute $attribute, $user = null, $object = null, array $getter_params = []);
}


text:
using Messaging.Models;
using Messaging.Shared;
using System.Threading.Tasks;

namespace Messaging.Services.GithubService
{
    public interface IGithubService
    {
        Task<GithubQueryResult<Repository>> GetRepositoriesAsync(string query, int pageIndex = 1);
    }
}


text:
namespace Contracts
{
    using PeinearyDevelopment.Framework.BaseClassLibraries.Contracts;

    public class Country : DateRangeEffectiveContractBase<int>
    {
        public string FullName { get; set; }
        public string ShortName { get; set; }
        public string Alpha2Code { get; set; }
        public string Alpha3Code { get; set; }
        public int Iso3166Code { get; set; }
        public string PostalCodeRegex { get; set; }
        public string PhoneNumberRegex { get; set; }
    }
}


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.
 */

#ifndef SRC_INTERCONNECT_COORDINTERFACE_H_
#define SRC_INTERCONNECT_COORDINTERFACE_H_

#include <concurrency/ThreadManager.h>
#include <protocol/TCompactProtocol.h>
#include <server/TSimpleServer.h>
#include <sys/time.h>
#include <transport/TBufferTransports.h>
#include <transport/TServerSocket.h>
#include <transport/TServerTransport.h>
#include <transport/TSocket.h>
#include <transport/TTransport.h>
#include <transport/TTransportException.h>

#include <algorithm>  // std::random_shuffle
#include <chrono>
#include <cstdlib>  // std::rand, std::srand
#include <ctime>    // std::time
#include <map>
#include <memory>
#include <set>
#include <string>
#include <thread>
#include <vector>  // std::vector

#include "../Scan.h"
#include "../scanrequest/ScanIdentifier.h"
#include "Transport.h"
#include "data/constructs/IterInfo.h"
#include "data/constructs/configuration/Configuration.h"
#include "data/constructs/inputvalidation.h"
#include "data/constructs/scanstate.h"
#include "data/constructs/security/AuthInfo.h"
#include "data/constructs/tablet/TabletType.h"
#include "data/exceptions/ClientException.h"
#include "data/exceptions/IllegalArgumentException.h"
#include "data/extern/thrift/ClientService.h"
#include "data/extern/thrift/MasterClientService.h"
#include "data/extern/thrift/ThriftWrapper.h"
#include "data/extern/thrift/data_types.h"
#include "data/extern/thrift/master_types.h"
#include "data/extern/thrift/tabletserver_types.h"

namespace interconnect {

/**
 * Pure virtual class that represents the master interface
 *
 **/
class CoordinatorInterface {
 public:
  /**
   * Recreates the master client, usually upon error.
   **/
  virtual void recreateCoordinatorClient() = 0;
  /**
   * Recreates a thrift transporter. This will usually happen upon error
   * @return a new thrift transport
   **/
  virtual std::shared_ptr<apache::thrift::transport::TTransport>
  recreateTransport() = 0;
};

}  // namespace interconnect

#endif


text:
.class final Lcom/android/server/display/LocalDisplayAdapter;
.super Lcom/android/server/display/DisplayAdapter;
.source "LocalDisplayAdapter.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/server/display/LocalDisplayAdapter$HotplugDisplayEventReceiver;,
        Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;
    }
.end annotation

# static fields
.field private static final BUILT_IN_DISPLAY_IDS_TO_SCAN:[I = null

.field private static final TAG:Ljava/lang/String; = "LocalDisplayAdapter"

# instance fields
.field private final mDevices:Landroid/util/SparseArray;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/util/SparseArray",
            "<",
            "Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;",
            ">;"
        }
    .end annotation
.end field

.field private mHotplugReceiver:Lcom/android/server/display/LocalDisplayAdapter$HotplugDisplayEventReceiver;

.field private final mTempPhys:Landroid/view/Surface$PhysicalDisplayInfo;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 41
    const/4 v0, 0x2

    new-array v0, v0, [I

    fill-array-data v0, :array_0

    sput-object v0, Lcom/android/server/display/LocalDisplayAdapter;->BUILT_IN_DISPLAY_IDS_TO_SCAN:[I

    return-void

    nop

    :array_0
    .array-data 0x4
        0x0t 0x0t 0x0t 0x0t
        0x1t 0x0t 0x0t 0x0t
    .end array-data
.end method

.method public constructor <init>(Lcom/android/server/display/DisplayManagerService$SyncRoot;Landroid/content/Context;Landroid/os/Handler;Lcom/android/server/display/DisplayAdapter$Listener;)V
    .locals 6
    .parameter "syncRoot"
    .parameter "context"
    .parameter "handler"
    .parameter "listener"

    .prologue
    .line 55
    const-string v5, "LocalDisplayAdapter"

    move-object v0, p0

    move-object v1, p1

    move-object v2, p2

    move-object v3, p3

    move-object v4, p4

    invoke-direct/range {v0 .. v5}, Lcom/android/server/display/DisplayAdapter;-><init>(Lcom/android/server/display/DisplayManagerService$SyncRoot;Landroid/content/Context;Landroid/os/Handler;Lcom/android/server/display/DisplayAdapter$Listener;Ljava/lang/String;)V

    .line 46
    new-instance v0, Landroid/util/SparseArray;

    invoke-direct {v0}, Landroid/util/SparseArray;-><init>()V

    iput-object v0, p0, Lcom/android/server/display/LocalDisplayAdapter;->mDevices:Landroid/util/SparseArray;

    .line 50
    new-instance v0, Landroid/view/Surface$PhysicalDisplayInfo;

    invoke-direct {v0}, Landroid/view/Surface$PhysicalDisplayInfo;-><init>()V

    iput-object v0, p0, Lcom/android/server/display/LocalDisplayAdapter;->mTempPhys:Landroid/view/Surface$PhysicalDisplayInfo;

    .line 56
    return-void
.end method

.method static synthetic access$000(Lcom/android/server/display/LocalDisplayAdapter;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 38
    invoke-direct {p0}, Lcom/android/server/display/LocalDisplayAdapter;->scanDisplaysLocked()V

    return-void
.end method

.method private scanDisplaysLocked()V
    .locals 7

    .prologue
    .line 67
    sget-object v0, Lcom/android/server/display/LocalDisplayAdapter;->BUILT_IN_DISPLAY_IDS_TO_SCAN:[I

    .local v0, arr$:[I
    array-length v5, v0

    .local v5, len$:I
    const/4 v4, 0x0

    .local v4, i$:I
    :goto_0
    if-ge v4, v5, :cond_3

    aget v1, v0, v4

    .line 68
    .local v1, builtInDisplayId:I
    invoke-static {v1}, Landroid/view/Surface;->getBuiltInDisplay(I)Landroid/os/IBinder;

    move-result-object v3

    .line 69
    .local v3, displayToken:Landroid/os/IBinder;
    if-eqz v3, :cond_2

    iget-object v6, p0, Lcom/android/server/display/LocalDisplayAdapter;->mTempPhys:Landroid/view/Surface$PhysicalDisplayInfo;

    invoke-static {v3, v6}, Landroid/view/Surface;->getDisplayInfo(Landroid/os/IBinder;Landroid/view/Surface$PhysicalDisplayInfo;)Z

    move-result v6

    if-eqz v6, :cond_2

    .line 70
    iget-object v6, p0, Lcom/android/server/display/LocalDisplayAdapter;->mDevices:Landroid/util/SparseArray;

    invoke-virtual {v6, v1}, Landroid/util/SparseArray;->get(I)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;

    .line 71
    .local v2, device:Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;
    if-nez v2, :cond_1

    .line 73
    new-instance v2, Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;

    .end local v2           #device:Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;
    iget-object v6, p0, Lcom/android/server/display/LocalDisplayAdapter;->mTempPhys:Landroid/view/Surface$PhysicalDisplayInfo;

    invoke-direct {v2, p0, v3, v1, v6}, Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;-><init>(Lcom/android/server/display/LocalDisplayAdapter;Landroid/os/IBinder;ILandroid/view/Surface$PhysicalDisplayInfo;)V

    .line 74
    .restart local v2       #device:Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;
    iget-object v6, p0, Lcom/android/server/display/LocalDisplayAdapter;->mDevices:Landroid/util/SparseArray;

    invoke-virtual {v6, v1, v2}, Landroid/util/SparseArray;->put(ILjava/lang/Object;)V

    .line 75
    const/4 v6, 0x1

    invoke-virtual {p0, v2, v6}, Lcom/android/server/display/LocalDisplayAdapter;->sendDisplayDeviceEventLocked(Lcom/android/server/display/DisplayDevice;I)V

    .line 67
    :cond_0
    :goto_1
    add-int/lit8 v4, v4, 0x1

    goto :goto_0

    .line 76
    :cond_1
    iget-object v6, p0, Lcom/android/server/display/LocalDisplayAdapter;->mTempPhys:Landroid/view/Surface$PhysicalDisplayInfo;

    invoke-virtual {v2, v6}, Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;->updatePhysicalDisplayInfoLocked(Landroid/view/Surface$PhysicalDisplayInfo;)Z

    move-result v6

    if-eqz v6, :cond_0

    .line 78
    const/4 v6, 0x2

    invoke-virtual {p0, v2, v6}, Lcom/android/server/display/LocalDisplayAdapter;->sendDisplayDeviceEventLocked(Lcom/android/server/display/DisplayDevice;I)V

    goto :goto_1

    .line 81
    .end local v2           #device:Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;
    :cond_2
    iget-object v6, p0, Lcom/android/server/display/LocalDisplayAdapter;->mDevices:Landroid/util/SparseArray;

    invoke-virtual {v6, v1}, Landroid/util/SparseArray;->get(I)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;

    .line 82
    .restart local v2       #device:Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;
    if-eqz v2, :cond_0

    .line 84
    iget-object v6, p0, Lcom/android/server/display/LocalDisplayAdapter;->mDevices:Landroid/util/SparseArray;

    invoke-virtual {v6, v1}, Landroid/util/SparseArray;->remove(I)V

    .line 85
    const/4 v6, 0x3

    invoke-virtual {p0, v2, v6}, Lcom/android/server/display/LocalDisplayAdapter;->sendDisplayDeviceEventLocked(Lcom/android/server/display/DisplayDevice;I)V

    goto :goto_1

    .line 89
    .end local v1           #builtInDisplayId:I
    .end local v2           #device:Lcom/android/server/display/LocalDisplayAdapter$LocalDisplayDevice;
    .end local v3           #displayToken:Landroid/os/IBinder;
    :cond_3
    return-void
.end method

# virtual methods
.method public registerLocked()V
    .locals 2

    .prologue
    .line 60
    invoke-super {p0}, Lcom/android/server/display/DisplayAdapter;->registerLocked()V

    .line 62
    new-instance v0, Lcom/android/server/display/LocalDisplayAdapter$HotplugDisplayEventReceiver;

    invoke-virtual {p0}, Lcom/android/server/display/LocalDisplayAdapter;->getHandler()Landroid/os/Handler;

    move-result-object v1

    invoke-virtual {v1}, Landroid/os/Handler;->getLooper()Landroid/os/Looper;

    move-result-object v1

    invoke-direct {v0, p0, v1}, Lcom/android/server/display/LocalDisplayAdapter$HotplugDisplayEventReceiver;-><init>(Lcom/android/server/display/LocalDisplayAdapter;Landroid/os/Looper;)V

    iput-object v0, p0, Lcom/android/server/display/LocalDisplayAdapter;->mHotplugReceiver:Lcom/android/server/display/LocalDisplayAdapter$HotplugDisplayEventReceiver;

    .line 63
    invoke-direct {p0}, Lcom/android/server/display/LocalDisplayAdapter;->scanDisplaysLocked()V

    .line 64
    return-void
.end method


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
	<context:component-scan base-package="com.testclient" />
	<!-- 引入属性文件 -->
	<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<!-- <value>classpath:config.properties</value> -->
				<value>classpath:log4j.properties</value>
			</list>
		</property>
	</bean>

	<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	        <property name="locations">
	            	<list>
	                	<value>classpath:config.properties</value>
	            	</list>
	        </property>
    	</bean>
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
	        <property name="properties" ref="configProperties" />
	</bean>

	<bean id="QuartzApplicationLoader" lazy-init="false"
		depends-on="quartzScheduleMgrService" class="com.testclient.quartz.QuartzApplicationLoader">
	</bean>
	<bean class="com.testclient.utils.SocketOperationUtils" id="SocketOperationUtils">
		<constructor-arg  value="${url}"/>
	</bean>

</beans>