text:
#ifndef SKY_ENGINE_PLATFORM_GRAPHICS_GRAPHICSCONTEXT_H_
#define SKY_ENGINE_PLATFORM_GRAPHICS_GRAPHICSCONTEXT_H_

#include "flutter/sky/engine/platform/PlatformExport.h"
#include "flutter/sky/engine/platform/fonts/Font.h"
#include "flutter/sky/engine/platform/geometry/FloatRect.h"
#include "flutter/sky/engine/platform/graphics/DashArray.h"
#include "flutter/sky/engine/platform/graphics/DrawLooperBuilder.h"
#include "flutter/sky/engine/platform/graphics/GraphicsContextState.h"
#include "flutter/sky/engine/platform/graphics/ImageFilter.h"
#include "flutter/sky/engine/platform/graphics/ImageOrientation.h"
#include "flutter/sky/engine/platform/graphics/RegionTracker.h"
#include "flutter/sky/engine/platform/graphics/skia/SkiaUtils.h"
#include "flutter/sky/engine/wtf/FastAllocBase.h"
#include "flutter/sky/engine/wtf/Forward.h"
#include "flutter/sky/engine/wtf/Noncopyable.h"
#include "flutter/sky/engine/wtf/PassOwnPtr.h"

class SkBitmap;
class SkPaint;
class SkPath;
class SkRRect;
class SkTextBlob;
struct SkRect;

namespace blink {

class KURL;

class PLATFORM_EXPORT GraphicsContext {
    WTF_MAKE_NONCOPYABLE(GraphicsContext); WTF_MAKE_FAST_ALLOCATED;
public:
    enum AntiAliasingMode {
        NotAntiAliased,
        AntiAliased
    };
    enum AccessMode {
        ReadOnly,
        ReadWrite
    };

    enum DisabledMode {
        NothingDisabled = 0, // Run as normal.
        FullyDisabled = 1 // Do absolutely minimal work to remove the cost of the context from performance tests.
    };

    explicit GraphicsContext(SkCanvas*, DisabledMode = NothingDisabled);
    ~GraphicsContext();

    // Returns the canvas used for painting. Must not be called if painting is disabled.
    // Accessing the backing canvas this way flushes all queued save ops,
    // so it should be avoided. Use the corresponding draw/matrix/clip methods instead.
    SkCanvas* canvas()
    {
        // Flush any pending saves.
        realizeCanvasSave();

        return m_canvas;
    }
    const SkCanvas* canvas() const
    {
        return m_canvas;
    }

    void resetCanvas(SkCanvas*);

    bool contextDisabled() const { return m_disabledState; }

    // ---------- State management methods -----------------
    void save();
    void restore();
    unsigned saveCount() { return m_canvasStateStack.size(); }
#if ENABLE(ASSERT)
    void disableDestructionChecks() { m_disableDestructionChecks = true; }
#endif

    void saveLayer(const SkRect* bounds, const SkPaint*);
    void restoreLayer();

    bool hasStroke() const { return strokeStyle() != NoStroke && strokeThickness() > 0; }

    float strokeThickness() const { return immutableState()->strokeData().thickness(); }
    void setStrokeThickness(float thickness) { mutableState()->setStrokeThickness(thickness); }

    StrokeStyle strokeStyle() const { return immutableState()->strokeData().style(); }
    void setStrokeStyle(StrokeStyle style) { mutableState()->setStrokeStyle(style); }

    Color strokeColor() const { return immutableState()->strokeData().color(); }
    void setStrokeColor(const Color& color) { mutableState()->setStrokeColor(color); }
    SkColor effectiveStrokeColor() const { return immutableState()->effectiveStrokeColor(); }

    Pattern* strokePattern() const { return immutableState()->strokeData().pattern(); }
    void setStrokePattern(PassRefPtr<Pattern>);

    Gradient* strokeGradient() const { return immutableState()->strokeData().gradient(); }
    void setStrokeGradient(PassRefPtr<Gradient>);

    void setLineCap(LineCap cap) { mutableState()->setLineCap(cap); }
    void setLineDash(const DashArray& dashes, float dashOffset) { mutableState()->setLineDash(dashes, dashOffset); }
    void setLineJoin(LineJoin join) { mutableState()->setLineJoin(join); }
    void setMiterLimit(float limit) { mutableState()->setMiterLimit(limit); }

    WindRule fillRule() const { return immutableState()->fillRule(); }
    void setFillRule(WindRule fillRule) { mutableState()->setFillRule(fillRule); }

    Color fillColor() const { return immutableState()->fillColor(); }
    void setFillColor(const Color& color) { mutableState()->setFillColor(color); }
    SkColor effectiveFillColor() const { return immutableState()->effectiveFillColor(); }

    void setFillPattern(PassRefPtr<Pattern>);
    Pattern* fillPattern() const { return immutableState()->fillPattern(); }

    void setFillGradient(PassRefPtr<Gradient>);
    Gradient* fillGradient() const { return immutableState()->fillGradient(); }

    const sk_sp<SkDrawLooper>& drawLooper() const { return immutableState()->drawLooper(); }

    bool getTransformedClipBounds(FloatRect* bounds) const;
    SkMatrix getTotalMatrix() const;

    void setShouldAntialias(bool antialias) { mutableState()->setShouldAntialias(antialias); }
    bool shouldAntialias() const { return immutableState()->shouldAntialias(); }

    // Disable the anti-aliasing optimization for scales/multiple-of-90-degrees
    // rotations of thin ("hairline") images.
    // Note: This will only be reliable when the device pixel scale/ratio is
    // fixed (e.g. when drawing to context backed by an ImageBuffer).
    void disableAntialiasingOptimizationForHairlineImages() { m_antialiasHairlineImages = true; }
    bool shouldAntialiasHairlineImages() const { return m_antialiasHairlineImages; }

    void setShouldClampToSourceRect(bool clampToSourceRect) { mutableState()->setShouldClampToSourceRect(clampToSourceRect); }
    bool shouldClampToSourceRect() const { return immutableState()->shouldClampToSourceRect(); }

    // FIXME: the setter is only used once, at construction time; convert to a constructor param,
    // and possibly consolidate with other flags (paintDisabled, isPrinting, ...)
    void setShouldSmoothFonts(bool smoothFonts) { m_shouldSmoothFonts = smoothFonts; }

    // Turn off LCD text for the paint if not supported on this context.
    void adjustTextRenderMode(SkPaint*);
    bool couldUseLCDRenderedText() const { return m_isCertainlyOpaque && m_shouldSmoothFonts; }

    void setTextDrawingMode(TextDrawingModeFlags mode) { mutableState()->setTextDrawingMode(mode); }
    TextDrawingModeFlags textDrawingMode() const { return immutableState()->textDrawingMode(); }

    void setAlphaAsFloat(float alpha) { mutableState()->setAlphaAsFloat(alpha);}
    int getNormalizedAlpha() const
    {
        int alpha = immutableState()->alpha();
        return alpha > 255 ? 255 : alpha;
    }

    void setImageInterpolationQuality(InterpolationQuality quality) { mutableState()->setInterpolationQuality(quality); }
    InterpolationQuality imageInterpolationQuality() const { return immutableState()->interpolationQuality(); }

    void setCompositeOperation(CompositeOperator, WebBlendMode = WebBlendModeNormal);
    CompositeOperator compositeOperation() const { return immutableState()->compositeOperator(); }
    WebBlendMode blendModeOperation() const { return immutableState()->blendMode(); }

    // Speicy the device scale factor which may change the way document markers
    // and fonts are rendered.
    void setDeviceScaleFactor(float factor) { m_deviceScaleFactor = factor; }
    float deviceScaleFactor() const { return m_deviceScaleFactor; }

    // If true we are (most likely) rendering to a web page and the
    // canvas has been prepared with an opaque background. If false,
    // the canvas may have transparency (as is the case when rendering
    // to a canvas object).
    void setCertainlyOpaque(bool isOpaque) { m_isCertainlyOpaque = isOpaque; }

    bool isAccelerated() const { return m_accelerated; }
    void setAccelerated(bool accelerated) { m_accelerated = accelerated; }

    // The opaque region is empty until tracking is turned on.
    // It is never clerared by the context.
    enum RegionTrackingMode {
        RegionTrackingDisabled = 0,
        RegionTrackingOpaque,
        RegionTrackingOverwrite
    };
    void setRegionTrackingMode(RegionTrackingMode);
    bool regionTrackingEnabled() { return m_regionTrackingMode != RegionTrackingDisabled; }
    const RegionTracker& opaqueRegion() const { return m_trackedRegion; }

    // The text region is empty until tracking is turned on.
    // It is never clerared by the context.
    void setTrackTextRegion(bool track) { m_trackTextRegion = track; }
    const SkRect& textRegion() const { return m_textRegion; }

    SkColorFilter* colorFilter() const;
    void setColorFilter(ColorFilterObsolete);
    // ---------- End state management methods -----------------

    // Get the contents of the image buffer
    bool readPixels(const SkImageInfo&, void* pixels, size_t rowBytes, int x, int y);

    // Get the current fill style.
    const SkPaint& fillPaint() const { return immutableState()->fillPaint(); }

    // Get the current stroke style.
    const SkPaint& strokePaint() const { return immutableState()->strokePaint(); }

    // These draw methods will do both stroking and filling.
    // FIXME: ...except drawRect(), which fills properly but always strokes
    // using a 1-pixel stroke inset from the rect borders (of the correct
    // stroke color).
    void drawRect(const IntRect&);
    void drawLine(const IntPoint&, const IntPoint&);
    void drawConvexPolygon(size_t numPoints, const FloatPoint*, bool shouldAntialias = false);

    void fillPath(const Path&);
    void strokePath(const Path&);

    void fillEllipse(const FloatRect&);
    void strokeEllipse(const FloatRect&);

    void fillRect(const FloatRect&);
    void fillRect(const FloatRect&, const Color&);
    void fillRect(const FloatRect&, const Color&, CompositeOperator);
    void fillRoundedRect(const IntRect&, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color&);
    void fillRoundedRect(const RoundedRect&, const Color&);

    void clearRect(const FloatRect&);

    void strokeRect(const FloatRect&);
    void strokeRect(const FloatRect&, float lineWidth);

    void fillBetweenRoundedRects(const IntRect&, const IntSize& outerTopLeft, const IntSize& outerTopRight, const IntSize& outerBottomLeft, const IntSize& outerBottomRight,
        const IntRect&, const IntSize& innerTopLeft, const IntSize& innerTopRight, const IntSize& innerBottomLeft, const IntSize& innerBottomRight, const Color&);
    void fillBetweenRoundedRects(const RoundedRect&, const RoundedRect&, const Color&);

    void drawImage(Image*, const IntPoint&, CompositeOperator = CompositeSourceOver, RespectImageOrientationEnum = DoNotRespectImageOrientation);
    void drawImage(Image*, const IntRect&, CompositeOperator = CompositeSourceOver, RespectImageOrientationEnum = DoNotRespectImageOrientation);
    void drawImage(Image*, const FloatRect& destRect);
    void drawImage(Image*, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator = CompositeSourceOver, RespectImageOrientationEnum = DoNotRespectImageOrientation);
    void drawImage(Image*, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator, WebBlendMode, RespectImageOrientationEnum = DoNotRespectImageOrientation);

