text:
import {
  Component,
  OnInit
} from '@angular/core';

import {
  ListItemModel
} from '@skyux/list-builder-common';

import {
  ListState,
  ListStateDispatcher,
  ListItemsLoadAction
} from '@skyux/list-builder/modules/list/state';

@Component({
  selector: 'sky-list-paging-demo',
  templateUrl: './list-paging-demo.component.html',
  providers: [
    ListState,
    ListStateDispatcher
  ]
})
export class SkyListPagingDemoComponent implements OnInit {
  constructor(
    private dispatcher: ListStateDispatcher
  ) { }

  public ngOnInit() {
    this.dispatcher.next(new ListItemsLoadAction([
      new ListItemModel('1'),
      new ListItemModel('2'),
      new ListItemModel('3'),
      new ListItemModel('4'),
      new ListItemModel('5'),
      new ListItemModel('6'),
      new ListItemModel('7')
    ], true));
  }
}


text:
using System;

namespace Robotlegs.Bender.Extensions.CommandCenter.DSL
{
	public interface ICommandUnmapper
	{
		/// <summary>
		/// Unmaps a Command
		/// </summary>
		/// <param name="commandType">Command to unmap</param>
		void FromCommand<T>();
		void FromCommand(Type commandType);

		/// <summary>
		/// Unmaps all commands from this trigger
		/// </summary>
		void FromAll();
	}
}

redpajama_set_name: RedPajamaGithub


text:
#include "SkLayerInfo.h"
#include "SkRecordDraw.h"
#include "SkPatchUtils.h"

void SkRecordDraw(const SkRecord& record,
                  SkCanvas* canvas,
                  SkPicture const* const drawablePicts[],
                  SkDrawable* const drawables[],
                  int drawableCount,
                  const SkBBoxHierarchy* bbh,
                  SkPicture::AbortCallback* callback) {
    SkAutoCanvasRestore saveRestore(canvas, true /*save now, restore at exit*/);

    if (bbh) {
        // Draw only ops that affect pixels in the canvas's current clip.
        // The SkRecord and BBH were recorded in identity space.  This canvas
        // is not necessarily in that same space.  getClipBounds() returns us
        // this canvas' clip bounds transformed back into identity space, which
        // lets us query the BBH.
        SkRect query;
        if (!canvas->getClipBounds(&query)) {
            query.setEmpty();
        }

        SkTDArray<unsigned> ops;
        bbh->search(query, &ops);

        SkRecords::Draw draw(canvas, drawablePicts, drawables, drawableCount);
        for (int i = 0; i < ops.count(); i++) {
            if (callback && callback->abort()) {
                return;
            }
            // This visit call uses the SkRecords::Draw::operator() to call
            // methods on the |canvas|, wrapped by methods defined with the
            // DRAW() macro.
            record.visit<void>(ops[i], draw);
        }
    } else {
        // Draw all ops.
        SkRecords::Draw draw(canvas, drawablePicts, drawables, drawableCount);
        for (unsigned i = 0; i < record.count(); i++) {
            if (callback && callback->abort()) {
                return;
            }
            // This visit call uses the SkRecords::Draw::operator() to call
            // methods on the |canvas|, wrapped by methods defined with the
            // DRAW() macro.
            record.visit<void>(i, draw);
        }
    }
}

void SkRecordPartialDraw(const SkRecord& record, SkCanvas* canvas,
                         SkPicture const* const drawablePicts[], int drawableCount,
                         unsigned start, unsigned stop,
                         const SkMatrix& initialCTM) {
    SkAutoCanvasRestore saveRestore(canvas, true /*save now, restore at exit*/);

    stop = SkTMin(stop, record.count());
    SkRecords::Draw draw(canvas, drawablePicts, NULL, drawableCount, &initialCTM);
    for (unsigned i = start; i < stop; i++) {
        record.visit<void>(i, draw);
    }
}

namespace SkRecords {

// NoOps draw nothing.
template <> void Draw::draw(const NoOp&) {}

#define DRAW(T, call) template <> void Draw::draw(const T& r) { fCanvas->call; }
DRAW(Restore, restore());
DRAW(Save, save());
DRAW(SaveLayer, saveLayer(r.bounds, r.paint, r.flags));
DRAW(SetMatrix, setMatrix(SkMatrix::Concat(fInitialCTM, r.matrix)));

DRAW(ClipPath, clipPath(r.path, r.opAA.op, r.opAA.aa));
DRAW(ClipRRect, clipRRect(r.rrect, r.opAA.op, r.opAA.aa));
DRAW(ClipRect, clipRect(r.rect, r.opAA.op, r.opAA.aa));
DRAW(ClipRegion, clipRegion(r.region, r.op));

DRAW(BeginCommentGroup, beginCommentGroup(r.description));
DRAW(AddComment, addComment(r.key, r.value));
DRAW(EndCommentGroup, endCommentGroup());

DRAW(DrawBitmap, drawBitmap(r.bitmap.shallowCopy(), r.left, r.top, r.paint));
DRAW(DrawBitmapNine, drawBitmapNine(r.bitmap.shallowCopy(), r.center, r.dst, r.paint));
DRAW(DrawBitmapRectToRect,
        drawBitmapRectToRect(r.bitmap.shallowCopy(), r.src, r.dst, r.paint,
                             SkCanvas::kNone_DrawBitmapRectFlag));
DRAW(DrawBitmapRectToRectBleed,
        drawBitmapRectToRect(r.bitmap.shallowCopy(), r.src, r.dst, r.paint,
                             SkCanvas::kBleed_DrawBitmapRectFlag));
DRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));
DRAW(DrawImage, drawImage(r.image, r.left, r.top, r.paint));
DRAW(DrawImageRect, drawImageRect(r.image, r.src, r.dst, r.paint));
DRAW(DrawOval, drawOval(r.oval, r.paint));
DRAW(DrawPaint, drawPaint(r.paint));
DRAW(DrawPath, drawPath(r.path, r.paint));
DRAW(DrawPatch, drawPatch(r.cubics, r.colors, r.texCoords, r.xmode, r.paint));
DRAW(DrawPicture, drawPicture(r.picture, &r.matrix, r.paint));
DRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));
DRAW(DrawPosText, drawPosText(r.text, r.byteLength, r.pos, r.paint));
DRAW(DrawPosTextH, drawPosTextH(r.text, r.byteLength, r.xpos, r.y, r.paint));
DRAW(DrawRRect, drawRRect(r.rrect, r.paint));
DRAW(DrawRect, drawRect(r.rect, r.paint));
DRAW(DrawSprite, drawSprite(r.bitmap.shallowCopy(), r.left, r.top, r.paint));
DRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));
DRAW(DrawTextBlob, drawTextBlob(r.blob, r.x, r.y, r.paint));
DRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, &r.matrix, r.paint));
DRAW(DrawVertices, drawVertices(r.vmode, r.vertexCount, r.vertices, r.texs, r.colors,
                                r.xmode.get(), r.indices, r.indexCount, r.paint));
#undef DRAW

template <> void Draw::draw(const DrawDrawable& r) {
    SkASSERT(r.index >= 0);
    SkASSERT(r.index < fDrawableCount);
    if (fDrawables) {
        SkASSERT(NULL == fDrawablePicts);
        fCanvas->drawDrawable(fDrawables[r.index]);
    } else {
        fCanvas->drawPicture(fDrawablePicts[r.index]);
    }
}

// This is an SkRecord visitor that fills an SkBBoxHierarchy.
//
// The interesting part here is how to calculate bounds for ops which don't
// have intrinsic bounds.  What is the bounds of a Save or a Translate?
//
// We answer this by thinking about a particular definition of bounds: if I
// don't execute this op, pixels in this rectangle might draw incorrectly.  So
// the bounds of a Save, a Translate, a Restore, etc. are the union of the
// bounds of Draw* ops that they might have an effect on.  For any given
// Save/Restore block, the bounds of the Save, the Restore, and any other
// non-drawing ("control") ops inside are exactly the union of the bounds of
// the drawing ops inside that block.
//
// To implement this, we keep a stack of active Save blocks.  As we consume ops
// inside the Save/Restore block, drawing ops are unioned with the bounds of
// the block, and control ops are stashed away for later.  When we finish the
// block with a Restore, our bounds are complete, and we go back and fill them
// in for all the control ops we stashed away.
class FillBounds : SkNoncopyable {
public:
    FillBounds(const SkRect& cullRect, const SkRecord& record)
        : fNumRecords(record.count())
        , fCullRect(cullRect)
        , fBounds(record.count())
    {
        // Calculate bounds for all ops.  This won't go quite in order, so we'll need
        // to store the bounds separately then feed them in to the BBH later in order.
        fCTM = &SkMatrix::I();
        fCurrentClipBounds = fCullRect;
    }

    void setCurrentOp(unsigned currentOp) { fCurrentOp = currentOp; }

    void cleanUp(SkBBoxHierarchy* bbh) {
        // If we have any lingering unpaired Saves, simulate restores to make
        // sure all ops in those Save blocks have their bounds calculated.
        while (!fSaveStack.isEmpty()) {
            this->popSaveBlock();
        }

        // Any control ops not part of any Save/Restore block draw everywhere.
        while (!fControlIndices.isEmpty()) {
            this->popControl(fCullRect);
        }

        // Finally feed all stored bounds into the BBH.  They'll be returned in this order.
        if (bbh) {
            bbh->insert(fBounds.get(), fNumRecords);
        }
    }

    template <typename T> void operator()(const T& op) {
        this->updateCTM(op);
        this->updateClipBounds(op);
        this->trackBounds(op);
    }

    // In this file, SkRect are in local coordinates, Bounds are translated back to identity space.
    typedef SkRect Bounds;

    unsigned currentOp() const { return fCurrentOp; }
    const SkMatrix& ctm() const { return *fCTM; }
    const Bounds& getBounds(unsigned index) const { return fBounds[index]; }

    // Adjust rect for all paints that may affect its geometry, then map it to identity space.
    Bounds adjustAndMap(SkRect rect, const SkPaint* paint) const {
        // Inverted rectangles really confuse our BBHs.
        rect.sort();

        // Adjust the rect for its own paint.
        if (!AdjustForPaint(paint, &rect)) {
            // The paint could do anything to our bounds.  The only safe answer is the current clip.
            return fCurrentClipBounds;
        }

        // Adjust rect for all the paints from the SaveLayers we're inside.
        if (!this->adjustForSaveLayerPaints(&rect)) {
            // Same deal as above.
            return fCurrentClipBounds;
        }

        // Map the rect back to identity space.
        fCTM->mapRect(&rect);

        // Nothing can draw outside the current clip.
        if (!rect.intersect(fCurrentClipBounds)) {
            return Bounds::MakeEmpty();
        }

        return rect;
    }

private:
    struct SaveBounds {
        int controlOps;        // Number of control ops in this Save block, including the Save.
        Bounds bounds;         // Bounds of everything in the block.
        const SkPaint* paint;  // Unowned.  If set, adjusts the bounds of all ops in this block.
    };

    // Only Restore and SetMatrix change the CTM.
    template <typename T> void updateCTM(const T&) {}
    void updateCTM(const Restore& op)   { fCTM = &op.matrix; }
    void updateCTM(const SetMatrix& op) { fCTM = &op.matrix; }

    // Most ops don't change the clip.
    template <typename T> void updateClipBounds(const T&) {}

    // Clip{Path,RRect,Rect,Region} obviously change the clip.  They all know their bounds already.
    void updateClipBounds(const ClipPath&   op) { this->updateClipBoundsForClipOp(op.devBounds); }
    void updateClipBounds(const ClipRRect&  op) { this->updateClipBoundsForClipOp(op.devBounds); }
    void updateClipBounds(const ClipRect&   op) { this->updateClipBoundsForClipOp(op.devBounds); }
    void updateClipBounds(const ClipRegion& op) { this->updateClipBoundsForClipOp(op.devBounds); }

