text:
// TnzBase includes
#include "tfxattributes.h"
#include "tfxutil.h"
#include "tmacrofx.h"
#include "toutputproperties.h"
#include "tparamcontainer.h"

// TnzLib includes
#include "toonz/txsheet.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/tcolumnfx.h"
#include "toonz/tcolumnfxset.h"
#include "toonz/fxdag.h"
#include "toonz/txshchildlevel.h"
#include "toonz/txshcell.h"
#include "toonz/txshleveltypes.h"
#include "toonz/txshlevelcolumn.h"
#include "toonz/txshpalettecolumn.h"
#include "toonz/txshzeraryfxcolumn.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/dpiscale.h"
#include "toonz/tcamera.h"
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
#include "toonz/plasticdeformerfx.h"
#include "toonz/stage.h"
#include "toonz/preferences.h"
#include "ttzpimagefx.h"

#include "../stdfx/motionawarebasefx.h"

#include "toonz/scenefx.h"

/*
  TODO: Some parts of the following render-tree building procedure should be
  revised. In particular,
        there is scarce support for frame-shifting fxs, whenever the frame-shift
  can be resolved
        only during rendering (as is the case for ParticlesFx).
*/

//***************************************************************************************************
//    TimeShuffleFx  definition
//***************************************************************************************************

//! TimeShuffleFx is the rendering-tree equivalent of a sub-xsheet column.
/*!
  TimeShuffleFx is a special-purpose fx which is used in render-tree building
procedures
  to simulate the effect of a sub-xsheet.
\n\n
  A rendering tree is a fully expanded tree that mixes implicit xsheet nesting
with
  the explicit fxs dag <I> for a specific frame <\I>. Since the frame the tree
is developed from
  is fixed, a sub-xsheet can be seen as a <I> frame setter <\I> fx.
*/

class TimeShuffleFx final : public TRasterFx {
  FX_DECLARATION(TimeShuffleFx)

private:
  int m_frame;                 //!< Frame this fx redirects to
  TFxTimeRegion m_timeRegion;  //!< Input (outer) valid column frame range
  TRasterFxPort m_port;        //!< Input port

public:
  TimeShuffleFx() : TRasterFx(), m_frame(0), m_timeRegion() {
    addInputPort("source", m_port);
  }
  ~TimeShuffleFx() {}

  TFx *clone(bool recursive = true) const override {
    TimeShuffleFx *fx = dynamic_cast<TimeShuffleFx *>(TFx::clone(recursive));
    assert(fx);

    fx->setFrame(m_frame);
    fx->setTimeRegion(getTimeRegion());

    return fx;
  }

  int getFrame() const { return m_frame; }
  void setFrame(int frame) { m_frame = frame; }

  void setTimeRegion(const TFxTimeRegion &timeRegion) {
    m_timeRegion = timeRegion;
  }
  TFxTimeRegion getTimeRegion() const override { return m_timeRegion; }

  bool canHandle(const TRenderSettings &info, double frame) override {
    return true;
  }

  std::string getPluginId() const override { return std::string(); }

  void compute(TFlash &flash, int frame) override {
    if (!m_port.isConnected()) return;

    TRasterFxP(m_port.getFx())->compute(flash, m_frame);
  }

  void doCompute(TTile &tile, double frame,
                 const TRenderSettings &ri) override {
    if (!m_port.isConnected()) {
      tile.getRaster()->clear();
      return;
    }

    // Exchange frame with the stored one
    TRasterFxP(m_port.getFx())->compute(tile, m_frame, ri);
  }

  bool doGetBBox(double frame, TRectD &bbox,
                 const TRenderSettings &info) override {
    if (!m_port.isConnected()) return false;

    return TRasterFxP(m_port.getFx())->doGetBBox(m_frame, bbox, info);
  }

  std::string getAlias(double frame,
                       const TRenderSettings &info) const override {
    return TRasterFx::getAlias(m_frame, info);
  }

  void doDryCompute(TRectD &rect, double frame,
                    const TRenderSettings &info) override {
    if (m_port.isConnected())
      TRasterFxP(m_port.getFx())->dryCompute(rect, m_frame, info);
  }

private:
  // not implemented
  TimeShuffleFx(const TimeShuffleFx &);
  TimeShuffleFx &operator=(const TimeShuffleFx &);
};

FX_IDENTIFIER_IS_HIDDEN(TimeShuffleFx, "timeShuffleFx")

//***************************************************************************************************
//    AffineFx  definition
//***************************************************************************************************

//! AffineFx is a specialization of TGeometryFx which implements animated or
//! stage-controlled affines
/*!
  This specific implementation of TGeometryFx is needed to deal with those
  affines which are best
  \b not resolved during the rendering-tree expansion procedure.
*/

class AffineFx final : public TGeometryFx {
  FX_DECLARATION(AffineFx)

private:
  TXsheet *m_xsheet;            //!< Xsheet owning m_stageObject
  TStageObject *m_stageObject;  //!< The stage object this AffineFx refers to
  TRasterFxPort m_input;        //!< The input port

public:
  AffineFx() : m_xsheet(0), m_stageObject(0) {
    addInputPort("source", m_input);
    setName(L"AffineFx");
  }
  AffineFx(TXsheet *xsh, TStageObject *pegbar)
      : m_xsheet(xsh), m_stageObject(pegbar) {
    addInputPort("source", m_input);
    setName(L"AffineFx");
  }
  ~AffineFx() {}

  TFx *clone(bool recursive = true) const override {
    AffineFx *fx = dynamic_cast<AffineFx *>(TFx::clone(recursive));
    assert(fx);
    fx->m_stageObject = m_stageObject;
    fx->m_xsheet      = m_xsheet;
    return fx;
  }

  bool canHandle(const TRenderSettings &info, double frame) override {
    return true;
  }

  TAffine getPlacement(double frame) override {
    TAffine objAff = m_stageObject->getPlacement(frame);

    double objZ        = m_stageObject->getZ(frame);
    double objNoScaleZ = m_stageObject->getGlobalNoScaleZ();

    TStageObjectId cameraId =
        m_xsheet->getStageObjectTree()->getCurrentCameraId();
    TStageObject *camera = m_xsheet->getStageObject(cameraId);
    TAffine cameraAff    = camera->getPlacement(frame);
    double cameraZ       = camera->getZ(frame);

    TAffine aff;
    bool isVisible = TStageObject::perspective(aff, cameraAff, cameraZ, objAff,
                                               objZ, objNoScaleZ);

    if (!isVisible)
      return TAffine();  // uh oh
    else
      return aff;
  }

  TAffine getParentPlacement(double frame) override {
    return m_stageObject->getPlacement(frame);
  }

  std::string getPluginId() const override { return std::string(); }

private:
  // not implemented
  AffineFx(const AffineFx &);
  AffineFx &operator=(const AffineFx &);
};

FX_IDENTIFIER_IS_HIDDEN(AffineFx, "affineFx")

//***************************************************************************************************
//    PlacedFx  definition
//***************************************************************************************************

//! PlacedFx is the enriched form of a TRasterFx during render-tree building.
class PlacedFx {
public:
  double m_z;         //!< Z value for this fx's column
  double m_so;        //!< Same as above, for stacking order
  int m_columnIndex;  //!< This fx's column index

  TFxP m_fx;      //!< The referenced fx
  TAffine m_aff;  //!<

  TFxPort *m_leftXsheetPort;

public:
  PlacedFx()
      : m_z(0)
      , m_so(0)
      , m_columnIndex(-1)
      , m_fx(0)
      , m_aff()
      , m_leftXsheetPort(0) {}
  explicit PlacedFx(const TFxP &fx)
      : m_z(0)
      , m_so(0)
      , m_columnIndex(-1)
      , m_fx(fx)
      , m_aff()
      , m_leftXsheetPort(0) {}

  bool operator<(const PlacedFx &pf) const {
    return (m_z < pf.m_z)
               ? true
               : (m_z > pf.m_z)
                     ? false
                     : (m_so < pf.m_so)
                           ? true
                           : (m_so > pf.m_so)
                                 ? false
                                 : (m_columnIndex < pf.m_columnIndex);
  }

  TFxP makeFx() {
    return (!m_fx)
               ? TFxP()
               : (m_aff == TAffine()) ? m_fx : TFxUtil::makeAffine(m_fx, m_aff);
  }
};

//***************************************************************************************************
//    Local namespace
//***************************************************************************************************

namespace {

TFxP timeShuffle(TFxP fx, int frame, TFxTimeRegion timeRegion) {
  TimeShuffleFx *timeShuffle = new TimeShuffleFx();

  timeShuffle->setFrame(frame);
  timeShuffle->setTimeRegion(timeRegion);
  if (!timeShuffle->connect("source", fx.getPointer()))
    assert(!"Could not connect ports!");

  return timeShuffle;
};

}  // namespace

//***************************************************************************************************
//    Column-related functions
//***************************************************************************************************

bool getColumnPlacement(TAffine &aff, TXsheet *xsh, double row, int col,
                        bool isPreview) {
  if (col < 0) return false;
  TStageObject *pegbar = xsh->getStageObject(TStageObjectId::ColumnId(col));
  TAffine objAff       = pegbar->getPlacement(row);
  double objZ          = pegbar->getZ(row);
  double noScaleZ      = pegbar->getGlobalNoScaleZ();

  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId           = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *camera = xsh->getStageObject(cameraId);
  TAffine cameraAff    = camera->getPlacement(row);
  double cameraZ       = camera->getZ(row);

  bool isVisible = TStageObject::perspective(aff, cameraAff, cameraZ, objAff,
                                             objZ, noScaleZ);

  return isVisible;
}

//-------------------------------------------------------------------

static bool getColumnPlacement(PlacedFx &pf, TXsheet *xsh, double row, int col,
                               bool isPreview) {
  if (col < 0) return false;
  TStageObject *pegbar = xsh->getStageObject(TStageObjectId::ColumnId(col));
  TAffine objAff       = pegbar->getPlacement(row);
  pf.m_z               = pegbar->getZ(row);
  pf.m_so              = pegbar->getSO(row);

  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId           = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *camera = xsh->getStageObject(cameraId);
  TAffine cameraAff    = camera->getPlacement(row);
  double cameraZ       = camera->getZ(row);

  bool isVisible =
      TStageObject::perspective(pf.m_aff, cameraAff, cameraZ, objAff, pf.m_z,
                                pegbar->getGlobalNoScaleZ());

  return isVisible;
}

//-------------------------------------------------------------------
/*-- Objectの位置を得る --*/
static bool getStageObjectPlacement(TAffine &aff, TXsheet *xsh, double row,
                                    TStageObjectId &id, bool isPreview) {
  TStageObject *pegbar = xsh->getStageObjectTree()->getStageObject(id, false);
  if (!pegbar) return false;

  TAffine objAff  = pegbar->getPlacement(row);
  double objZ     = pegbar->getZ(row);
  double noScaleZ = pegbar->getGlobalNoScaleZ();

  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId           = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *camera = xsh->getStageObject(cameraId);
  TAffine cameraAff    = camera->getPlacement(row);
  double cameraZ       = camera->getZ(row);

  bool isVisible = TStageObject::perspective(aff, cameraAff, cameraZ, objAff,
                                             objZ, noScaleZ);

  return isVisible;
}

/*-- typeとindexからStageObjectIdを得る --*/
namespace {
TStageObjectId getMotionObjectId(MotionObjectType type, int index) {
  switch (type) {
  case OBJTYPE_OWN:
    return TStageObjectId::NoneId;
    break;
  case OBJTYPE_COLUMN:
    if (index == 0) return TStageObjectId::NoneId;
    return TStageObjectId::ColumnId(index - 1);
    break;
  case OBJTYPE_PEGBAR:
    if (index == 0) return TStageObjectId::NoneId;
    return TStageObjectId::PegbarId(index - 1);
    break;
  case OBJTYPE_TABLE:
    return TStageObjectId::TableId;
    break;
  case OBJTYPE_CAMERA:
    if (index == 0) return TStageObjectId::NoneId;
    return TStageObjectId::CameraId(index - 1);
    break;
  }

  return TStageObjectId::NoneId;
}
};  // namespace

//-------------------------------------------------------------------