    void drawTiledImage(Image*, const IntRect& destRect, const IntPoint& srcPoint, const IntSize& tileSize,
        CompositeOperator = CompositeSourceOver, WebBlendMode = WebBlendModeNormal, const IntSize& repeatSpacing = IntSize());
    void drawTiledImage(Image*, const IntRect& destRect, const IntRect& srcRect,
        const FloatSize& tileScaleFactor, Image::TileRule hRule = Image::StretchTile, Image::TileRule vRule = Image::StretchTile,
        CompositeOperator = CompositeSourceOver);

    void drawBitmap(const SkBitmap&, SkScalar, SkScalar, const SkPaint* = 0);
    void drawBitmapRect(const SkBitmap&, const SkRect*, const SkRect&, const SkPaint* = 0);
    void drawOval(const SkRect&, const SkPaint&);
    void drawPath(const SkPath&, const SkPaint&);
    // After drawing directly to the context's canvas, use this function to notify the context so
    // it can track the opaque region.
    // FIXME: this is still needed only because ImageSkia::paintSkBitmap() may need to notify for a
    //        smaller rect than the one drawn to, due to its clipping logic.
    void didDrawRect(const SkRect&, const SkPaint&, const SkBitmap* = 0);
    void drawRect(const SkRect&, const SkPaint&);
    void drawPosText(const void* text, size_t byteLength, const SkPoint pos[], const SkRect& textRect, const SkPaint&);
    void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY, const SkRect& textRect, const SkPaint&);
    void drawTextBlob(const SkTextBlob*, const SkPoint& origin, const SkPaint&);

    void clip(const IntRect& rect) { clipRect(rect); }
    void clip(const FloatRect& rect) { clipRect(rect); }
    void clipRoundedRect(const RoundedRect&, SkClipOp = kIntersect_SkClipOp);
    void clipOut(const IntRect& rect) { clipRect(rect, NotAntiAliased, kDifference_SkClipOp); }
    void clipOutRoundedRect(const RoundedRect&);
    void clipPath(const Path&, WindRule = RULE_EVENODD);
    void clipConvexPolygon(size_t numPoints, const FloatPoint*, bool antialias = true);
    void clipRect(const SkRect&, AntiAliasingMode = NotAntiAliased, SkClipOp = kIntersect_SkClipOp);

    void drawText(const Font&, const TextRunPaintInfo&, const FloatPoint&);
    void drawEmphasisMarks(const Font&, const TextRunPaintInfo&, const AtomicString& mark, const FloatPoint&);
    void drawBidiText(const Font&, const TextRunPaintInfo&, const FloatPoint&, Font::CustomFontNotReadyAction = Font::DoNotPaintIfFontNotReady);
    void drawHighlightForText(const Font&, const TextRun&, const FloatPoint&, int h, const Color& backgroundColor, int from = 0, int to = -1);

    void drawLineForText(const FloatPoint&, float width);
    enum DocumentMarkerLineStyle {
        DocumentMarkerSpellingLineStyle,
        DocumentMarkerGrammarLineStyle
    };
    void drawLineForDocumentMarker(const FloatPoint&, float width, DocumentMarkerLineStyle);

    void beginTransparencyLayer(float opacity, const FloatRect* = 0);
    void beginLayer(float opacity, CompositeOperator, const FloatRect* = 0, ColorFilterObsolete = ColorFilterNone, SkImageFilter* = 0);
    void endLayer();

    bool hasShadow() const;
    void setShadow(const FloatSize& offset, float blur, const Color&,
        DrawLooperBuilder::ShadowTransformMode = DrawLooperBuilder::ShadowRespectsTransforms,
        DrawLooperBuilder::ShadowAlphaMode = DrawLooperBuilder::ShadowRespectsAlpha);
    void clearShadow() { clearDrawLooper(); }

    // It is assumed that this draw looper is used only for shadows
    // (i.e. a draw looper is set if and only if there is a shadow).
    // The builder passed into this method will be destroyed.
    void setDrawLooper(PassOwnPtr<DrawLooperBuilder>);
    void clearDrawLooper();

    enum Edge {
        NoEdge = 0,
        TopEdge = 1 << 1,
        RightEdge = 1 << 2,
        BottomEdge = 1 << 3,
        LeftEdge = 1 << 4
    };
    typedef unsigned Edges;
    void drawInnerShadow(const RoundedRect&, const Color& shadowColor, const IntSize shadowOffset, int shadowBlur, int shadowSpread, Edges clippedEdges = NoEdge);

    // This clip function is used only by <canvas> code. It allows
    // implementations to handle clipping on the canvas differently since
    // the discipline is different.
    void canvasClip(const Path&, WindRule = RULE_EVENODD);
    void clipOut(const Path&);

    // ---------- Transformation methods -----------------
    // Note that the getCTM method returns only the current transform from Blink's perspective,
    // which is not the final transform used to place content on screen. It cannot be relied upon
    // for testing where a point will appear on screen or how large it will be.
    AffineTransform getCTM() const;
    void concatCTM(const AffineTransform& affine) { concat(affineTransformToSkMatrix(affine)); }
    void setCTM(const AffineTransform& affine) { setMatrix(affineTransformToSkMatrix(affine)); }
    void setMatrix(const SkMatrix&);

    void scale(float x, float y);
    void rotate(float angleInRadians);
    void translate(float x, float y);

    // This function applies the device scale factor to the context, making the context capable of
    // acting as a base-level context for a HiDPI environment.
    void applyDeviceScaleFactor(float deviceScaleFactor) { scale(deviceScaleFactor, deviceScaleFactor); }
    // ---------- End transformation methods -----------------

    static void adjustLineToPixelBoundaries(FloatPoint& p1, FloatPoint& p2, float strokeWidth, StrokeStyle);

    void preparePaintForDrawRectToRect(
        SkPaint*,
        const SkRect& srcRect,
        const SkRect& destRect,
        CompositeOperator,
        WebBlendMode,
        bool isLazyDecoded = false,
        bool isDataComplete = true) const;

    static int focusRingOutsetExtent(int offset, int width)
    {
        return focusRingOutset(offset) + (focusRingWidth(width) + 1) / 2;
    }

private:
    const GraphicsContextState* immutableState() const { return m_paintState; }

    GraphicsContextState* mutableState()
    {
        realizePaintSave();
        return m_paintState;
    }

    static void setPathFromConvexPoints(SkPath*, size_t, const FloatPoint*);
    static void setRadii(SkVector*, IntSize, IntSize, IntSize, IntSize);

    static inline int focusRingOutset(int offset) { return 0; }
    static inline int focusRingWidth(int width) { return 1; }
    static SkPMColor lineColors(int);
    static SkPMColor antiColors1(int);
    static SkPMColor antiColors2(int);
    static void draw1xMarker(SkBitmap*, int);
    static void draw2xMarker(SkBitmap*, int);

    // Helpers for drawing a focus ring (drawFocusRing)
    float prepareFocusRingPaint(SkPaint&, const Color&, int width) const;
    void drawFocusRingPath(const SkPath&, const Color&, int width);
    void drawFocusRingRect(const SkRect&, const Color&, int width);

    // SkCanvas wrappers.
    void clipPath(const SkPath&, AntiAliasingMode = NotAntiAliased, SkClipOp = kIntersect_SkClipOp);
    void clipRRect(const SkRRect&, AntiAliasingMode = NotAntiAliased, SkClipOp = kIntersect_SkClipOp);
    void concat(const SkMatrix&);
    void drawRRect(const SkRRect&, const SkPaint&);

    // Apply deferred paint state saves
    void realizePaintSave()
    {
        if (contextDisabled())
            return;

        if (m_paintState->saveCount()) {
            m_paintState->decrementSaveCount();
            ++m_paintStateIndex;
            if (m_paintStateStack.size() == m_paintStateIndex) {
                m_paintStateStack.append(GraphicsContextState::createAndCopy(*m_paintState));
                m_paintState = m_paintStateStack[m_paintStateIndex].get();
            } else {
                GraphicsContextState* priorPaintState = m_paintState;
                m_paintState = m_paintStateStack[m_paintStateIndex].get();
                m_paintState->copy(*priorPaintState);
            }
        }
    }

    // Apply deferred canvas state saves
    void realizeCanvasSave()
    {
        if (!m_pendingCanvasSave || contextDisabled())
            return;

        m_canvas->save();
        m_pendingCanvasSave = false;
    }

    void didDrawTextInRect(const SkRect& textRect);

    void fillRectWithRoundedHole(const IntRect&, const RoundedRect& roundedHoleRect, const Color&);

    // null indicates painting is contextDisabled. Never delete this object.
    SkCanvas* m_canvas;

    // Paint states stack. Enables local drawing state change with save()/restore() calls.
    // This state controls the appearance of drawn content.
    // We do not delete from this stack to avoid memory churn.
    Vector<OwnPtr<GraphicsContextState> > m_paintStateStack;
    // Current index on the stack. May not be the last thing on the stack.
    unsigned m_paintStateIndex;
    // Raw pointer to the current state.
    GraphicsContextState* m_paintState;

    // Currently pending save flags for Skia Canvas state.
    // Canvas state includes the canavs, it's matrix and clips. Think of it as _where_
    // the draw operations will happen.
    struct CanvasSaveState;
    Vector<CanvasSaveState> m_canvasStateStack;
    bool m_pendingCanvasSave;

#if ENABLE(ASSERT)
    unsigned m_layerCount;
    bool m_disableDestructionChecks;
#endif
    // Tracks the region painted opaque via the GraphicsContext.
    RegionTracker m_trackedRegion;

    // Tracks the region where text is painted via the GraphicsContext.
    SkRect m_textRegion;

    unsigned m_disabledState;

    float m_deviceScaleFactor;

    // Activation for the above region tracking features
    unsigned m_regionTrackingMode : 2;
    bool m_trackTextRegion : 1;

    bool m_accelerated : 1;
    bool m_isCertainlyOpaque : 1;
    bool m_antialiasHairlineImages : 1;
    bool m_shouldSmoothFonts : 1;
};

} // namespace blink

#endif  // SKY_ENGINE_PLATFORM_GRAPHICS_GRAPHICSCONTEXT_H_


text:
package io.druid.benchmark.datagen;