    // The bounds of clip ops need to be adjusted for the paints of saveLayers they're inside.
    void updateClipBoundsForClipOp(const SkIRect& devBounds) {
        Bounds clip = SkRect::Make(devBounds);
        // We don't call adjustAndMap() because as its last step it would intersect the adjusted
        // clip bounds with the previous clip, exactly what we can't do when the clip grows.
        fCurrentClipBounds = this->adjustForSaveLayerPaints(&clip) ? clip : fCullRect;
    }

    // Restore holds the devBounds for the clip after the {save,saveLayer}/restore block completes.
    void updateClipBounds(const Restore& op) {
        // This is just like the clip ops above, but we need to skip the effects (if any) of our
        // paired saveLayer (if it is one); it has not yet been popped off the save stack.  Our
        // devBounds reflect the state of the world after the saveLayer/restore block is done,
        // so they are not affected by the saveLayer's paint.
        const int kSavesToIgnore = 1;
        Bounds clip = SkRect::Make(op.devBounds);
        fCurrentClipBounds =
            this->adjustForSaveLayerPaints(&clip, kSavesToIgnore) ? clip : fCullRect;
    }

    // We also take advantage of SaveLayer bounds when present to further cut the clip down.
    void updateClipBounds(const SaveLayer& op)  {
        if (op.bounds) {
            // adjustAndMap() intersects these layer bounds with the previous clip for us.
            fCurrentClipBounds = this->adjustAndMap(*op.bounds, op.paint);
        }
    }

    // The bounds of these ops must be calculated when we hit the Restore
    // from the bounds of the ops in the same Save block.
    void trackBounds(const Save&)          { this->pushSaveBlock(NULL); }
    void trackBounds(const SaveLayer& op)  { this->pushSaveBlock(op.paint); }
    void trackBounds(const Restore&) { fBounds[fCurrentOp] = this->popSaveBlock(); }

    void trackBounds(const SetMatrix&)         { this->pushControl(); }
    void trackBounds(const ClipRect&)          { this->pushControl(); }
    void trackBounds(const ClipRRect&)         { this->pushControl(); }
    void trackBounds(const ClipPath&)          { this->pushControl(); }
    void trackBounds(const ClipRegion&)        { this->pushControl(); }
    void trackBounds(const BeginCommentGroup&) { this->pushControl(); }
    void trackBounds(const AddComment&)        { this->pushControl(); }
    void trackBounds(const EndCommentGroup&)   { this->pushControl(); }

    // For all other ops, we can calculate and store the bounds directly now.
    template <typename T> void trackBounds(const T& op) {
        fBounds[fCurrentOp] = this->bounds(op);
        this->updateSaveBounds(fBounds[fCurrentOp]);
    }

    void pushSaveBlock(const SkPaint* paint) {
        // Starting a new Save block.  Push a new entry to represent that.
        SaveBounds sb;
        sb.controlOps = 0;
        // If the paint affects transparent black, the bound shouldn't be smaller
        // than the current clip bounds.
        sb.bounds =
            PaintMayAffectTransparentBlack(paint) ? fCurrentClipBounds : Bounds::MakeEmpty();
        sb.paint = paint;

        fSaveStack.push(sb);
        this->pushControl();
    }

    static bool PaintMayAffectTransparentBlack(const SkPaint* paint) {
        if (paint) {
            // FIXME: this is very conservative
            if (paint->getImageFilter() || paint->getColorFilter()) {
                return true;
            }

            // Unusual Xfermodes require us to process a saved layer
            // even with operations outisde the clip.
            // For example, DstIn is used by masking layers.
            // https://code.google.com/p/skia/issues/detail?id=1291
            // https://crbug.com/401593
            SkXfermode* xfermode = paint->getXfermode();
            SkXfermode::Mode mode;
            // SrcOver is ok, and is also the common case with a NULL xfermode.
            // So we should make that the fast path and bypass the mode extraction
            // and test.
            if (xfermode && xfermode->asMode(&mode)) {
                switch (mode) {
                    // For each of the following transfer modes, if the source
                    // alpha is zero (our transparent black), the resulting
                    // blended alpha is not necessarily equal to the original
                    // destination alpha.
                    case SkXfermode::kClear_Mode:
                    case SkXfermode::kSrc_Mode:
                    case SkXfermode::kSrcIn_Mode:
                    case SkXfermode::kDstIn_Mode:
                    case SkXfermode::kSrcOut_Mode:
                    case SkXfermode::kDstATop_Mode:
                    case SkXfermode::kModulate_Mode:
                        return true;
                        break;
                    default:
                        break;
                }
            }
        }
        return false;
    }

    Bounds popSaveBlock() {
        // We're done the Save block.  Apply the block's bounds to all control ops inside it.
        SaveBounds sb;
        fSaveStack.pop(&sb);

        while (sb.controlOps --> 0) {
            this->popControl(sb.bounds);
        }

        // This whole Save block may be part another Save block.
        this->updateSaveBounds(sb.bounds);

        // If called from a real Restore (not a phony one for balance), it'll need the bounds.
        return sb.bounds;
    }

    void pushControl() {
        fControlIndices.push(fCurrentOp);
        if (!fSaveStack.isEmpty()) {
            fSaveStack.top().controlOps++;
        }
    }

    void popControl(const Bounds& bounds) {
        fBounds[fControlIndices.top()] = bounds;
        fControlIndices.pop();
    }

    void updateSaveBounds(const Bounds& bounds) {
        // If we're in a Save block, expand its bounds to cover these bounds too.
        if (!fSaveStack.isEmpty()) {
            fSaveStack.top().bounds.join(bounds);
        }
    }

    // FIXME: this method could use better bounds
    Bounds bounds(const DrawText&) const { return fCurrentClipBounds; }

    Bounds bounds(const DrawPaint&) const { return fCurrentClipBounds; }
    Bounds bounds(const NoOp&)  const { return Bounds::MakeEmpty(); }    // NoOps don't draw.

    Bounds bounds(const DrawSprite& op) const {  // Ignores the matrix.
        return Bounds::MakeXYWH(op.left, op.top, op.bitmap.width(), op.bitmap.height());
    }

    Bounds bounds(const DrawRect& op) const { return this->adjustAndMap(op.rect, &op.paint); }
    Bounds bounds(const DrawOval& op) const { return this->adjustAndMap(op.oval, &op.paint); }
    Bounds bounds(const DrawRRect& op) const {
        return this->adjustAndMap(op.rrect.rect(), &op.paint);
    }
    Bounds bounds(const DrawDRRect& op) const {
        return this->adjustAndMap(op.outer.rect(), &op.paint);
    }
    Bounds bounds(const DrawImage& op) const {
        const SkImage* image = op.image;
        SkRect rect = SkRect::MakeXYWH(op.left, op.top, image->width(), image->height());

        return this->adjustAndMap(rect, op.paint);
    }
    Bounds bounds(const DrawImageRect& op) const {
        return this->adjustAndMap(op.dst, op.paint);
    }
    Bounds bounds(const DrawBitmapRectToRect& op) const {
        return this->adjustAndMap(op.dst, op.paint);
    }
    Bounds bounds(const DrawBitmapRectToRectBleed& op) const {
        return this->adjustAndMap(op.dst, op.paint);
    }
    Bounds bounds(const DrawBitmapNine& op) const {
        return this->adjustAndMap(op.dst, op.paint);
    }
    Bounds bounds(const DrawBitmap& op) const {
        return this->adjustAndMap(
                SkRect::MakeXYWH(op.left, op.top, op.bitmap.width(), op.bitmap.height()),
                op.paint);
    }

    Bounds bounds(const DrawPath& op) const {
        return op.path.isInverseFillType() ? fCurrentClipBounds
                                           : this->adjustAndMap(op.path.getBounds(), &op.paint);
    }
    Bounds bounds(const DrawPoints& op) const {
        SkRect dst;
        dst.set(op.pts, op.count);

        // Pad the bounding box a little to make sure hairline points' bounds aren't empty.
        SkScalar stroke = SkMaxScalar(op.paint.getStrokeWidth(), 0.01f);
        dst.outset(stroke/2, stroke/2);

        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawPatch& op) const {
        SkRect dst;
        dst.set(op.cubics, SkPatchUtils::kNumCtrlPts);
        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawVertices& op) const {
        SkRect dst;
        dst.set(op.vertices, op.vertexCount);
        return this->adjustAndMap(dst, &op.paint);
    }

    Bounds bounds(const DrawPicture& op) const {
        SkRect dst = op.picture->cullRect();
        op.matrix.mapRect(&dst);
        return this->adjustAndMap(dst, op.paint);
    }

    Bounds bounds(const DrawPosText& op) const {
        const int N = op.paint.countText(op.text, op.byteLength);
        if (N == 0) {
            return Bounds::MakeEmpty();
        }

        SkRect dst;
        dst.set(op.pos, N);
        AdjustTextForFontMetrics(&dst, op.paint);
        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawPosTextH& op) const {
        const int N = op.paint.countText(op.text, op.byteLength);
        if (N == 0) {
            return Bounds::MakeEmpty();
        }

        SkScalar left = op.xpos[0], right = op.xpos[0];
        for (int i = 1; i < N; i++) {
            left  = SkMinScalar(left,  op.xpos[i]);
            right = SkMaxScalar(right, op.xpos[i]);
        }
        SkRect dst = { left, op.y, right, op.y };
        AdjustTextForFontMetrics(&dst, op.paint);
        return this->adjustAndMap(dst, &op.paint);
    }
    Bounds bounds(const DrawTextOnPath& op) const {
        SkRect dst = op.path.getBounds();

        // Pad all sides by the maximum padding in any direction we'd normally apply.
        SkRect pad = { 0, 0, 0, 0};
        AdjustTextForFontMetrics(&pad, op.paint);

        // That maximum padding happens to always be the right pad today.
        SkASSERT(pad.fLeft == -pad.fRight);
        SkASSERT(pad.fTop  == -pad.fBottom);
        SkASSERT(pad.fRight > pad.fBottom);
        dst.outset(pad.fRight, pad.fRight);

        return this->adjustAndMap(dst, &op.paint);
    }

    Bounds bounds(const DrawTextBlob& op) const {
        SkRect dst = op.blob->bounds();
        dst.offset(op.x, op.y);
        return this->adjustAndMap(dst, &op.paint);
    }

    Bounds bounds(const DrawDrawable& op) const {
        return this->adjustAndMap(op.worstCaseBounds, NULL);
    }

    static void AdjustTextForFontMetrics(SkRect* rect, const SkPaint& paint) {
#ifdef SK_DEBUG
        SkRect correct = *rect;
#endif
        // crbug.com/373785 ~~> xPad = 4x yPad
        // crbug.com/424824 ~~> bump yPad from 2x text size to 2.5x
        const SkScalar yPad = 2.5f * paint.getTextSize(),
                       xPad = 4.0f * yPad;
        rect->outset(xPad, yPad);
#ifdef SK_DEBUG
        SkPaint::FontMetrics metrics;
        paint.getFontMetrics(&metrics);
        correct.fLeft   += metrics.fXMin;
        correct.fTop    += metrics.fTop;
        correct.fRight  += metrics.fXMax;
        correct.fBottom += metrics.fBottom;
        // See skia:2862 for why we ignore small text sizes.
        SkASSERTF(paint.getTextSize() < 0.001f || rect->contains(correct),
                  "%f %f %f %f vs. %f %f %f %f\n",
                  -xPad, -yPad, +xPad, +yPad,
                  metrics.fXMin, metrics.fTop, metrics.fXMax, metrics.fBottom);
#endif
    }