static TPointD getColumnSpeed(TXsheet *xsh, double row, int col,
                              bool isPreview) {
  TAffine aff;
  TPointD a, b;
  const double h = 0.001;
  getColumnPlacement(aff, xsh, row + h, col, isPreview);

  /*-- カラムと、カメラの動きに反応 --*/
  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId           = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *camera = xsh->getStageObject(cameraId);
  TAffine cameraAff    = camera->getPlacement(row + h);
  a                    = aff * TPointD(-cameraAff.a13, -cameraAff.a23);

  aff = TAffine();
  getColumnPlacement(aff, xsh, row - h, col, isPreview);

  cameraAff = camera->getPlacement(row - h);
  b         = aff * TPointD(-cameraAff.a13, -cameraAff.a23);

  return (b - a) * (0.5 / h);
}

//-------------------------------------------------------------------
/*-- オブジェクトの軌跡を、基準点との差分で得る
        objectId: 移動の参考にするオブジェクト。自分自身の場合はNoneId
--*/
static QList<TPointD> getColumnMotionPoints(TXsheet *xsh, double row, int col,
                                            TStageObjectId &objectId,
                                            bool isPreview, double shutterStart,
                                            double shutterEnd,
                                            int traceResolution) {
  /*-- 前後フレームが共に0なら空のリストを返す --*/
  if (shutterStart == 0.0 && shutterEnd == 0.0) return QList<TPointD>();

  /*-- 現在のカメラを得る --*/
  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId           = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *camera = xsh->getStageObject(cameraId);
  TAffine dpiAff       = getDpiAffine(camera->getCamera());

  /*-- 基準点の位置を得る --*/
  TAffine aff;

  /*-- objectIdが有効なものかどうかチェック --*/
  bool useOwnMotion = false;
  if (objectId == TStageObjectId::NoneId ||
      !xsh->getStageObjectTree()->getStageObject(objectId, false)) {
    getColumnPlacement(aff, xsh, row, col, isPreview);
    useOwnMotion = true;
  } else {
    getStageObjectPlacement(aff, xsh, row, objectId, isPreview);
  }

  TAffine cameraAff = camera->getPlacement(row);
  TPointD basePos =
      dpiAff.inv() * aff * TPointD(-cameraAff.a13, -cameraAff.a23);

  /*-- 結果を収めるリスト --*/
  QList<TPointD> points;
  /*-- 軌跡点間のフレーム間隔 --*/
  double dFrame = (shutterStart + shutterEnd) / (double)traceResolution;
  /*-- 各点の位置を、基準点との差分で格納していく --*/
  for (int i = 0; i <= traceResolution; i++) {
    /*-- 基準位置とのフレーム差 --*/
    double frameOffset = -shutterStart + dFrame * (double)i;
    /*-- 基準位置とのフレーム差が無ければ、基準点に一致するので差分は0を入れる
     * --*/
    if (frameOffset == 0.0) {
      points.append(TPointD(0.0, 0.0));
      continue;
    }

    /*-- 自分自身の動きを使うか、別オブジェクトの動きを使うか --*/
    if (useOwnMotion)
      getColumnPlacement(aff, xsh, row + frameOffset, col, isPreview);
    else
      getStageObjectPlacement(aff, xsh, row + frameOffset, objectId, isPreview);

    TAffine cameraAff = camera->getPlacement(row + frameOffset);
    TPointD tmpPos =
        dpiAff.inv() * aff * TPointD(-cameraAff.a13, -cameraAff.a23);

    /*-- 基準位置との差を記録 --*/
    points.append(tmpPos - basePos);
  }
  return points;
}

//***************************************************************************************************
//    FxBuilder  definition
//***************************************************************************************************

class FxBuilder {
public:
  ToonzScene *m_scene;
  TXsheet *m_xsh;
  TAffine m_cameraAff;
  double m_cameraZ;
  double m_frame;
  int m_whichLevels;
  bool m_isPreview;
  bool m_expandXSheet;

  // in the makePF() methods m_particleDescendentCount>0 iff the TFx* is an
  // ancestor
  // (at least) of a particle Fx
  int m_particleDescendentCount;

public:
  FxBuilder(ToonzScene *scene, TXsheet *xsh, double frame, int whichLevels,
            bool isPreview = false, bool expandXSheet = true);

  TFxP buildFx();
  TFxP buildFx(const TFxP &root, BSFX_Transforms_Enum transforms);

  PlacedFx makePF(TLevelColumnFx *fx);
  PlacedFx makePF(TPaletteColumnFx *fx);
  PlacedFx makePF(TZeraryColumnFx *fx);
  PlacedFx makePF(TXsheetFx *fx);
  PlacedFx makePFfromUnaryFx(TFx *fx);
  PlacedFx makePFfromGenericFx(TFx *fx);
  PlacedFx makePF(TFx *fx);

  TFxP getFxWithColumnMovements(const PlacedFx &pf);

  bool addPlasticDeformerFx(PlacedFx &pf);
};

//===================================================================

FxBuilder::FxBuilder(ToonzScene *scene, TXsheet *xsh, double frame,
                     int whichLevels, bool isPreview, bool expandXSheet)
    : m_scene(scene)
    , m_xsh(xsh)
    , m_frame(frame)
    , m_whichLevels(whichLevels)
    , m_isPreview(isPreview)
    , m_expandXSheet(expandXSheet)
    , m_particleDescendentCount(0) {
  TStageObjectId cameraId;
  if (m_isPreview)
    cameraId = m_xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId = m_xsh->getStageObjectTree()->getCurrentCameraId();

  TStageObject *camera = m_xsh->getStageObject(cameraId);
  m_cameraAff          = camera->getPlacement(m_frame);
  m_cameraZ            = camera->getZ(m_frame);
}

//-------------------------------------------------------------------

TFxP FxBuilder::buildFx() {
  TFx *outputFx = m_xsh->getFxDag()->getOutputFx(0);
  if (!outputFx || outputFx->getInputPortCount() != 1 ||
      outputFx->getInputPort(0)->getFx() == 0)
    return TFxP();

  outputFx->setName(L"OutputFx");

  assert(m_particleDescendentCount == 0);
  PlacedFx pf = makePF(outputFx->getInputPort(0)->getFx());
  assert(m_particleDescendentCount == 0);

  TAffine cameraFullAff = m_cameraAff * TScale((1000 + m_cameraZ) / 1000);
  return TFxUtil::makeAffine(pf.makeFx(), cameraFullAff.inv());
}

//-------------------------------------------------------------------

TFxP FxBuilder::buildFx(const TFxP &root, BSFX_Transforms_Enum transforms) {
  assert(m_particleDescendentCount == 0);
  PlacedFx pf = makePF(root.getPointer());
  assert(m_particleDescendentCount == 0);

  TFxP fx = (transforms & BSFX_COLUMN_TR) ? pf.makeFx() : pf.m_fx;
  if (transforms & BSFX_CAMERA_TR) {
    TAffine cameraFullAff = m_cameraAff * TScale((1000 + m_cameraZ) / 1000);
    fx                    = TFxUtil::makeAffine(fx, cameraFullAff.inv());
  }

  return fx;
}

//-------------------------------------------------------------------

TFxP FxBuilder::getFxWithColumnMovements(const PlacedFx &pf) {
  TFxP fx = pf.m_fx;
  if (!fx) return fx;

  if (pf.m_columnIndex == -1) return pf.m_fx;

  TStageObjectId id    = TStageObjectId::ColumnId(pf.m_columnIndex);
  TStageObject *pegbar = m_xsh->getStageObject(id);

  AffineFx *affFx = new AffineFx(m_xsh, pegbar);
  affFx->getInputPort(0)->setFx(fx.getPointer());

  return affFx;
}

//-------------------------------------------------------------------

bool FxBuilder::addPlasticDeformerFx(PlacedFx &pf) {
  TStageObject *obj =
      m_xsh->getStageObject(TStageObjectId::ColumnId(pf.m_columnIndex));
  TStageObjectId parentId(obj->getParent());

  if (parentId.isColumn() && obj->getParentHandle()[0] != 'H') {
    const SkDP &sd =
        m_xsh->getStageObject(parentId)->getPlasticSkeletonDeformation();

    const TXshCell &parentCell = m_xsh->getCell(m_frame, parentId.getIndex());
    TXshSimpleLevel *parentSl  = parentCell.getSimpleLevel();

    if (sd && parentSl && (parentSl->getType() == MESH_XSHLEVEL)) {
      // Plastic Deformer case - add the corresponding fx,
      // absorb the dpi and local column placement affines

      PlasticDeformerFx *plasticFx = new PlasticDeformerFx;
      plasticFx->m_xsh             = m_xsh;
      plasticFx->m_col             = parentId.getIndex();
      plasticFx->m_texPlacement    = obj->getLocalPlacement(m_frame);

      if (!plasticFx->connect("source", pf.m_fx.getPointer()))
        assert(!"Could not connect ports!");

      pf.m_fx  = plasticFx;
      pf.m_aff = pf.m_aff * plasticFx->m_texPlacement.inv();

      return true;
    }
  }

  return false;
}

//-------------------------------------------------------------------

PlacedFx FxBuilder::makePF(TFx *fx) {
  if (!fx) return PlacedFx();

  if (TLevelColumnFx *lcfx = dynamic_cast<TLevelColumnFx *>(fx))
    return makePF(lcfx);
  else if (TPaletteColumnFx *pcfx = dynamic_cast<TPaletteColumnFx *>(fx))
    return makePF(pcfx);
  else if (TZeraryColumnFx *zcfx = dynamic_cast<TZeraryColumnFx *>(fx))
    return makePF(zcfx);
  else if (TXsheetFx *xsfx = dynamic_cast<TXsheetFx *>(fx))
    return makePF(xsfx);
  else if (fx->getInputPortCount() == 1)
    return makePFfromUnaryFx(fx);
  else
    return makePFfromGenericFx(fx);
}

//-------------------------------------------------------------------

PlacedFx FxBuilder::makePF(TXsheetFx *fx) {
  if (!m_expandXSheet)  // Xsheet expansion is typically blocked for render-tree
                        // building of
    return PlacedFx(fx);  // post-xsheet fxs only.

  // Expand the render-tree from terminal fxs
  TFxSet *fxs = m_xsh->getFxDag()->getTerminalFxs();
  int m       = fxs->getFxCount();
  if (m == 0) return PlacedFx();

  std::vector<PlacedFx> pfs(m);
  int i;
  for (i = 0; i < m; i++) {
    // Expand each terminal fx
    TFx *fx = fxs->getFx(i);
    assert(fx);
    pfs[i] = makePF(fx);  // Builds the sub-render-trees here
  }

  /*--
   * Xsheetに複数ノードが繋がっていた場合、PlacedFxの条件に従ってOverノードの付く順番を決める
   * --*/
  std::sort(pfs.begin(),
            pfs.end());  // Sort each terminal depending on Z/SO/Column index

  // Compose them in a cascade of overs (or affines 'leftXsheetPort' cases)
  TFxP currentFx =
      pfs[0].makeFx();  // Adds an NaAffineFx if pf.m_aff is not the identity
  for (i = 1; i < m; i++) {
    TFxP fx = pfs[i].makeFx();  // See above
    if (pfs[i].m_leftXsheetPort) {
      // LeftXsheetPort cases happen for those fxs like Add, Multiply, etc that
      // declare an xsheet-like input port.
      // That is, all terminal fxs below ours are attached COMPOSED to enter the
      // fx's leftXsheet input port.

      TFxP inputFx = currentFx;
      inputFx      = TFxUtil::makeAffine(inputFx, pfs[i].m_aff.inv());
      pfs[i].m_leftXsheetPort->setFx(inputFx.getPointer());
      currentFx = fx;
    } else {
      if (Preferences::instance()
              ->isShowRasterImagesDarkenBlendedInViewerEnabled())
        currentFx = TFxUtil::makeDarken(currentFx, fx);
      else
        currentFx = TFxUtil::makeOver(currentFx, fx);  // Common over case
    }
  }

  return PlacedFx(currentFx);
}

//-------------------------------------------------------------------