import io.druid.segment.column.ValueType;
import org.apache.commons.math3.distribution.AbstractIntegerDistribution;
import org.apache.commons.math3.distribution.AbstractRealDistribution;
import org.apache.commons.math3.distribution.EnumeratedDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.distribution.UniformRealDistribution;
import org.apache.commons.math3.distribution.ZipfDistribution;
import org.apache.commons.math3.util.Pair;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class BenchmarkColumnValueGenerator
{
  private final BenchmarkColumnSchema schema;
  private final long seed;

  private Serializable distribution;
  private Random simpleRng;

  public BenchmarkColumnValueGenerator(
      BenchmarkColumnSchema schema,
      long seed
  )
  {
    this.schema = schema;
    this.seed = seed;

    simpleRng = new Random(seed);
    initDistribution();
  }

  public Object generateRowValue()
  {
    Double nullProbability = schema.getNullProbability();
    int rowSize = schema.getRowSize();

    if (nullProbability != null) {
      double randDouble = simpleRng.nextDouble();
      if (randDouble <= nullProbability) {
        return null;
      }
    }

    if (rowSize == 1) {
      return generateSingleRowValue();
    } else {
      List<Object> rowVals = new ArrayList<>(rowSize);
      for (int i = 0; i < rowSize; i++) {
        rowVals.add(generateSingleRowValue());
      }
      return rowVals;
    }
  }

  public BenchmarkColumnSchema getSchema()
  {
    return schema;
  }

  public long getSeed()
  {
    return seed;
  }

  private Object generateSingleRowValue()
  {
    Object ret = null;
    ValueType type = schema.getType();

    if (distribution instanceof AbstractIntegerDistribution) {
      ret = ((AbstractIntegerDistribution) distribution).sample();
    } else if (distribution instanceof AbstractRealDistribution) {
      ret = ((AbstractRealDistribution) distribution).sample();
    } else if (distribution instanceof EnumeratedDistribution) {
      ret = ((EnumeratedDistribution) distribution).sample();
    }

    ret = convertType(ret, type);
    return ret;
  }

  private Object convertType(Object input, ValueType type)
  {
    if (input == null) {
      return null;
    }

    Object ret;
    switch (type) {
      case STRING:
        ret = input.toString();
        break;
      case LONG:
        if (input instanceof Number) {
          ret = ((Number) input).longValue();
        } else {
          ret = Long.parseLong(input.toString());
        }
        break;
      case FLOAT:
        if (input instanceof Number) {
          ret = ((Number) input).floatValue();
        } else {
          ret = Float.parseFloat(input.toString());
        }
        break;
      default:
        throw new UnsupportedOperationException("Unknown data type: " + type);
    }
    return ret;
  }

  private void initDistribution()
  {
    BenchmarkColumnSchema.ValueDistribution distributionType = schema.getDistributionType();
    ValueType type = schema.getType();
    List<Object> enumeratedValues = schema.getEnumeratedValues();
    List<Double> enumeratedProbabilities = schema.getEnumeratedProbabilities();
    List<Pair<Object, Double>> probabilities = new ArrayList<>();

    switch (distributionType) {
      case SEQUENTIAL:
        // not random, just cycle through numbers from start to end, or cycle through enumerated values if provided
        distribution = new SequentialDistribution(
            schema.getStartInt(),
            schema.getEndInt(),
            schema.getEnumeratedValues()
        );
        break;
      case UNIFORM:
        distribution = new UniformRealDistribution(schema.getStartDouble(), schema.getEndDouble());
        break;
      case DISCRETE_UNIFORM:
        if (enumeratedValues == null) {
          enumeratedValues = new ArrayList<>();
          for (int i = schema.getStartInt(); i < schema.getEndInt(); i++) {
            Object val = convertType(i, type);
            enumeratedValues.add(val);
          }
        }
        // give them all equal probability, the library will normalize probabilities to sum to 1.0
        for (int i = 0; i < enumeratedValues.size(); i++) {
          probabilities.add(new Pair<>(enumeratedValues.get(i), 0.1));
        }
        distribution = new EnumeratedTreeDistribution<>(probabilities);
        break;
      case NORMAL:
        distribution = new NormalDistribution(schema.getMean(), schema.getStandardDeviation());
        break;
      case ROUNDED_NORMAL:
        NormalDistribution normalDist = new NormalDistribution(schema.getMean(), schema.getStandardDeviation());
        distribution = new RealRoundingDistribution(normalDist);
        break;
      case ZIPF:
        int cardinality;
        if (enumeratedValues == null) {
          Integer startInt = schema.getStartInt();
          cardinality = schema.getEndInt() - startInt;
          ZipfDistribution zipf = new ZipfDistribution(cardinality, schema.getZipfExponent());
          for (int i = 0; i < cardinality; i++) {
            probabilities.add(new Pair<>((Object) (i + startInt), zipf.probability(i)));
          }
        } else {
          cardinality = enumeratedValues.size();
          ZipfDistribution zipf = new ZipfDistribution(enumeratedValues.size(), schema.getZipfExponent());
          for (int i = 0; i < cardinality; i++) {
            probabilities.add(new Pair<>(enumeratedValues.get(i), zipf.probability(i)));
          }
        }
        distribution = new EnumeratedTreeDistribution<>(probabilities);
        break;
      case ENUMERATED:
        for (int i = 0; i < enumeratedValues.size(); i++) {
          probabilities.add(new Pair<>(enumeratedValues.get(i), enumeratedProbabilities.get(i)));
        }
        distribution = new EnumeratedTreeDistribution<>(probabilities);
        break;

      default:
        throw new UnsupportedOperationException("Unknown distribution type: " + distributionType);
    }

    if (distribution instanceof AbstractIntegerDistribution) {
      ((AbstractIntegerDistribution) distribution).reseedRandomGenerator(seed);
    } else if (distribution instanceof AbstractRealDistribution) {
      ((AbstractRealDistribution) distribution).reseedRandomGenerator(seed);
    } else {
      ((EnumeratedDistribution) distribution).reseedRandomGenerator(seed);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace {

class MockNetworkChangeNotifierNeverOffline :
    public net::NetworkChangeNotifier {
 public:
  net::NetworkChangeNotifier::ConnectionType GetCurrentConnectionType() const
      override {
    return NetworkChangeNotifier::CONNECTION_3G;
  }
};

class MockNetworkChangeNotifierOfflineUntilChange :
    public net::NetworkChangeNotifier {
 public:
  MockNetworkChangeNotifierOfflineUntilChange() : online_(false) {}
  net::NetworkChangeNotifier::ConnectionType GetCurrentConnectionType() const
      override {
    return online_ ? net::NetworkChangeNotifier::CONNECTION_3G
                   : net::NetworkChangeNotifier::CONNECTION_NONE;
  }

  void GoOnline() {
    online_ = true;
    net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests(
        net::NetworkChangeNotifier::CONNECTION_3G);
  }

 private:
  bool online_;
};

class CallbackTester {
 public:
  CallbackTester() : called_(0) {}

  void Increment();
  bool WasCalledExactlyOnce();

 private:
  int called_;
};

void CallbackTester::Increment() {
  called_++;
}

bool CallbackTester::WasCalledExactlyOnce() {
  return called_ == 1;
}

}  // namespace

class ChromeSigninClientTest : public testing::Test {
 public:
  ChromeSigninClientTest() {}
  void SetUp() override;

  Profile* profile() { return profile_.get(); }
  SigninClient* signin_client() { return signin_client_; }

 private:
  content::TestBrowserThreadBundle thread_bundle_;
  std::unique_ptr<Profile> profile_;
  SigninClient* signin_client_;
};

void ChromeSigninClientTest::SetUp() {
  // Create a signed-in profile.
  TestingProfile::Builder builder;
  profile_ = builder.Build();

  signin_client_ = ChromeSigninClientFactory::GetForProfile(profile());
}

TEST_F(ChromeSigninClientTest, DelayNetworkCallRunsImmediatelyWithNetwork) {
  std::unique_ptr<net::NetworkChangeNotifier> mock(
      new MockNetworkChangeNotifierNeverOffline);
  CallbackTester tester;
  signin_client()->DelayNetworkCall(base::Bind(&CallbackTester::Increment,
                                               base::Unretained(&tester)));
  ASSERT_TRUE(tester.WasCalledExactlyOnce());
}

TEST_F(ChromeSigninClientTest, DelayNetworkCallRunsAfterNetworkFound) {
  std::unique_ptr<MockNetworkChangeNotifierOfflineUntilChange> mock(
      new MockNetworkChangeNotifierOfflineUntilChange());
  // Install a SigninClient after the NetworkChangeNotifier's created.
  SetUp();

  CallbackTester tester;
  signin_client()->DelayNetworkCall(base::Bind(&CallbackTester::Increment,
                                               base::Unretained(&tester)));
  ASSERT_FALSE(tester.WasCalledExactlyOnce());
  mock->GoOnline();
  base::RunLoop().RunUntilIdle();
  ASSERT_TRUE(tester.WasCalledExactlyOnce());
}

#if !defined(OS_ANDROID)

class MockChromeSigninClient : public ChromeSigninClient {
 public:
  MockChromeSigninClient(Profile* profile, SigninErrorController* controller)
      : ChromeSigninClient(profile, controller) {}

  MOCK_METHOD1(ShowUserManager, void(const base::FilePath&));
  MOCK_METHOD1(LockForceSigninProfile, void(const base::FilePath&));
};

class MockSigninManager : public SigninManager {
 public:
  explicit MockSigninManager(SigninClient* client)
      : SigninManager(client, nullptr, &fake_service_, nullptr) {}

  MOCK_METHOD2(DoSignOut,
               void(signin_metrics::ProfileSignout,
                    signin_metrics::SignoutDelete));

  AccountTrackerService fake_service_;
};

class ChromeSigninClientSignoutTest : public BrowserWithTestWindowTest {
 public:
  void SetUp() override {
    BrowserWithTestWindowTest::SetUp();

    prefs_.reset(new TestingPrefServiceSimple());
    chrome::RegisterLocalState(prefs_->registry());
    TestingBrowserProcess::GetGlobal()->SetLocalState(prefs_.get());
    prefs_->SetBoolean(prefs::kForceBrowserSignin, true);

    CreateClient(browser()->profile());
    manager_.reset(new MockSigninManager(client_.get()));
  }

  void TearDown() override {
    BrowserWithTestWindowTest::TearDown();
    TestingBrowserProcess::GetGlobal()->SetLocalState(nullptr);
  }

  void CreateClient(Profile* profile) {
    SigninErrorController* controller = new SigninErrorController();
    client_.reset(new MockChromeSigninClient(profile, controller));
    fake_controller_.reset(controller);
  }

  std::unique_ptr<SigninErrorController> fake_controller_;
  std::unique_ptr<MockChromeSigninClient> client_;
  std::unique_ptr<MockSigninManager> manager_;
  std::unique_ptr<TestingPrefServiceSimple> prefs_;
};

TEST_F(ChromeSigninClientSignoutTest, SignOut) {
  signin_metrics::ProfileSignout source_metric =
      signin_metrics::ProfileSignout::SIGNOUT_TEST;
  signin_metrics::SignoutDelete delete_metric =
      signin_metrics::SignoutDelete::IGNORE_METRIC;

  EXPECT_CALL(*client_, ShowUserManager(browser()->profile()->GetPath()))
      .Times(1);
  EXPECT_CALL(*client_, LockForceSigninProfile(browser()->profile()->GetPath()))
      .Times(1);
  EXPECT_CALL(*manager_, DoSignOut(source_metric, delete_metric)).Times(1);

  manager_->SignOut(source_metric, delete_metric);
}

TEST_F(ChromeSigninClientSignoutTest, SignOutWithoutManager) {
  signin_metrics::ProfileSignout source_metric =
      signin_metrics::ProfileSignout::SIGNOUT_TEST;
  signin_metrics::SignoutDelete delete_metric =
      signin_metrics::SignoutDelete::IGNORE_METRIC;

  MockSigninManager other_manager(client_.get());
  other_manager.CopyCredentialsFrom(*manager_.get());

  EXPECT_CALL(*client_, ShowUserManager(browser()->profile()->GetPath()))
      .Times(0);
  EXPECT_CALL(*client_, LockForceSigninProfile(browser()->profile()->GetPath()))
      .Times(1);
  EXPECT_CALL(*manager_, DoSignOut(source_metric, delete_metric)).Times(1);
  manager_->SignOut(source_metric, delete_metric);

  ::testing::Mock::VerifyAndClearExpectations(manager_.get());

  EXPECT_CALL(*client_, ShowUserManager(browser()->profile()->GetPath()))
      .Times(1);
  EXPECT_CALL(*client_, LockForceSigninProfile(browser()->profile()->GetPath()))
      .Times(1);
  EXPECT_CALL(*manager_, DoSignOut(source_metric, delete_metric)).Times(1);
  manager_->SignOut(source_metric, delete_metric);
}

TEST_F(ChromeSigninClientSignoutTest, SignOutWithoutForceSignin) {
  prefs_->SetBoolean(prefs::kForceBrowserSignin, false);
  CreateClient(browser()->profile());
  manager_.reset(new MockSigninManager(client_.get()));

  signin_metrics::ProfileSignout source_metric =
      signin_metrics::ProfileSignout::SIGNOUT_TEST;
  signin_metrics::SignoutDelete delete_metric =
      signin_metrics::SignoutDelete::IGNORE_METRIC;

  EXPECT_CALL(*client_, ShowUserManager(browser()->profile()->GetPath()))
      .Times(0);
  EXPECT_CALL(*client_, LockForceSigninProfile(browser()->profile()->GetPath()))
      .Times(0);
  EXPECT_CALL(*manager_, DoSignOut(source_metric, delete_metric)).Times(1);
  manager_->SignOut(source_metric, delete_metric);
}

TEST_F(ChromeSigninClientSignoutTest, SignOutGuestSession) {
  TestingProfile::Builder builder;
  builder.SetGuestSession();
  std::unique_ptr<TestingProfile> profile = builder.Build();

  CreateClient(profile.get());
  manager_.reset(new MockSigninManager(client_.get()));

  signin_metrics::ProfileSignout source_metric =
      signin_metrics::ProfileSignout::SIGNOUT_TEST;
  signin_metrics::SignoutDelete delete_metric =
      signin_metrics::SignoutDelete::IGNORE_METRIC;

  EXPECT_CALL(*client_, ShowUserManager(browser()->profile()->GetPath()))
      .Times(0);
  EXPECT_CALL(*client_, LockForceSigninProfile(browser()->profile()->GetPath()))
      .Times(0);
  EXPECT_CALL(*manager_, DoSignOut(source_metric, delete_metric)).Times(1);
  manager_->SignOut(source_metric, delete_metric);
}

#endif  // !defined(OS_ANDROID)
#endif  // !defined(OS_CHROMEOS)


text:
package com.netflix.zeno.fastblob;

import static com.netflix.zeno.fastblob.FastBlobFrameworkSerializer.NULL_DOUBLE_BITS;
import static com.netflix.zeno.fastblob.FastBlobFrameworkSerializer.NULL_FLOAT_BITS;

import com.netflix.zeno.fastblob.record.ByteData;
import com.netflix.zeno.fastblob.record.FastBlobDeserializationRecord;
import com.netflix.zeno.fastblob.record.VarInt;
import com.netflix.zeno.fastblob.state.FastBlobTypeDeserializationState;
import com.netflix.zeno.serializer.FrameworkDeserializer;
import com.netflix.zeno.serializer.NFTypeSerializer;
import com.netflix.zeno.util.collections.CollectionImplementation;
import com.netflix.zeno.util.collections.MinimizedUnmodifiableCollections;
import com.netflix.zeno.util.collections.builder.ListBuilder;
import com.netflix.zeno.util.collections.builder.MapBuilder;
import com.netflix.zeno.util.collections.builder.SetBuilder;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 *
 * Defines the operations necessary to decode each of the "Zeno native" elements from FastBlob record fields.
 *
 * @author dkoszewnik
 *
 */
public class FastBlobFrameworkDeserializer extends FrameworkDeserializer<FastBlobDeserializationRecord> {

    private MinimizedUnmodifiableCollections minimizedCollections = new MinimizedUnmodifiableCollections(CollectionImplementation.JAVA_UTIL);

    public FastBlobFrameworkDeserializer(FastBlobStateEngine framework) {
        super(framework);
    }

    public void setCollectionImplementation(CollectionImplementation impl) {
        minimizedCollections = new MinimizedUnmodifiableCollections(impl);
    }

    /**
     * Read a boolean as a single byte.  Might be null.
     */
    @Override
    public Boolean deserializeBoolean(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        return byteData.get(fieldPosition) == (byte) 1 ? Boolean.TRUE : Boolean.FALSE;
    }

    /**
     * Read a boolean as a single byte.
     */
    @Override
    public boolean deserializePrimitiveBoolean(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        return byteData.get(fieldPosition) == (byte) 1;
    }

    /**
     * Read an integer as a variable-byte sequence.  After read, the value must be zig-zag decoded.  Might be null.
     */
    @Override
    public Integer deserializeInteger(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int value = VarInt.readVInt(byteData, fieldPosition);

        return Integer.valueOf((value >>> 1) ^ ((value << 31) >> 31));
    }

    /**
     * Read an integer as a variable-byte sequence.  After read, the value must be zig-zag decoded.
     */
    @Override
    public int deserializePrimitiveInt(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        int value = VarInt.readVInt(byteData, fieldPosition);

        return (value >>> 1) ^ ((value << 31) >> 31);
    }

    /**
     * Read a long as a variable-byte sequence.  After read, the value must be zig-zag decoded.  Might be null.
     */
    @Override
    public Long deserializeLong(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        long value = VarInt.readVLong(byteData, fieldPosition);

        return Long.valueOf((value >>> 1) ^ ((value << 63) >> 63));
    }

    /**
     * Read a long as a variable-byte sequence.  After read, the value must be zig-zag decoded.
     */
    @Override
    public long deserializePrimitiveLong(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        long value = VarInt.readVLong(byteData, fieldPosition);

        return (value >>> 1) ^ ((value << 63) >> 63);
    }

    /**
     * Read a float as a fixed-length sequence of 4 bytes.  Might be null.
     */
    @Override
    public Float deserializeFloat(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1)
            return null;

        int intBits = readIntBits(byteData, fieldPosition);

        if(intBits == NULL_FLOAT_BITS)
            return null;

        return Float.valueOf(Float.intBitsToFloat(intBits));
    }

    /**
     * Read a float as a fixed-length sequence of 4 bytes.
     */
    @Override
    public float deserializePrimitiveFloat(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        int intBits = readIntBits(byteData, fieldPosition);

        return Float.intBitsToFloat(intBits);
    }

    private int readIntBits(ByteData byteData, long fieldPosition) {
        int intBits = (byteData.get(fieldPosition++) & 0xFF) << 24;
        intBits |= (byteData.get(fieldPosition++) & 0xFF) << 16;
        intBits |= (byteData.get(fieldPosition++) & 0xFF) << 8;
        intBits |= (byteData.get(fieldPosition) & 0xFF);
        return intBits;
    }

    /**
     * Read a double as a fixed-length sequence of 8 bytes.  Might be null.
     */
    @Override
    public Double deserializeDouble(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1)
            return null;

        long longBits = readLongBits(byteData, fieldPosition);

        if(longBits == NULL_DOUBLE_BITS)
            return null;

        return Double.valueOf(Double.longBitsToDouble(longBits));
    }

    /**
     * Read a double as a fixed-length sequence of 8 bytes.
     */
    @Override
    public double deserializePrimitiveDouble(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        long longBits = readLongBits(byteData, fieldPosition);

        return Double.longBitsToDouble(longBits);
    }

    private long readLongBits(ByteData byteData, long fieldPosition) {
        long longBits = (long) (byteData.get(fieldPosition++) & 0xFF) << 56;
        longBits |= (long) (byteData.get(fieldPosition++) & 0xFF) << 48;
        longBits |= (long) (byteData.get(fieldPosition++) & 0xFF) << 40;
        longBits |= (long) (byteData.get(fieldPosition++) & 0xFF) << 32;
        longBits |= (long) (byteData.get(fieldPosition++) & 0xFF) << 24;
        longBits |= (byteData.get(fieldPosition++) & 0xFF) << 16;
        longBits |= (byteData.get(fieldPosition++) & 0xFF) << 8;
        longBits |= (byteData.get(fieldPosition) & 0xFF);
        return longBits;
    }

    /**
     * Read a String as UTF-8 encoded characters.  The length is encoded as a variable-byte integer.
     */
    @Override
    public String deserializeString(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int length = VarInt.readVInt(byteData, fieldPosition);
        fieldPosition += VarInt.sizeOfVInt(length);

        return readString(byteData, fieldPosition, length);
    }

    /**
     * Read a sequence of bytes directly from the stream.  The length is encoded as a variable-byte integer.
     */
    @Override
    public byte[] deserializeBytes(FastBlobDeserializationRecord rec, String fieldName) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int length = VarInt.readVInt(byteData, fieldPosition);
        fieldPosition += VarInt.sizeOfVInt(length);

        byte data[] = new byte[length];

        for(int i=0;i<length;i++) {
            data[i] = byteData.get(fieldPosition++);
        }

        return data;
    }

    /**
     * Read an Object's ordinal reference as a variable-byte integer.  Use the framework to look up the Object by ordinal.
     */
    @Override
    public <T> T deserializeObject(FastBlobDeserializationRecord rec, String fieldName, Class<T> clazz) {
        long fieldPosition = rec.getPosition(fieldName);
        if (fieldPosition == -1)
            return null;
        return deserializeObject(rec, fieldPosition, rec.getObjectType(fieldName));
    }

    /**
     * @deprecated use instead deserializeObject(FlatBlobDeserializationRecord rec, String fieldName, Class<T> clazz);
     *
     * Read an Object's ordinal reference as a variable-byte integer.  Use the framework to look up the Object by ordinal.
     */
    @Deprecated
    @Override
    public <T> T deserializeObject(FastBlobDeserializationRecord rec, String fieldName, String typeName, Class<T> clazz) {
        long fieldPosition = rec.getPosition(fieldName);
        if (fieldPosition == -1)
            return null;
        return deserializeObject(rec, fieldPosition, typeName);
    }

    private <T> T deserializeObject(FastBlobDeserializationRecord rec, long fieldPosition, String typeName) {
        ByteData byteData = rec.getByteData();

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int ordinal = VarInt.readVInt(byteData, fieldPosition);

        FastBlobTypeDeserializationState<T> deserializationState = ((FastBlobStateEngine) framework).getTypeDeserializationState(typeName);

        return deserializationState.get(ordinal);
    }

    /**
     * Read a List as a sequence of ordinals encoded as variable-byte integers.  Use the framework to look up each Object by it's ordinals.
     */
    @Override
    public <T> List<T> deserializeList(FastBlobDeserializationRecord rec, String fieldName, NFTypeSerializer<T> itemSerializer) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int length = VarInt.readVInt(byteData, fieldPosition);
        fieldPosition += VarInt.sizeOfVInt(length);

        int numElements = VarInt.countVarIntsInRange(byteData, fieldPosition, length);

        if(numElements == 0)
            return Collections.emptyList();

        ListBuilder<T> list = minimizedCollections.createListBuilder();
        list.builderInit(numElements);

        FastBlobTypeDeserializationState<T> elementDeserializationState = ((FastBlobStateEngine) framework).getTypeDeserializationState(itemSerializer.getName());

        for(int i=0;i<numElements;i++) {
            if(VarInt.readVNull(byteData, fieldPosition)) {
                list.builderSet(i, null);
                fieldPosition += 1;
            } else {
                int ordinal = VarInt.readVInt(byteData, fieldPosition);
                fieldPosition += VarInt.sizeOfVInt(ordinal);
                T element = elementDeserializationState.get(ordinal);

                if(element != null)
                    list.builderSet(i, element);
            }
        }

        return minimizedCollections.minimizeList(list.builderFinish());
    }

    /**
     * Read a Set as a sequence of ordinals encoded as gap-encoded variable-byte integers.  Use the framework to look up each Object by it's ordinals.
     */
    @Override
    public <T> Set<T> deserializeSet(FastBlobDeserializationRecord rec, String fieldName, NFTypeSerializer<T> itemSerializer) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int length = VarInt.readVInt(byteData, fieldPosition);
        fieldPosition += VarInt.sizeOfVInt(length);

        int numElements = VarInt.countVarIntsInRange(byteData, fieldPosition, length);

        if(numElements == 0)
            return Collections.emptySet();

        SetBuilder<T> set = minimizedCollections.createSetBuilder();
        set.builderInit(numElements);

        FastBlobTypeDeserializationState<T> elementDeserializationState = ((FastBlobStateEngine) framework).getTypeDeserializationState(itemSerializer.getName());

        int previousOrdinal = 0;

        for(int i=0;i<numElements;i++) {
            if(VarInt.readVNull(byteData, fieldPosition)) {
                fieldPosition++;
                set.builderSet(i, null);
            } else {
                int ordinal = VarInt.readVInt(byteData, fieldPosition);
                fieldPosition += VarInt.sizeOfVInt(ordinal);

                ordinal += previousOrdinal;
                previousOrdinal = ordinal;

                T element = elementDeserializationState.get(ordinal);

                if(element != null)
                    set.builderSet(i, element);
            }
        }

        return minimizedCollections.minimizeSet(set.builderFinish());
    }

    /**
     * Read a Map as a sequence of key/value pairs encoded as variable-byte integers (value are gap-encoded).  Use the framework to look up each Object by it's ordinals.
     */
    @Override
    public <K, V> Map<K, V> deserializeMap(FastBlobDeserializationRecord rec, String fieldName, NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if (fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int length = VarInt.readVInt(byteData, fieldPosition);
        fieldPosition += VarInt.sizeOfVInt(length);

        int numElements = VarInt.countVarIntsInRange(byteData, fieldPosition, length);

        numElements /= 2;

        if(numElements == 0)
            return Collections.emptyMap();

        MapBuilder<K, V> map = minimizedCollections.createMapBuilder();
        map.builderInit(numElements);

        FastBlobTypeDeserializationState<K> keyDeserializationState = ((FastBlobStateEngine) framework).getTypeDeserializationState(keySerializer.getName());
        FastBlobTypeDeserializationState<V> valueDeserializationState = ((FastBlobStateEngine) framework).getTypeDeserializationState(valueSerializer.getName());

        populateMap(byteData, fieldPosition, numElements, map, keyDeserializationState, valueDeserializationState);

        return minimizedCollections.minimizeMap(map.builderFinish());
    }

    /**
     * Read a SortedMap as a sequence of key/value pairs encoded as variable-byte integers (value are gap-encoded).  Use the framework to look up each Object by it's ordinals.
     */
    @Override
    public <K, V> SortedMap<K, V> deserializeSortedMap(FastBlobDeserializationRecord rec, String fieldName, NFTypeSerializer<K> keySerializer, NFTypeSerializer<V> valueSerializer) {
        ByteData byteData = rec.getByteData();
        long fieldPosition = rec.getPosition(fieldName);

        if(fieldPosition == -1 || VarInt.readVNull(byteData, fieldPosition))
            return null;

        int length = VarInt.readVInt(byteData, fieldPosition);
        fieldPosition += VarInt.sizeOfVInt(length);

        int numElements = VarInt.countVarIntsInRange(byteData, fieldPosition, length);

        numElements /= 2;

        if(numElements == 0)
            return minimizedCollections.emptySortedMap();

        MapBuilder<K, V> map = minimizedCollections.createSortedMapBuilder();
        map.builderInit(numElements);

        FastBlobTypeDeserializationState<K> keyDeserializationState = ((FastBlobStateEngine) framework).getTypeDeserializationState(keySerializer.getName());
        FastBlobTypeDeserializationState<V> valueDeserializationState = ((FastBlobStateEngine) framework).getTypeDeserializationState(valueSerializer.getName());

        populateMap(byteData, fieldPosition, numElements, map, keyDeserializationState, valueDeserializationState);

        return minimizedCollections.minimizeSortedMap( (SortedMap<K, V>) map.builderFinish() );
    }

    private <K, V> void populateMap(ByteData byteData, long fieldPosition, int numElements, MapBuilder<K, V> mapToPopulate, FastBlobTypeDeserializationState<K> keyState, FastBlobTypeDeserializationState<V> valueState) {
        int previousValueOrdinal = 0;

        for(int i=0;i<numElements;i++) {
            K key = null;
            V value = null;

            boolean undefinedKeyOrValue = false;

            if(VarInt.readVNull(byteData, fieldPosition)) {
                fieldPosition++;
            } else {
                int keyOrdinal = VarInt.readVInt(byteData, fieldPosition);
                fieldPosition += VarInt.sizeOfVInt(keyOrdinal);

                key = keyState.get(keyOrdinal);

                if(key == null)
                    undefinedKeyOrValue = true;
            }

            if(VarInt.readVNull(byteData, fieldPosition)) {
                fieldPosition++;
            } else {
                int valueOrdinal = VarInt.readVInt(byteData, fieldPosition);
                fieldPosition += VarInt.sizeOfVInt(valueOrdinal);

                valueOrdinal += previousValueOrdinal;
                previousValueOrdinal = valueOrdinal;

                value = valueState.get(valueOrdinal);

                if(value == null)
                    undefinedKeyOrValue = true;
            }

            if(!undefinedKeyOrValue)
                mapToPopulate.builderPut(i, key, value);
        }
    }

    /**
     * Decode a String as a series of VarInts, one per character.<p/>
     *
     * @param str
     * @param out
     * @return
     * @throws IOException
     */
    private final ThreadLocal<char[]> chararr = new ThreadLocal<char[]>();

    protected String readString(ByteData data, long position, int length) {
        long endPosition = position + length;

        char chararr[] = getCharArray();

        if(length > chararr.length)
            chararr = new char[length];

        int count = 0;

        while(position < endPosition) {
            int c = VarInt.readVInt(data, position);
            chararr[count++] = (char)c;
            position += VarInt.sizeOfVInt(c);
        }

        // The number of chars may be fewer than the number of bytes in the serialized data
        return new String(chararr, 0, count);
    }

    private char[] getCharArray() {
        char ch[] = chararr.get();
        if(ch == null) {
            ch = new char[100];
            chararr.set(ch);
        }
        return ch;
    }

}