    // Returns true if rect was meaningfully adjusted for the effects of paint,
    // false if the paint could affect the rect in unknown ways.
    static bool AdjustForPaint(const SkPaint* paint, SkRect* rect) {
        if (paint) {
            if (paint->canComputeFastBounds()) {
                *rect = paint->computeFastBounds(*rect, rect);
                return true;
            }
            return false;
        }
        return true;
    }

    bool adjustForSaveLayerPaints(SkRect* rect, int savesToIgnore = 0) const {
        for (int i = fSaveStack.count() - 1 - savesToIgnore; i >= 0; i--) {
            if (!AdjustForPaint(fSaveStack[i].paint, rect)) {
                return false;
            }
        }
        return true;
    }

    const unsigned fNumRecords;

    // We do not guarantee anything for operations outside of the cull rect
    const SkRect fCullRect;

    // Conservative identity-space bounds for each op in the SkRecord.
    SkAutoTMalloc<Bounds> fBounds;

    // We walk fCurrentOp through the SkRecord, as we go using updateCTM()
    // and updateClipBounds() to maintain the exact CTM (fCTM) and conservative
    // identity-space bounds of the current clip (fCurrentClipBounds).
    unsigned fCurrentOp;
    const SkMatrix* fCTM;
    Bounds fCurrentClipBounds;

    // Used to track the bounds of Save/Restore blocks and the control ops inside them.
    SkTDArray<SaveBounds> fSaveStack;
    SkTDArray<unsigned>   fControlIndices;
};

// SkRecord visitor to gather saveLayer/restore information.
class CollectLayers : SkNoncopyable {
public:
    CollectLayers(const SkRect& cullRect, const SkRecord& record,
                  const SkPicture::SnapshotArray* pictList, SkLayerInfo* accelData)
        : fSaveLayersInStack(0)
        , fAccelData(accelData)
        , fPictList(pictList)
        , fFillBounds(cullRect, record)
    {}

    void setCurrentOp(unsigned currentOp) { fFillBounds.setCurrentOp(currentOp); }

    void cleanUp(SkBBoxHierarchy* bbh) {
        // fFillBounds must perform its cleanUp first so that all the bounding
        // boxes associated with unbalanced restores are updated (prior to
        // fetching their bound in popSaveLayerInfo).
        fFillBounds.cleanUp(bbh);

        while (!fSaveLayerStack.isEmpty()) {
            this->popSaveLayerInfo();
        }
    }

    template <typename T> void operator()(const T& op) {
        fFillBounds(op);
        this->trackSaveLayers(op);
    }

private:
    struct SaveLayerInfo {
        SaveLayerInfo() { }
        SaveLayerInfo(int opIndex, bool isSaveLayer, const SkRect* bounds, const SkPaint* paint)
            : fStartIndex(opIndex)
            , fIsSaveLayer(isSaveLayer)
            , fHasNestedSaveLayer(false)
            , fBounds(bounds ? *bounds : SkRect::MakeEmpty())
            , fPaint(paint) {
        }

        int                fStartIndex;
        bool               fIsSaveLayer;
        bool               fHasNestedSaveLayer;
        SkRect             fBounds;
        const SkPaint*     fPaint;
    };

    template <typename T> void trackSaveLayers(const T& op) {
        /* most ops aren't involved in saveLayers */
    }
    void trackSaveLayers(const Save& s) { this->pushSaveLayerInfo(false, NULL, NULL); }
    void trackSaveLayers(const SaveLayer& sl) { this->pushSaveLayerInfo(true, sl.bounds, sl.paint); }
    void trackSaveLayers(const Restore& r) { this->popSaveLayerInfo(); }

    void trackSaveLayersForPicture(const SkPicture* picture, const SkPaint* paint) {
        // For sub-pictures, we wrap their layer information within the parent
        // picture's rendering hierarchy
        SkPicture::AccelData::Key key = SkLayerInfo::ComputeKey();

        const SkLayerInfo* childData =
            static_cast<const SkLayerInfo*>(picture->EXPERIMENTAL_getAccelData(key));
        if (!childData) {
            // If the child layer hasn't been generated with saveLayer data we
            // assume the worst (i.e., that it does contain layers which nest
            // inside existing layers). Layers within sub-pictures that don't
            // have saveLayer data cannot be hoisted.
            // TODO: could the analysis data be use to fine tune this?
            this->updateStackForSaveLayer();
            return;
        }

        for (int i = 0; i < childData->numBlocks(); ++i) {
            const SkLayerInfo::BlockInfo& src = childData->block(i);

            FillBounds::Bounds newBound = fFillBounds.adjustAndMap(src.fBounds, paint);
            if (newBound.isEmpty()) {
                continue;
            }

            this->updateStackForSaveLayer();

            SkLayerInfo::BlockInfo& dst = fAccelData->addBlock();

            // If src.fPicture is NULL the layer is in dp.picture; otherwise
            // it belongs to a sub-picture.
            dst.fPicture = src.fPicture ? src.fPicture : picture;
            dst.fPicture->ref();
            dst.fBounds = newBound;
            dst.fSrcBounds = src.fSrcBounds;
            dst.fLocalMat = src.fLocalMat;
            dst.fPreMat = src.fPreMat;
            dst.fPreMat.postConcat(fFillBounds.ctm());
            if (src.fPaint) {
                dst.fPaint = SkNEW_ARGS(SkPaint, (*src.fPaint));
            }
            dst.fSaveLayerOpID = src.fSaveLayerOpID;
            dst.fRestoreOpID = src.fRestoreOpID;
            dst.fHasNestedLayers = src.fHasNestedLayers;
            dst.fIsNested = fSaveLayersInStack > 0 || src.fIsNested;

            // Store 'saveLayer ops from enclosing picture' + drawPict op + 'ops from sub-picture'
            dst.fKeySize = fSaveLayerOpStack.count() + src.fKeySize + 1;
            dst.fKey = SkNEW_ARRAY(unsigned, dst.fKeySize);
            memcpy(dst.fKey, fSaveLayerOpStack.begin(), fSaveLayerOpStack.count() * sizeof(unsigned));
            dst.fKey[fSaveLayerOpStack.count()] = fFillBounds.currentOp();
            memcpy(&dst.fKey[fSaveLayerOpStack.count()+1], src.fKey, src.fKeySize * sizeof(unsigned));
        }
    }

    void trackSaveLayers(const DrawPicture& dp) {
        this->trackSaveLayersForPicture(dp.picture, dp.paint);
    }

    void trackSaveLayers(const DrawDrawable& dp) {
        SkASSERT(fPictList);
        SkASSERT(dp.index >= 0 && dp.index < fPictList->count());
        const SkPaint* paint = NULL;    // drawables don't get a side-car paint
        this->trackSaveLayersForPicture(fPictList->begin()[dp.index], paint);
    }

    // Inform all the saveLayers already on the stack that they now have a
    // nested saveLayer inside them
    void updateStackForSaveLayer() {
        for (int index = fSaveLayerStack.count() - 1; index >= 0; --index) {
            if (fSaveLayerStack[index].fHasNestedSaveLayer) {
                break;
            }
            fSaveLayerStack[index].fHasNestedSaveLayer = true;
            if (fSaveLayerStack[index].fIsSaveLayer) {
                break;
            }
        }
    }

    void pushSaveLayerInfo(bool isSaveLayer, const SkRect* bounds, const SkPaint* paint) {
        if (isSaveLayer) {
            this->updateStackForSaveLayer();
            ++fSaveLayersInStack;
            fSaveLayerOpStack.push(fFillBounds.currentOp());
        }

        fSaveLayerStack.push(SaveLayerInfo(fFillBounds.currentOp(), isSaveLayer, bounds, paint));
    }

    void popSaveLayerInfo() {
        if (fSaveLayerStack.count() <= 0) {
            SkASSERT(false);
            return;
        }

        SkASSERT(fSaveLayersInStack == fSaveLayerOpStack.count());

        SaveLayerInfo sli;
        fSaveLayerStack.pop(&sli);

        if (!sli.fIsSaveLayer) {
            return;
        }

        --fSaveLayersInStack;

        SkLayerInfo::BlockInfo& block = fAccelData->addBlock();

        SkASSERT(NULL == block.fPicture);  // This layer is in the top-most picture

        block.fBounds = fFillBounds.getBounds(sli.fStartIndex);
        block.fLocalMat = fFillBounds.ctm();
        block.fPreMat = SkMatrix::I();
        if (sli.fPaint) {
            block.fPaint = SkNEW_ARGS(SkPaint, (*sli.fPaint));
        }

        block.fSrcBounds = sli.fBounds;
        block.fSaveLayerOpID = sli.fStartIndex;
        block.fRestoreOpID = fFillBounds.currentOp();
        block.fHasNestedLayers = sli.fHasNestedSaveLayer;
        block.fIsNested = fSaveLayersInStack > 0;

        block.fKeySize = fSaveLayerOpStack.count();
        block.fKey = SkNEW_ARRAY(unsigned, block.fKeySize);
        memcpy(block.fKey, fSaveLayerOpStack.begin(), block.fKeySize * sizeof(unsigned));

        fSaveLayerOpStack.pop();
    }

    // Used to collect saveLayer information for layer hoisting
    int                      fSaveLayersInStack;
    SkTDArray<SaveLayerInfo> fSaveLayerStack;
    // The op code indices of all the currently active saveLayers
    SkTDArray<unsigned>      fSaveLayerOpStack;
    SkLayerInfo*             fAccelData;
    const SkPicture::SnapshotArray* fPictList;

    SkRecords::FillBounds fFillBounds;
};

}  // namespace SkRecords

void SkRecordFillBounds(const SkRect& cullRect, const SkRecord& record, SkBBoxHierarchy* bbh) {
    SkRecords::FillBounds visitor(cullRect, record);

    for (unsigned curOp = 0; curOp < record.count(); curOp++) {
        visitor.setCurrentOp(curOp);
        record.visit<void>(curOp, visitor);
    }

    visitor.cleanUp(bbh);
}

void SkRecordComputeLayers(const SkRect& cullRect, const SkRecord& record,
                           const SkPicture::SnapshotArray* pictList, SkBBoxHierarchy* bbh,
                           SkLayerInfo* data) {
    SkRecords::CollectLayers visitor(cullRect, record, pictList, data);

    for (unsigned curOp = 0; curOp < record.count(); curOp++) {
        visitor.setCurrentOp(curOp);
        record.visit<void>(curOp, visitor);
    }

    visitor.cleanUp(bbh);
}


text:
<?php

namespace Wunderlist\Entity;

use JMS\Serializer\Annotation\Type;

class Note implements IdentifiableInterface
{
    use Revisionable,
        Identifiable,
        Timestampable;

    /**
     * @var integer
     * @Type("integer")
     */
    protected $taskId;

    /**
     * @var string
     * @Type("string")
     */
    protected $content;

    /**
     * @return int
     */
    public function getTaskId()
    {
        return $this->taskId;
    }

    /**
     * @param int $taskId
     * @return $this
     */
    public function setTaskId($taskId)
    {
        $this->taskId = $taskId;
        return $this;
    }

    /**
     * @return string
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * @param string $content
     * @return $this
     */
    public function setContent($content)
    {
        $this->content = $content;
        return $this;
    }
}


text:
from models import UXCscale, UDHscale
from django.contrib import admin

class UXCscaleAdmin(admin.ModelAdmin):
    pass

class UDHscaleAdmin(admin.ModelAdmin):
    pass

admin.site.register(UXCscale, UXCscaleAdmin)
admin.site.register(UDHscale, UDHscaleAdmin)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 9: 45 (1955)