//! Creates and returns a PlacedFx for a TLevelColumnFx.
/*
  Fxs under a ParticlesFx node seem to have special treatment - that is,
  empty column cells are still attached to a not-empty PlacedFx.

  This must be a remnant of old Toonz code, that should no longer remain here -
  in fact, well, you can only extract an empty render from an empty column!
  So why bother?
*/
PlacedFx FxBuilder::makePF(TLevelColumnFx *lcfx) {
  assert(m_scene);
  assert(lcfx);
  assert(lcfx->getColumn());
  if (!lcfx || !lcfx->getColumn()) return PlacedFx();

  if (!lcfx->getColumn()->isPreviewVisible())  // This is the 'eye' icon
                                               // property in the column header
                                               // interface
    return PlacedFx();  // that disables rendering of this particular column

  // Retrieve the corresponding xsheet cell to build up
  /*-- 現在のフレームのセルを取得 --*/
  TXshCell cell  = lcfx->getColumn()->getCell(tfloor(m_frame));
  int levelFrame = cell.m_frameId.getNumber() - 1;

  /*--  ParticlesFxに繋がっておらず、空セルの場合は 中身無しを返す --*/
  if (m_particleDescendentCount == 0 && cell.isEmpty()) return PlacedFx();

  if (m_whichLevels == TOutputProperties::AnimatedOnly) {
    // In case only 'animated levels' are selected to be rendered, exclude all
    // 'backgrounds' - that is,
    // fullcolor levels...

    // Still, I wonder if this is still used in Toonz. I don't remember seeing
    // it anywhere :\ ?

    TXshLevel *xl = cell.m_level.getPointer();

    /*-- ParticleFxのTextureポートに繋がっていない場合 --*/
    if (m_particleDescendentCount == 0) {
      if (!xl ||
          xl->getType() != PLI_XSHLEVEL && xl->getType() != TZP_XSHLEVEL &&
              xl->getType() != CHILD_XSHLEVEL)
        return PlacedFx();
    }
    /*-- ParticleFxのTextureポートに繋がっている場合 --*/
    else {
      if (xl && xl->getType() != PLI_XSHLEVEL &&
          xl->getType() != TZP_XSHLEVEL && xl->getType() != CHILD_XSHLEVEL)
        return PlacedFx();
    }
  }

  // Build a PlacedFx for the column - start with the standard version for
  // common (image) levels
  PlacedFx pf;
  pf.m_columnIndex = lcfx->getColumn()->getIndex();
  pf.m_fx          = lcfx;

  // Build column placement
  bool columnVisible =
      getColumnPlacement(pf, m_xsh, m_frame, pf.m_columnIndex, m_isPreview);

  /*-- subXsheetのとき、その中身もBuildFxを実行 --*/
  if (!cell.isEmpty() && cell.m_level->getChildLevel()) {
    // Treat the sub-xsheet case - build the sub-render-tree and reassign stuff
    // to pf
    TXsheet *xsh = cell.m_level->getChildLevel()->getXsheet();

    // Build the sub-render-tree
    FxBuilder builder(m_scene, xsh, levelFrame, m_whichLevels, m_isPreview);

    // Then, add the TimeShuffleFx
    pf.m_fx = timeShuffle(builder.buildFx(), levelFrame, lcfx->getTimeRegion());
    pf.m_fx->setIdentifier(lcfx->getIdentifier());
    pf.m_fx->getAttributes()->passiveCacheDataIdx() =
        lcfx->getAttributes()->passiveCacheDataIdx();

    // If the level should sustain a Plastic deformation, add the corresponding
    // fx
    addPlasticDeformerFx(pf);
  }

  if (columnVisible) {
    // Column is visible, alright
    TXshSimpleLevel *sl = cell.isEmpty() ? 0 : cell.m_level->getSimpleLevel();
    if (sl) {
      // If the level should sustain a Plastic deformation, add the
      // corresponding fx
      if (!addPlasticDeformerFx(pf)) {
        // Common (image) level case - add an NaAffineFx to compensate for the
        // image's dpi
        TAffine dpiAff = ::getDpiAffine(
            sl, cell.m_frameId, true);  // true stands for 'force full-sampling'
        pf.m_fx = TFxUtil::makeAffine(pf.m_fx, dpiAff);
        if (pf.m_fx) pf.m_fx->setName(L"LevelColumn AffineFx");
      }
    } else {
      // Okay, weird code ensues. This is what happens on non-common image
      // cases, which should be:

      //  1. Sub-Xsheet cases - and it really shouldn't
      //  2. Empty cell cases - with m_particles_blabla > 0; and again I don't
      //  get why on earth this should happen...

      // Please, note that (1) is a bug, although it happens when inserting a
      // common level and a sub-xsh
      // level in the same column...

      // when a cell not exists, there is no way to keep the dpi of the image!
      // in this case it is kept the dpi of the first cell not empty in the
      // column!
      /*--
       * 空セルのとき、Dpiアフィン変換には、その素材が入っている一番上のセルのものを使う
       * --*/
      TXshLevelColumn *column = lcfx->getColumn();
      int i;
      for (i = 0; i < column->getRowCount(); i++) {
        TXshCell dpiCell = lcfx->getColumn()->getCell(i);
        if (dpiCell.isEmpty()) continue;

        sl = dpiCell.m_level->getSimpleLevel();
        if (!sl) break;

        TAffine dpiAff = ::getDpiAffine(sl, dpiCell.m_frameId, true);
        pf.m_fx        = TFxUtil::makeAffine(pf.m_fx, dpiAff);
        break;
      }
    }

    return pf;
  } else
    return PlacedFx();
}

//-------------------------------------------------------------------

PlacedFx FxBuilder::makePF(TPaletteColumnFx *pcfx) {
  assert(pcfx);
  assert(pcfx->getColumn());
  if (!pcfx->getColumn()->isPreviewVisible()) return PlacedFx();

  TXshCell cell = pcfx->getColumn()->getCell(tfloor(m_frame));
  if (cell.isEmpty()) return PlacedFx();

  PlacedFx pf;
  pf.m_columnIndex = pcfx->getColumn()->getIndex();
  pf.m_fx          = pcfx;

  return pf;
}

//-------------------------------------------------------------------

PlacedFx FxBuilder::makePF(TZeraryColumnFx *zcfx) {
  assert(zcfx);
  assert(zcfx->getColumn());

  if (!zcfx->getColumn()->isPreviewVisible())  // ...
    return PlacedFx();

  if (!zcfx->getAttributes()->isEnabled())  // ...
    return PlacedFx();

  TFx *fx = zcfx->getZeraryFx();
  if (!fx || !fx->getAttributes()->isEnabled())  // ... Perhaps these shouldn't
                                                 // be tested altogether? Only 1
                                                 // truly works !
    return PlacedFx();

  TXshCell cell = zcfx->getColumn()->getCell(tfloor(m_frame));
  if (cell.isEmpty()) return PlacedFx();

  // Build
  PlacedFx pf;
  pf.m_columnIndex = zcfx->getColumn()->getIndex();
  pf.m_fx          = fx->clone(
      false);  // Detach the fx with a clone. Why? It's typically done to
               // build fx connections in the render-tree freely. Here, it's
               // used just for particles, I guess...
  // Deal with input sub-trees
  for (int i = 0; i < fx->getInputPortCount(); ++i) {
    // Note that only particles should end up here, currently
    if (TFxP inputFx = fx->getInputPort(i)->getFx()) {
      PlacedFx inputPF;

      // if the effect is a particle fx, it is necessary to consider also empty
      // cells
      // this causes a connection with the effect and a level also with empty
      // cells.
      if (fx->getFxType() == "STD_particlesFx" ||
          fx->getFxType() == "STD_iwa_TiledParticlesFx" ||
          fx->getFxType() == "STD_tiledParticlesFx") {
        m_particleDescendentCount++;
        inputPF = makePF(inputFx.getPointer());
        m_particleDescendentCount--;
      } else
        inputPF = makePF(inputFx.getPointer());

      inputFx = getFxWithColumnMovements(inputPF);
      if (!inputFx) continue;

      inputFx = TFxUtil::makeAffine(inputFx, pf.m_aff.inv());
      if (!pf.m_fx->connect(pf.m_fx->getInputPortName(i), inputFx.getPointer()))
        assert(!"Could not connect ports!");
    }
  }

  // Add the column placement NaAffineFx
  if (getColumnPlacement(pf, m_xsh, m_frame, pf.m_columnIndex, m_isPreview))
    return pf;
  else
    return PlacedFx();
}

//-------------------------------------------------------------------

PlacedFx FxBuilder::makePFfromUnaryFx(TFx *fx) {
  assert(!dynamic_cast<TLevelColumnFx *>(fx));
  assert(!dynamic_cast<TZeraryColumnFx *>(fx));
  assert(fx->getInputPortCount() == 1);

  TFx *inputFx = fx->getInputPort(0)->getFx();
  if (!inputFx) return PlacedFx();

  PlacedFx pf = makePF(inputFx);  // Build sub-render-tree
  if (!pf.m_fx) return PlacedFx();

  if (fx->getAttributes()->isEnabled()) {
    // Fx is enabled, so insert it in the render-tree

    // Clone this fx necessary
    if (pf.m_fx.getPointer() != inputFx ||  // As in an earlier makePF, clone
                                            // whenever input connections have
                                            // changed
        fx->getAttributes()->isSpeedAware() ||  // In the 'speedAware' case,
                                                // we'll alter the fx's
                                                // attributes (see below)
        dynamic_cast<TMacroFx *>(fx))  // As for macros... I'm not sure. Not
                                       // even who wrote this *understood*
    // why - it just solved a bug  X( . Investigate!
    {
      fx = fx->clone(false);
      if (!fx->connect(fx->getInputPortName(0), pf.m_fx.getPointer()))
        assert(!"Could not connect ports!");
    }

    pf.m_fx = fx;

    if (fx->getAttributes()->isSpeedAware()) {
      /*-- スピードでなく、軌跡を取得する場合 --*/
      MotionAwareBaseFx *mabfx = dynamic_cast<MotionAwareBaseFx *>(fx);
      if (mabfx) {
        double shutterStart = mabfx->getShutterStart()->getValue(m_frame);
        double shutterEnd   = mabfx->getShutterEnd()->getValue(m_frame);
        int traceResolution = mabfx->getTraceResolution()->getValue();
        /*-- 移動の参考にするオブジェクトの取得。自分自身の場合はNoneId --*/
        MotionObjectType type   = mabfx->getMotionObjectType();
        int index               = mabfx->getMotionObjectIndex()->getValue();
        TStageObjectId objectId = getMotionObjectId(type, index);
        fx->getAttributes()->setMotionPoints(getColumnMotionPoints(
            m_xsh, m_frame, pf.m_columnIndex, objectId, m_isPreview,
            shutterStart, shutterEnd, traceResolution));
      } else {
        TPointD speed =
            getColumnSpeed(m_xsh, m_frame, pf.m_columnIndex, m_isPreview);
        fx->getAttributes()->setSpeed(speed);
      }
    }
  }

  return pf;
}

//-------------------------------------------------------------------