text:
package gnieh.coroutines.plugin

import scala.tools.nsc
import scala.tools.nsc.typechecker._
import nsc.Global
import nsc.Phase
import nsc.plugins.Plugin
import nsc.plugins.PluginComponent

class CoroutinesPlugin(val global: Global) extends Plugin {
  import global._

  val name = "coroutines"
  val description = "applies coroutines conversion"

  val phase = new CoroutinesTransform() {
    val global = CoroutinesPlugin.this.global
    val runsAfter = List("typer")
    // it must run before continuations are transformed
//    override val runsBefore = List("selectiveanf")
  }

  val components = List[PluginComponent](phase)

  global.log("instantiated coroutines plugin: " + this)

  // TODO: require -enabled command-line flag?

  override def processOptions(options: List[String], error: String => Unit) = {
    var enabled = false
    for (option <- options) {
      if (option == "enable") {
        enabled = true
      } else if(option == "verbose"){
        phase.verbose = true
      }else {
        error("Option not understood: "+option)
      }
    }
  }

  override val optionsHelp: Option[String] =
    Some("  -P:coroutines:verbose        verbose mode")
    //Some("  -P:coroutines:enable        Enable coroutines (continuations must be enabled too)")
}


text:
package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Collection;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import controller.MutantController;
import mutant.Mutant;