#### Original name
Meliola panici var. major Hansf.

### Remarks
null


text:
package com.zsz.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zsz.jdbc.Dao;
import com.zsz.jdbc.Users;

public class QueryServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet.

	 *
	 * This method is called when a form has its tag value method equals to get.
	 *
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet.

	 *
	 * This method is called when a form has its tag value method equals to post.
	 *
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
//
		Dao Duser=new Dao();
		List<Users> userList =Duser.getAllUsers();
//
		request.setAttribute("UserL", userList);
//
		request.getRequestDispatcher("QueryUsers.jsp").forward(request,  response);
		out.flush();
		out.close();
	}

}


text:
/**
 * LogEnhancer
 *
 * Used within AngularJS to enhance functionality within the AngularJS $log service.
 *
 * @author  Thomas Burleson
 * @website http://www.theSolutionOptimist.com
 *
 */
(function(define){
    "use strict";

    var dependencies          = [
            'myApp/utils/supplant',
            'myApp/utils/DateTime',
            'myApp/utils/BrowserDetect'
        ];

    define( dependencies, function( supplant, DateTime, BrowserDetect )
    {
        var enchanceLogger = function( $log )
            {
                var separator = "::",
                    /**
                     * Chrome Dev tools supports color logging
                     * @see https://developers.google.com/chrome-developer-tools/docs/console#styling_console_output_with_css
                     */
                    colorify  = function( message, colorCSS )
                    {
                        var isChrome    = ( BrowserDetect.browser == "Chrome"),
                            canColorize = isChrome && (colorCSS !== undefined );

                        return canColorize ? [ "%c" + message, colorCSS ] : [ message ];
                    },
                    /**
                     * Partial application to pre-capture a logger function
                     */
                    prepareLogFn = function( logFn, className, colorCSS )
                    {
                        /**
                         * Invoke the specified `logFn` with the supplant functionality...
                         */
                        var enhancedLogFn = function ( )
                            {
                                var args = Array.prototype.slice.call(arguments),
                                    now  = DateTime.formattedNow();

                                // prepend a timestamp and optional classname to the original output message
                                args[0] = supplant("{0} - {1}{2}", [ now, className, args[0] ]);
                                args    = colorify( supplant.apply( null, args ), colorCSS );

                                logFn.apply( null, args );
                            };

                        return enhancedLogFn;
                    },
                    /**
                     * Support to generate class-specific logger instance with classname only
                     *
                     * @param className Name of object in which $log.<function> calls is invoked.
                     * @param colorCSS Object with CSS style color information for Chrome Dev Tools console log colorizing
                     *
                     * @returns {*} Logger instance
                     */
                    getInstance = function( className, colorCSS )
                    {
                        className = ( className !== undefined ) ? className + separator : "";

                        return {
                            log   : prepareLogFn( $log.log,    className, colorCSS ),
                            info  : prepareLogFn( $log.info,   className, colorCSS ),
                            warn  : prepareLogFn( $log.warn,   className, colorCSS ),
                            debug : prepareLogFn( $log.debug,  className, colorCSS ),
                            error : prepareLogFn( $log.error,  className )  // NO styling of ERROR messages
                        };
                    };

                $log.log   = prepareLogFn( $log.log );
                $log.info  = prepareLogFn( $log.info );
                $log.warn  = prepareLogFn( $log.warn );
                $log.debug = prepareLogFn( $log.debug );
                $log.error = prepareLogFn( $log.error );

                // Add special method to AngularJS $log
                $log.getInstance = getInstance;

                return $log;
            };

        return enchanceLogger;
    });

})(define);


text:
layout: post
category: class
style: text
title: Introduction to Unity3d
class_date: 2014-01-18
upcoming: false
start: 1pm
end: 5pm
location: Brooklyn, NY
registration_url: https://www.eventbrite.com/event/9224596015
fee_list: [["Students", "$80"],
           ["Freelancers", "$120"],
           ["Everyone Else", "$250"]]
published: true
instructor: Jeff Crouse
---

Unity3D is a high performance game engine that supports tons of platforms, including MacOS, Windows, iOS, Android, web plugin, PS3, XBox, and Wii.  It also features the PhysX physics engine, a full animation system, FMOD for spatialized audio, and a pretty nice asset market, too!  All wrapped in an easy to use interface.

This 4 hour workshop will cover the following:

Creating basic GameObjects

Prefabs

Using the built in physics engine (RigidBody, Colliders)

Importing 3D models and other assets

Basic scripting using both JavaScript and C#

Animating using the Animation interface

Particle systems

3D Audio effects

Camera effects, Skyboxes, Lighting

Character Controller

Unity is a commercial game engine, but there is a free version available with most of the features of the commercial version. If you'd like to participate, I recommend downloading and installing before coming to the workshop.

Prerequisites

For the scripting section of the workshop, you should have some familiarity with some kind of programming language.


text:
from __future__ import absolute_import

from sqlalchemy.engine import create_engine
from sqlalchemy import Table, Column, select
from sqlalchemy.schema import MetaData, CreateTable

from impala.sqlalchemy import STRING, INT, DOUBLE, TINYINT, DATE, VARCHAR
from impala.tests.util import ImpylaTestEnv

TEST_ENV = ImpylaTestEnv()

def create_partitioned_test_table(engine):
    metadata = MetaData(engine)
    # TODO: add other types to this table (e.g., functional.all_types)
    return Table("mytable",
                    metadata,
                    Column('col1', STRING),
                    Column('col2', TINYINT),
                    Column('col3', INT),
                    Column('col4', DOUBLE),
                    Column('col5', DATE),
                    Column('col6', VARCHAR(10)),
                    impala_partitioned_by='(part_col STRING)',
                    impala_stored_as='PARQUET',
                    impala_table_properties={
                      'transactional': 'true',
                      'transactional_properties': 'insert_only'
                    })

def create_simple_test_table(engine):
  metadata = MetaData(engine)
  return Table("mytable",
               metadata,
               Column('col1', STRING),
               Column('col2', TINYINT),
               Column('col3', INT),
               Column('col4', DOUBLE)
               )

def create_test_engine(diealect):
    return create_engine('{0}://{1}:{2}'.format(diealect, TEST_ENV.host, TEST_ENV.port))

def test_sqlalchemy_impala_compilation():
    engine = create_test_engine("impala")
    observed = CreateTable(create_partitioned_test_table(engine), bind=engine)
    # The DATE column type of 'col5' will be replaced with TIMESTAMP.
    expected = ('\nCREATE TABLE mytable (\n\tcol1 STRING, \n\tcol2 TINYINT, '
                '\n\tcol3 INT, \n\tcol4 DOUBLE, \n\tcol5 TIMESTAMP, \n\tcol6 VARCHAR(10)\n)'
                '\nPARTITIONED BY (part_col STRING)\nSTORED AS PARQUET\n'
                "TBLPROPERTIES ('transactional' = 'true', "
                "'transactional_properties' = 'insert_only')\n\n")
    assert expected == str(observed)

def test_sqlalchemy_impala4_compilation():
    engine = create_test_engine("impala4")
    observed = CreateTable(create_partitioned_test_table(engine), bind=engine)
    # The DATE column type of 'col5' will be left as is.
    expected = ('\nCREATE TABLE mytable (\n\tcol1 STRING, \n\tcol2 TINYINT, '
                '\n\tcol3 INT, \n\tcol4 DOUBLE, \n\tcol5 DATE, \n\tcol6 VARCHAR(10)\n)'
                '\nPARTITIONED BY (part_col STRING)\nSTORED AS PARQUET\n'
                "TBLPROPERTIES ('transactional' = 'true', "
                "'transactional_properties' = 'insert_only')\n\n")
    assert expected == str(observed)

def test_sqlalchemy_multiinsert():
    engine = create_test_engine("impala4")
    table = create_simple_test_table(engine)
    # TODO: Creating a non partitioned table as I am not sure about how to insert to
    #       a partitioned table in SQL alchemy
    create_table_stmt = CreateTable(table, bind=engine)

    data = [
        {"col1": "a", "col2": 1, "col3": 1, "col4": 1.0},
        {"col1": "b", "col2": 2, "col3": 3, "col4": 2.0}
    ]
    insert_stmt = table.insert(data)
    expected_insert = 'INSERT INTO mytable (col1, col2, col3, col4) VALUES '\
        '(%(col1_m0)s, %(col2_m0)s, %(col3_m0)s, %(col4_m0)s), '\
        '(%(col1_m1)s, %(col2_m1)s, %(col3_m1)s, %(col4_m1)s)'
    assert expected_insert == str(insert_stmt)

    engine.execute(create_table_stmt)
    try:
        engine.execute(insert_stmt)
        result = engine.execute(select(table.c).order_by(table.c.col1)).fetchall()
        expected_result = [('a', 1, 1, 1.0), ('b', 2, 3, 2.0)]
        assert expected_result == result
    finally:
        table.drop()


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Form\Type;

use Doctrine\Common\Persistence\ManagerRegistry;
use Oro\Bundle\EntityConfigBundle\Config\Id\EntityConfigId;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Form\Type\WorkflowSelectType;
use Oro\Bundle\WorkflowBundle\Helper\WorkflowTranslationHelper;
use Oro\Component\Testing\Unit\PreloadedExtension;
use Symfony\Component\Form\ChoiceList\View\ChoiceView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Test\FormIntegrationTestCase;
use Symfony\Contracts\Translation\TranslatorInterface;

class WorkflowSelectTypeTest extends FormIntegrationTestCase
{
    const TEST_ENTITY_CLASS   = 'Test\Entity\Class';
    const TEST_WORKFLOW_NAME  = 'test_workflow_name';
    const TEST_WORKFLOW_LABEL = 'Test Workflow Label';

    /** @var \PHPUnit\Framework\MockObject\MockObject|ManagerRegistry */
    protected $registry;

    /** @var WorkflowSelectType */
    protected $type;

    /** @var \PHPUnit\Framework\MockObject\MockObject|TranslatorInterface */
    protected $translator;

    protected function setUp()
    {
        $this->registry = $this->getMockBuilder(ManagerRegistry::class)->disableOriginalConstructor()->getMock();

        $this->translator = $this->createMock('Symfony\Contracts\Translation\TranslatorInterface');

        $this->type = new WorkflowSelectType($this->registry, $this->translator);
        parent::setUp();
    }

    protected function tearDown()
    {
        parent::tearDown();

        unset($this->registry, $this->type);
    }

    /**
     * {@inheritdoc}
     */
    protected function getExtensions()
    {
        return [
            new PreloadedExtension(
                [
                    $this->type
                ],
                []
            ),
        ];
    }

    /**
     * @param array $inputOptions
     * @param array $expectedOptions
     * @dataProvider configureOptionsDataProvider
     */
    public function testConfigureOptions(array $inputOptions, array $expectedOptions)
    {
        $testWorkflowDefinition = new WorkflowDefinition();
        $testWorkflowDefinition->setName(self::TEST_WORKFLOW_NAME)
            ->setLabel(self::TEST_WORKFLOW_LABEL);

        $repository = $this->getMockBuilder('Doctrine\ORM\EntityRepository')
            ->disableOriginalConstructor()
            ->getMock();
        $repository->expects($this->any())
            ->method('findBy')
            ->with(['relatedEntity' => self::TEST_ENTITY_CLASS])
            ->will($this->returnValue([$testWorkflowDefinition]));

        $this->registry->expects($this->any())
            ->method('getRepository')
            ->with(WorkflowDefinition::class)
            ->will($this->returnValue($repository));

        $form = $this->factory->create(WorkflowSelectType::class, null, $inputOptions);

        $actualOptions = $form->getConfig()->getOptions();
        foreach ($expectedOptions as $name => $expectedValue) {
            $this->assertArrayHasKey($name, $actualOptions);
            $this->assertEquals($expectedValue, $actualOptions[$name]);
        }
    }