PlacedFx FxBuilder::makePFfromGenericFx(TFx *fx) {
  assert(!dynamic_cast<TLevelColumnFx *>(fx));
  assert(!dynamic_cast<TZeraryColumnFx *>(fx));

  PlacedFx pf;

  if (!fx->getAttributes()->isEnabled()) {
    if (fx->getInputPortCount() == 0) return PlacedFx();

    TFxP inputFx = fx->getInputPort(fx->getPreferredInputPort())->getFx();
    if (inputFx) return makePF(inputFx.getPointer());

    return pf;
  }

  // Multi-input fxs are always cloned - since at least one of its input ports
  // will have an NaAffineFx
  // injected just before its actual input fx.
  pf.m_fx = fx->clone(false);

  bool firstInput = true;

  int m = fx->getInputPortCount();
  for (int i = 0; i < m; ++i) {
    if (TFxP inputFx = fx->getInputPort(i)->getFx()) {
      PlacedFx inputPF = makePF(inputFx.getPointer());
      inputFx          = inputPF.m_fx;
      if (!inputFx) continue;

      if (firstInput) {
        firstInput = false;

        // The first found input PlacedFx carries its placement infos up
        pf.m_aff         = inputPF.m_aff;
        pf.m_columnIndex = inputPF.m_columnIndex;
        pf.m_z           = inputPF.m_z;
        pf.m_so          = inputPF.m_so;

        /*-- 軌跡を取得するBinaryFxの場合 --*/
        if (pf.m_fx->getAttributes()->isSpeedAware()) {
          MotionAwareBaseFx *mabfx = dynamic_cast<MotionAwareBaseFx *>(fx);
          if (mabfx) {
            double shutterStart = mabfx->getShutterStart()->getValue(m_frame);
            double shutterEnd   = mabfx->getShutterEnd()->getValue(m_frame);
            int traceResolution = mabfx->getTraceResolution()->getValue();
            /*-- 移動の参考にするオブジェクトの取得。自分自身の場合はNoneId --*/
            MotionObjectType type   = mabfx->getMotionObjectType();
            int index               = mabfx->getMotionObjectIndex()->getValue();
            TStageObjectId objectId = getMotionObjectId(type, index);
            fx->getAttributes()->setMotionPoints(getColumnMotionPoints(
                m_xsh, m_frame, pf.m_columnIndex, objectId, m_isPreview,
                shutterStart, shutterEnd, traceResolution));
          }
        }

      } else {
        // The follow-ups traduce their PlacedFx::m_aff into an NaAffineFx,
        // instead
        inputFx = getFxWithColumnMovements(inputPF);
        inputFx = TFxUtil::makeAffine(inputFx, pf.m_aff.inv());
      }

      if (!pf.m_fx->connect(pf.m_fx->getInputPortName(i), inputFx.getPointer()))
        assert(!"Could not connect ports!");
    }
  }

  // The xsheet-like input port is activated and brought upwards whenever it is
  // both
  // specified by the fx, and there is no input fx attached to it.
  if (pf.m_fx->getXsheetPort() && pf.m_fx->getXsheetPort()->getFx() == 0)
    pf.m_leftXsheetPort = pf.m_fx->getXsheetPort();

  return pf;
}

//***************************************************************************************************
//    Exported  Render-Tree building  functions
//***************************************************************************************************

TFxP buildSceneFx(ToonzScene *scene, TXsheet *xsh, double row, int whichLevels,
                  int shrink, bool isPreview) {
  FxBuilder builder(scene, xsh, row, whichLevels, isPreview);
  TFxP fx = builder.buildFx();
  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId                 = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *cameraPegbar = xsh->getStageObject(cameraId);
  assert(cameraPegbar);
  TCamera *camera = cameraPegbar->getCamera();
  assert(camera);

  TAffine aff = getDpiAffine(camera).inv();
  if (shrink > 1) {
    double fac = 0.5 * (1.0 / shrink - 1.0);
    aff = TTranslation(fac * camera->getRes().lx, fac * camera->getRes().ly) *
          TScale(1.0 / shrink) * aff;
  }

  fx = TFxUtil::makeAffine(fx, aff);
  if (fx) fx->setName(L"CameraDPI and Shrink NAffineFx");

  fx = TFxUtil::makeOver(
      TFxUtil::makeColorCard(scene->getProperties()->getBgColor()), fx);
  return fx;
}

//===================================================================

TFxP buildSceneFx(ToonzScene *scene, TXsheet *xsh, double row, int shrink,
                  bool isPreview) {
  int whichLevels =
      scene->getProperties()->getOutputProperties()->getWhichLevels();
  return buildSceneFx(scene, xsh, row, whichLevels, shrink, isPreview);
}

//===================================================================

TFxP buildSceneFx(ToonzScene *scene, double row, int shrink, bool isPreview) {
  return buildSceneFx(scene, scene->getXsheet(), row, shrink, isPreview);
}

//===================================================================

TFxP buildSceneFx(ToonzScene *scene, TXsheet *xsh, double row, const TFxP &root,
                  bool isPreview) {
  int whichLevels =
      scene->getProperties()->getOutputProperties()->getWhichLevels();
  FxBuilder builder(scene, xsh, row, whichLevels, isPreview);
  return builder.buildFx(root, BSFX_NO_TR);
}

//===================================================================

TFxP buildSceneFx(ToonzScene *scene, double row, const TFxP &root,
                  bool isPreview) {
  return buildSceneFx(scene, scene->getXsheet(), row, root, isPreview);
}

//===================================================================

//! Similar to buildSceneFx(ToonzScene *scene, double row, const TFxP &root,
//! bool isPreview) method, build the sceneFx
//! adding also camera transformations. Used for Preview Fx function.
DVAPI TFxP buildPartialSceneFx(ToonzScene *scene, double row, const TFxP &root,
                               int shrink, bool isPreview) {
  int whichLevels =
      scene->getProperties()->getOutputProperties()->getWhichLevels();
  FxBuilder builder(scene, scene->getXsheet(), row, whichLevels, isPreview);
  TFxP fx = builder.buildFx(
      root, BSFX_Transforms_Enum(BSFX_CAMERA_TR | BSFX_COLUMN_TR));

  TXsheet *xsh = scene->getXsheet();
  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId                 = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *cameraPegbar = xsh->getStageObject(cameraId);
  assert(cameraPegbar);
  TCamera *camera = cameraPegbar->getCamera();
  assert(camera);

  TAffine aff = getDpiAffine(camera).inv();
  if (shrink > 1) {
    double fac = 0.5 * (1.0 / shrink - 1.0);

    aff = TTranslation(fac * camera->getRes().lx, fac * camera->getRes().ly) *
          TScale(1.0 / shrink) * aff;
  }

  fx = TFxUtil::makeAffine(fx, aff);
  return fx;
}

//===================================================================

DVAPI TFxP buildPartialSceneFx(ToonzScene *scene, TXsheet *xsheet, double row,
                               const TFxP &root, int shrink, bool isPreview) {
  int whichLevels =
      scene->getProperties()->getOutputProperties()->getWhichLevels();
  FxBuilder builder(scene, xsheet, row, whichLevels, isPreview);
  TFxP fx = builder.buildFx(
      root, BSFX_Transforms_Enum(BSFX_CAMERA_TR | BSFX_COLUMN_TR));

  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsheet->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId = xsheet->getStageObjectTree()->getCurrentCameraId();
  TStageObject *cameraPegbar = xsheet->getStageObject(cameraId);
  assert(cameraPegbar);
  TCamera *camera = cameraPegbar->getCamera();
  assert(camera);

  TAffine aff = getDpiAffine(camera).inv();
  if (shrink > 1) {
    double fac = 0.5 * (1.0 / shrink - 1.0);

    aff = TTranslation(fac * camera->getRes().lx, fac * camera->getRes().ly) *
          TScale(1.0 / shrink) * aff;
  }

  fx = TFxUtil::makeAffine(fx, aff);
  return fx;
}

//===================================================================

/*!
  Builds the post-rendering fxs tree - that is, all fxs between the xsheet node
  and
  current output node.

  This function can be used to isolate global post-processing fxs that typically
  do not
  contribute to scene compositing. When encountered, the xsheet node is \a not
  xpanded - it must be replaced manually.
*/
DVAPI TFxP buildPostSceneFx(ToonzScene *scene, double frame, int shrink,
                            bool isPreview) {
  // NOTE: Should whichLevels access output AND PREVIEW settings?
  int whichLevels =
      scene->getProperties()->getOutputProperties()->getWhichLevels();

  TXsheet *xsh  = scene->getXsheet();
  if (!xsh) xsh = scene->getXsheet();

  // Do not expand the xsheet node
  FxBuilder builder(scene, xsh, frame, whichLevels, isPreview, false);

  TFxP fx = builder.buildFx();

  TStageObjectId cameraId;
  if (isPreview)
    cameraId = xsh->getStageObjectTree()->getCurrentPreviewCameraId();
  else
    cameraId                 = xsh->getStageObjectTree()->getCurrentCameraId();
  TStageObject *cameraPegbar = xsh->getStageObject(cameraId);
  assert(cameraPegbar);
  TCamera *camera = cameraPegbar->getCamera();
  assert(camera);

  TAffine aff = getDpiAffine(camera).inv();

  if (shrink > 1) {
    double fac = 0.5 * (1.0 / shrink - 1.0);
    aff = TTranslation(fac * camera->getRes().lx, fac * camera->getRes().ly) *
          TScale(1.0 / shrink) * aff;
  }

  if (!aff.isIdentity()) fx = TFxUtil::makeAffine(fx, aff);

  return fx;
}

//===================================================================

DVAPI TFxP buildSceneFx(ToonzScene *scene, double frame, TXsheet *xsh,
                        const TFxP &root, BSFX_Transforms_Enum transforms,
                        bool isPreview, int whichLevels, int shrink) {
  // NOTE: Should whichLevels access output AND PREVIEW settings?
  if (whichLevels == -1)
    whichLevels =
        scene->getProperties()->getOutputProperties()->getWhichLevels();

  if (!xsh) xsh = scene->getXsheet();

  FxBuilder builder(scene, xsh, frame, whichLevels, isPreview);

  TFxP fx = root ? builder.buildFx(root, transforms) : builder.buildFx();

  TStageObjectId cameraId =
      isPreview ? xsh->getStageObjectTree()->getCurrentPreviewCameraId()
                : xsh->getStageObjectTree()->getCurrentCameraId();

  TStageObject *cameraPegbar = xsh->getStageObject(cameraId);
  assert(cameraPegbar);

  TCamera *camera = cameraPegbar->getCamera();
  assert(camera);

  TAffine aff;
  if (transforms & BSFX_CAMERA_DPI_TR) aff = getDpiAffine(camera).inv();

  if (shrink > 1) {
    double fac = 0.5 * (1.0 / shrink - 1.0);
    aff = TTranslation(fac * camera->getRes().lx, fac * camera->getRes().ly) *
          TScale(1.0 / shrink) * aff;
  }

  if (!aff.isIdentity()) fx = TFxUtil::makeAffine(fx, aff);

  return fx;
}


text:
import logging

from cliff.lister import Lister
from cliff.show import ShowOne
from atmosphere.api import AtmosphereAPI
from atmosphere.utils import ts_to_isodate

class ProviderList(Lister):
    """
    List cloud providers managed by Atmosphere.
    """

    log = logging.getLogger(__name__)

    def take_action(self, parsed_args):
        column_headers = ('id', 'uuid', 'name', 'type', 'virtualization', 'public', 'active', 'start_date')
        api = AtmosphereAPI(self.app_args.auth_token, base_url=self.app_args.base_url, timeout=self.app_args.api_server_timeout, verify=self.app_args.verify_cert)
        data = api.get_providers()
        providers = []
        if data.ok:
            for provider in data.message['results']:
                start_date = ts_to_isodate(provider['start_date'])
                providers.append((
                    provider['id'],
                    provider['uuid'],
                    provider['name'],
                    provider['type']['name'],
                    provider['virtualization']['name'],
                    provider['public'],
                    provider['active'],
                    start_date if start_date else provider['start_date']
                ))

        return (column_headers, tuple(providers))

class ProviderShow(ShowOne):
    """
    Show details for a cloud provider.
    """

    log = logging.getLogger(__name__)

    def get_parser(self, prog_name):
        parser = super(ProviderShow, self).get_parser(prog_name)
        parser.add_argument('id', help='the provider uuid')
        return parser

    def take_action(self, parsed_args):
        column_headers = ('id',
                          'uuid',
                          'name',
                          'description',
                          'type',
                          'virtualization',
                          'sizes',
                          'auto_imaging',
                          'public',
                          'is_admin',
                          'active',
                          'start_date',
                          'end_date')
        api = AtmosphereAPI(self.app_args.auth_token, base_url=self.app_args.base_url, timeout=self.app_args.api_server_timeout, verify=self.app_args.verify_cert)
        data = api.get_provider(parsed_args.id)
        provider = ()
        if data.ok:
            message = data.message
            start_date = ts_to_isodate(message['start_date'])
            end_date = ''
            if message['end_date']:
                end_date = ts_to_isodate(message['end_date'])
            provider = (
                message['id'],
                message['uuid'],
                message['name'],
                message['description'],
                message['type']['name'],
                message['virtualization']['name'],
                ', '.join([value['name'] for value in message['sizes']]),
                message['auto_imaging'],
                message['public'],
                message['is_admin'],
                message['active'],
                start_date,
                end_date
            )

        return (column_headers, provider)