public class MutantsView extends ViewComponent{

	protected MutantController mutant_controller;
	protected JScrollPane mutantPane;
	private JPanel innerPanel;

	private ArrayList<Mutant> d;

	public MutantsView(){
		d = new ArrayList<Mutant>();
		innerPanel =  new JPanel(new FlowLayout(FlowLayout.CENTER));
		mutantPane = new JScrollPane(innerPanel);
	}

	public void connectMutantController(MutantController m){
		mutant_controller = m;
	}

	@Override
	public void update(Collection<Mutant> data, Mutant current, JButton button) {
		// TODO Auto-generated method stub
		d = (ArrayList<Mutant>) data;
	}

	@Override
	public void draw() {
		//innerPanel.setLocation(0, 30);
		//innerPanel.add(new JLabel("Mutants"));
		innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));
		for(int i = 0; i < d.size(); i++){
			JButton temp = new JButton("Mutant " + (i+1));
			if(d.get(i).isKilled()){
				temp.setBackground(Color.GREEN);
			}
			else{
				temp.setBackground(Color.RED);
			}
			temp.setName(String.valueOf((i+1)));
			temp.setOpaque(true);
			//temp.setBorderPainted(true);
			temp.setPreferredSize(new Dimension(30,25));
			temp.setMaximumSize(new Dimension(125,25));
			temp.setBorder(BorderFactory.createEtchedBorder());
			temp.addActionListener(mutant_controller);
			innerPanel.add(temp);
		}

		mutantPane = new JScrollPane(innerPanel);
		mutantPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		//mutantPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		mutantPane.setBounds(0, 30, 150, 350);

		container.add(mutantPane, BorderLayout.CENTER);
	}

}


text:
//
//  NSFetchedResultsController+AKOLibrary.h
//  AKOLibrary
//
//  Created by Adrian Kosmaczewski on 4/10/12.
//  Copyright (c) 2009, 2010, 2011, Adrian Kosmaczewski & akosma software
//  All rights reserved.
//
//  Use in source and/or binary forms without modification is permitted following the
//  instructions in the LICENSE file.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
//  OF THE POSSIBILITY OF SUCH DAMAGE.
//

#import <CoreData/CoreData.h>

/**
 @category NSFetchedResultsController(AKOLibrary)
 A category on NSFetchedResultsController
 */
@interface NSFetchedResultsController (AKOLibrary)

/**
 Returns the next NSIndexPath.
 This method returns the next object to be displayed in a table view that
 uses the current fetched results controller as data source. It is the
 equivalent of incrementing the NSIndexPath by one unit, which might mean
 incrementing the section if required. This method returns nil if the parameter
 represents the last object on the current results controller.
 @param oldIndexPath The index path to increment.
 @return An NSIndexPath object, or nil if the parameter represented
 the last index path.
 */
- (NSIndexPath *)ako_incrementIndexPath:(NSIndexPath *)oldIndexPath;

/**
 Returns the previous NSIndexPath.
 This method returns the prevoius object to be displayed in a table view that
 uses the current fetched results controller as data source. It is the
 equivalent of decrementing the NSIndexPath by one unit, which might mean
 decrementing the section if required. This method returns nil if the parameter
 represents the first object on the current results controller.
 @param oldIndexPath The index path to decrement.
 @return An NSIndexPath object, or nil if the parameter represented
 the first index path.
 */