    /**
     * @return array
     */
    public function configureOptionsDataProvider()
    {
        return [
            'no additional data' => [
                'inputOptions' => [],
                'expectedOptions' => [
                    'entity_class' => null,
                    'choices' => [],
                ]
            ],
            'custom choices' => [
                'inputOptions' => [
                    'choices' => ['key' => 'value']
                ],
                'expectedOptions' => [
                    'choices' => ['key' => 'value'],
                ]
            ],
            'custom entity class' => [
                'inputOptions' => [
                    'entity_class' => self::TEST_ENTITY_CLASS,
                ],
                'expectedOptions' => [
                    'entity_class' => self::TEST_ENTITY_CLASS,
                    'choices' => [self::TEST_WORKFLOW_LABEL => self::TEST_WORKFLOW_NAME],
                ]
            ],
            'parent configuration id' => [
                'inputOptions' => [
                    'config_id' => new EntityConfigId('test', self::TEST_ENTITY_CLASS),
                ],
                'expectedOptions' => [
                    'choices' => [self::TEST_WORKFLOW_LABEL => self::TEST_WORKFLOW_NAME],
                ]
            ],
        ];
    }

    public function testFinishView()
    {
        $label = 'test_label';
        $translatedLabel = 'translated_test_label';

        $view = new FormView();
        $view->vars['choices'] = [new ChoiceView([], 'test', $label)];

        $this->translator->expects($this->once())
            ->method('trans')
            ->with($label, [], WorkflowTranslationHelper::TRANSLATION_DOMAIN)
            ->willReturn($translatedLabel);

        $this->type->finishView($view, $this->createMock(FormInterface::class), []);

        $this->assertEquals([new ChoiceView([], 'test', $translatedLabel)], $view->vars['choices']);
    }
}


text:
package org.codenergic.theskeleton.post;

import org.codenergic.theskeleton.core.data.AbstractAuditingEntity;
import org.codenergic.theskeleton.user.UserEntity;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "ts_post_reaction", uniqueConstraints = {@UniqueConstraint(columnNames = {"post_id", "user_id", "reaction_type"})})
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class PostReactionEntity extends AbstractAuditingEntity {
	@NotNull
	@ManyToOne
	@JoinColumn(name = "post_id", nullable = false)
	private PostEntity post;
	@NotNull
	@ManyToOne
	@JoinColumn(name = "user_id", nullable = false)
	private UserEntity user;
	@NotNull
	@Enumerated(EnumType.STRING)
	@Column(name = "reaction_type", nullable = false)
	private PostReactionType reactionType;

	public PostEntity getPost() {
		return post;
	}

	public PostReactionEntity setPost(PostEntity post) {
		this.post = post;
		return this;
	}

	public PostReactionType getReactionType() {
		return reactionType;
	}

	public PostReactionEntity setReactionType(PostReactionType reactionType) {
		this.reactionType = reactionType;
		return this;
	}

	public UserEntity getUser() {
		return user;
	}

	public PostReactionEntity setUser(UserEntity user) {
		this.user = user;
		return this;
	}
}


text:
//
//  ImageAndTextCell.m
//  Vienna
//
//  Created by Steve on Sat Jan 24 2004.
//  Copyright (c) 2004-2005 Steve Palmer. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "ImageAndTextCell.h"

#import "TreeNode.h"

/* All of this stuff taken from public stuff published
 * by Apple.
 */
@implementation ImageAndTextCell

@synthesize image = image;

/* init
 * Initialise a default instance of our cell.
 */
-(instancetype)init
{
	if ((self = [super init]) != nil)
	{
		image = nil;
		auxiliaryImage = nil;
		offset = 0;
		hasCount = NO;
		count = 0;
        countLabelShadow = [self defaultCountLabelShadow];
		[self setCountBackgroundColour:NSColor.systemGrayColor];
	}
	return self;
}

- (id)copyWithZone:(NSZone *)zone {
	ImageAndTextCell *cell = (ImageAndTextCell *)[super copyWithZone:zone];
	cell->image = image;
	cell->auxiliaryImage = auxiliaryImage;
	cell->offset = offset;
	cell->hasCount = hasCount;
	cell->count = count;
	cell->inProgress = inProgress;
	cell->countBackgroundColour = countBackgroundColour;
    cell->countBackgroundColourGradientEnd = countBackgroundColourGradientEnd;
    cell->countLabelShadow = countLabelShadow;
	cell->item = item;

	return cell;
}

/* setOffset
 * Sets the new offset at which the cell contents will be drawn.
 */
-(void)setOffset:(NSInteger)newOffset
{
	offset = newOffset;
}

/* offset
 * Returns the current cell offset in effect.
 */
-(NSInteger)offset
{
	return offset;
}

/* setAuxiliaryImage
 * Sets the auxiliary image to be displayed. Nil removes any existing
 * auxiliary image.
 */
-(void)setAuxiliaryImage:(NSImage *)newAuxiliaryImage
{
	auxiliaryImage = newAuxiliaryImage;
}

/* auxiliaryImage
 * Returns the current auxiliary image.
 */
-(NSImage *)auxiliaryImage
{
	return auxiliaryImage;;
}

/* setCount
 * Sets the value to be displayed in the count button.
 */
-(void)setCount:(NSInteger)newCount
{
	count = newCount;
	hasCount = YES;
}

/* clearCount
 * Removes the count button.
 */
-(void)clearCount
{
	hasCount = NO;
}

/* setCountBackgroundColour
 * Sets the colour used for the count button background.
 */
-(void)setCountBackgroundColour:(NSColor *)newColour
{
	countBackgroundColour = newColour;

    NSColor *newColourRGB = [newColour colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]];

    if (newColourRGB)
    {
        countBackgroundColourGradientEnd = [NSColor colorWithHue:newColourRGB.hueComponent
                                                      saturation:newColourRGB.saturationComponent - 0.07
                                                      brightness:newColourRGB.brightnessComponent + 0.07
                                                           alpha:newColourRGB.alphaComponent];
    }
    else
    {
        countBackgroundColourGradientEnd = countBackgroundColour.copy;
    }
}

/* setInProgress
 * Set whether an active progress should be shown for the item. This should be used in a willDisplayCell: style method.
 */
-(void)setInProgress:(BOOL)newInProgress
{
	inProgress = newInProgress;
}

/* setItem
 * Set the item which is being displayed. This should be used in a willDisplayCell: style method.
 */
-(void)setItem:(TreeNode *)newItem
{
	item = newItem;
}

/* drawCellImage
 * Just draw the cell image.
 */
-(void)drawCellImage:(NSRect *)cellFrame inView:(NSView *)controlView
{
	if (image != nil)
	{
		NSSize imageSize;
		NSRect imageFrame;

		imageSize = image.size;
		NSDivideRect(*cellFrame, &imageFrame, cellFrame, 3 + imageSize.width, NSMinXEdge);
		imageFrame.origin.x += 3;
		imageFrame.size = imageSize;
		// vertically center
		imageFrame.origin.y += (cellFrame->size.height - imageSize.height) / 2.0;

        [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0f respectFlipped:YES hints:NULL];

	}
}

/* drawInteriorWithFrame:inView:
 * Draw the cell complete the image and count button if specified.
 */
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
	// If the cell has an image, draw the image and then reduce
	// cellFrame to move the text to the right of the image.
	if (image != nil)
		[self drawCellImage:&cellFrame inView:controlView];

	// If we have an error image, it appears on the right hand side.
	if (auxiliaryImage)
	{
		NSSize imageSize;
		NSRect imageFrame;

		imageSize = auxiliaryImage.size;
		NSDivideRect(cellFrame, &imageFrame, &cellFrame, 3 + imageSize.width, NSMaxXEdge);
		imageFrame.size = imageSize;
		// vertically center
		imageFrame.origin.y += (cellFrame.size.height - imageSize.height) / 2.0;

        [auxiliaryImage drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1.0f respectFlipped:YES hints:NULL];

	}

	// If the cell has a count button, draw the count
	// button on the right of the cell.
	if (hasCount)
	{
		NSString * number = [NSString stringWithFormat:@"%li", (long)count];

		// Use the current font point size as a guide for the count font size
		CGFloat pointSize = self.font.pointSize;

		// Create attributes for drawing the count.
		NSDictionary * attributes = @{NSFontAttributeName: [NSFont fontWithName:@"Helvetica-Bold" size:pointSize],
			NSForegroundColorAttributeName: [NSColor whiteColor]};
		NSSize numSize = [number sizeWithAttributes:attributes];

		// Compute the dimensions of the count rectangle.
		CGFloat cellWidth = MAX(numSize.width + 6.0, numSize.height + 1.0) + 1.0;

		NSRect countFrame;
		NSDivideRect(cellFrame, &countFrame, &cellFrame, cellWidth, NSMaxXEdge);

        // Provide a small amount of additional visual padding beyond the actual
        // count rectangle to ensure the text does not hit the edge of the count bubble
        cellFrame.size.width -= 4.0;

		countFrame.origin.y += 1;
		countFrame.size.height -= 2;

        NSBezierPath *bp = [NSBezierPath bezierPath];
        CGFloat radius = MIN(numSize.height / 2, 0.5f * MIN(NSWidth(countFrame), NSHeight(countFrame)));
        NSRect rect = NSInsetRect(countFrame, radius, radius);
        [bp appendBezierPathWithArcWithCenter:NSMakePoint(NSMinX(rect), NSMinY(rect)) radius:radius startAngle:180.0 endAngle:270.0];
        [bp appendBezierPathWithArcWithCenter:NSMakePoint(NSMaxX(rect), NSMinY(rect)) radius:radius startAngle:270.0 endAngle:360.0];
        [bp appendBezierPathWithArcWithCenter:NSMakePoint(NSMaxX(rect), NSMaxY(rect)) radius:radius startAngle:  0.0 endAngle: 90.0];
        [bp appendBezierPathWithArcWithCenter:NSMakePoint(NSMinX(rect), NSMaxY(rect)) radius:radius startAngle: 90.0 endAngle:180.0];
        [bp closePath];

        NSGradient * countLabelGradient = [[NSGradient alloc] initWithStartingColor:countBackgroundColour endingColor:countBackgroundColourGradientEnd];
        [countLabelGradient drawInBezierPath:bp angle:-90.0];

        // Push new graphics state so we can draw using a shadow if needed
        [NSGraphicsContext saveGraphicsState];
        {
            if (countLabelShadow)
                [countLabelShadow set];

            // Draw the count in the rounded rectangle we just created.
            NSPoint point = NSMakePoint(NSMidX(countFrame) - numSize.width / 2.0f,  NSMidY(countFrame) - numSize.height / 2.0f );
            [number drawAtPoint:point withAttributes:attributes];
        }
        [NSGraphicsContext restoreGraphicsState];
	}

	// Draw the text
	cellFrame.origin.x += 2;
	cellFrame.size.height -= 1;

	[super drawInteriorWithFrame:cellFrame inView:controlView];
}

- (NSString *)accessibilityLabel {
    NSMutableArray *bits = [NSMutableArray arrayWithCapacity:3];

    if (auxiliaryImage && auxiliaryImage.accessibilityDescription) {
        [bits addObject:auxiliaryImage.accessibilityDescription];
    }

    if (hasCount) {
        [bits addObject:[NSString stringWithFormat:NSLocalizedString(@"%d unread articles", nil), (int)count]];
    }

    if (inProgress) {
        [bits addObject:NSLocalizedString(@"Loading", nil)];
    }

    if (bits.count) {
        return [bits componentsJoinedByString:@", "];
    } else {
        return [super accessibilityLabel];
    }
}