redpajama_set_name: RedPajamaGithub


text:
//Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
//
package com.leibmann.android.myupcommingevents;

import android.text.format.Time;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by matthias on 2/1/2015.
 */
public class LocalDateTimeConverter {

    private Time mLocalTime;

    public Time getLocalTime() {
        return mLocalTime;
    }

    public LocalDateTimeConverter(String utcDateRFC3339) {
        // RFC3339
        // "Start": "2015-01-23T20:00:00Z",
        // "End": "2015-01-23T21:00:00Z",
        Time localTime = new Time();
        localTime.parse3339(utcDateRFC3339);
        int utcOffset = TimeZone.getDefault().getOffset(localTime.toMillis(false));
        localTime.set(localTime.toMillis(false) + utcOffset);
        this.mLocalTime = localTime;
    }

    public String getLocalDayString() {
        String s = mLocalTime.format("%m/%d/%Y");
        return s;
    }
    public String getLocalTimeString() {
        //String s = mLocalTime.format("%H:%M:%S");
        String s = mLocalTime.format("%H:%M");
        return s;
    }

    public String getLocalDayTimeString() {
        String s = mLocalTime.format("%m/%d/%Y %H:%M:%S");
        return s;
    }

    public boolean isAM() {
        String s = mLocalTime.format("%p");
        boolean am = s.toLowerCase().equals("am");
        return am;
    }

    public String getLocalDayOfWeekString() {
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");

        Calendar c = Calendar.getInstance();
        c.set(mLocalTime.year, mLocalTime.month, mLocalTime.monthDay);
        String dayOfTheWeek = sdf.format(c.getTime());

        return dayOfTheWeek;
    }
}


text:
HLSL shadertoy, inspired by Iñigo Quilez (www.shadertoy.com).

## Usage

1. Run.

	```
	./hlsl-toy.exe toys/default.hlsl
	```
	or to specify the resolution:

	```
	./hlsl-toy.exe toys/default.hlsl 1920 1080
	```

2. Edit your file in your favorite editor.
3. Press F5 to reload and check the results. Shader compilation errors will be reported if any.
4. Have fun!

## Advanced

You can import up to 8 textures. Just include textures file names in the shader source as comments. Textures will be reloaded automatically on F5 reload.

    // tex1.png
    // tex2.jpg
    // noise.bmp

    // ... shader code goes here ...

Set of parameters, that are exposed to the shader:

    cbuffer Parameters {
    	// mouse pixel coords. xy: current (if MLB down), zw: click
    	float4 mouse;
    	// current backbuffer size
    	float2 resolution;
    	// application global time
    	float time;
    };

There are predefined sampler states - all with wrap addressing:

	SamplerState sampler_point;
	SamplerState sampler_linear;
	SamplerState sampler_aniso;


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

/*********************************************************************************

 * Description:  TODO: To be written.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/

require_once('modules/EmailMarketing/Forms.php');

global $app_strings;
global $app_list_strings;
global $mod_strings;
global $current_user;

// Unimplemented until jscalendar language files are fixed
// global $current_language;
// global $default_language;
// global $cal_codes;

$focus = new EmailMarketing();

if(isset($_REQUEST['record'])) {
    $focus->retrieve($_REQUEST['record']);
}

global $theme;

$GLOBALS['log']->info("EmailMarketing Edit View");

$xtpl=new XTemplate ('modules/EmailMarketing/DetailView.html');

$xtpl->assign("MOD", $mod_strings);
$xtpl->assign("APP", $app_strings);

if (isset($_REQUEST['return_module'])) {
	$xtpl->assign("RETURN_MODULE", $_REQUEST['return_module']);
} else {
	$xtpl->assign("RETURN_MODULE", 'Campaigns');
}
if (isset($_REQUEST['return_action'])) {
	$xtpl->assign("RETURN_ACTION", $_REQUEST['return_action']);
} else {
	$xtpl->assign("RETURN_ACTION", 'DetailView');
}
if (isset($_REQUEST['return_id'])) {
	$xtpl->assign("RETURN_ID", $_REQUEST['return_id']);
} else {
	if (!empty($focus->campaign_id)) {
		$xtpl->assign("RETURN_ID", $focus->campaign_id);
	}
}

if($focus->campaign_id) {
	$campaign_id=$focus->campaign_id;
}
else {
	$campaign_id=$_REQUEST['campaign_id'];
}
$xtpl->assign("CAMPAIGN_ID", $campaign_id);

$xtpl->assign("PRINT_URL", "index.php?".$GLOBALS['request_string']);
$xtpl->assign("JAVASCRIPT", get_set_focus_js());
$xtpl->assign("DATE_ENTERED", $focus->date_entered);
$xtpl->assign("DATE_MODIFIED", $focus->date_modified);
$xtpl->assign("ID", $focus->id);
$xtpl->assign("NAME", $focus->name);
$xtpl->assign("FROM_NAME", $focus->from_name);
$xtpl->assign("FROM_ADDR", $focus->from_addr);
$xtpl->assign("REPLY_TO_NAME", $focus->reply_to_name);
$xtpl->assign("REPLY_TO_ADDR", $focus->reply_to_addr);
$xtpl->assign("DATE_START", $focus->date_start);
$xtpl->assign("TIME_START", $focus->time_start);

$email_templates_arr = get_bean_select_array(true, 'EmailTemplate','name');
if($focus->template_id) {
	$xtpl->assign("EMAIL_TEMPLATE", $email_templates_arr[$focus->template_id]);
}

//include campaign utils..
require_once('modules/Campaigns/utils.php');
if (empty($_REQUEST['campaign_name'])) {

	$campaign = new Campaign();
	$campaign->retrieve($campaign_id);
	$campaign_name=$campaign->name;
} else {
	$campaign_name=$_REQUEST['campaign_name'];
}

$params = array();
$params[] = "{$mod_strings['LNK_CAMPAIGN_LIST']}";
$params[] = "{$campaign_name}";
$params[] = $focus->name;

echo getClassicModuleTitle($focus->module_dir, $params, true);

if (!empty($focus->all_prospect_lists)) {
	$xtpl->assign("MESSAGE_FOR", $mod_strings['LBL_ALL_PROSPECT_LISTS']);
} else {
	$xtpl->assign("MESSAGE_FOR", $mod_strings['LBL_RELATED_PROSPECT_LISTS']);
}

if (!empty($focus->status)) {
	$xtpl->assign("STATUS",$app_list_strings['email_marketing_status_dom'][$focus->status]);
}
$emails=array();
$mailboxes=get_campaign_mailboxes($emails);
//_ppd($emails[$focus->inbound_email_id]);
if (!empty($focus->inbound_email_id) && isset($mailboxes[$focus->inbound_email_id])) {
	$xtpl->assign("FROM_MAILBOX_NAME", $mailboxes[$focus->inbound_email_id]." <{$emails[$focus->inbound_email_id]}>");
}

$xtpl->parse("main");
$xtpl->out("main");

$javascript = new javascript();
$javascript->setFormName('EditView');
$javascript->setSugarBean($focus);
$javascript->addAllFields('');
echo $javascript->getScript();

require_once('include/SubPanel/SubPanelTiles.php');
$subpanel = new SubPanelTiles($focus, 'EmailMarketing');

if ($focus->all_prospect_lists == 1) {
	$subpanel->subpanel_definitions->exclude_tab('prospectlists');
}
else {
	$subpanel->subpanel_definitions->exclude_tab('allprospectlists');

}

echo $subpanel->display();

?>


text:
$packageName = 'nsis.install'
$installerType = 'exe'
$silentArgs = '/S'
$url = 'http://sourceforge.net/projects/nsis/files/NSIS%202/2.47/nsis-2.47-setup.exe/download'
$checksum = '43545716316b4bac9f5bd1cbda86fd4d4be53796'
$checksumType = 'sha1'
$validExitCodes = @(0)

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -SilentArgs "$silentArgs" `
                          -Url "$url" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"


text:
package com.haskforce.parsing.srcExtsDatatypes;

import java.util.Arrays;

/**
 * data FunDep l = FunDep l [Name l] [Name l]
 */
public class FunDep {
    public SrcInfoSpan srcInfoSpan;
    public NameTopType[] fromNames;
    public NameTopType[] toNames;