- (NSIndexPath *)ako_decrementIndexPath:(NSIndexPath *)oldIndexPath;

@end


text:
import wpMenuItem from 'ember-cli-to-wp-theme/components/wp-menu-item';

export default wpMenuItem;


text:
require 'stringio'

class ChunkWriterIO < StringIO
  # Writer for chunked data.

  MAX_CHUNK_SIZE = 0xFFFF

  def initialize
    @output_buffer = []
    @output_size = 0
    super
  end

  # Write some bytes, splitting into chunks if necessary.
  def write_with_chunking(string)
    until string.empty?
      future_size = @output_size + string.size
      if future_size >= MAX_CHUNK_SIZE
        last = MAX_CHUNK_SIZE - @output_size
        write_buffer!(string[0, last], MAX_CHUNK_SIZE)
        string = string[last..-1]

        write_without_chunking(buffer_result)
        clear_buffer!
      else
        write_buffer!(string, future_size)

        string = ''
      end
    end
  end

  alias write_without_chunking write
  alias write write_with_chunking

  def flush(zero_chunk = false)
    write_without_chunking(buffer_result(zero_chunk))
    clear_buffer!

    super()
  end

  # Close the stream.
  def close(zero_chunk = false)
    flush(zero_chunk)
    super
  end

  # private
  def write_buffer!(string, size)
    @output_buffer << string
    @output_size = size
  end

  def buffer_result(zero_chunk = false)
    result = ''

    if !@output_buffer.empty?
      result << [@output_size].pack('s>*')
      result.concat(@output_buffer.join)
    end

    result << "\x00\x00" if zero_chunk

    result
  end

  def clear_buffer!
    @output_buffer.clear
    @output_size = 0
  end
end


text:
var Emitter = require('events').EventEmitter;
var assert = require('assert');
var querystring = require('querystring');

var WRAPPER_SELECTOR = '.gt_wrapper';

var bus = new Emitter();

window.gt_custom_ajax = function (result, id, message) {
  var elements;
  if (typeof id === 'function') {
    elements = [id('.geetest_challenge'), id('.geetest_validate'), id('.geetest_seccode')];
  } else {
    elements = document.getElementById(id).getElementsByTagName('input');
  }
  bus.emit('receive', {
    id: id,
    result: !!result,
    message: (message + '').toLowerCase(),
    value: {
      geetest_challenge: elements[0].value,
      geetest_validate: elements[1].value,
      geetest_seccode: elements[2].value
    }
  });
};

var id = function (container) {
  var wrapper = container.querySelector(WRAPPER_SELECTOR);
  return wrapper && wrapper.id;
};

module.exports = function (container, config) {
  var channel, script;

  assert(container, 'container is required');
  assert(config, 'config is required');
  assert(config.gt, 'config.gt is required');

  channel = new Emitter();
  script = document.createElement('script');

  script.src = 'http://api.geetest.com/get.php?' + querystring.stringify(config);
  script.async = true;

  bus.on('receive', function (info) {
    if (id(container) === info.id) {
      channel.emit('MESSAGE', info);
      channel.emit(info.message, info.value);
    }
  });

  container.appendChild(script);

  return channel;
};


text:
namespace SeeScript
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------------------------------------------------------
PrimitiveType Register::GetRootPrimitiveType() const
{
  switch (Type)
  {
    case RegisterType::Virtual:
    case RegisterType::Integer:
      return PrimitiveType::Integer;

    case RegisterType::VirtualFloat:
    case RegisterType::Float:
      return PrimitiveType::Float;

    case RegisterType::VirtualDouble:
    case RegisterType::Double:
      return PrimitiveType::Double;

    case RegisterType::Variable:
    {
      TypeDesc *typeDesc = Variable.GetDesc()->Type;
      while (typeDesc)
      {
        if (typeDesc->Base == nullptr)
          return typeDesc->PrimitiveType;

        typeDesc = typeDesc->Base;
      }
    }
    break;

    case RegisterType::Pointer:
      return Pointer.GetDesc()->PrimitiveType;

    default:
      break;
  }

  return PrimitiveType::Void;
}

//---------------------------------------------------------------------------------------------------------------------
TypeDesc* Register::GetTypeDesc() const
{
  if (Type == RegisterType::Variable)
    return Variable.GetDesc()->Type;

  if (Type == RegisterType::Pointer)
    return Pointer.GetDesc();

  return nullptr;
}