-(NSShadow *)defaultCountLabelShadow
{
    NSShadow *shadow = [NSShadow new];
    shadow.shadowColor = [NSColor colorWithWhite:0 alpha:0.1];
    shadow.shadowBlurRadius = 1.0;
    shadow.shadowOffset = NSMakeSize(0.0, -1.0);

    return shadow;
}

@end


text:
package edu.utah.further.mdr.ws.impl.domain;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * DTS web service unit test suite. Note: run mvn jetty:run before running this
 * suite.
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, AVP Health Sciences IT Office, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author Oren E. Livne {@code <oren.livne@utah.edu>}
 * @version Feb 18, 2009
 */
@RunWith(Suite.class)
@Suite.SuiteClasses(
{ UTestMarshalEntities.class })
public final class SuiteDomain
{
}


text:
<?php
require_once __DIR__.'/src/Module.php';


text:
[![Build Status](https://travis-ci.org/maddevsio/screen-monitoring.svg?branch=master)](https://travis-ci.org/maddevsio/screen-monitoring)
#Screen Monitor project

## Installation

1. Install Go 1.7.x or greater, git, setup `$GOPATH`, and `PATH=$PATH:$GOPATH/bin`
2. Install nodejs 5.8 or greater
3. Run `npm install`
4. Run `npm run build`
```
cd $GOPATH/src/github.com/maddevsio/screen-monitoring
go get -v && go build -v
./screen-monitoring
```

## Docker
```
docker build -t screen-monitoring .
docker run -p 8888:8080 -it --rm --name my_screen_monitoring screen-monitoring
```

###Example Dashboard API

#### Step 1 (Create page for widgets)

Request:

```
curl -H "Content-Type: application/json" -X POST -d '{"title":"First page","visible":true}' http://localhost:8080/dashboard/v1/page/new
```

Response (success):
```
{"Id":1,"Success":true}
```

Response (fail):
```
{"error":"Do: UNIQUE constraint failed: pages.title"}
```

#### Step 2 (Register widget)

```
curl -H "Content-Type: application/json" -X POST -d '{"id": "github_http_agent2", "width": 200, "height": 122, "content": "", "url":"http://www.w3schools.com/html/default.asp"}' http://localhost:8080/dashboard/v1/register
```

Response (success):

```
{"Success":true}
```

Response (fail) (only for invalid data inside JSON):

```
{"error":"Decode: invalid character 's' looking for beginning of value"}
```

#### Step 3 (Register widget on page)

```
curl -X GET http://localhost:8080/dashboard/v1/register/github_http_agent2/page/1

```

Note:

```
http://localhost:8080/dashboard/v1/register/{widgetId}/page/{pageId}
```

Response (success): `{"Success":true}`

Response (fail):
```
{"error":"Do: UNIQUE constraint failed: page_widgets.id_widget, page_widgets.id_page"}
```

###React sources:
  * Install node.js version ```>= 5.8```
  * Execute: ```npm install```
  * For Development:
    * Execute ```npm run build```
    * Created files ```index.html```, ```bundle-[hash].js```, ```bundle-[hash].js.map``` inside ```public```
  * For Production:
    * Execute ```npm run build-production```
    * Created files ```index.html```, ```bundle-[hash].js``` inside ```public```

###Running Go backend service:
  * Execute: ```go build``` then ```./screen-monitoring```
  * Open browser and use url ```http://localhost:8080/```
  * See dashboard page without widgets

###Agents:
  * Every agent should register using dashboard api ```/dashboard/v1/register```
  * Make ```POST``` request to ```/dashboard/v1/register``` with data, for example

  ```
  {
    "id": "github_http_agent",
    "width": 200,
    "height": 122,
    "content": "",
    "url": "http://IP_OF_AGENT/api/method/for/getting/html/page/with/js/and/css"
  }
  ```
  * Now new parameter url used for fetching agents html page and loading this page inside iframe

###Dashboard
  * After agents registration need refresh browser page for displaying all registered agents (because now simple solution realized)

###Migrations
  * Automatic
    * When application starts database created automatically and migrations apply to database.
    * If database exists, then only new migrations applied.
  * Manual running migrations
    * Install go-migrate using command:
      ```
      go get -u github.com/mattes/migrate
      ```
    * Create db:
      ```
      touch screen_monitoring.db
      ```
    * For migrations run command:
      ```
      migrate -url sqlite3://screen_monitoring.db -path ./dashboard/migrations up
      ```
    * This command will create database file with name ```screen_monitoring```
      inside root directory of project

### URL of monitoring application
   * ```#/unregistered``` - displays list with unregistered widgets.
   * ```#/pages/list```   - displays list of pages with ability to add new page
   * ```#/pages/new```    - displays form for adding new page.


text:
import novaclient.exceptions

from rally.benchmark import context
from rally.common.i18n import _
from rally.common import log as logging
from rally.common import utils
from rally import osclients
from rally.plugins.openstack.context.cleanup import manager as resource_manager

LOG = logging.getLogger(__name__)

@context.context(name="keypair", order=310)
class Keypair(context.Context):
    KEYPAIR_NAME = "rally_ssh_key"

    def _generate_keypair(self, endpoint):
        keypair_name = "%s_%s" % (
            self.KEYPAIR_NAME, self.context["task"]["uuid"])

        nova_client = osclients.Clients(endpoint).nova()

        # NOTE(hughsaunders): If keypair exists, it must be deleted as we can't
        # retrieve the private key
        try:
            nova_client.keypairs.delete(keypair_name)
        except novaclient.exceptions.NotFound:
            pass

        keypair = nova_client.keypairs.create(keypair_name)
        return {"private": keypair.private_key,
                "public": keypair.public_key,
                "name": keypair_name,
                "id": keypair.id}

    @utils.log_task_wrapper(LOG.info, _("Enter context: `keypair`"))
    def setup(self):
        for user in self.context["users"]:
            user["keypair"] = self._generate_keypair(user["endpoint"])

    @utils.log_task_wrapper(LOG.info, _("Exit context: `keypair`"))
    def cleanup(self):
        # TODO(boris-42): Delete only resources created by this context
        resource_manager.cleanup(names=["nova.keypairs"],
                                 users=self.context.get("users", []))


text:
package post

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/codedellemc/gorackhd/models"
)

// PostLookupsIDReader is a Reader for the PostLookupsID structure.
type PostLookupsIDReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the recieved o.
func (o *PostLookupsIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewPostLookupsIDOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	default:
		result := NewPostLookupsIDDefault(response.Code())
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	}
}

// NewPostLookupsIDOK creates a PostLookupsIDOK with default headers values
func NewPostLookupsIDOK() *PostLookupsIDOK {
	return &PostLookupsIDOK{}
}

/*PostLookupsIDOK handles this case with default header values.

waterline response
*/
type PostLookupsIDOK struct {
	Payload PostLookupsIDOKBodyBody
}

func (o *PostLookupsIDOK) Error() string {
	return fmt.Sprintf("[POST /lookups/{id}][%d] postLookupsIdOK  %+v", 200, o.Payload)
}