    @Override
    public String toString() {
        return "FunDep{" +
                "fromNames=" + Arrays.toString(fromNames) +
                ", toNames=" + Arrays.toString(toNames) +
                '}';
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>SWFObject 2 dynamic publishing example page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

Alternative content


text:
import os
import re
import sys
import gzip
import json
import pprint
import urllib
import urllib2
import hashlib
import tarfile
import shutil
import StringIO

PYNET_PATH = os.path.expanduser('~/.pynet')
VIRTUALENV_PATH = 'virtualenv'

class TarGzPackageNotFoundError(Exception):
    pass

class Md5MismatchError(Exception):
    pass

def splitext(path):
    for ext in ('.tar.gz', '.tar.bz2'):
        if path.endswith(ext):
            return path[:-len(ext)], path[-len(ext):]
    return os.path.splitext(path)

def checksum(filename):
    h = hashlib.md5()
    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            h.update(chunk)
    return h.hexdigest()

def latest_virtualenv():
    url = 'https://pypi.python.org/pypi/virtualenv/json'
    response = urllib2.urlopen(url)
    listing = json.load(response)
    latest = sorted(listing['releases'].keys())[-1]
    packages = listing['releases'][latest]
    for package in packages:
        if package['filename'].endswith('tar.gz'):
            return package
    raise TarGzPackageNotFoundError

def setup_virtualenv(path=os.path.join(PYNET_PATH, VIRTUALENV_PATH)):
    package = latest_virtualenv()
    tempfile = urllib.urlretrieve(package['url'], filename=None)[0]
    md5_digest = checksum(tempfile)
    if checksum(tempfile) != package['md5_digest']:
        raise Md5DigestMismatchError
    tar = tarfile.open(tempfile)
    tar.extractall(PYNET_PATH)
    os.remove(tempfile)
    return splitext(package['filename'])[0]

def main():
    print 'pynet.py:'
    print sys.argv
    version = setup_virtualenv()
    print version

if __name__ == '__main__':
    main()


text:
Faça parte dessa rede!

A Open Data for Development Network lorem ipsum dolor sit amet anno domini die vero. Você pode colaborar de três maneiras:

						<picture>
						  	<source media="(max-width: 767px)" srcset="img/be-part/mobile/be-part--send-small.svg">

						</picture>

Mande sua notícia

Envie a sua notícia, publique-a dentro da plataforma OD4D e se torne um correspondente do nosso site.

					Saiba como

						<picture>
							<source media="(max-width: 767px)" srcset="img/be-part/mobile/be-part--share-small.svg">

						</picture>

Que tal abrir os seus dados?

Você tem um site que fale sobre dados abertos? Saiba como participar dessa comunidade via RSS.

					Entenda melhor

						<picture>
							<source media="(max-width: 767px)" srcset="img/be-part/mobile/be-part--develop-small.svg">

						</picture>

Ajude a desenvolver a plataforma

É desenvolvedor e se interessa por lorem ipsum dolor sit amet? Consectetur adipiscing elit, sed do eiusmod.

					Acesse o Github

Não entendeu nada? Confira nosso roteiro explicativo dos conceitos de dados abertos


text:
#ifndef TEXTTERMINAL_HPP
#define TEXTTERMINAL_HPP

#include "terminal/terminal.hpp"

class TextTerminal : public Terminal
{
public:
    TextTerminal(uintptr_t fb, size_t iwidth, size_t iheight, TerminalData &data);

private:
    virtual void move_cursor(size_t x, size_t y) override;
    virtual void putchar(size_t x, size_t y, TermEntry entry) override;
    virtual void clear_line(size_t y, graphics::Color color, size_t size) override;
    virtual void draw_impl() override;
    virtual void disable_impl() override {}

private:
    uintptr_t m_fb;
};

#endif // TEXTTERMINAL_HPP


text:
package petablox.analyses.escape.metaback;

import gnu.trove.map.hash.TObjectIntHashMap;

import java.io.File;
import java.util.*;

import petablox.analyses.alias.CICGAnalysis;
import petablox.analyses.alias.ICICG;
import petablox.analyses.alloc.DomH;
import petablox.analyses.escape.hybrid.full.Edge;
import petablox.analyses.escape.hybrid.full.ThreadEscapeFullAnalysis;
import petablox.analyses.field.DomF;
import petablox.analyses.heapacc.DomE;
import petablox.analyses.invk.DomI;
import petablox.analyses.method.DomM;
import petablox.analyses.var.DomV;
import petablox.program.Loc;
import petablox.program.Program;
import petablox.project.Petablox;
import petablox.project.ClassicProject;
import petablox.project.analyses.ProgramRel;
import petablox.project.analyses.metaback.AbstractJobDispatcher;
import petablox.project.analyses.metaback.QueryResult;
import petablox.project.analyses.metaback.dnf.ClauseSizeCMP;
import petablox.project.analyses.metaback.dnf.DNF;
import petablox.project.analyses.parallelizer.JobDispatcher;
import petablox.project.analyses.parallelizer.Mode;
import petablox.project.analyses.parallelizer.ParallelAnalysis;
import petablox.project.analyses.parallelizer.Scenario;
import petablox.project.analyses.rhs.BackTraceIterator;
import petablox.project.analyses.rhs.IWrappedPE;
import petablox.project.analyses.rhs.TimeoutException;
import petablox.util.Execution;
import petablox.util.Utils;
import petablox.util.soot.ICFG;
import petablox.util.soot.SootUtilities;
import soot.*;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceFieldRef;
import soot.toolkits.graph.Block;

/**
 * petablox.ssa = [true|false] (default = true)

 * petablox.rhs.timeout = N milliseconds (default = 0, no timeouts)

 * petablox.iter-thresc-java.mode = [master|worker] (default = null)

 * petablox.iter-thresc-java.optimize = [true|false] (default = false)

 * petablox.iter-thresc-java.debug= [true|false] (default = false)

 * petablox.iter-thresc-java.disjuncts = [int] (default = 1)

 * petablox.iter-thresc-java.query = [int] (default = -1)

 * petablox.iter-thresc-java.explode = [int] (default = -1)

 * petablox.iter-thresc-java.jobpatch = [int] (default = 100)

 * petablox.iter-thresc-java.iterlimit = [int] (default = 1000)

 * petablox.iter-thresc-java.xmlToHtmlTask = [String] (default = null)
 *
 * @author xin
 *
 */
@Petablox(name = "iter-thresc-java",consumes = { "queryE" })
public class IterThrEscAnalysis extends ParallelAnalysis {

	private String xmlToHtmlTask;
	private DomH domH;
	private DomE domE;
	private boolean DEBUG;

	// Fields used by the worker
	private EscAbsFactory absFac = EscAbsFactory.getSingleton();
	private EscQueryFactory qFac = EscQueryFactory.getSingleton();
	private boolean optimizeSumms;
	private int numDisjuncts;
	private int timeout;
	private boolean dnegation;
	private boolean prune;

	private DomM domM;
	private DomI domI;
	private DomV domV;
	private DomF domF;
	private int varId[];
	private TObjectIntHashMap<SootMethod> methToNumVars = new TObjectIntHashMap<SootMethod>();
	private TObjectIntHashMap<SootMethod> methToFstVar = new TObjectIntHashMap<SootMethod>();
	private ICICG cicg;
	private SootMethod mainMethod;
	private SootMethod threadStartMethod;
	private TObjectIntHashMap<Object> quadToRPOid;
	private Map<Unit, Loc> invkQuadToLoc;
	private Map<SootMethod, Set<Unit>> callersMap = new HashMap<SootMethod, Set<Unit>>();
	private Map<Unit, Set<SootMethod>> targetsMap = new HashMap<Unit, Set<SootMethod>>();

	// Fields used by the master
	private EscJobDispatcher dispatcher;
	private int trackedQuery;
	private String trackedQueryFiles;
	private int explode;
	private int jobPatch;
	private int iterLimit;

	@Override
	public void init() {
		X = new Execution("iter-thresc-java");

		this.xmlToHtmlTask = X.getStringArg("xmlToHtmlTask", null);
		this.optimizeSumms = X.getBooleanArg("optimize", false);
		this.numDisjuncts = X.getIntArg("disjuncts", 1);
		this.DEBUG = X.getBooleanArg("debug", false);
		this.timeout = X.getIntArg("timeout", -1);
		this.trackedQuery = X.getIntArg("query", -1);
		this.trackedQueryFiles = X.getStringArg("queryFiles", null);
		this.explode = X.getIntArg("explode", -1);
		this.jobPatch = X.getIntArg("jobpatch", 100);
		this.dnegation = X.getBooleanArg("negate", true);
		this.prune = X.getBooleanArg("prune", true);
		this.iterLimit = X.getIntArg("iterlimit", 1000);

		ThrEscForwardAnalysis.setOptimize(optimizeSumms);
		MetaBackAnalysis.setDEBUG(DEBUG);
		MetaBackAnalysis.setErrSufSize(numDisjuncts);
		MetaBackAnalysis.setOptimizeSumms(optimizeSumms);
		MetaBackAnalysis.setTimeout(timeout);
		MetaBackAnalysis.setDNegation(dnegation);
		MetaBackAnalysis.setPrune(prune);
		AbstractJobDispatcher.setDEBUG(DEBUG);
		AbstractJobDispatcher.setExplode(explode);
		AbstractJobDispatcher.setJobPatchSize(jobPatch);
		AbstractJobDispatcher.setIterLimit(iterLimit);

		domH = (DomH) ClassicProject.g().getTrgt("H");
		ClassicProject.g().runTask(domH);
		domE = (DomE) ClassicProject.g().getTrgt("E");
		ClassicProject.g().runTask(domE);

		EscAbsFactory.setDomH(domH);
		EscQueryFactory.setDomE(domE);

		if (getMode() == Mode.MASTER)
			initMaster();
		else
			initWorker();
	}

	private void initMaster() {
		ProgramRel relQueryE = (ProgramRel) ClassicProject.g().getTrgt("queryE");
		relQueryE.load();
		Iterable<Unit> tuples = relQueryE.getAry1ValTuples();
		List<Unit> allEs = new ArrayList<Unit>();
		if(trackedQueryFiles!=null)
			allEs = getQueriesFromFiles(trackedQueryFiles);
		else
		for (Unit q : tuples) {
			if(trackedQuery<0||domE.indexOf(q) == trackedQuery)
			allEs.add(q);
		}
//		fillInQuery(allEs);
		dispatcher = new EscJobDispatcher(xmlToHtmlTask,this,allEs,domE,domH);
	}

	private List<Unit> getQueriesFromFiles(String s){
		try{
		List<Unit> allEs = new ArrayList<Unit>();
		String files[] = s.split(",");
		for(String f:files){
			Scanner sc = new Scanner(new File(f.trim()));
			while(sc.hasNext()){
				String line = sc.nextLine().trim();
				if(!line.equals("")){
					allEs.add(domE.get((Integer.parseInt(line))));
				}
			}
		}
		return allEs;
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	private void initWorker() {
		Program program = Program.g();
		mainMethod = program.getMainMethod();
		threadStartMethod = program.getThreadStartMethod();
		domI = (DomI) ClassicProject.g().getTrgt("I");
		ClassicProject.g().runTask(domI);
		domM = (DomM) ClassicProject.g().getTrgt("M");
		ClassicProject.g().runTask(domM);
		domV = (DomV) ClassicProject.g().getTrgt("V");
		ClassicProject.g().runTask(domV);
		domF = (DomF) ClassicProject.g().getTrgt("F");
		ClassicProject.g().runTask(domF);
		int numV = domV.size();
		varId = new int[numV];
		for (int vIdx = 0; vIdx < numV;) {
			Local v = domV.get(vIdx);
			SootMethod m = domV.getMethod(v);
			List<Local> refVars = new ArrayList<Local>();
			List<Local> locals = SootUtilities.getLocals(m);
			Iterator<Local> itr = locals.iterator();
			while(itr.hasNext()){
				Local v1 = itr.next();
				if(v1.getType() instanceof RefLikeType)
					refVars.add(v1);
			}
			int n = refVars.size();
			methToNumVars.put(m, n);
			methToFstVar.put(m, vIdx);
			// System.out.println("Method: " + m);
			for (int i = 0; i < n; i++) {
				varId[vIdx + i] = i;
				// System.out.println("\t" + domV.get(vIdx + i));
			}
			vIdx += n;
		}
		domI = (DomI) ClassicProject.g().getTrgt("I");
		ClassicProject.g().runTask(domI);
		domM = (DomM) ClassicProject.g().getTrgt("M");
		ClassicProject.g().runTask(domM);
		cicg = getCallGraph();
		quadToRPOid = new TObjectIntHashMap<Object>();
		invkQuadToLoc = new HashMap<Unit, Loc>();
		for (SootMethod m : cicg.getNodes()) {
			if (m.isAbstract())
				continue;
			ICFG cfg = SootUtilities.getCFG(m);
			quadToRPOid.put(cfg.getHeads().get(0), 0);
			int rpoId = 1;
			for (Block bb : cfg.reversePostOrder()) {
				int i = 0;
				Iterator<Unit> itr = bb.getBody().getUnits().iterator();
				while(itr.hasNext()) {
					Unit q = itr.next();
					quadToRPOid.put(q, rpoId++);
					if (SootUtilities.isInvoke(q)) {
						Loc loc = new Loc(q, i);
						invkQuadToLoc.put(q, loc);
					}
					i++;
				}
			}
			quadToRPOid.put(cfg.getTails().get(0), rpoId);
		}
		ThreadEscapeFullAnalysis.setDomF(domF);
	}

	public ICICG getCallGraph() {
		if (cicg == null) {
			CICGAnalysis cicgAnalysis = (CICGAnalysis) ClassicProject.g()
					.getTrgt("cicg-java");
			ClassicProject.g().runTask(cicgAnalysis);
			cicg = cicgAnalysis.getCallGraph();
		}
		return cicg;
	}

	public SootMethod getMainMethod() {
		return mainMethod;
	}

	public SootMethod getThreadStartMethod() {
		return threadStartMethod;
	}

	public int methToNumVars(SootMethod m) {
		return methToNumVars.get(m);
	}

	public int methToFstVar(SootMethod m){
		return methToFstVar.get(m);
	}

	public int getLocalIdx(soot.Value ro) {
		Local r = (Local)ro;
		int vIdx = domV.indexOf(r);
		return varId[vIdx];
	}

	public int getLocalIdx(int domIndex) {
		return varId[domIndex];
	}

	public int getDomVIdx(Local r) {
		return domV.indexOf(r);
	}

	public int getDomFIdx(SootField f){
		if(f == null)
			return EscFVariable.ARRAY_ELEMENT;
		else
			return domF.indexOf(f);
	}

	public DomE domE() {
		return domE;
	}

	public DomV domV() {
		return domV;
	}

	public DomH domH(){
		return domH;
	}

	public DomF domF(){
		return domF;
	}

	@Override
	public void done() {
		// TODO Auto-generated method stub

	}

	@Override
	public JobDispatcher getJobDispatcher() {
		return dispatcher;
	}

	/**
	 * This is where the job is really done for workers
	 */
	@Override
	public String apply(String line) {
		Scenario in = new Scenario(line, EscJobDispatcher.MAJSEP);
		String absStr = in.getIn();
		EscAbstraction abs = (EscAbstraction) absFac.genAbsFromStr(absStr);
		String qStrs[] = Utils.split(in.getOut(), EscJobDispatcher.MINSEP,
				true, true, -1);
		List<EscQueryResult> results = new ArrayList<EscQueryResult>();
		HashSet<Unit> es = new HashSet<Unit>();
		for (String qStr : qStrs) {
			EscQuery q = (EscQuery) qFac.getQueryFromStr(qStr);
			es.add(q.getQuad());
		}
		ThrEscForwardAnalysis forAnalysis = new ThrEscForwardAnalysis(this,
				abs.getLHs(), es);
		forAnalysis.run();
		if (forAnalysis.isTimeOut()) {
			for (Unit q : es) {
				EscQuery query = new EscQuery(domE.indexOf(q),domE);
				EscQueryResult r = new EscQueryResult(query,
						QueryResult.TIMEOUT, null);
				results.add(r);
			}
		} else {
			Set<Unit> Ls = forAnalysis.getLocs();
			for (Unit q : Ls) {
				EscQuery query = new EscQuery(domE.indexOf(q),domE);
				EscQueryResult result = new EscQueryResult(query,
						QueryResult.PROVEN, null);
				results.add(result);
			}
			Set<Unit> Es = forAnalysis.getEscs();
			for (Unit q : Es) {
				EscQuery query = new EscQuery(domE.indexOf(q),domE);
				IWrappedPE<Edge, Edge> wpe = forAnalysis.getEscEdge(q);
				DNF errSuf = getErrSuf(q);
				BackTraceIterator<Edge, Edge> backIter = forAnalysis
						.getBackTraceIterator(wpe);
				backIter.addMethodToSkipList(threadStartMethod);
				MetaBackAnalysis backAnalysis = new MetaBackAnalysis(this,
						errSuf, backIter,  abs.getLIdxes());
				DNF nc;
				try{
				nc = backAnalysis.run();
				}catch(TimeoutException E){
					EscQueryResult result = new EscQueryResult(query,
							QueryResult.TIMEOUT, null);
					results.add(result);
					continue;
				}
				int resultType;
				if(nc.isFalse())
					resultType = QueryResult.IMPOSSIBILITY;
				else
					 resultType = QueryResult.REFINE;
				EscQueryResult result = new EscQueryResult(query,
						resultType, nc);
				results.add(result);
			}
		}
		StringBuffer sb = new StringBuffer();
		for (EscQueryResult r : results) {
			if (sb.length() != 0)
				sb.append(EscJobDispatcher.MINSEP);
			sb.append(r.encode());
		}
		in.setOut(sb.toString());
		in.setType(AbstractJobDispatcher.RESULT);
		return in.encode();
	}

	public DNF getErrSuf(Unit q) {
		if (!(q instanceof AssignStmt)) return null;
		AssignStmt s = (AssignStmt)q;
		soot.Value lhs = s.getLeftOp();
		soot.Value rhs = s.getRightOp();

		soot.Value rx;
		if (rhs instanceof ArrayRef)
			rx = ((ArrayRef)rhs).getBase();
		else if (rhs instanceof InstanceFieldRef)
			rx = ((InstanceFieldRef)rhs).getBase();
		else if (lhs instanceof ArrayRef)
			rx = ((ArrayRef)lhs).getBase();
		else if (lhs instanceof InstanceFieldRef)
			rx = ((InstanceFieldRef)lhs).getBase();
		else
			throw new RuntimeException("Wrong query + " + q);
		EscVVariable escv = null;
		if (rx instanceof Local) {
			int vidx = this.getDomVIdx((Local)rx);
			escv = new EscVVariable(vidx,domV);
		}
		return new DNF(new ClauseSizeCMP(), escv, Value.E());
	}

	public boolean isSkippedMethod(Unit i) {
		Set<SootMethod> targets = targetsMap.get(i);
		if (targets == null) {
			targets = cicg.getTargets(i);
			targetsMap.put(i, targets);
		}
		return targets.isEmpty();
	}

	public boolean isThreadStart(Unit i){
		Set<SootMethod> targets = targetsMap.get(i);
		if (targets == null) {
			targets = cicg.getTargets(i);
			targetsMap.put(i, targets);
		}
		return targets.contains(this.getThreadStartMethod());
	}

}


text:
#ifndef _WALKPACKET_H
#define _WALKPACKET_H

#include "IPacket.h"
#include "define.h"
#include <string.h>

typedef struct _WALK_PACKET {
    int player_id;
    short sx;
    short sy;
    short dx;
    short dy;
}WALK_PACKET;

class WalkPacket : virtual IPacket
{
public:

    WalkPacket( CPacket packet );

    virtual CPacket pack( void ) { CPacket packet; return packet; }

public:

    int     m_playerID;

    short   m_startX;
    short   m_startY;
    short   m_destX;
    short   m_destY;

};

#endif


text:
package com.a21vianet.wallet.vport.library.commom.crypto.callback;

/**
 * Created by ben on 2017/6/20.
 */

public interface OnVerifiedListener {
    void onVerified(boolean isValid);
}


text:
import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'email_reply_parser'))
import version

setup(
    name='email_reply_parser',
    version=version.VERSION,
    description='Email reply parser',
    packages=['email_reply_parser'],
    package_data={'email_reply_parser': ['../VERSION']},
    author='Royce Haynes',
    author_email='royce.haynes@gmail.com',
    url='https://github.com/zapier/email-reply-parser',
    license='MIT',
    test_suite='test'
)


text:
using System;

namespace NSaga
{
    /// <summary>
    /// Extension class that allows SqlSagaRepository to be configured as part of general Wireup builder
    /// </summary>
    public static class SqlServerWireup
    {
        /// <summary>
        /// Starts the fluent chain to configure <see cref="SqlSagaRepository"/>
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <returns></returns>
        public static SqlServerBuilderExtension UseSqlServer(this SagaMediatorBuilder builder)
        {
            return new SqlServerBuilderExtension(builder);
        }
    }

    /// <summary>
    /// Class that allows SqlSagaRepository to be configured as part of general Wireup builder
    /// </summary>
    public sealed class SqlServerBuilderExtension
    {
        private readonly SagaMediatorBuilder builder;

        /// <summary>
        /// Initializes a new instance of the <see cref="SqlServerBuilderExtension"/> class.
        /// </summary>
        /// <param name="builder">The builder.</param>
        public SqlServerBuilderExtension(SagaMediatorBuilder builder)
        {
            this.builder = builder;
        }

        /// <summary>
        /// Configures a connection string that will be used in SqlSagaRepository
        /// </summary>
        /// <param name="connectionString">The connection string.</param>
        /// <returns></returns>
        public SagaMediatorBuilder WithConnectionString(String connectionString)
        {
            builder.Register(typeof(IConnectionFactory), new ConnectionFactory(connectionString));

            builder.UseRepository<SqlSagaRepository>();

            return builder;
        }

        /// <summary>
        /// Configures a connection string name that will be used in SqlSagaRepository
        /// </summary>
        /// <param name="connectionStringName">Name of the connection string.</param>
        /// <returns></returns>
        public SagaMediatorBuilder WithConnectionStringName(String connectionStringName)
        {
            builder.Register(typeof(IConnectionFactory), ConnectionFactory.FromConnectionStringName(connectionStringName));

            builder.UseRepository<SqlSagaRepository>();

            return builder;
        }
    }
}


text:
using namespace gorc;
using namespace gorc::cog;

lval_expression_gen_visitor::lval_expression_gen_visitor(script &out_script,
                                                         ir_printer &ir,
                                                         verb_table const &verbs,
                                                         constant_table const &constants)
    : out_script(out_script)
    , ir(ir)
    , verbs(verbs)
    , constants(constants)
{
    return;
}

// LCOV_EXCL_START
//
// Assertion - already handled by earlier semantic analysis

void lval_expression_gen_visitor::visit(ast_node &)
{
    LOG_FATAL("generated assignment for target which is not an l-value");
}

// LCOV_EXCL_STOP

void lval_expression_gen_visitor::visit(ast::identifier_expression &e)
{
    auto si = out_script.symbols.get_symbol_index(e.value->value);
    switch(std::get<0>(si)) {
    case symbol_scope::global_symbol:
        ir.storg(std::get<1>(si));
        break;

    default:
    case symbol_scope::local_symbol:
        ir.stor(std::get<1>(si));
        break;
    }
}

void lval_expression_gen_visitor::visit(ast::subscript_expression &e)
{
    // Generate code for subscript
    rval_expression_gen_visitor ev(out_script, ir, verbs, constants);
    ast_visit(ev, *e.index);

    auto si = out_script.symbols.get_symbol_index(e.base->value);
    switch(std::get<0>(si)) {
    case symbol_scope::global_symbol:
        ir.storgi(std::get<1>(si));
        break;

    default:
    case symbol_scope::local_symbol:
        ir.stori(std::get<1>(si));
        break;
    }
}


text:
/**
 *
 */
/**
 * @author christopher
 *
 */
package com.csvanefalk.phatgeo.object;


text: C++ game ( in collaboration with Emanuele Vineti ) developed using Allegro 5 library


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
        <meta name="generator" content="Doxygen 1.8.9.1"/>

        <title>Traffic Assignment frameworK (TAsK): Class Members</title>

        <link href="search/search.css" rel="stylesheet" type="text/css"/>

        <link href="doxygen.css" rel="stylesheet" type="text/css" />
        <link href="customdoxygen.css" rel="stylesheet" type="text/css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

                    Traffic Assignment frameworK (TAsK)

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

a

b

c

d

e

f

g

h

i

l

m

n

o

p

q

r

s

t

u

w

~

Here is a list of all documented class members with links to the class documentation for each member:

- w -

worthAdding()
: DAGraph

writeLine()
: FileWriter

writePathSetToFile()
: PathSetPrinterToFile

writeToFile()
: IndiffCurveContainer

<address class="footer">
Generated on Tue Mar 10 2015 15:45:17 for Traffic Assignment frameworK (TAsK) by

 1.8.9.1
</address>


text:
package com.github.mtakaki.credentialstorage.hibernate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.google.common.collect.ImmutableMap;

import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyFactory;

/**
 * A factory for creating proxies for components that use Hibernate data access objects
 * outside Jersey resources.
 *
A created proxy will be aware of the {@link UnitOfWork} annotation
 * on the original class methods and will open a Hibernate session with a transaction
 * around them.

 */
public class UnitOfWorkAwareProxyFactory {

    private final ImmutableMap<String, RemoteCredentialHibernateBundle<?>> sessionFactories;

    public UnitOfWorkAwareProxyFactory(final String name, final RemoteCredentialHibernateBundle<?> sessionFactory) {
        this.sessionFactories = ImmutableMap.of(name, sessionFactory);
    }

    public UnitOfWorkAwareProxyFactory(final RemoteCredentialHibernateBundle<?>... bundles) {
        final ImmutableMap.Builder<String, RemoteCredentialHibernateBundle<?>> sessionFactoriesBuilder = ImmutableMap.builder();
        for (final RemoteCredentialHibernateBundle<?> bundle : bundles) {
            sessionFactoriesBuilder.put(bundle.name(), bundle);
        }
        this.sessionFactories = sessionFactoriesBuilder.build();
    }

    /**
     * Creates a new @UnitOfWork aware proxy of a class with the default constructor.
     *
     * @param clazz the specified class definition
     * @param <T>   the type of the class
     * @return a new proxy
     */
    public <T> T create(final Class<T> clazz) {
        return this.create(clazz, new Class<?>[]{}, new Object[]{});
    }

    /**
     * Creates a new @UnitOfWork aware proxy of a class with an one-parameter constructor.
     *
     * @param clazz                the specified class definition
     * @param constructorParamType the type of the constructor parameter
     * @param constructorArguments the argument passed to the constructor
     * @param <T>                  the type of the class
     * @return a new proxy
     */
    public <T> T create(final Class<T> clazz, final Class<?> constructorParamType, final Object constructorArguments) {
        return this.create(clazz, new Class<?>[]{constructorParamType}, new Object[]{constructorArguments});
    }

    /**
     * Creates a new @UnitOfWork aware proxy of a class with a complex constructor.
     *
     * @param clazz                 the specified class definition
     * @param constructorParamTypes the types of the constructor parameters
     * @param constructorArguments  the arguments passed to the constructor
     * @param <T>                   the type of the class
     * @return a new proxy
     */
    @SuppressWarnings("unchecked")
    public <T> T create(final Class<T> clazz, final Class<?>[] constructorParamTypes, final Object[] constructorArguments) {
        final ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(clazz);

        try {
            final Proxy proxy = (Proxy) (constructorParamTypes.length == 0 ?
                    factory.createClass().newInstance() :
                    factory.create(constructorParamTypes, constructorArguments));
            proxy.setHandler(new MethodHandler() {
                @Override
                public Object invoke(final Object self, final Method overridden, final Method proceed, final Object[] args) throws Throwable {
                    final UnitOfWork unitOfWork = overridden.getAnnotation(UnitOfWork.class);
                    final UnitOfWorkAspect unitOfWorkAspect = new UnitOfWorkAspect(UnitOfWorkAwareProxyFactory.this.sessionFactories);
                    try {
                        unitOfWorkAspect.beforeStart(unitOfWork);
                        final Object result = proceed.invoke(self, args);
                        unitOfWorkAspect.afterEnd();
                        return result;
                    } catch (final InvocationTargetException e) {
                        unitOfWorkAspect.onError();
                        throw e.getCause();
                    } catch (final Exception e) {
                        unitOfWorkAspect.onError();
                        throw e;
                    }
                }
            });
            return (T) proxy;
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
                InvocationTargetException e) {
            throw new IllegalStateException("Unable to create a proxy for the class '" + clazz + "'", e);
        }
    }
}


text:
require "LuaScripts/Utilities/Sample"

local rearCameraNode = nil

function Start()
    -- Execute the common startup for samples
    SampleStart()

    -- Create the scene content
    CreateScene()

    -- Create the UI content
    CreateInstructions()

    -- Setup the viewports for displaying the scene
    SetupViewports()

    -- Set the mouse mode to use in the sample
    SampleInitMouseMode(MM_RELATIVE)

    -- Hook up to the frame update and render post-update events
    SubscribeToEvents()
end

function CreateScene()
    scene_ = Scene()

    -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
    -- Also create a DebugRenderer component so that we can draw debug geometry
    scene_:CreateComponent("Octree")
    scene_:CreateComponent("DebugRenderer")

    -- Create scene node & StaticModel component for showing a static plane
    local planeNode = scene_:CreateChild("Plane")
    planeNode.scale = Vector3(100.0, 1.0, 100.0)
    local planeObject = planeNode:CreateComponent("StaticModel")
    planeObject.model = cache:GetResource("Model", "Models/Plane.mdl")
    planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml")

    -- Create a Zone component for ambient lighting & fog control
    local zoneNode = scene_:CreateChild("Zone")
    local zone = zoneNode:CreateComponent("Zone")
    zone.boundingBox = BoundingBox(-1000.0, 1000.0)
    zone.ambientColor = Color(0.15, 0.15, 0.15)
    zone.fogColor = Color(0.5, 0.5, 0.7)
    zone.fogStart = 100.0
    zone.fogEnd = 300.0

    -- Create a directional light to the world. Enable cascaded shadows on it
    local lightNode = scene_:CreateChild("DirectionalLight")
    lightNode.direction = Vector3(0.6, -1.0, 0.8)
    local light = lightNode:CreateComponent("Light")
    light.lightType = LIGHT_DIRECTIONAL
    light.castShadows = true
    light.shadowBias = BiasParameters(0.00025, 0.5)
    -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance
    light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8)