//---------------------------------------------------------------------------------------------------------------------
RegisterType Register::GetRegisterTypeFromPrimitive(PrimitiveType type)
{
  switch (type)
  {
    case PrimitiveType::Void:
      return RegisterType::NotUsed;

    case PrimitiveType::Bool:
    case PrimitiveType::Integer:
    case PrimitiveType::Struct:
    case PrimitiveType::Class:
    case PrimitiveType::Array:
      return RegisterType::Virtual;

    case PrimitiveType::Float:
      return RegisterType::VirtualFloat;

    case PrimitiveType::Double:
      return RegisterType::VirtualDouble;

    default:
      break;
  }

  return RegisterType::Invalid;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------------------------------------------------------
bool LabelGraphNode::InsertPhiFunctions()
{
  // Are there any domination frontiers?
  if (!Frontiers.IsEmpty())
  {
    auto i = LabelInstruction;
    do
    {
      i = i->GetNext();

      if (i->GetType() == InstructionType::Operation &&
         (i->Operation.Type == ElementType::OpAssign ||
          i->Operation.Type == ElementType::OpIncrement ||
          i->Operation.Type == ElementType::OpDecrement
         ))
      {
        auto &reg = i->Operation.Params[0];
        if (reg.Type == RegisterType::Variable)
        {
          PushPhiReference(reg.Variable.GetDesc(), this);
        }
      }
      else if (i->GetType() == InstructionType::Phi)
      {
        auto var = i->Phi.Variable;
        PushPhiReference(var, this);
      }

    } while (i && i->GetType() != InstructionType::Label);
  }

  for (auto &&f : Followers)
    if (!f->InsertPhiFunctions())
      return false;

  return true;
}

//---------------------------------------------------------------------------------------------------------------------
void LabelGraphNode::PushPhiReference(VariableDesc* var, LabelGraphNode* node)
{
  // Instruction allocator
  auto alloc = Block->Instructions.GetAllocator();

  // Go through all domination frontiers and try to insert phi functions there
  for (auto &&df : Frontiers)
  {
    auto pp = df->GetOrCreatePhi(var);
    for (auto &&item : pp->Phi.Items)
      if (item->Node == node)
        return;

    // If no reference to current block has been found, create new one
    auto ppItem = alloc->New<PhiItem>();
    ppItem->SetNext(nullptr);
    ppItem->Node = node;
    ppItem->SetVersion(-1);
    pp->Phi.Items.Add(ppItem);
  }
}

//---------------------------------------------------------------------------------------------------------------------
Instruction *LabelGraphNode::GetOrCreatePhi(VariableDesc *var)
{
  auto prev = LabelInstruction;
  auto i = LabelInstruction->GetNext();
  while (i)
  {
    if (i->GetType() != InstructionType::Phi)
      break;

    if (i->Phi.Variable == var)
      return i;

    prev = i;
    i = i->GetNext();
  }

  // "i" now points to first "invalid" instruction (instruction, that is NOT a phi),
  // go one step back
  if (i == nullptr)
    i = LabelInstruction;
  else
    i = prev;

  auto instr = Block->Instructions.GetAllocator()->ZeroNew<Instruction>();
  Block->Instructions.InsertAfter(instr, i);

  instr->SetType(InstructionType::Phi);
  instr->Phi.Variable = var;
  instr->Phi.Version = -1;
  return instr;
}

//---------------------------------------------------------------------------------------------------------------------
bool LabelGraphNode::RenameVariables()
{
  auto i = LabelInstruction->GetNext();
  while (i)
  {
    if (i->GetType() == InstructionType::Label || i->GetType() == InstructionType::Jump)
      break;

    if (i->GetType() == InstructionType::Operation)
    {
      bool allocateNewVersion = false;

      if (i->Operation.Type == ElementType::OpAssign ||
          i->Operation.Type == ElementType::OpIncrement ||
          i->Operation.Type == ElementType::OpDecrement
        )
        allocateNewVersion = true;

      for (int r = 0; r < 2; ++r)
      {
        auto &reg = i->Operation.Params[r];
        if (reg.Type == RegisterType::Variable)
        {
          if (allocateNewVersion)
          {
            reg.Variable.Version = reg.Variable.GetDesc()->VersionCounter++;
            allocateNewVersion = false;
          }
          else
            reg.Variable.Version = reg.Variable.GetDesc()->VersionCounter - 1;
        }
      }
    }
    else if (i->GetType() == InstructionType::Phi)
    {
      i->Phi.Version = i->Phi.Variable->VersionCounter++;
    }

    i = i->GetNext();
  }

  for (auto &&f : Followers)
  {
    if (!f->RenameVariables())
      return false;
  }

  return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------------------------------------------------------
JumpType Instruction::GetJumpTypeFromOperator(ElementType op)
{
  switch (op)
  {
    case ElementType::OpLesser:
      return JumpType::JL;

    case ElementType::OpLesserEqual:
      return JumpType::JLE;

    case ElementType::OpGreater:
      return JumpType::JG;

    case ElementType::OpGreaterEqual:
      return JumpType::JGE;

    case ElementType::OpEqual:
      return JumpType::JE;

    case ElementType::OpNotEqual:
      return JumpType::JNE;

    default:
      break;
  }

  return JumpType::Unknown;
}

//---------------------------------------------------------------------------------------------------------------------
Instruction::Instruction(InstructionType type)
{
  SetParam(type);

  switch (type)
  {
    case InstructionType::Operation:
      Operation.Target.Type = RegisterType::Invalid;
      Operation.Type = ElementType::Unknown;
      Operation.Params[0].Type = RegisterType::Invalid;
      Operation.Params[1].Type = RegisterType::Invalid;
      break;

    case InstructionType::Jump:
      Jump.Type = JumpType::Unknown;
      Jump.Index = -1;
      break;

    case InstructionType::Label:
      Label.Index = -1;
      break;

    default:
      break;
  }
}

//---------------------------------------------------------------------------------------------------------------------
Instruction::Instruction(const Instruction& copy)
{
  memcpy(this, &copy, sizeof(Instruction));
}

//---------------------------------------------------------------------------------------------------------------------
Instruction& Instruction::operator=(const Instruction& copy)
{
  memcpy(this, &copy, sizeof(Instruction));
  return *this;
}

//---------------------------------------------------------------------------------------------------------------------
void PrintGPR(Compiler &c, int index)
{
  switch (index)
  {
    case 0:
      c.Log("EAX");
      break;

    case 1:
      c.Log("EBX");
      break;

    case 2:
      c.Log("ECX");
      break;

    case 3:
      c.Log("EDX");
      break;

    default:
      break;
  }

  c.Log("(unknown GPR)");
}

//---------------------------------------------------------------------------------------------------------------------
void PrintJump(Compiler &c, JumpType jmp)
{
  switch (jmp)
  {
    case JumpType::JMP:
      c.Log("JMP");
      break;

    case JumpType::JE:
      c.Log("JE");
      break;

    case JumpType::JNE:
      c.Log("JNE");
      break;

    case JumpType::JZ:
      c.Log("JZ");
      break;

    case JumpType::JNZ:
      c.Log("JNZ");
      break;

    case JumpType::JL:
      c.Log("JL");
      break;

    case JumpType::JLE:
      c.Log("JLE");
      break;

    case JumpType::JG:
      c.Log("JG");
      break;

    case JumpType::JGE:
      c.Log("JGE");
      break;

    default:
      c.Log("(unknown jump)");
      break;
  }
}

//---------------------------------------------------------------------------------------------------------------------
void PrintRegister(Compiler &c, const Register &reg)
{
  switch (reg.Type)
  {
    case RegisterType::Virtual:
      c.Log("$%d", reg.Slot.Index);
      break;

    case RegisterType::GPR:
      PrintGPR(c, reg.Slot.Index);
      break;

    case RegisterType::Integer:
      c.Log("%d", reg.Integer.Value);
      break;

    case RegisterType::CompareState:
      c.Log("$CMP");
      break;

    case RegisterType::VirtualFloat:
      c.Log("$%df", reg.Slot.Index);
      break;

    case RegisterType::XMM:
      c.Log("XMM%d", reg.Slot.Index);
      break;

    case RegisterType::Float:
      c.Log("%f", static_cast<float>(reg.Double.Value));
      break;

    case RegisterType::VirtualDouble:
      c.Log("$%dd", reg.Slot.Index);
      break;

    case RegisterType::Double:
      c.Log("%lf", reg.Double.Value);
      break;

    case RegisterType::Variable:
    {
      c.Log("%s", reg.Variable.GetDesc()->Name.c_str());

      if (reg.Variable.Version >= 0)
        c.Log("(%d)", reg.Variable.Version);
    }
    break;

    case RegisterType::Pointer:
      if (reg.Pointer.OffsetSize == 1)
      {
        if (reg.Pointer.OffsetIndex >= 0)
          c.Log("[$%d + $%d]", reg.Pointer.Index, reg.Pointer.OffsetIndex);
        else
          c.Log("[$%d]", reg.Pointer.Index);
      }
      else
      {
        c.Log("[$%d + $%d * %d]", reg.Pointer.Index, reg.Pointer.OffsetIndex, reg.Pointer.OffsetSize);
      }
      break;

    default:
      break;
  }
}

//---------------------------------------------------------------------------------------------------------------------
void PrintDominatorTree(Compiler &c, LabelGraphNode *node, int depth)
{
  for (int i = 0; i < depth; ++i) c.Log("  ");

  c.Log("L%d:", node->GetIndex());

  for (auto &&f : node->Frontiers)
    c.Log(" L%d", f->GetIndex());

  c.Log("\n");

  for (auto &&f : node->Followers)
    PrintDominatorTree(c, f, depth + 1);
}

//---------------------------------------------------------------------------------------------------------------------
void Instruction::Print(Compiler& c)
{
  switch (GetType())
  {
    case InstructionType::Operation:
    {
      c.Log("  ");

      if (Operation.Target.IsUsed())
      {
        PrintRegister(c, Operation.Target);
        c.Log(" := ");
      }

      if (Operation.Params[0].IsUsed())
        PrintRegister(c, Operation.Params[0]);

      auto &tokenDesc = Token::GetStaticDesc(Operation.Type);
      c.Log(" %s ", tokenDesc.Text);

      if (Operation.Params[1].IsUsed())
        PrintRegister(c, Operation.Params[1]);
    }
    break;

    case InstructionType::Jump:
    {
      c.Log("  ");
      PrintJump(c, Jump.Type);
      c.Log(" L%d", Jump.Index);
    }
    break;

    case InstructionType::Label:
    {
      c.Log("L%d:", Label.Index);
    }
    break;

    case InstructionType::NOP:
      c.Log("  NOP");
      break;

    case InstructionType::Phi:
    {
      c.Log("  %s", Phi.Variable->Name.c_str());
      if (Phi.Version >= 0)
        c.Log("(%d)", Phi.Version);

      c.Log(" := PHI(", Phi.Variable->Name.c_str());

      for (auto &&item : Phi.Items)
      {
        if (item->GetVersion() < 0)
          c.Log("L%d", item->Node->GetIndex());
        else
          c.Log("%s(%d)", item->Variable->Name.c_str(), item->GetVersion());

        if (item->GetNext())
          c.Log(", ");
      }

      c.Log(")");
    }
    break;

    default:
      return;
  }

  c.Log("\n");
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//---------------------------------------------------------------------------------------------------------------------
InstructionBlock::InstructionBlock(Generator& g)
  : G(g)
{
  Instructions.SetAllocator(g.m_Allocator);
  LabelGraph.SetAllocator(g.m_Allocator);
  RootScope.Locals.SetAllocator(g.m_Allocator);
}

//---------------------------------------------------------------------------------------------------------------------
bool InstructionBlock::ConnectLabels(LabelGraphNode *source, int targetIndex, bool chainedConnection)
{
  LabelGraphNode *target = GetOrCreateLabelGraphNode(targetIndex);
  source->Children.PushUnique(target);
  target->Parents.PushUnique(source);

  return true;
}

//---------------------------------------------------------------------------------------------------------------------
LabelGraphNode *InstructionBlock::GetOrCreateLabelGraphNode(int index)
{
  for (auto &&item : LabelGraph)
    if (item->GetIndex() == index)
      return item;

  auto newNode = LabelGraph.New(G.m_Allocator, index);
  newNode->Block = this;
  return newNode;
}

//---------------------------------------------------------------------------------------------------------------------
void InstructionBlock::PrintDisassembly()
{
  auto &c = G.m_Compiler;

  c.Log("Disassembly:\n");

  for (auto &&i : Instructions)
    i->Print(c);

  c.Log("\nLabel graph parents:\n");

  for (auto &&node : LabelGraph)
  {
    c.Log("  L%d (%d):", node->GetIndex(), node->PostOrderID);

    for (auto &&p : node->Parents)
      c.Log(" L%d", p->GetIndex());

    c.Log("\n");
  }

  c.Log("\nDominator tree:\n");

  PrintDominatorTree(c, EntryLabel, 0);
}

//---------------------------------------------------------------------------------------------------------------------
bool InstructionBlock::Optimize()
{
  if (!BuildLabelGraph())
    return false;

  if (!FindDominators())
    return false;

  if (!GeneratePhiFunctions())
    return false;

  if (!RenameVariables())
    return false;

  return true;
}

//---------------------------------------------------------------------------------------------------------------------
LabelGraphNode *Intersect(LabelGraphNode *b1, LabelGraphNode *b2)
{
  LabelGraphNode *finger1 = b1;
  LabelGraphNode *finger2 = b2;

  while (finger1 != finger2)
  {
    while (finger1->PostOrderID < finger2->PostOrderID)
      finger1 = finger1->Dominator;

    while (finger2->PostOrderID < finger1->PostOrderID)
      finger2 = finger2->Dominator;
  }

  return finger1;
}

//---------------------------------------------------------------------------------------------------------------------
bool InstructionBlock::BuildLabelGraph()
{
  auto iter = Instructions.begin();
  while (iter != Instructions.end())
  {
    bool moveToNext = true;

    auto next = iter->GetNext();
    if (iter->GetType() == InstructionType::Label && next)
    {
      if (next->GetType() == InstructionType::Label)
      {
        // We can remove current label instruction
        int oldIndex = iter->Label.Index;
        int newIndex = next->Label.Index;

        for (auto &&i : Instructions)
        {
          if (i->GetType() == InstructionType::Jump && i->Jump.Index == oldIndex)
            i->Jump.Index = newIndex;
        }

        LabelGraph.Remove(LabelGraph.Find(iter->Label.Node), false);
        iter = Instructions.Remove(iter);
        moveToNext = false;
      }
    }

    if (moveToNext)
      ++iter;
  }

  // Go through all instructions and store label/jump relationships as a graph
  LabelGraphNode *currentLabel = nullptr;
  Instruction *prev = nullptr;
  for (auto &&i : Instructions)
  {
    if (i->GetType() == InstructionType::Label)
    {
      bool connect = true;

      // Test, if this label is preceded by JMP instruction - if so, and this
      // JMP jumps to somewhere else, that means this label should NOT be
      // connected to previous block. For example:
      //   ...
      // L3:
      //   ...
      //   ...
      //   JMP L4
      // L5:
      //   ...
      //
      // Label L5 is NOT connected to L3, because the control flow always jumps
      // to L4 instead.
      if (prev)
      {
        int target = prev->GetDirectJumpTarget();
        if (target >= 0 && target != i->Label.Index)
          connect = false;
      }

      if (currentLabel && connect)
        ConnectLabels(currentLabel, i->Label.Index, true);

      currentLabel = i->Label.Node;
    }
    else if (i->GetType() == InstructionType::Jump)
    {
      if (!currentLabel)
        return false;

      ConnectLabels(currentLabel, i->Jump.Index);
    }

    prev = i;
  }

  // Generate post order IDs
  int nextID = 0;
  DynamicArray<LabelGraphNode *, 64> postOrderList;
  postOrderList.SetAllocator(G.m_Allocator);

  EntryLabel->PostOrderVisit([&nextID, &postOrderList](LabelGraphNode *node)
  {
    node->PostOrderID = nextID++;
    postOrderList.Push(node);
  });

  // Find dominators
  EntryLabel->Dominator = EntryLabel;

  bool changed = true;
  while (changed)
  {
    changed = false;

    for (int i = postOrderList.GetSize(); i--; )
    {
      auto node = postOrderList[i];

      if (node == EntryLabel)
        continue;

      LabelGraphNode *newIdom = nullptr;
      for (auto &&p : node->Parents)
      {
        if (p->Dominator)
        {
          newIdom = p;
          break;
        }
      }

      LabelGraphNode *origIdom = newIdom;
      for (auto &&p : node->Parents)
      {
        if (p == origIdom)
          continue;

        if (p->Dominator)
          newIdom = Intersect(p, newIdom);
      }

      if (node->Dominator != newIdom)
      {
        node->Dominator = newIdom;
        changed = true;
      }
    }
  }

  return true;
}

//---------------------------------------------------------------------------------------------------------------------
bool InstructionBlock::FindDominators()
{
  // Find dominance frontiers
  for (auto &&node : LabelGraph)
  {
    auto &parents = node->Parents;
    if (parents.GetSize() >= 2)
    {
      for (auto &&p : parents)
      {
        auto runner = p;
        while (runner && runner != node->Dominator)
        {
          runner->Frontiers.PushUnique(node);
          runner = runner->Dominator;
        }
      }
    }
  }

  EntryLabel->Dominator = nullptr;

  for (auto &&node : LabelGraph)
  {
    if (node->Dominator)
      node->Dominator->Followers.Push(node);
  }

  return true;
}

//---------------------------------------------------------------------------------------------------------------------
bool InstructionBlock::GeneratePhiFunctions()
{
  if (!EntryLabel->InsertPhiFunctions())
    return false;

  return true;
}

//---------------------------------------------------------------------------------------------------------------------
bool InstructionBlock::RenameVariables()
{
  if (!EntryLabel->RenameVariables())
    return false;

  return true;
}

}


text:
<?php

namespace Namecheap\Element\Collection;

use Sabre\XML\Reader;

class Errors extends AbstractCollectionElement
{

    static public function deserializeXml(Reader $reader)
    {
        $element = new self();
        $element->seed($reader);
        return $element;
    }

}


text:
namespace media {

class UrlIndexTest : public testing::Test {
 public:
  UrlIndexTest() : url_index_(nullptr) {}

  scoped_refptr<UrlData> GetByUrl(const GURL& gurl,
                                  UrlData::CORSMode cors_mode) {
    scoped_refptr<UrlData> ret = url_index_.GetByUrl(gurl, cors_mode);
    EXPECT_EQ(ret->url(), gurl);
    EXPECT_EQ(ret->cors_mode(), cors_mode);
    return ret;
  }

  // TODO(hubbe): Make UrlIndex take a task_runner_
  base::MessageLoop message_loop_;
  UrlIndex url_index_;
};

TEST_F(UrlIndexTest, SimpleTest) {
  GURL url1("http://foo.bar.com");
  GURL url2("http://foo.bar.com/urgel");
  scoped_refptr<UrlData> a = GetByUrl(url1, UrlData::CORS_UNSPECIFIED);
  // Make sure it's valid, we still shouldn't get the same one.
  a->Use();
  a->set_range_supported();
  EXPECT_TRUE(a->Valid());
  EXPECT_EQ(a, url_index_.TryInsert(a));
  scoped_refptr<UrlData> b = GetByUrl(url1, UrlData::CORS_ANONYMOUS);
  b->Use();
  b->set_range_supported();
  EXPECT_TRUE(b->Valid());
  EXPECT_EQ(b, url_index_.TryInsert(b));
  scoped_refptr<UrlData> c = GetByUrl(url1, UrlData::CORS_USE_CREDENTIALS);
  c->Use();
  c->set_range_supported();
  EXPECT_TRUE(c->Valid());
  EXPECT_EQ(c, url_index_.TryInsert(c));
  scoped_refptr<UrlData> d = GetByUrl(url2, UrlData::CORS_UNSPECIFIED);
  d->Use();
  d->set_range_supported();
  EXPECT_TRUE(d->Valid());
  EXPECT_EQ(d, url_index_.TryInsert(d));

  EXPECT_NE(a, b);
  EXPECT_NE(a, c);
  EXPECT_NE(a, d);
  EXPECT_NE(b, c);
  EXPECT_NE(b, d);
  EXPECT_NE(c, d);
  EXPECT_EQ(a, GetByUrl(url1, UrlData::CORS_UNSPECIFIED));
  EXPECT_EQ(b, GetByUrl(url1, UrlData::CORS_ANONYMOUS));
  EXPECT_EQ(c, GetByUrl(url1, UrlData::CORS_USE_CREDENTIALS));
  EXPECT_EQ(d, GetByUrl(url2, UrlData::CORS_UNSPECIFIED));
}

TEST_F(UrlIndexTest, UrlDataTest) {
  GURL url("http://foo.bar.com");
  scoped_refptr<UrlData> a = GetByUrl(url, UrlData::CORS_UNSPECIFIED);

  // Check default values.
  EXPECT_FALSE(a->range_supported());
  EXPECT_FALSE(a->cacheable());
  EXPECT_EQ(a->length(), kPositionNotSpecified);
  EXPECT_FALSE(a->Valid());

  a->set_length(117);
  EXPECT_EQ(a->length(), 117);

  a->set_cacheable(true);
  EXPECT_TRUE(a->cacheable());

  base::Time now = base::Time::Now();
  base::Time valid_until = now + base::TimeDelta::FromSeconds(500);
  a->set_valid_until(valid_until);
  a->set_range_supported();
  EXPECT_EQ(valid_until, a->valid_until());
  EXPECT_TRUE(a->Valid());

  base::Time last_modified = now - base::TimeDelta::FromSeconds(500);
  a->set_last_modified(last_modified);
  EXPECT_EQ(last_modified, a->last_modified());
}

TEST_F(UrlIndexTest, UseTest) {
  GURL url("http://foo.bar.com");
  scoped_refptr<UrlData> a = GetByUrl(url, UrlData::CORS_UNSPECIFIED);
  EXPECT_FALSE(a->Valid());
  a->Use();
  a->set_range_supported();
  EXPECT_TRUE(a->Valid());
}

TEST_F(UrlIndexTest, TryInsert) {
  GURL url("http://foo.bar.com");
  scoped_refptr<UrlData> a = GetByUrl(url, UrlData::CORS_UNSPECIFIED);
  scoped_refptr<UrlData> c = GetByUrl(url, UrlData::CORS_UNSPECIFIED);
  EXPECT_NE(a, c);
  EXPECT_FALSE(a->Valid());
  base::Time now = base::Time::Now();
  base::Time last_modified = now - base::TimeDelta::FromSeconds(500);
  base::Time valid_until = now + base::TimeDelta::FromSeconds(500);

  // Not sharable yet. (no ranges)
  EXPECT_EQ(a, url_index_.TryInsert(a));
  EXPECT_NE(a, GetByUrl(url, UrlData::CORS_UNSPECIFIED));
  a->set_last_modified(last_modified);

  // Not sharable yet. (no ranges)
  EXPECT_EQ(a, url_index_.TryInsert(a));
  EXPECT_NE(a, GetByUrl(url, UrlData::CORS_UNSPECIFIED));

  // Now we should be able to insert it into the index.
  a->set_range_supported();
  a->set_valid_until(valid_until);
  EXPECT_TRUE(a->Valid());
  EXPECT_EQ(a, url_index_.TryInsert(a));
  EXPECT_EQ(a, GetByUrl(url, UrlData::CORS_UNSPECIFIED));

  // |a| becomes expired...
  a->set_valid_until(now - base::TimeDelta::FromSeconds(100));
  EXPECT_FALSE(a->Valid());
  scoped_refptr<UrlData> b = GetByUrl(url, UrlData::CORS_UNSPECIFIED);
  EXPECT_NE(a, b);

  b->set_range_supported();
  b->set_valid_until(valid_until);
  b->set_last_modified(last_modified);
  EXPECT_TRUE(b->Valid());

  EXPECT_EQ(b, url_index_.TryInsert(b));
  EXPECT_EQ(b, GetByUrl(url, UrlData::CORS_UNSPECIFIED));

  c->set_range_supported();
  c->set_valid_until(valid_until);
  c->set_last_modified(last_modified);
  EXPECT_TRUE(c->Valid());

  // B is still valid, so it should be preferred over C.
  EXPECT_EQ(b, url_index_.TryInsert(c));
  EXPECT_EQ(b, GetByUrl(url, UrlData::CORS_UNSPECIFIED));
}

}  // namespace media


text:
/**
 * @generated SignedSource<<cf1d01a9b6666e7d11f8cae1ffcc016f>>
 * @lightSyntaxTransform
 * @nogrep
 */

/* tslint:disable */
/* eslint-disable */
// @ts-nocheck

import { Fragment, ReaderFragment } from 'relay-runtime';
import { FragmentRefs } from "relay-runtime";
export type ArtworkSidebarCommercial_artwork$data = {
  readonly artists: ReadonlyArray<{
    readonly internalID: string;
  } | null> | null;
  readonly edition_sets: ReadonlyArray<{
    readonly id: string;
    readonly internalID: string;
    readonly is_acquireable: boolean | null;
    readonly is_offerable: boolean | null;
    readonly sale_message: string | null;
    readonly " $fragmentSpreads": FragmentRefs<"ArtworkSidebarSizeInfo_piece">;
  } | null> | null;
  readonly internalID: string;
  readonly isOfferableFromInquiry: boolean | null;
  readonly isPriceHidden: boolean | null;
  readonly is_acquireable: boolean | null;
  readonly is_for_sale: boolean | null;
  readonly is_inquireable: boolean | null;
  readonly is_offerable: boolean | null;
  readonly is_sold: boolean | null;
  readonly listPrice: {
    readonly display?: string | null;
  } | null;
  readonly priceIncludesTaxDisplay: string | null;
  readonly sale_message: string | null;
  readonly shippingInfo: string | null;
  readonly shippingOrigin: string | null;
  readonly slug: string;
  readonly " $fragmentSpreads": FragmentRefs<"ArtworkSidebarCreateAlertButton_artwork">;
  readonly " $fragmentType": "ArtworkSidebarCommercial_artwork";
};
export type ArtworkSidebarCommercial_artwork$key = {
  readonly " $data"?: ArtworkSidebarCommercial_artwork$data;
  readonly " $fragmentSpreads": FragmentRefs<"ArtworkSidebarCommercial_artwork">;
};

const node: ReaderFragment = (function(){
var v0 = {
  "alias": null,
  "args": null,
  "kind": "ScalarField",
  "name": "internalID",
  "storageKey": null
},
v1 = {
  "alias": "is_acquireable",
  "args": null,
  "kind": "ScalarField",
  "name": "isAcquireable",
  "storageKey": null
},
v2 = {
  "alias": "is_offerable",
  "args": null,
  "kind": "ScalarField",
  "name": "isOfferable",
  "storageKey": null
},
v3 = {
  "alias": "sale_message",
  "args": null,
  "kind": "ScalarField",
  "name": "saleMessage",
  "storageKey": null
},
v4 = [
  {
    "alias": null,
    "args": null,
    "kind": "ScalarField",
    "name": "display",
    "storageKey": null
  }
];
return {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "ArtworkSidebarCommercial_artwork",
  "selections": [
    {
      "alias": "edition_sets",
      "args": null,
      "concreteType": "EditionSet",
      "kind": "LinkedField",
      "name": "editionSets",
      "plural": true,
      "selections": [
        (v0/*: any*/),
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "id",
          "storageKey": null
        },
        (v1/*: any*/),
        (v2/*: any*/),
        (v3/*: any*/),
        {
          "args": null,
          "kind": "FragmentSpread",
          "name": "ArtworkSidebarSizeInfo_piece"
        }
      ],
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": "Artist",
      "kind": "LinkedField",
      "name": "artists",
      "plural": true,
      "selections": [
        (v0/*: any*/)
      ],
      "storageKey": null
    },
    (v0/*: any*/),
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "isOfferableFromInquiry",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "isPriceHidden",
      "storageKey": null
    },
    (v1/*: any*/),
    {
      "alias": "is_for_sale",
      "args": null,
      "kind": "ScalarField",
      "name": "isForSale",
      "storageKey": null
    },
    {
      "alias": "is_inquireable",
      "args": null,
      "kind": "ScalarField",
      "name": "isInquireable",
      "storageKey": null
    },
    (v2/*: any*/),
    {
      "alias": "is_sold",
      "args": null,
      "kind": "ScalarField",
      "name": "isSold",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": null,
      "kind": "LinkedField",
      "name": "listPrice",
      "plural": false,
      "selections": [
        {
          "kind": "InlineFragment",
          "selections": (v4/*: any*/),
          "type": "PriceRange",
          "abstractKey": null
        },
        {
          "kind": "InlineFragment",
          "selections": (v4/*: any*/),
          "type": "Money",
          "abstractKey": null
        }
      ],
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "priceIncludesTaxDisplay",
      "storageKey": null
    },
    (v3/*: any*/),
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "shippingInfo",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "shippingOrigin",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "slug",
      "storageKey": null
    },
    {
      "args": null,
      "kind": "FragmentSpread",
      "name": "ArtworkSidebarCreateAlertButton_artwork"
    }
  ],
  "type": "Artwork",
  "abstractKey": null
};
})();

(node as any).hash = "fa1b44a872f484b512f07d4f65494d0b";

export default node;