func (o *PostLookupsIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	// response payload
	if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewPostLookupsIDDefault creates a PostLookupsIDDefault with default headers values
func NewPostLookupsIDDefault(code int) *PostLookupsIDDefault {
	return &PostLookupsIDDefault{
		_statusCode: code,
	}
}

/*PostLookupsIDDefault handles this case with default header values.

Unexpected error
*/
type PostLookupsIDDefault struct {
	_statusCode int

	Payload *models.Error
}

// Code gets the status code for the post lookups ID default response
func (o *PostLookupsIDDefault) Code() int {
	return o._statusCode
}

func (o *PostLookupsIDDefault) Error() string {
	return fmt.Sprintf("[POST /lookups/{id}][%d] PostLookupsID default  %+v", o._statusCode, o.Payload)
}

func (o *PostLookupsIDDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.Error)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

/*PostLookupsIDOKBodyBody post lookups ID o k body body

swagger:model PostLookupsIDOKBodyBody
*/
type PostLookupsIDOKBodyBody interface{}


text:
package org.laladev.moneyjinn.service;

public class CacheNames {

	public static final String USER_BY_ID = "userById";
	public static final String USER_BY_NAME = "userByName";

	public static final String ALL_ACCESS_RELATIONS_BY_USER_ID = "allAccessRelationsByUserId";
	public static final String ACCESS_RELATION_BY_USER_ID_AND_DATE = "accessRelationsByUserIdDate";

	public static final String ALL_GROUPS = "allGroups";
	public static final String GROUP_BY_ID = "groupById";

	public static final String ALL_POSTINGACCOUNTS = "allPostingAccounts";
	public static final String POSTINGACCOUNT_BY_ID = "postingAccountById";

	public static final String ALL_CAPITALSOURCES = "allCapitalsources";
	public static final String GROUP_CAPITALSOURCES_BY_DATE = "groupCapitalsourcesByDate";
	public static final String CAPITALSOURCE_BY_ID = "capitalsourceById";

	public static final String ALL_CONTRACTPARTNER = "allContractpartner";
	public static final String ALL_CONTRACTPARTNER_BY_DATE = "allContractpartnerByDate";
	public static final String CONTRACTPARTNER_BY_ID = "contractpartnerById";

	public static final String ALL_PRE_DEF_MONEYFLOWS = "allPreDefMoneyflows";

	public static final String MONEYFLOW_BY_ID = "moneyflowById";
	public static final String MONEYFLOW_YEARS = "moneyflowYears";
	public static final String MONEYFLOW_MONTH = "moneyflowMonths";

	public static final String CONTRACTPARTNER_ACCOUNT_BY_ID = "contractpartnerAccountById";
	public static final String CONTRACTPARTNER_ACCOUNTS_BY_PARTNER = "contractpartnerAccountsByPartner";

	private CacheNames() {

	}

}


text:
module Houdini
  class Task
    attr :options
    protected :options

    def initialize(klass, blueprint, options={})
      @class_name         = klass.name
      @blueprint          = blueprint.to_s
      @input              = options[:input]
      @after_submit       = options[:after_submit]
      @on_task_completion = options[:on_task_completion]
      @finder             = options[:finder] || :find
      @id_method          = options[:id_method] || :id
    end

    def process(object_id, results, verbose_results)
      # we have to re-constantize the class name because Rails reloads the classes in development
      obj = self.class.callable @class_name.constantize, @finder, object_id
      self.class.callable obj, @on_task_completion, results, verbose_results  if @on_task_completion
    end

    def submit!(object, options={})
      get_input   = options[:input_transformer] || self.class.method(:get_input)
      submit_task = options[:submit_task]       || Houdini.method(:submit!)

      id = self.class.callable object, @id_method

      submit_task.call @blueprint, object.class.name, id, get_input.call(object, @input)

      self.class.callable(object, @after_submit) if @after_submit
    end

    def self.get_input(object, input)
      input.inject({}) do |hash, (info_name, model_attribute)|
        hash.merge info_name => callable(object, model_attribute){ model_attribute }
      end
    end

    def self.callable(object, callable, *args)
      if callable.is_a? Symbol
        object.send callable, *args
      elsif callable.respond_to? :call
        object.instance_exec *args, &callable
      elsif block_given?
        yield callable, *args
      else
        raise "#{callable.inspect} is not a Symbol and does not respond to #call"
      end
    end
  end
end


text:
This code is based on fast-rcnn.

**Good Luck!**


text:
exec ruby -S -x $0 "$@"
#!ruby
# coding: utf-8

##### require
require 'yaml'
require 'optparse'
require 'fileutils'
require 'pp'

if RUBY_VERSION >= '1.9.2'
  require_relative 'lib/config.rb'
  require_relative 'lib/func.rb'
  require_relative 'lib/init.rb'
  require_relative 'lib/targetwrapper.rb'
else
  require File.expand_path(File.dirname(__FILE__) + '/lib/config.rb')
  require File.expand_path(File.dirname(__FILE__) + '/lib/func.rb')
  require File.expand_path(File.dirname(__FILE__) + '/lib/init.rb')
  require File.expand_path(File.dirname(__FILE__) + '/lib/targetwrapper.rb')
end

##### option parse
option = {}
OptionParser.new do |opt|
  opt.on('-H', '--hosts=VALUE', 'The host list separated by a comma') {|v| option[:hosts] = v}
  opt.on('-f', '--file=VALUE', 'input file (Required)') {|v| option[:input_file] = v}
  opt.parse!(ARGV)
end
pp option if $DEBUG

if option[:input_file] == nil
  puts "ERROR: option"
  puts "\t--file <input file>"
  exit 1
end
if option[:hosts] != nil
  targets = option[:hosts].split(',')
else
  targets = ['localhost']
end

##### configuration
work_dir = File.expand_path(File.dirname(__FILE__))
Dir.chdir(work_dir)
if work_dir == '/'
  puts "ERROR: This script do not suppport run on root(/)."
  exit 1
end

# read input file
input_data = YAML.load_file(option[:input_file])
pp input_data if $DEBUG

# read config file
config_list = ["default.yaml", "customize.yaml"]
config_list.map! { |name| File.join(work_dir, "conf", name) }
config = read_config_file(config_list)
pp config if $DEBUG

##### target open
targets.each do |target|
  puts '+' * 50
  puts " #{target}"
  puts '+' * 50
  begin
    server = TargetWrapper.new
    server.set_puppet_path(config['puppet']['path'])
    server.set_facter_path(config['facter']['path'])
    server.open(target, config['ssh']['user'], config['ssh']['options'])

    ##### scan uid
    user_id_hash = {}
    if config['resource']['file']['user_name'] == true
    puts 'create uid list'
    server.run("cat /etc/passwd").each_line do |line|
      user_info = line.split(':')
      user_id_hash[user_info[2]] = user_info[0]
    end
    end
    pp user_id_hash if config["verbose"]

    ##### scan gid
    group_id_hash = {}
    if config['resource']['file']['group_name'] == true
    puts 'create gid list'
    server.run("cat /etc/group").each_line do |line|
      group_info = line.split(':')
      group_id_hash[group_info[2]] = group_info[0]
    end
    end
    pp group_id_hash if config["verbose"]

    ##### create output directory
    puts '-' * 50
    puts 'create output directory - '
    puts puppet_dir = File.join(work_dir, 'receive', target)
    create_initial_directory(puppet_dir)

    ##### create initial puppet file
    puts '-' * 50
    puts 'create files - '
    create_initial_file(puppet_dir, config["verbose"])

    ##### create modules
    puts '-' * 50
    puts 'create modules - '

    hiera_value_hash = {}
    hiera_value_hash["classes"] = []
    input_data.each do |key, val|
    ##### class name
    puts '-'*3 + key
    if !val.kind_of?(Hash)
      puts 'Error : format error. skip.'
      next
    end
    class_name = key
    class_name = server.replace_facter(class_name, config['facter']['allow'], {:downcase => true, :space => false})
    if class_name.split('::').size != 2
      puts 'Error : format error. skip. ::'
      next
    end
    hiera_value_hash["classes"].push(class_name)

    module_dir, pp_name = class_name.split('::')
    module_dir = File.join(puppet_dir, 'modules', module_dir)
    pp_name += ".pp"
    puts pp_path = File.join(module_dir, 'manifests' , pp_name)

    ##### make class body
    class_body = ''
    params_list = []
    val.each do |resource, lists|
      #puts resource
      #pp lists
      case resource
      ##### user resource
      when "user" then
      lists.each do |user|
        ret = server.run("#{config['puppet']['path']} resource user #{user.gsub(' ', '')}")
        reject = config['resource']['user']['attributes']['reject']
        ret.each_line.reject { |line|
        is_match = false
        reject.each do |attributes|
          is_match = true if line =~ /\s*#{attributes}\s*=>\s*/
        end
        is_match
        }.each do|line|
        class_body += (' '*2 + line.chomp + "\n")
        end
        class_body += ("\n")
      end
      ##### group resource
      when "group" then
      lists.each do |group|
        ret = server.run("#{config['puppet']['path']} resource group #{group.gsub(' ', '')}")
        reject = config['resource']['group']['attributes']['reject']
        ret.each_line.reject { |line|
        is_match = false
        reject.each do |attributes|
          is_match = true if line =~ /\s*#{attributes}\s*=>\s*/
        end
        is_match
        }.each do|line|
        class_body += (' '*2 + line.chomp + "\n")
        end
        class_body += ("\n")
      end
      ##### file resource
      when "file" then
      lists.each do |file_info|
        if file_info.kind_of?(String)
        file = file_info
        content = "no_content"
        elsif file_info.kind_of?(Hash)
        file, content = file_info.flatten
        else
        puts "Error: file resource format"
        pp file_info
        end
    #        pp file
    #        pp content
        ret = server.run("#{config['puppet']['path']} resource file #{file.gsub(' ', '')}")
        content.gsub!(" ", "")
        is_complement_content_path = false
        if /.*=.*/ =~ content
        content_type = content.split('=')[0]
        content_path = content.split('=')[1]
        content_path.gsub!(/\\\"|\"|\'/, "")
        else
        content_type = content.gsub(" ", "")
        content_path = file.gsub(" ", "").gsub(/^\//, "#{class_name.split("::")[0]}/")
        is_complement_content_path = true
        end

        reject = config['resource']['file']['attributes']['reject']
        ret.each_line.reject { |line|
        is_match = false
        reject.each do |attributes|
          is_match = true if line =~ /\s*#{attributes}\s*=>\s*/
        end
        is_match
        }.each do|line|
        if /\s*owner\s*=>\s*'(\d+)',/ =~ line
          owner = user_id_hash.has_key?($1) ? user_id_hash[$1] : $1
          pre = line.match(/\s*owner\s*=>\s*'/)[0]
          post = line.match(/',$/)[0]
          line = pre + owner + post
        elsif /\s*group\s*=>\s*'(\d+)',/ =~ line
          group = group_id_hash.has_key?($1) ? group_id_hash[$1] : $1
          pre = line.match(/\s*group\s*=>\s*'/)[0]
          post = line.match(/',$/)[0]
          line = pre + group + post
        elsif /\s*content\s*=>\s*'.*',/ =~ line
          pre = line.match(/\s*content\s*=>\s*/)[0]
          post = line.match(/,$/)[0]

          if content_type == "template"
          if is_complement_content_path == true and /\.erb$/ !~ content_path
            content_path += ".erb"
          end
          template_parameter = config['resource']['file']['param_template']
          if template_parameter == true
            param_name = File.basename(file.gsub(" ", "")).gsub(/[\.\-]/, '_')+'_tmpl'
            file_dirname = File.dirname(file.gsub(" ", ""))
            while params_list.include?(param_name)
            if file_dirname == '/'
              puts "Error: #{file} was dupulicate"
              break
            end
            param_name = File.basename(file_dirname).gsub(/[\.\-]/, '_') + "_" + param_name
            file_dirname = File.dirname(file_dirname)
            end
            params_list.push(param_name)
            hiera_value_hash["#{class_name}::#{param_name}"] = server.replace_facter(content_path, config['facter']['allow'])
            line = pre + "template($#{param_name})" + post
          else
            line = pre + "template(\"" + content_path + "\")" + post
          end

          # template copy
          file_src = file.gsub(" ", "")
          module_name = content_path.gsub(/\/.*/, '')
          post_path = content_path.gsub(/^[^\/]*\//, '')
          file_dist = File.join(puppet_dir, 'modules', module_name, 'templates', post_path)
          file_dist = server.replace_facter(file_dist, config['facter']['allow'])

          FileUtils.mkdir_p (File.dirname(file_dist))
          puts "copy : #{file_src}"
          puts "  => : #{file_dist}"
          server.copy(file_src, file_dist)
          FileUtils.chmod("a+r", file_dist)
          elsif content_type == "source"
          pre.sub!("content", "source ")
          source_parameter = config['resource']['file']['param_source']
          if source_parameter == true
            param_name = File.basename(file.gsub(" ", "")).gsub(/[\.\-]/, '_')+'_src'
            file_dirname = File.dirname(file.gsub(" ", ""))
            while params_list.include?(param_name)
            if file_dirname == '/'
              puts "Error: #{file} was dupulicate"
              break
            end
            param_name = File.basename(file_dirname).gsub(/[\.\-]/, '_') + "_" + param_name
            file_dirname = File.dirname(file_dirname)
            end
            params_list.push(param_name)
            hiera_value_hash["#{class_name}::#{param_name}"] = server.replace_facter(content_path, config['facter']['allow'])
            line = pre + "\"puppet:///modules/" + "${#{param_name}}" + "\"" + post
          else
            line = pre + "\"puppet:///modules/" + content_path + "\"" + post
          end

          # source copy
          file_src = file.gsub(" ", "")
          module_name = content_path.gsub(/\/.*/, '')
          post_path = content_path.gsub(/^[^\/]*\//, '')
          file_dist = File.join(puppet_dir, 'modules', module_name, 'files', post_path)
          file_dist = server.replace_facter(file_dist, config['facter']['allow'])

          FileUtils.mkdir_p (File.dirname(file_dist))
          puts "copy : #{file_src}"
          puts "  => : #{file_dist}"
          server.copy(file_src, file_dist)
          FileUtils.chmod("a+r", file_dist)
          end
        end
        class_body += (' '*2 + line.chomp + "\n")
        end
        class_body += ("\n")
      end
      ##### service resource
      when "service" then
      lists.each do |service|
        ret = server.run("#{config['puppet']['path']} resource service #{service.gsub(' ', '')}")
        reject = config['resource']['service']['attributes']['reject']
        ret.each_line.reject { |line|
        is_match = false
        reject.each do |attributes|
          is_match = true if line =~ /\s*#{attributes}\s*=>\s*/
        end
        is_match
        }.each do|line|
        ensure_parameter = config['resource']['service']['param_ensure']
        if ensure_parameter == true
          if /\s*ensure\s*=>\s*'(.*)',/ =~ line
          ensure_val = $1
          param_name = service.gsub(" ", "").gsub(/[\.\-]/, '_')+'_ensure'
          params_list.push(param_name)
          hiera_value_hash["#{class_name}::#{param_name}"] = ensure_val
          pre = line.match(/\s*ensure\s*=>\s*/)[0]
          post = line.match(/,$/)[0]
          line = pre + "$#{param_name}" + post
          end
        end

        enable_parameter = config['resource']['service']['param_enable']
        if enable_parameter == true
          if /\s*enable\s*=>\s*'(.*)',/ =~ line
          enable_val = $1
          param_name = service.gsub(" ", "").gsub(/[\.\-]/, '_')+'_enable'
          params_list.push(param_name)
          hiera_value_hash["#{class_name}::#{param_name}"] = enable_val
          pre = line.match(/\s*enable\s*=>\s*/)[0]
          post = line.match(/,$/)[0]
          line = pre + "$#{param_name}" + post
          end
        end

        class_body += (' '*2 + line.chomp + "\n")
        end
        class_body += ("\n")
      end
      ##### package resource
      when "package" then
      lists.each do |package|
      ret = server.run("#{config['puppet']['path']} resource package #{package.gsub(' ', '')}")
      reject = config['resource']['package']['attributes']['reject']
      ret.each_line.reject { |line|
        is_match = false
        reject.each do |attributes|
        is_match = true if line =~ /\s*#{attributes}\s*=>\s*/
        end
        is_match
        }.each do|line|
        ensure_parameter = config['resource']['package']['param_ensure']
        if ensure_parameter == true
          if /\s*ensure\s*=>\s*'(.*)',/ =~ line
          ensure_val = $1
          param_name = package.gsub(" ", "").gsub(/[\.\-]/, '_')+'_ensure'
          params_list.push(param_name)
          hiera_value_hash["#{class_name}::#{param_name}"] = ensure_val
          pre = line.match(/\s*ensure\s*=>\s*/)[0]
          post = line.match(/,$/)[0]
          line = pre + "$#{param_name}" + post
          end
        end

        class_body += (' '*2 + line.chomp + "\n")
        end
        class_body += ("\n")
      end
      ##### yumrepo resource
      when "yumrepo" then
      lists.each do |yumrepo|
        ret = server.run("#{config['puppet']['path']} resource yumrepo #{yumrepo.gsub(' ', '')}")
        reject = config['resource']['yumrepo']['attributes']['reject']
        ret.each_line.reject { |line|
        is_match = false
        reject.each do |attributes|
          is_match = true if line =~ /\s*#{attributes}\s*=>\s*/
        end
        is_match
        }.each do|line|
        ensure_parameter = config['resource']['yumrepo']['param_ensure']
        if ensure_parameter == true
          if /\s*ensure\s*=>\s*'(.*)',/ =~ line
          ensure_val = $1
          param_name = yumrepo.gsub(" ", "").gsub(/[\.\-]/, '_')+'_ensure'
          params_list.push(param_name)
          hiera_value_hash["#{class_name}::#{param_name}"] = ensure_val
          pre = line.match(/\s*ensure\s*=>\s*/)[0]
          post = line.match(/,$/)[0]
          line = pre + "$#{param_name}" + post
          end
        end

        enabled_parameter = config['resource']['yumrepo']['param_enabled']
        if enabled_parameter == true
          if /\s*enabled\s*=>\s*'(.*)',/ =~ line
          enabled_val = $1
          param_name = yumrepo.gsub(" ", "").gsub(/[\.\-]/, '_')+'_enabled'
          params_list.push(param_name)
          hiera_value_hash["#{class_name}::#{param_name}"] = enabled_val
          pre = line.match(/\s*enabled\s*=>\s*/)[0]
          post = line.match(/,$/)[0]
          line = pre + "$#{param_name}" + post
          end
        end

        class_body += (' '*2 + line.chomp + "\n")
        end
        class_body += ("\n")
      end
      else
      puts "Error: not support resource #{resource}"
      pp lists
      end
    end

    ##### output class
    if config["verbose"]
      puts "class #{class_name} ("
      params_list.each do |param|
      puts " "*2 + "$#{param},"
      end
      puts ") {"
      puts ""
      puts class_body
      puts "}"
      puts ""
    end

    FileUtils.mkdir_p (File.dirname(pp_path))
    File::open(pp_path, "w") do |fio|
      fio.puts "class #{class_name} ("
      params_list.each do |param|
      fio.puts " "*2 + "$#{param},"
      end
      fio.puts ") {"
      fio.puts ""
      fio.puts class_body
      fio.puts "}"
      fio.puts ""
    end

    end

    ##### output hieradata
    puts '-' * 50
    puts 'create hieradata - '
    hostname = server.run("#{config['facter']['path']} hostname").chomp
    puts yaml_file = File.join(puppet_dir, 'hieradata', "#{hostname}.yaml")
    hiera_data = YAML.dump(hiera_value_hash)
    puts hiera_data if config["verbose"]
    File::open(yaml_file, "w") do |fio|
    fio.puts hiera_data
    end
  rescue => exc
    p exc
  ensure
    server.close
  end
  puts ''
end


text:
<bill session="110" type="hr" number="1466" updated="2009-01-09T10:57:54-05:00">
	<status><vote date="1222109580" datetime="2008-09-22T15:53:00-04:00" where="h" result="pass" how="by voice vote" roll=""/></status>

	<introduced date="1221710400" datetime="2008-09-18"/>
	<titles>
		<title type="official" as="introduced">Honoring Dr. Guion S. "Guy" Bluford, Jr., and the 25th anniversary of his historic flight as the first African-American in space.</title>
	</titles>
	<sponsor id="412263"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1221710400" datetime="2008-09-18"><text>Referred to the House Committee on Science and Technology.</text></action>
		<action date="1222109040" datetime="2008-09-22T15:44:00-04:00"><text>Ms. Edwards (MD) moved to suspend the rules and agree to the resolution.</text></action>
		<action date="1222109040" datetime="2008-09-22T15:44:00-04:00"><text>Considered under suspension of the rules.</text><reference label="consideration" ref="CR H8533-8534"/></action>
		<action date="1222109040" datetime="2008-09-22T15:44:00-04:00"><text>DEBATE - The House proceeded with forty minutes of debate on H. Res. 1466.</text></action>
		<vote date="1222109580" how="by voice vote" datetime="2008-09-22T15:53:00-04:00" where="h" type="vote" result="pass" ><text>On motion to suspend the rules and agree to the resolution Agreed to by voice vote.</text><reference label="text" ref="CR H8533-8534"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	9/22/2008--Passed House without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.)
Salutes the 25th anniversary of the pioneering accomplishments of Dr. Guion "Guy" S. Bluford, Jr. as the first African-American in space.
Extends gratitude and deep appreciation of the House of Representatives for Dr. Bluford's dedication, commitment, and excellence as an astronaut and a leader in support of the nation's space program.

</bill>


text:
Polysquare Travis Container
===========================

Creates a self-contained package-management installation, without root access.

This allows you to install a pre-defined set of packages to a directory and
then execute commands using the packages installed in that directory.

Supports Windows, OS X and Linux.

On Windows and OS X, local versions of chocolatey and brew are installed
respectively, with packages installing to the specified folder. Commands
are executed with environment variables set such that the locally
installed packages will be used by any software built or installed
using the `psq-travis-container-exec` wrapper. Only the host architecture
is supported.

On Linux, [`proot`](http://proot.me) is used to "containerize" a downloaded
linux distribution, where the package manage operates only on the directory
in which the downloaded linux distribution exists. This allows you to
install packages using `apt-get` or `yum` without touching other
system files. `proot` allow allows for different architectures to be
specified as well, which are emulated transparently using the
`qemu-user-mode` tool.

For Linux, an alternative 'local' option is also provided which does not
incur the overhead of `proot` but is not as flexible. Sadly, on Travis-CI,
`proot` no longer functions correctly and so the latter mode of operation
is required.

Status
------

| Travis CI (Ubuntu) | AppVeyor (Windows) | Coverage | PyPI | Licence |
|--------------------|--------------------|----------|------|---------|
|[![Travis](https://img.shields.io/travis/polysquare/polysquare-travis-container.svg)](http://travis-ci.org/polysquare/polysquare-travis-container)|[![AppVeyor](https://img.shields.io/appveyor/ci/smspillaz/polysquare-travis-container-vd3yj.svg)](https://ci.appveyor.com/project/smspillaz/polysquare-travis-container-vd3yj)|[![Coveralls](https://img.shields.io/coveralls/polysquare/polysquare-travis-container.svg)](http://coveralls.io/polysquare/polysquare-travis-container)|[![PyPIVersion](https://img.shields.io/pypi/v/polysquare-travis-container.svg)](https://pypi.python.org/pypi/polysquare-travis-container)[![PyPIPythons](https://img.shields.io/pypi/pyversions/polysquare-travis-container.svg)](https://pypi.python.org/pypi/polysquare-travis-container)|[![License](https://img.shields.io/github/license/polysquare/polysquare-travis-container.svg)](http://github.com/polysquare/polysquare-travis-container)|

Caveats
-------

64 bit executables cannot be emulated on a 32 bit architecture.

Installation
------------

`polysquare-travis-container` can be installed using using `pip` from PyPI

Creating a container
--------------------

Containers can be created with `psq-travis-container-create`:

    usage: psq-travis-container-create [-h] [--distro {Fedora,
                                                       Debian,
                                                       Ubuntu,
                                                       Windows,
                                                       OSX}]
                                       [--release RELEASE]
                                       [--arch {ppc,x86_64,x86,arm}]
                                       [--repositories REPOSITORIES]
                                       [--packages PACKAGES]
                                       CONTAINER_DIRECTORY

    Create a Travis CI container If an arg is specified in more than one place,
    then command-line values override environment variables which override
    defaults.

    positional arguments:
      CONTAINER_DIRECTORY   Directory to place container in

    optional arguments:
      -h, --help            show this help message and exit
      --distro {Fedora,Debian,Ubuntu,Windows,OSX}
                            Distribution name to create container of
                            [env var: CONTAINER_DISTRO]
      --release RELEASE     Distribution release to create container of
                            [env var: CONTAINER_RELEASE]
      --arch {ppc,x86_64,x86,arm}
                            Architecture (all architectures other than the
                            system architecture will be emulated with qemu)
                            [env var: CONTAINER_ARCH]
      --repositories REPOSITORIES
                            A file containing a list of repositories to add
                            before installing packages.  Special keywords will
                            control the operation of this file: {release}: The
                            distribution release (eg, precise) {ubuntu}: Ubuntu
                            archive URL {launchpad}: Launchpad PPA URL header
                            (eg, http://ppa.launchpad.net)
      --packages PACKAGES   A file containing a list of packages to install

The distribution filesystem itself is placed in a subdirectory of
`CONTAINER_DIRECTORY`, so multiple distribution configurations can be placed in
a single `CONTAINER_DIRECTORY`. A mini-distribution of `proot` will also be
placed in `CONTAINER_DIRECTORY`. This directory should be cached, for instance:

    cache:
      directories:
      - CONTAINER_DIRECTORY

Packages will only be installed if the container is being created and not
restored from the cache. To install additional packages, the travis caches
should be deleted.

Special directories like `/tmp` and `/home` are linked automatically, so you
can run binaries or scripts directly from the project root.

Using a container
-----------------

To run a command inside a container, use `psq-travis-container-exec`:

    usage: psq-travis-container-exec [-h] [--distro {Fedora,
                                                     Debian,
                                                     Ubuntu,
                                                     Windows,
                                                     OSX}]
                                     [--release RELEASE]
                                     [--arch {ppc,x86_64,x86,arm}] --cmd
                                     [CMD [CMD ...]]
                                     CONTAINER_DIRECTORY

    Use a Travis CI container If an arg is specified in more than one place,
    then command-line values override environment variables which override
    defaults.

    positional arguments:
      CONTAINER_DIRECTORY   Directory to place container in

    optional arguments:
      -h, --help            show this help message and exit
      --distro {Fedora,Debian,Ubuntu,Windows,OSX}
                            Distribution name to create container of
                            [env var: CONTAINER_DISTRO]
      --release RELEASE     Distribution release to create container of
                            [env var: CONTAINER_RELEASE]
      --arch {ppc,x86_64,x86,arm}
                            Architecture (all architectures other than the
                            system architecture will be emulated with qemu)
                            [env var: CONTAINER_ARCH]
      -- [CMD [CMD ...]]    Command to run inside of container

Executables in CMD are resolved relative to the distribution container, so
running `bash` would run `CONTAINER_DIR/bin/bash` and not `/bin/bash`
inside travis.

The `--container`, `--release` and `--arch` options are used to select a
pre-existing distribution container set up with `psq-travis-container-create`.


text:
namespace MaterialDesignColors.WpfExample.Domain
{
    public enum DocumentationLinkType
    {
        Wiki,
        DemoPageSource,
        ControlSource,
        StyleSource,
        Video
    }
}