    -- Create some mushrooms
    local NUM_MUSHROOMS = 240
    for i = 1, NUM_MUSHROOMS do
        local mushroomNode = scene_:CreateChild("Mushroom")
        mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)
        mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0)
        mushroomNode:SetScale(0.5 + Random(2.0))
        local mushroomObject = mushroomNode:CreateComponent("StaticModel")
        mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl")
        mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml")
        mushroomObject.castShadows = true
    end

    -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before
    -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility
    local NUM_BOXES = 20
    for i = 1, NUM_BOXES do
        local boxNode = scene_:CreateChild("Box")
        local size = 1.0 + Random(10.0)
        boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0)
        boxNode:SetScale(size)
        local boxObject = boxNode:CreateComponent("StaticModel")
        boxObject.model = cache:GetResource("Model", "Models/Box.mdl")
        boxObject.material = cache:GetResource("Material", "Materials/Stone.xml")
        boxObject.castShadows = true
        if size >= 3.0 then
            boxObject.occluder = true
        end
    end

    -- Create the camera. Limit far clip distance to match the fog
    cameraNode = scene_:CreateChild("Camera")
    local camera = cameraNode:CreateComponent("Camera")
    camera.farClip = 300.0

    -- Parent the rear camera node to the front camera node and turn it 180 degrees to face backward
    -- Here, we use the angle-axis constructor for Quaternion instead of the usual Euler angles
    rearCameraNode = cameraNode:CreateChild("RearCamera")
    rearCameraNode:Rotate(Quaternion(180.0, Vector3(0.0, 1.0, 0.0)))
    local rearCamera = rearCameraNode:CreateComponent("Camera")
    rearCamera.farClip = 300.0
    -- Because the rear viewport is rather small, disable occlusion culling from it. Use the camera's
    -- "view override flags" for this. We could also disable eg. shadows or force low material quality
    -- if we wanted
    rearCamera.viewOverrideFlags = VO_DISABLE_OCCLUSION

    -- Set an initial position for the front camera scene node above the plane
    cameraNode.position = Vector3(0.0, 5.0, 0.0)
end

function CreateInstructions()
    -- Construct new Text object, set string to display and font to use
    local instructionText = ui.root:CreateChild("Text")
    instructionText.text =
        "Use WASD keys and mouse to move\n"..
        "B to toggle bloom, F to toggle FXAA\n"..
        "Space to toggle debug geometry\n"
    instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
    -- The text has multiple rows. Center them in relation to each other
    instructionText.textAlignment = HA_CENTER

    -- Position the text relative to the screen center
    instructionText.horizontalAlignment = HA_CENTER
    instructionText.verticalAlignment = VA_CENTER
    instructionText:SetPosition(0, ui.root.height / 4)
end

function SetupViewports()
    renderer.numViewports = 2

    -- Set up the front camera viewport
    local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
    renderer:SetViewport(0, viewport)

    -- Clone the default render path so that we do not interfere with the other viewport, then add
    -- bloom and FXAA post process effects to the front viewport. Render path commands can be tagged
    -- for example with the effect name to allow easy toggling on and off. We start with the effects
    -- disabled.
    local effectRenderPath = viewport:GetRenderPath():Clone()
    effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/Bloom.xml"))
    effectRenderPath:Append(cache:GetResource("XMLFile", "PostProcess/FXAA2.xml"))
    -- Make the bloom mixing parameter more pronounced
    effectRenderPath:SetShaderParameter("BloomMix", Variant(Vector2(0.9, 0.6)))
    effectRenderPath:SetEnabled("Bloom", false)
    effectRenderPath:SetEnabled("FXAA2", false)
    viewport:SetRenderPath(effectRenderPath)

    -- Set up the rear camera viewport on top of the front view ("rear view mirror")
    -- The viewport index must be greater in that case, otherwise the view would be left behind
    local rearViewport = Viewport:new(scene_, rearCameraNode:GetComponent("Camera"),
        IntRect(graphics.width * 2 / 3, 32, graphics.width - 32, graphics.height / 3))
    renderer:SetViewport(1, rearViewport)
end

function SubscribeToEvents()
    -- Subscribe HandleUpdate() function for processing update events
    SubscribeToEvent("Update", "HandleUpdate")

    -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request
    -- debug geometry
    SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate")
end

function MoveCamera(timeStep)
    -- Do not move if the UI has a focused element (the console)
    if ui.focusElement ~= nil then
        return
    end

    -- Movement speed as world units per second
    local MOVE_SPEED = 20.0
    -- Mouse sensitivity as degrees per pixel
    local MOUSE_SENSITIVITY = 0.1

    -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
    local mouseMove = input.mouseMove
    yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
    pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
    pitch = Clamp(pitch, -90.0, 90.0)

    -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
    cameraNode.rotation = Quaternion(pitch, yaw, 0.0)

    -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
    if input:GetKeyDown(KEY_W) then
        cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
    end
    if input:GetKeyDown(KEY_S) then
        cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
    end
    if input:GetKeyDown(KEY_A) then
        cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
    end
    if input:GetKeyDown(KEY_D) then
        cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
    end

    -- Toggle post processing effects on the front viewport. Note that the rear viewport is unaffected
    local effectRenderPath = renderer:GetViewport(0).renderPath
    if input:GetKeyPress(KEY_B) then
        effectRenderPath:ToggleEnabled("Bloom")
    end
    if input:GetKeyPress(KEY_F) then
        effectRenderPath:ToggleEnabled("FXAA2")
    end

    -- Toggle debug geometry with space
    if input:GetKeyPress(KEY_SPACE) then
        drawDebug = not drawDebug
    end
end

function HandleUpdate(eventType, eventData)
    -- Take the frame time step, which is stored as a float
    local timeStep = eventData["TimeStep"]:GetFloat()

    -- Move the camera, scale movement with time step
    MoveCamera(timeStep)
end

function HandlePostRenderUpdate(eventType, eventData)
    -- If draw debug mode is enabled, draw viewport debug geometry. Disable depth test so that we can see the effect of occlusion
    if drawDebug then
        renderer:DrawDebugGeometry(false)
    end
end

-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
    return
        "<patch>" ..
        "    <add sel=\"/element\">" ..
        "        <element type=\"Button\">" ..
        "            <attribute name=\"Name\" value=\"Button3\" />" ..
        "            <attribute name=\"Position\" value=\"-120 -120\" />" ..
        "            <attribute name=\"Size\" value=\"96 96\" />" ..
        "            <attribute name=\"Horiz Alignment\" value=\"Right\" />" ..
        "            <attribute name=\"Vert Alignment\" value=\"Bottom\" />" ..
        "            <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" ..
        "            <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" ..
        "            <attribute name=\"Hover Image Offset\" value=\"0 0\" />" ..
        "            <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" ..
        "            <element type=\"Text\">" ..
        "                <attribute name=\"Name\" value=\"Label\" />" ..
        "                <attribute name=\"Horiz Alignment\" value=\"Center\" />" ..
        "                <attribute name=\"Vert Alignment\" value=\"Center\" />" ..
        "                <attribute name=\"Color\" value=\"0 0 0 1\" />" ..
        "                <attribute name=\"Text\" value=\"FXAA\" />" ..
        "            </element>" ..
        "            <element type=\"Text\">" ..
        "                <attribute name=\"Name\" value=\"KeyBinding\" />" ..
        "                <attribute name=\"Text\" value=\"F\" />" ..
        "            </element>" ..
        "        </element>" ..
        "    </add>" ..
        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Bloom</replace>" ..
        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
        "        <element type=\"Text\">" ..
        "            <attribute name=\"Name\" value=\"KeyBinding\" />" ..
        "            <attribute name=\"Text\" value=\"B\" />" ..
        "        </element>" ..
        "    </add>" ..
        "    <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
        "    <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" ..
        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
        "        <element type=\"Text\">" ..
        "            <attribute name=\"Name\" value=\"KeyBinding\" />" ..
        "            <attribute name=\"Text\" value=\"SPACE\" />" ..
        "        </element>" ..
        "    </add>" ..
        "</patch>"
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>nucleo-dynamixel: FLASH Exported Constants</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

nucleo-dynamixel
    0.0.1

A library for controlling dynamixel servomotors, designed for nucleo stm32

Main Page

Related Pages

Modules

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Modules

FLASH Exported Constants
STM32F4xx_HAL_Driver » FLASHEx

Modules

 	FLASH Type Erase

 	FLASH Voltage Range

 	FLASH WRP State

 	FLASH Option Type

 	FLASH Option Bytes Read Protection

 	FLASH Option Bytes IWatchdog

 	FLASH Option Bytes nRST_STOP

 	FLASH Option Bytes nRST_STDBY

 	FLASH BOR Reset Level

 	FLASH PCROP State

 	FLASH Advanced Option Type

 	FLASH Latency

 	FLASH Banks

 	FLASH Mass Erase bit

 	FLASH Sectors

 	FLASH Option Bytes Write Protection

 	FLASH Option Bytes PC ReadWrite Protection

 	FLASH Dual Boot

 	FLASH Selection Protection Mode

Detailed Description

Generated by

     1.8.11


text:
package org.power.requests.struct;

/**
 * @author Kuo Hong
 */
public class Pair<K, V> {
    private final K name;
    private final V value;

    public Pair(K name, V value) {
        this.name = name;
        this.value = value;
    }

    public K getName() {
        return name;
    }

    public V getValue() {
        return value;
    }

}


text:
<component name="libraryTable">
  <library name="android-times-square-1.5.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.squareup/android-times-square/1.5.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.squareup/android-times-square/1.5.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.squareup/android-times-square/1.5.0/8ea91b929890b763915b022cfae6b1e66d2a5a56/android-times-square-1.5.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>