text:
/**
 * @fileoverview Based on PlotKit.CanvasRenderer, but modified to meet the
 * needs of dygraphs.
 *
 * In particular, support for:
 * - grid overlays
 * - error bars
 * - dygraphs attribute system
 */

/**
 * The DygraphCanvasRenderer class does the actual rendering of the chart onto
 * a canvas. It's based on PlotKit.CanvasRenderer.
 * @param {Object} element The canvas to attach to
 * @param {Object} elementContext The 2d context of the canvas (injected so it
 * can be mocked for testing.)
 * @param {Layout} layout The DygraphLayout object for this graph.
 * @constructor
 */

var DygraphCanvasRenderer = (function() {
/*global Dygraph:false */
"use strict";

/**
 * @constructor
 *
 * This gets called when there are "new points" to chart. This is generally the
 * case when the underlying data being charted has changed. It is _not_ called
 * in the common case that the user has zoomed or is panning the view.
 *
 * The chart canvas has already been created by the Dygraph object. The
 * renderer simply gets a drawing context.
 *
 * @param {Dygraph} dygraph The chart to which this renderer belongs.
 * @param {HTMLCanvasElement} element The <canvas> DOM element on which to draw.
 * @param {CanvasRenderingContext2D} elementContext The drawing context.
 * @param {DygraphLayout} layout The chart's DygraphLayout object.
 *
 * TODO(danvk): remove the elementContext property.
 */
var DygraphCanvasRenderer = function(dygraph, element, elementContext, layout) {
  this.dygraph_ = dygraph;

  this.layout = layout;
  this.element = element;
  this.elementContext = elementContext;

  this.height = dygraph.height_;
  this.width = dygraph.width_;

  // --- check whether everything is ok before we return
  // NOTE(konigsberg): isIE is never defined in this object. Bug of some sort.
  if (!this.isIE && !(Dygraph.isCanvasSupported(this.element)))
      throw "Canvas is not supported.";

  // internal state
  this.area = layout.getPlotArea();

  // Set up a clipping area for the canvas (and the interaction canvas).
  // This ensures that we don't overdraw.
  if (this.dygraph_.isUsingExcanvas_) {
    this._createIEClipArea();
  } else {
    // on Android 3 and 4, setting a clipping area on a canvas prevents it from
    // displaying anything.
    if (!Dygraph.isAndroid()) {
      var ctx = this.dygraph_.canvas_ctx_;
      ctx.beginPath();
      ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
      ctx.clip();

      ctx = this.dygraph_.hidden_ctx_;
      ctx.beginPath();
      ctx.rect(this.area.x, this.area.y, this.area.w, this.area.h);
      ctx.clip();
    }
  }
};

/**
 * Clears out all chart content and DOM elements.
 * This is called immediately before render() on every frame, including
 * during zooms and pans.
 * @private
 */
DygraphCanvasRenderer.prototype.clear = function() {
  var context;
  if (this.isIE) {
    // VML takes a while to start up, so we just poll every this.IEDelay
    try {
      if (this.clearDelay) {
        this.clearDelay.cancel();
        this.clearDelay = null;
      }
      context = this.elementContext;
    }
    catch (e) {
      // TODO(danvk): this is broken, since MochiKit.Async is gone.
      // this.clearDelay = MochiKit.Async.wait(this.IEDelay);
      // this.clearDelay.addCallback(bind(this.clear, this));
      return;
    }
  }

  context = this.elementContext;
  context.clearRect(0, 0, this.width, this.height);
};

/**
 * This method is responsible for drawing everything on the chart, including
 * lines, error bars, fills and axes.
 * It is called immediately after clear() on every frame, including during pans
 * and zooms.
 * @private
 */
DygraphCanvasRenderer.prototype.render = function() {
  // attaches point.canvas{x,y}
  this._updatePoints();

  // actually draws the chart.
  this._renderLineChart();
};

DygraphCanvasRenderer.prototype._createIEClipArea = function() {
  var className = 'dygraph-clip-div';
  var graphDiv = this.dygraph_.graphDiv;

  // Remove old clip divs.
  for (var i = graphDiv.childNodes.length-1; i >= 0; i--) {
    if (graphDiv.childNodes[i].className == className) {
      graphDiv.removeChild(graphDiv.childNodes[i]);
    }
  }

  // Determine background color to give clip divs.
  var backgroundColor = document.bgColor;
  var element = this.dygraph_.graphDiv;
  while (element != document) {
    var bgcolor = element.currentStyle.backgroundColor;
    if (bgcolor && bgcolor != 'transparent') {
      backgroundColor = bgcolor;
      break;
    }
    element = element.parentNode;
  }

  function createClipDiv(area) {
    if (area.w === 0 || area.h === 0) {
      return;
    }
    var elem = document.createElement('div');
    elem.className = className;
    elem.style.backgroundColor = backgroundColor;
    elem.style.position = 'absolute';
    elem.style.left = area.x + 'px';
    elem.style.top = area.y + 'px';
    elem.style.width = area.w + 'px';
    elem.style.height = area.h + 'px';
    graphDiv.appendChild(elem);
  }

  var plotArea = this.area;
  // Left side
  createClipDiv({
    x:0, y:0,
    w:plotArea.x,
    h:this.height
  });

  // Top
  createClipDiv({
    x: plotArea.x, y: 0,
    w: this.width - plotArea.x,
    h: plotArea.y
  });

  // Right side
  createClipDiv({
    x: plotArea.x + plotArea.w, y: 0,
    w: this.width - plotArea.x - plotArea.w,
    h: this.height
  });

  // Bottom
  createClipDiv({
    x: plotArea.x,
    y: plotArea.y + plotArea.h,
    w: this.width - plotArea.x,
    h: this.height - plotArea.h - plotArea.y
  });
};

/**
 * Returns a predicate to be used with an iterator, which will
 * iterate over points appropriately, depending on whether
 * connectSeparatedPoints is true. When it's false, the predicate will
 * skip over points with missing yVals.
 */
DygraphCanvasRenderer._getIteratorPredicate = function(connectSeparatedPoints) {
  return connectSeparatedPoints ?
      DygraphCanvasRenderer._predicateThatSkipsEmptyPoints :
      null;
};

DygraphCanvasRenderer._predicateThatSkipsEmptyPoints =
    function(array, idx) {
  return array[idx].yval !== null;
};

/**
 * Draws a line with the styles passed in and calls all the drawPointCallbacks.
 * @param {Object} e The dictionary passed to the plotter function.
 * @private
 */
DygraphCanvasRenderer._drawStyledLine = function(e,
    color, strokeWidth, strokePattern, drawPoints,
    drawPointCallback, pointSize) {
  var g = e.dygraph;
  // TODO(konigsberg): Compute attributes outside this method call.
  var stepPlot = g.getBooleanOption("stepPlot", e.setName);

  if (!Dygraph.isArrayLike(strokePattern)) {
    strokePattern = null;
  }

  var drawGapPoints = g.getBooleanOption('drawGapEdgePoints', e.setName);

  var points = e.points;
  var setName = e.setName;
  var iter = Dygraph.createIterator(points, 0, points.length,
      DygraphCanvasRenderer._getIteratorPredicate(
          g.getBooleanOption("connectSeparatedPoints", setName)));

  var stroking = strokePattern && (strokePattern.length >= 2);

  var ctx = e.drawingContext;
  ctx.save();
  if (stroking) {
    ctx.installPattern(strokePattern);
  }

  var pointsOnLine = DygraphCanvasRenderer._drawSeries(
      e, iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color);
  DygraphCanvasRenderer._drawPointsOnLine(
      e, pointsOnLine, drawPointCallback, color, pointSize);

  if (stroking) {
    ctx.uninstallPattern();
  }

  ctx.restore();
};

/**
 * This does the actual drawing of lines on the canvas, for just one series.
 * Returns a list of [canvasx, canvasy] pairs for points for which a
 * drawPointCallback should be fired.  These include isolated points, or all
 * points if drawPoints=true.
 * @param {Object} e The dictionary passed to the plotter function.
 * @private
 */
DygraphCanvasRenderer._drawSeries = function(e,
    iter, strokeWidth, pointSize, drawPoints, drawGapPoints, stepPlot, color) {

  var prevCanvasX = null;
  var prevCanvasY = null;
  var nextCanvasY = null;
  var isIsolated; // true if this point is isolated (no line segments)
  var point; // the point being processed in the while loop
  var pointsOnLine = []; // Array of [canvasx, canvasy] pairs.
  var first = true; // the first cycle through the while loop

  var ctx = e.drawingContext;
  ctx.beginPath();
  ctx.strokeStyle = color;
  ctx.lineWidth = strokeWidth;

  // NOTE: we break the iterator's encapsulation here for about a 25% speedup.
  var arr = iter.array_;
  var limit = iter.end_;
  var predicate = iter.predicate_;

  for (var i = iter.start_; i < limit; i++) {
    point = arr[i];
    if (predicate) {
      while (i < limit && !predicate(arr, i)) {
        i++;
      }
      if (i == limit) break;
      point = arr[i];
    }

    // FIXME: The 'canvasy != canvasy' test here catches NaN values but the test
    // doesn't catch Infinity values. Could change this to
    // !isFinite(point.canvasy), but I assume it avoids isNaN for performance?
    if (point.canvasy === null || point.canvasy != point.canvasy) {
      if (stepPlot && prevCanvasX !== null) {
        // Draw a horizontal line to the start of the missing data
        ctx.moveTo(prevCanvasX, prevCanvasY);
        ctx.lineTo(point.canvasx, prevCanvasY);
      }
      prevCanvasX = prevCanvasY = null;
    } else {
      isIsolated = false;
      if (drawGapPoints || !prevCanvasX) {
        iter.nextIdx_ = i;
        iter.next();
        nextCanvasY = iter.hasNext ? iter.peek.canvasy : null;

        var isNextCanvasYNullOrNaN = nextCanvasY === null ||
            nextCanvasY != nextCanvasY;
        isIsolated = (!prevCanvasX && isNextCanvasYNullOrNaN);
        if (drawGapPoints) {
          // Also consider a point to be "isolated" if it's adjacent to a
          // null point, excluding the graph edges.
          if ((!first && !prevCanvasX) ||
              (iter.hasNext && isNextCanvasYNullOrNaN)) {
            isIsolated = true;
          }
        }
      }

      if (prevCanvasX !== null) {
        if (strokeWidth) {
          if (stepPlot) {
            ctx.moveTo(prevCanvasX, prevCanvasY);
            ctx.lineTo(point.canvasx, prevCanvasY);
          }

          ctx.lineTo(point.canvasx, point.canvasy);
        }
      } else {
        ctx.moveTo(point.canvasx, point.canvasy);
      }
      if (drawPoints || isIsolated) {
        pointsOnLine.push([point.canvasx, point.canvasy, point.idx]);
      }
      prevCanvasX = point.canvasx;
      prevCanvasY = point.canvasy;
    }
    first = false;
  }
  ctx.stroke();
  return pointsOnLine;
};

/**
 * This fires the drawPointCallback functions, which draw dots on the points by
 * default. This gets used when the "drawPoints" option is set, or when there
 * are isolated points.
 * @param {Object} e The dictionary passed to the plotter function.
 * @private
 */
DygraphCanvasRenderer._drawPointsOnLine = function(
    e, pointsOnLine, drawPointCallback, color, pointSize) {
  var ctx = e.drawingContext;
  for (var idx = 0; idx < pointsOnLine.length; idx++) {
    var cb = pointsOnLine[idx];
    ctx.save();
    drawPointCallback.call(e.dygraph,
        e.dygraph, e.setName, ctx, cb[0], cb[1], color, pointSize, cb[2]);
    ctx.restore();
  }
};

/**
 * Attaches canvas coordinates to the points array.
 * @private
 */
DygraphCanvasRenderer.prototype._updatePoints = function() {
  // Update Points
  // TODO(danvk): here
  //
  // TODO(bhs): this loop is a hot-spot for high-point-count charts. These
  // transformations can be pushed into the canvas via linear transformation
  // matrices.
  // NOTE(danvk): this is trickier than it sounds at first. The transformation
  // needs to be done before the .moveTo() and .lineTo() calls, but must be
  // undone before the .stroke() call to ensure that the stroke width is
  // unaffected.  An alternative is to reduce the stroke width in the
  // transformed coordinate space, but you can't specify different values for
  // each dimension (as you can with .scale()). The speedup here is ~12%.
  var sets = this.layout.points;
  for (var i = sets.length; i--;) {
    var points = sets[i];
    for (var j = points.length; j--;) {
      var point = points[j];
      point.canvasx = this.area.w * point.x + this.area.x;
      point.canvasy = this.area.h * point.y + this.area.y;
    }
  }
};

/**
 * Add canvas Actually draw the lines chart, including error bars.
 *
 * This function can only be called if DygraphLayout's points array has been
 * updated with canvas{x,y} attributes, i.e. by
 * DygraphCanvasRenderer._updatePoints.
 *
 * @param {string=} opt_seriesName when specified, only that series will
 *     be drawn. (This is used for expedited redrawing with highlightSeriesOpts)
 * @param {CanvasRenderingContext2D} opt_ctx when specified, the drawing
 *     context.  However, lines are typically drawn on the object's
 *     elementContext.
 * @private
 */
DygraphCanvasRenderer.prototype._renderLineChart = function(opt_seriesName, opt_ctx) {
  var ctx = opt_ctx || this.elementContext;
  var i;

  var sets = this.layout.points;
  var setNames = this.layout.setNames;
  var setName;

  this.colors = this.dygraph_.colorsMap_;

  // Determine which series have specialized plotters.
  var plotter_attr = this.dygraph_.getOption("plotter");
  var plotters = plotter_attr;
  if (!Dygraph.isArrayLike(plotters)) {
    plotters = [plotters];
  }

  var setPlotters = {};  // series name -> plotter fn.
  for (i = 0; i < setNames.length; i++) {
    setName = setNames[i];
    var setPlotter = this.dygraph_.getOption("plotter", setName);
    if (setPlotter == plotter_attr) continue;  // not specialized.

    setPlotters[setName] = setPlotter;
  }

  for (i = 0; i < plotters.length; i++) {
    var plotter = plotters[i];
    var is_last = (i == plotters.length - 1);

    for (var j = 0; j < sets.length; j++) {
      setName = setNames[j];
      if (opt_seriesName && setName != opt_seriesName) continue;

      var points = sets[j];

      // Only throw in the specialized plotters on the last iteration.
      var p = plotter;
      if (setName in setPlotters) {
        if (is_last) {
          p = setPlotters[setName];
        } else {
          // Don't use the standard plotters in this case.
          continue;
        }
      }

      var color = this.colors[setName];
      var strokeWidth = this.dygraph_.getOption("strokeWidth", setName);

      ctx.save();
      ctx.strokeStyle = color;
      ctx.lineWidth = strokeWidth;
      p({
        points: points,
        setName: setName,
        drawingContext: ctx,
        color: color,
        strokeWidth: strokeWidth,
        dygraph: this.dygraph_,
        axis: this.dygraph_.axisPropertiesForSeries(setName),
        plotArea: this.area,
        seriesIndex: j,
        seriesCount: sets.length,
        singleSeriesName: opt_seriesName,
        allSeriesPoints: sets
      });
      ctx.restore();
    }
  }
};

/**
 * Standard plotters. These may be used by clients via Dygraph.Plotters.
 * See comments there for more details.
 */
DygraphCanvasRenderer._Plotters = {
  linePlotter: function(e) {
    DygraphCanvasRenderer._linePlotter(e);
  },

  fillPlotter: function(e) {
    DygraphCanvasRenderer._fillPlotter(e);
  },

  errorPlotter: function(e) {
    DygraphCanvasRenderer._errorPlotter(e);
  }
};

/**
 * Plotter which draws the central lines for a series.
 * @private
 */
DygraphCanvasRenderer._linePlotter = function(e) {
  var g = e.dygraph;
  var setName = e.setName;
  var strokeWidth = e.strokeWidth;

  // TODO(danvk): Check if there's any performance impact of just calling
  // getOption() inside of _drawStyledLine. Passing in so many parameters makes
  // this code a bit nasty.
  var borderWidth = g.getNumericOption("strokeBorderWidth", setName);
  var drawPointCallback = g.getOption("drawPointCallback", setName) ||
      Dygraph.Circles.DEFAULT;
  var strokePattern = g.getOption("strokePattern", setName);
  var drawPoints = g.getBooleanOption("drawPoints", setName);
  var pointSize = g.getNumericOption("pointSize", setName);

  if (borderWidth && strokeWidth) {
    DygraphCanvasRenderer._drawStyledLine(e,
        g.getOption("strokeBorderColor", setName),
        strokeWidth + 2 * borderWidth,
        strokePattern,
        drawPoints,
        drawPointCallback,
        pointSize
        );
  }

  DygraphCanvasRenderer._drawStyledLine(e,
      e.color,
      strokeWidth,
      strokePattern,
      drawPoints,
      drawPointCallback,
      pointSize
  );
};

/**
 * Draws the shaded error bars/confidence intervals for each series.
 * This happens before the center lines are drawn, since the center lines
 * need to be drawn on top of the error bars for all series.
 * @private
 */
DygraphCanvasRenderer._errorPlotter = function(e) {
  var g = e.dygraph;
  var setName = e.setName;
  var errorBars = g.getBooleanOption("errorBars") ||
      g.getBooleanOption("customBars");
  if (!errorBars) return;

  var fillGraph = g.getBooleanOption("fillGraph", setName);
  if (fillGraph) {
    console.warn("Can't use fillGraph option with error bars");
  }

  var ctx = e.drawingContext;
  var color = e.color;
  var fillAlpha = g.getNumericOption('fillAlpha', setName);
  var stepPlot = g.getBooleanOption("stepPlot", setName);
  var points = e.points;

  var iter = Dygraph.createIterator(points, 0, points.length,
      DygraphCanvasRenderer._getIteratorPredicate(
          g.getBooleanOption("connectSeparatedPoints", setName)));

  var newYs;

  // setup graphics context
  var prevX = NaN;
  var prevY = NaN;
  var prevYs = [-1, -1];
  // should be same color as the lines but only 15% opaque.
  var rgb = Dygraph.toRGB_(color);
  var err_color =
      'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
  ctx.fillStyle = err_color;
  ctx.beginPath();

  var isNullUndefinedOrNaN = function(x) {
    return (x === null ||
            x === undefined ||
            isNaN(x));
  };

  while (iter.hasNext) {
    var point = iter.next();
    if ((!stepPlot && isNullUndefinedOrNaN(point.y)) ||
        (stepPlot && !isNaN(prevY) && isNullUndefinedOrNaN(prevY))) {
      prevX = NaN;
      continue;
    }

    newYs = [ point.y_bottom, point.y_top ];
    if (stepPlot) {
      prevY = point.y;
    }

    // The documentation specifically disallows nulls inside the point arrays,
    // but in case it happens we should do something sensible.
    if (isNaN(newYs[0])) newYs[0] = point.y;
    if (isNaN(newYs[1])) newYs[1] = point.y;

    newYs[0] = e.plotArea.h * newYs[0] + e.plotArea.y;
    newYs[1] = e.plotArea.h * newYs[1] + e.plotArea.y;
    if (!isNaN(prevX)) {
      if (stepPlot) {
        ctx.moveTo(prevX, prevYs[0]);
        ctx.lineTo(point.canvasx, prevYs[0]);
        ctx.lineTo(point.canvasx, prevYs[1]);
      } else {
        ctx.moveTo(prevX, prevYs[0]);
        ctx.lineTo(point.canvasx, newYs[0]);
        ctx.lineTo(point.canvasx, newYs[1]);
      }
      ctx.lineTo(prevX, prevYs[1]);
      ctx.closePath();
    }
    prevYs = newYs;
    prevX = point.canvasx;
  }
  ctx.fill();
};

/**
 * Proxy for CanvasRenderingContext2D which drops moveTo/lineTo calls which are
 * superfluous. It accumulates all movements which haven't changed the x-value
 * and only applies the two with the most extreme y-values.
 *
 * Calls to lineTo/moveTo must have non-decreasing x-values.
 */
DygraphCanvasRenderer._fastCanvasProxy = function(context) {
  var pendingActions = [];  // array of [type, x, y] tuples
  var lastRoundedX = null;

  var LINE_TO = 1,
      MOVE_TO = 2;

  var actionCount = 0;  // number of moveTos and lineTos passed to context.

  // Drop superfluous motions
  // Assumes all pendingActions have the same (rounded) x-value.
  var compressActions = function(opt_losslessOnly) {
    if (pendingActions.length <= 1) return;

    // Lossless compression: drop inconsequential moveTos.
    for (var i = pendingActions.length - 1; i > 0; i--) {
      var action = pendingActions[i];
      if (action[0] == MOVE_TO) {
        var prevAction = pendingActions[i - 1];
        if (prevAction[1] == action[1] && prevAction[2] == action[2]) {
          pendingActions.splice(i, 1);
        }
      }
    }

    // Lossless compression: ... drop consecutive moveTos ...
    for (var i = 0; i < pendingActions.length - 1; /* incremented internally */) {
      var action = pendingActions[i];
      if (action[0] == MOVE_TO && pendingActions[i + 1][0] == MOVE_TO) {
        pendingActions.splice(i, 1);
      } else {
        i++;
      }
    }

    // Lossy compression: ... drop all but the extreme y-values ...
    if (pendingActions.length > 2 && !opt_losslessOnly) {
      // keep an initial moveTo, but drop all others.
      var startIdx = 0;
      if (pendingActions[0][0] == MOVE_TO) startIdx++;
      var minIdx = null, maxIdx = null;
      for (var i = startIdx; i < pendingActions.length; i++) {
        var action = pendingActions[i];
        if (action[0] != LINE_TO) continue;
        if (minIdx === null && maxIdx === null) {
          minIdx = i;
          maxIdx = i;
        } else {
          var y = action[2];
          if (y < pendingActions[minIdx][2]) {
            minIdx = i;
          } else if (y > pendingActions[maxIdx][2]) {
            maxIdx = i;
          }
        }
      }
      var minAction = pendingActions[minIdx],
          maxAction = pendingActions[maxIdx];
      pendingActions.splice(startIdx, pendingActions.length - startIdx);
      if (minIdx < maxIdx) {
        pendingActions.push(minAction);
        pendingActions.push(maxAction);
      } else if (minIdx > maxIdx) {
        pendingActions.push(maxAction);
        pendingActions.push(minAction);
      } else {
        pendingActions.push(minAction);
      }
    }
  };

  var flushActions = function(opt_noLossyCompression) {
    compressActions(opt_noLossyCompression);
    for (var i = 0, len = pendingActions.length; i < len; i++) {
      var action = pendingActions[i];
      if (action[0] == LINE_TO) {
        context.lineTo(action[1], action[2]);
      } else if (action[0] == MOVE_TO) {
        context.moveTo(action[1], action[2]);
      }
    }
    actionCount += pendingActions.length;
    pendingActions = [];
  };

  var addAction = function(action, x, y) {
    var rx = Math.round(x);
    if (lastRoundedX === null || rx != lastRoundedX) {
      flushActions();
      lastRoundedX = rx;
    }
    pendingActions.push([action, x, y]);
  };

  return {
    moveTo: function(x, y) {
      addAction(MOVE_TO, x, y);
    },
    lineTo: function(x, y) {
      addAction(LINE_TO, x, y);
    },

    // for major operations like stroke/fill, we skip compression to ensure
    // that there are no artifacts at the right edge.
    stroke:    function() { flushActions(true); context.stroke(); },
    fill:      function() { flushActions(true); context.fill(); },
    beginPath: function() { flushActions(true); context.beginPath(); },
    closePath: function() { flushActions(true); context.closePath(); },

    _count: function() { return actionCount; }
  };
};

/**
 * Draws the shaded regions when "fillGraph" is set. Not to be confused with
 * error bars.
 *
 * For stacked charts, it's more convenient to handle all the series
 * simultaneously. So this plotter plots all the points on the first series
 * it's asked to draw, then ignores all the other series.
 *
 * @private
 */
DygraphCanvasRenderer._fillPlotter = function(e) {
  // Skip if we're drawing a single series for interactive highlight overlay.
  if (e.singleSeriesName) return;

  // We'll handle all the series at once, not one-by-one.
  if (e.seriesIndex !== 0) return;

  var g = e.dygraph;
  var setNames = g.getLabels().slice(1);  // remove x-axis

  // getLabels() includes names for invisible series, which are not included in
  // allSeriesPoints. We remove those to make the two match.
  // TODO(danvk): provide a simpler way to get this information.
  for (var i = setNames.length; i >= 0; i--) {
    if (!g.visibility()[i]) setNames.splice(i, 1);
  }

  var anySeriesFilled = (function() {
    for (var i = 0; i < setNames.length; i++) {
      if (g.getBooleanOption("fillGraph", setNames[i])) return true;
    }
    return false;
  })();

  if (!anySeriesFilled) return;

  var area = e.plotArea;
  var sets = e.allSeriesPoints;
  var setCount = sets.length;

  var fillAlpha = g.getNumericOption('fillAlpha');
  var stackedGraph = g.getBooleanOption("stackedGraph");
  var colors = g.getColors();

  // For stacked graphs, track the baseline for filling.
  //
  // The filled areas below graph lines are trapezoids with two
  // vertical edges. The top edge is the line segment being drawn, and
  // the baseline is the bottom edge. Each baseline corresponds to the
  // top line segment from the previous stacked line. In the case of
  // step plots, the trapezoids are rectangles.
  var baseline = {};
  var currBaseline;
  var prevStepPlot;  // for different line drawing modes (line/step) per series

  // Helper function to trace a line back along the baseline.
  var traceBackPath = function(ctx, baselineX, baselineY, pathBack) {
    ctx.lineTo(baselineX, baselineY);
    if (stackedGraph) {
      for (var i = pathBack.length - 1; i >= 0; i--) {
        var pt = pathBack[i];
        ctx.lineTo(pt[0], pt[1]);
      }
    }
  };

  // process sets in reverse order (needed for stacked graphs)
  for (var setIdx = setCount - 1; setIdx >= 0; setIdx--) {
    var ctx = e.drawingContext;
    var setName = setNames[setIdx];
    if (!g.getBooleanOption('fillGraph', setName)) continue;

    var stepPlot = g.getBooleanOption('stepPlot', setName);
    var color = colors[setIdx];
    var axis = g.axisPropertiesForSeries(setName);
    var axisY = 1.0 + axis.minyval * axis.yscale;
    if (axisY < 0.0) axisY = 0.0;
    else if (axisY > 1.0) axisY = 1.0;
    axisY = area.h * axisY + area.y;

    var points = sets[setIdx];
    var iter = Dygraph.createIterator(points, 0, points.length,
        DygraphCanvasRenderer._getIteratorPredicate(
            g.getBooleanOption("connectSeparatedPoints", setName)));

    // setup graphics context
    var prevX = NaN;
    var prevYs = [-1, -1];
    var newYs;
    // should be same color as the lines but only 15% opaque.
    var rgb = Dygraph.toRGB_(color);
    var err_color =
        'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + fillAlpha + ')';
    ctx.fillStyle = err_color;
    ctx.beginPath();
    var last_x, is_first = true;

    // If the point density is high enough, dropping segments on their way to
    // the canvas justifies the overhead of doing so.
    if (points.length > 2 * g.width_) {
      ctx = DygraphCanvasRenderer._fastCanvasProxy(ctx);
    }

    // For filled charts, we draw points from left to right, then back along
    // the x-axis to complete a shape for filling.
    // For stacked plots, this "back path" is a more complex shape. This array
    // stores the [x, y] values needed to trace that shape.
    var pathBack = [];

    // TODO(danvk): there are a lot of options at play in this loop.
    //     The logic would be much clearer if some (e.g. stackGraph and
    //     stepPlot) were split off into separate sub-plotters.
    var point;
    while (iter.hasNext) {
      point = iter.next();
      if (!Dygraph.isOK(point.y) && !stepPlot) {
        traceBackPath(ctx, prevX, prevYs[1], pathBack);
        pathBack = [];
        prevX = NaN;
        if (point.y_stacked !== null && !isNaN(point.y_stacked)) {
          baseline[point.canvasx] = area.h * point.y_stacked + area.y;
        }
        continue;
      }
      if (stackedGraph) {
        if (!is_first && last_x == point.xval) {
          continue;
        } else {
          is_first = false;
          last_x = point.xval;
        }

        currBaseline = baseline[point.canvasx];
        var lastY;
        if (currBaseline === undefined) {
          lastY = axisY;
        } else {
          if(prevStepPlot) {
            lastY = currBaseline[0];
          } else {
            lastY = currBaseline;
          }
        }
        newYs = [ point.canvasy, lastY ];

        if (stepPlot) {
          // Step plots must keep track of the top and bottom of
          // the baseline at each point.
          if (prevYs[0] === -1) {
            baseline[point.canvasx] = [ point.canvasy, axisY ];
          } else {
            baseline[point.canvasx] = [ point.canvasy, prevYs[0] ];
          }
        } else {
          baseline[point.canvasx] = point.canvasy;
        }

      } else {
        if (isNaN(point.canvasy) && stepPlot) {
          newYs = [ area.y + area.h, axisY ];
        } else {
          newYs = [ point.canvasy, axisY ];
        }
      }
      if (!isNaN(prevX)) {
        // Move to top fill point
        if (stepPlot) {
          ctx.lineTo(point.canvasx, prevYs[0]);
          ctx.lineTo(point.canvasx, newYs[0]);
        } else {
          ctx.lineTo(point.canvasx, newYs[0]);
        }

        // Record the baseline for the reverse path.
        if (stackedGraph) {
          pathBack.push([prevX, prevYs[1]]);
          if (prevStepPlot && currBaseline) {
            // Draw to the bottom of the baseline
            pathBack.push([point.canvasx, currBaseline[1]]);
          } else {
            pathBack.push([point.canvasx, newYs[1]]);
          }
        }
      } else {
        ctx.moveTo(point.canvasx, newYs[1]);
        ctx.lineTo(point.canvasx, newYs[0]);
      }
      prevYs = newYs;
      prevX = point.canvasx;
    }
    prevStepPlot = stepPlot;
    if (newYs && point) {
      traceBackPath(ctx, point.canvasx, newYs[1], pathBack);
      pathBack = [];
    }
    ctx.fill();
  }
};

return DygraphCanvasRenderer;

})();


text:
package com.microsoft.azure.management.cosmosdb.v2020_06_01_preview;

/**
 * The SqlContainerGetPropertiesOptions model.
 */
public class SqlContainerGetPropertiesOptions extends OptionsResource {
}

redpajama_set_name: RedPajamaGithub


text:
import xml.etree.ElementTree
from opentuner import MeasurementInterface
from opentuner import Result

class ProgramTunerWrapper(MeasurementInterface):
  def get_qor(self):
    """ return qor & [BRAM, FF, LUT, DSP]"""

    filename = 'vivado_hls.log'
    f = open(filename, 'r')
    while True:
      line = f.readline()
      if not line: break
      if 'LUT:' in line:
        LUT = line.strip('\n').split()[-1]
        continue
      if 'FF:' in line:
        FF = line.strip('\n').split()[-1]
        continue
      if 'DSP' in line:
        DSP = line.strip('\n').split()[-1]
        continue
      if 'BRAM:' in line:
        BRAM = line.strip('\n').split()[-1]
        continue
      if 'achieved post-implementation' in line:
        timing = line.strip('\n').split()[-1]
        continue
      if 'Average error:' in line:
        err_degree = float(line.strip('\n').split()[-2])
        continue
    f.close()
    if err_degree > 20.0:
      LUT = 10000
    else:
      pass
    metadata = [FF, DSP, BRAM, timing, err_rate]
    #e = xml.etree.ElementTree.parse(filename).getroot()
    #for item in e.iter('EstimatedClockPeriod'):
    #  timing = item.text
    #metadata = []
    #for tag in e.iter('Resources'):
    #  for item in tag.getchildren():
    #    metadata.append(item.text)
    return float(LUT), metadata

  def run(self, desired_result, input, limit):
    """
    Compile and run a given configuration then
    return performance
    """

    param_list = [
      'BW1',
      'BW2',
      'BW3',
      'BW4',
      'BW5'
    ]

    cfg = desired_result.configuration.data
    result_id = desired_result.id

    # dump cfg in tcl
    f = open('./options.tcl', 'w')
    f.write('set CFLAGS "-DFIXED_TYPE')
    for index in param_list:
      f.write(' -D' + index  + '=' + str(cfg[index]))
    f.write('"\n')
    f.close()

    cmd = 'vivado_hls ./run.tcl'
    run_result = self.call_program(cmd)
    assert run_result['returncode'] == 0

    result, metadata = self.get_qor()
    self.dumpresult(cfg, result, metadata)
    return Result(time = result)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_log_in"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="mprog.nl.programmeerproject.Activities.LogInActivity">

    <EditText
        android:id="@+id/logInEmailEdit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/email"
        android:padding="10dp"
        />

    <EditText
        android:id="@+id/logInPassEdit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/pass"
        android:layout_below="@+id/logInEmailEdit"
        android:inputType="textPassword"
        android:padding="10dp"
        />

    <Button
        android:id="@+id/logInButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/logIn"
        android:layout_below="@+id/logInPassEdit"
        android:padding="10dp"
        />

    <TextView
        android:id="@+id/logInSignUpText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/logInButton"
        android:layout_centerHorizontal="true"
        android:text="@string/signUp"
        android:padding="10dp"
        />

</RelativeLayout>


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/breadcrumbs/core/breadcrumb_persistent_storage_manager.h"

#include <memory>
#include <string>
#include <vector>

#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/test/task_environment.h"
#include "components/breadcrumbs/core/breadcrumb_manager_keyed_service.h"
#include "components/breadcrumbs/core/breadcrumb_persistent_storage_util.h"
#include "testing/platform_test.h"

namespace breadcrumbs {

namespace {

// Estimate number of events too large to fit in the persisted file. 6 is based
// on the event string format which is slightly smaller than each event.
constexpr unsigned long kEventCountTooManyForPersisting =
    kPersistedFilesizeInBytes / 6.0;

// Validates that the events in `persisted_events` are contiguous and that the
// `last_logged_event` matches the last persisted event.
bool ValidatePersistedEvents(const std::string& last_logged_event,
                             std::vector<std::string> persisted_events) {
  if (persisted_events.empty())
    return false;

  // The newest event is at the back of the vector.
  const std::string last_event = persisted_events.back();
  if (last_event.find(last_logged_event) == std::string::npos)
    return false;

  // The oldest event is at the front of the vector.
  const std::string first_event = persisted_events.front();
  int first_event_index;
  if (!base::StringToInt(first_event.substr(first_event.find_last_of(' ') + 1),
                         &first_event_index)) {
    // `first_event_index` could not be parsed.
    return false;
  }

  int last_event_index;
  if (!base::StringToInt(last_event.substr(last_event.find_last_of(' ') + 1),
                         &last_event_index)) {
    // `last_event_index` could not be parsed.
    return false;
  }

  // Validate no events are missing from within the persisted range.
  return last_event_index - first_event_index + 1 ==
         static_cast<int>(persisted_events.size());
}

}  // namespace

class BreadcrumbPersistentStorageManagerTest : public PlatformTest {
 protected:
  BreadcrumbPersistentStorageManagerTest() {
    EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
    persistent_storage_ = std::make_unique<BreadcrumbPersistentStorageManager>(
        scoped_temp_dir_.GetPath(),
        /*is_metrics_enabled_callback=*/base::BindRepeating(
            &BreadcrumbPersistentStorageManagerTest::is_metrics_enabled,
            base::Unretained(this)));
    breadcrumb_manager_service_.StartPersisting(persistent_storage_.get());
  }

  ~BreadcrumbPersistentStorageManagerTest() override {
    breadcrumb_manager_service_.StopPersisting();
  }

  // Calls `GetStoredEvents()` and wait for its posted tasks to complete.
  std::vector<std::string> GetPersistedEvents() {
    base::RunLoop run_loop;
    persistent_storage_->GetStoredEvents(
        base::BindOnce(&BreadcrumbPersistentStorageManagerTest::WaitForEvents,
                       base::Unretained(this), run_loop.QuitClosure()));
    run_loop.Run();
    return events_;
  }

  // Run `quit_closure` to signal to the run loop that the function being tested
  // has completed, and sets `events_` to the `events` vector received from the
  // function being tested (so that tests may make assertions about the events).
  void WaitForEvents(base::OnceClosure quit_closure,
                     std::vector<std::string> events) {
    events_.clear();
    events_ = events;
    std::move(quit_closure).Run();
  }

  bool is_metrics_enabled() { return is_metrics_enabled_; }

  void EnableMetricsConsent() { is_metrics_enabled_ = true; }
  void DisableMetricsConsent() { is_metrics_enabled_ = false; }

  base::test::TaskEnvironment task_env_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  base::ScopedTempDir scoped_temp_dir_;
  BreadcrumbManagerKeyedService breadcrumb_manager_service_{
      /*is_off_the_record=*/false};

 private:
  std::unique_ptr<BreadcrumbPersistentStorageManager> persistent_storage_;

  // Stores events returned by BreadcrumbPersistentStorageManager::GetEvents().
  std::vector<std::string> events_;

  bool is_metrics_enabled_ = true;
};

// Ensures that logged events are persisted.
TEST_F(BreadcrumbPersistentStorageManagerTest, PersistEvents) {
  breadcrumb_manager_service_.AddEvent("event");

  // Advance clock to trigger writing final events.
  task_env_.FastForwardBy(base::Minutes(1));

  const auto events = GetPersistedEvents();
  ASSERT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos, events.front().find("event"));
}

// Ensures that persisted events do not grow too large for a single large
// event bucket when events are logged very quickly one after the other.
TEST_F(BreadcrumbPersistentStorageManagerTest, PersistLargeBucket) {
  std::string event;
  unsigned long event_count = 0;
  while (event_count < kEventCountTooManyForPersisting) {
    event = base::StringPrintf("event %lu", event_count);
    breadcrumb_manager_service_.AddEvent(event);
    task_env_.FastForwardBy(base::Milliseconds(1));

    event_count++;
  }

  // Advance clock to trigger writing final events.
  task_env_.FastForwardBy(base::Minutes(1));

  const auto events = GetPersistedEvents();
  EXPECT_LT(events.size(), event_count);
  EXPECT_TRUE(ValidatePersistedEvents(event, events));
}

// Ensures that persisted events do not grow too large for events logged a few
// seconds apart from each other.
TEST_F(BreadcrumbPersistentStorageManagerTest, PersistManyEventsOverTime) {
  std::string event;
  unsigned long event_count = 0;
  while (event_count < kEventCountTooManyForPersisting) {
    event = base::StringPrintf("event %lu", event_count);
    breadcrumb_manager_service_.AddEvent(event);
    task_env_.FastForwardBy(base::Seconds(1));

    event_count++;
  }

  // Advance clock to trigger writing final events.
  task_env_.FastForwardBy(base::Minutes(1));

  const auto events = GetPersistedEvents();
  ASSERT_GT(events.size(), 0ul);
  EXPECT_LT(events.size(), event_count);
  EXPECT_TRUE(ValidatePersistedEvents(event, events));
}

// Ensures that old events are removed from the persisted file when old buckets
// are dropped.
TEST_F(BreadcrumbPersistentStorageManagerTest,
       OldEventsRemovedFromPersistedFile) {
  std::string event;
  unsigned long event_counter = 0;
  constexpr int kNumEventsPerBucket = 200;
  constexpr int kNumEvents = kNumEventsPerBucket * 3;
  while (event_counter < kNumEvents) {
    event = base::StringPrintf("event %lu", event_counter);
    breadcrumb_manager_service_.AddEvent(event);
    event_counter++;

    if (event_counter % kNumEventsPerBucket == 0)
      task_env_.FastForwardBy(base::Hours(1));
  }

  // Advance clock to trigger writing final events.
  task_env_.FastForwardBy(base::Minutes(1));

  // The exact number of events could vary based on changes in the
  // implementation. The important part of this test is to verify that a single
  // event bucket will not grow unbounded and it will be limited to a value
  // smaller than the overall total number of events which have been logged.
  const auto events = GetPersistedEvents();
  EXPECT_LT(events.size(), event_counter);
  EXPECT_TRUE(ValidatePersistedEvents(event, events));
}

// Ensures that events are read correctly if the persisted file becomes
// corrupted by losing the EOF token or if kPersistedFilesizeInBytes is reduced.
TEST_F(BreadcrumbPersistentStorageManagerTest,
       GetStoredEventsAfterFilesizeReduction) {
  const base::FilePath breadcrumbs_file_path =
      GetBreadcrumbPersistentStorageFilePath(scoped_temp_dir_.GetPath());
  base::File file(breadcrumbs_file_path,
                  base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE);
  ASSERT_TRUE(file.IsValid());

  // Simulate an old persisted file larger than the current one.
  const size_t old_filesize = kPersistedFilesizeInBytes * 1.2;
  std::string past_breadcrumbs;
  unsigned long written_events = 0;
  while (past_breadcrumbs.length() < old_filesize) {
    past_breadcrumbs += "08:27 event\n";
    written_events++;
  }

  ASSERT_TRUE(file.WriteAndCheck(
      /*offset=*/0, base::as_bytes(base::make_span(past_breadcrumbs))));
  ASSERT_TRUE(file.Flush());
  file.Close();

  const auto events = GetPersistedEvents();
  EXPECT_GT(events.size(), 1ul);
  EXPECT_LT(events.size(), written_events);
}

// Ensures that the breadcrumbs file is deleted if metrics consent is not
// provided, and recreated if it is re-enabled.
TEST_F(BreadcrumbPersistentStorageManagerTest, ChangeMetricsConsent) {
  const base::FilePath breadcrumbs_file_path =
      GetBreadcrumbPersistentStorageFilePath(scoped_temp_dir_.GetPath());

  breadcrumb_manager_service_.AddEvent("event 1");
  task_env_.FastForwardBy(base::Seconds(1));
  ASSERT_TRUE(base::PathExists(breadcrumbs_file_path));
  auto events = GetPersistedEvents();
  ASSERT_EQ(1ul, events.size());
  ASSERT_NE(std::string::npos, events.front().find("event 1"));

  // Turn off metrics consent; the breadcrumbs file should be deleted when an
  // event is logged.
  DisableMetricsConsent();

  breadcrumb_manager_service_.AddEvent("event 2");
  task_env_.FastForwardBy(base::Seconds(1));
  EXPECT_FALSE(base::PathExists(breadcrumbs_file_path));
  EXPECT_TRUE(GetPersistedEvents().empty());

  // Turn metrics consent back on; the breadcrumbs file should be recreated and
  // include only events logged since metrics were re-enabled.
  EnableMetricsConsent();

  breadcrumb_manager_service_.AddEvent("event 3");
  task_env_.FastForwardBy(base::Seconds(1));
  EXPECT_TRUE(base::PathExists(breadcrumbs_file_path));
  events = GetPersistedEvents();
  EXPECT_EQ(1ul, events.size());
  EXPECT_NE(std::string::npos, events.front().find("event 3"));
}

}  // namespace breadcrumbs


text:
class PDFConverterTableRole < (Asciidoctor::Converter.for 'pdf')
  register_for 'pdf'

  def convert_table node
    return super unless node.role?
    key_prefix = %(role_<table>_#{node.roles[0]}_)
    role_entries = theme.each_pair.select {|name, val| name.to_s.start_with? key_prefix }
    return super if role_entries.empty?
    save_theme do
      role_entries.each do |name, val|
        theme[%(table_#{name.to_s.delete_prefix key_prefix})] = val
      end
      super
    end
  end
end


text:
this.socket = new WebSocket('ws://localhost');
// Make sure the binary data transmitted
// is interpreted as an ArrayBuffer
// More on ArrayBuffers and Blobs in:
// - https://developer.mozilla.org/en/docs/Web/API/Blob
// - https://developer.mozilla.org/en-US/docs/Web/JavaScript/
//           Reference/Global_Objects/ArrayBuffer
this.socket.binaryType = 'arraybuffer';

// Define all the callback handlers
connection.onopen = function () {
    // The connection was established; send some regards.
    connection.send('Hello World!');
};

connection.onerror = function (error) {
    // An error has occurred; print it to the console.
    console.log('WebSocket Error: ' + error);
};

connection.onmessage = function (e) {
    if (typeof e.data == 'string') {
        // If a text type message was received, print it out.
        console.log('Text message received: ' + e.data);
    } else {
        // A binary type message was received.
        // Interpret the values as 16 bit uints.
        var arr = new Uint16Array(e.data);
        // Plot the data.
        plot(arr);
    }
};


text:
<?php

/**
 * Model_Base_UserRequest
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $id
 * @property integer $user_id
 * @property text $request
 * @property Model_User $User
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class Model_Base_UserRequest extends Ext_Doctrine_Record
{
    public function setTableDefinition()
    {
        $this->setTableName('user_request');
        $this->hasColumn('id', 'integer', 4, array(
             'type' => 'integer',
             'primary' => true,
             'autoincrement' => true,
             'length' => '4',
             ));
        $this->hasColumn('user_id', 'integer', 4, array(
             'type' => 'integer',
             'length' => '4',
             ));
        $this->hasColumn('request', 'text', null, array(
             'type' => 'text',
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasOne('Model_User as User', array(
             'local' => 'user_id',
             'foreign' => 'id',
             'onDelete' => 'cascade'));

        $timestampable0 = new Doctrine_Template_Timestampable(array(
             'created' =>
             array(
              'name' => 'created_at',
             ),
             'updated' =>
             array(
              'name' => 'updated_at',
             ),
             ));
        $this->actAs($timestampable0);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

		<item value="257" key="DIALOG_WIDTH"/>
		<item value="329" key="DIALOG_Y_ORIGIN"/>
		<item value="1031" key="DIALOG_X_ORIGIN"/>
		<item value="380" key="DIALOG_HEIGHT"/>
		<item value="1|Segoe UI|9.0|0|WINDOWS|1|-12|0|0|0|400|0|0|0|1|0|0|0|0|Segoe UI" key="DIALOG_FONT_NAME"/>

		<item value="true" key="wrap"/>
		<item value="false" key="casesensitive"/>
		<item value="false" key="isRegEx"/>
		<item value="false" key="incremental"/>
		<item value="false" key="wholeword"/>
		<item value="output" key="selection"/>
		<list key="findhistory">
			<item value="output"/>
			<item value="SetSysClock();"/>
			<item value="Reset"/>
			<item value="export"/>
			<item value="FMC"/>
			<item value="NVIC_"/>
		</list>
		<list key="replacehistory">
		</list>


text:
//-----------------------------------------------------------------------
// <copyright file="Decorator.cs" company="Copacetic Software">
// Copyright (c) Copacetic Software.
// <author>Philip Pittle</author>
// <date>Saturday, March 15, 2014 7:04:16 PM</date>
// Licensed under the Apache License, Version 2.0,
// you may not use this file except in compliance with this License.
//
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

using System;
using CopaceticSoftware.pMixins.Tests.Common;
using NUnit.Framework;

namespace CopaceticSoftware.pMixins.CodeGenerator.Tests.IntegrationTests.CompileTests.AdvancedMixinTypes
{
    [TestNotWrittenYet]
    [TestFixture]
    public class Decorator : GenerateCodeAndCompileTestBase
    {
        protected override string SourceCode
        {
            get { throw new NotImplementedException(); }
        }
    }
}


text:
var classMethods = {};

classMethods.getFieldsNames = function() {
  return this.schema.fieldsNames;
};

classMethods.hasField = function(fieldName) {
  return _.has(this.schema.fields, fieldName);
};

classMethods.getField = function(fieldName) {
  return this.schema.fields[fieldName];
};

classMethods.getFields = function() {
  return this.schema.fields;
};

Astro.eventManager.on(
  'initClass', function onInitClassFields(schemaDefinition) {
    var Class = this;

    // Add fields methods to the class.
    _.extend(Class, classMethods);
  }
);


text: A personal page for Ke Lei


text:
name             'cakephp2_deploy'
maintainer       'MikeBThun'
license          'All rights reserved'
description      'Installs/Configures cakephp2_deploy'
long_description 'Installs/Configures cakephp2_deploy'
version          '0.1.0'


text:
@implementation ErrorManager

+ (NSError *)errorForErrorIdentifier:(NSInteger)errorIdentifier {
    return [NSError errorWithDomain:[[NSBundle mainBundle] bundleIdentifier]
                               code:errorIdentifier
                           userInfo:[self userInfoForErrorIdentifier:errorIdentifier]];
}

+ (UIAlertController *)alertControllerFromError:(NSError *)error {
    NSLog(@"An error occured. Error description: %@. Possible failure reason: %@. Possible recovery suggestion: %@",error.localizedDescription,error.localizedFailureReason,error.localizedRecoverySuggestion);

    NSString *possibleRecoverySuggestion = @" ";
    if (error.localizedRecoverySuggestion) {
        possibleRecoverySuggestion = [NSString stringWithFormat:@"\nPossible recovery suggestion: %@",error.localizedRecoverySuggestion];
    }

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:error.localizedDescription message:[NSString stringWithFormat:@"Possible reason: %@ %@",error.localizedFailureReason,possibleRecoverySuggestion] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK") style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    return alert;
}

+ (UIAlertController *)alertControllerFromErrorIdentifier:(NSInteger)errorIdentifier {
    return [self alertControllerFromError:[self errorForErrorIdentifier:errorIdentifier]];
}

#pragma mark - Helpers

+ (NSDictionary *)userInfoForErrorIdentifier:(NSInteger)error {

    switch (error) {
        case ERROR_WRITING_DATA:
            return @{NSLocalizedDescriptionKey: NSLocalizedString(@"Error Writing Data", nil),
                     NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"This occured when trying to write an output to the opened socket, when trying to send message to the server.", nil)
                     };
        case ERROR_OPENING_STREAM:
            return @{NSLocalizedDescriptionKey: NSLocalizedString(@"Error Opening Stream", nil),
                     NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"This occured when trying to open a stream.", nil)
                     };
        case ERROR_NO_CONNECTION_FOUND:
            return @{NSLocalizedDescriptionKey: NSLocalizedString(@"There's no active connection.", nil),
                     NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"This error occured when trying to close a connection, while there wasnt't a connection available.", nil)
                     };
        case ERROR_ALREADY_CONNECTED:
            return @{NSLocalizedDescriptionKey: NSLocalizedString(@"There's a connection stablished already.", nil),
                     NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"This error occured when trying to open a connection, while there was already a stablished connection.", nil)
                     };
        case ERROR_INVALID_RESPONSE_FORMAT:
            return @{NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid Response.", nil),
                     NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"This error occurs when receiving a message with an unexpected format.", nil)
                     };
        default:
            return @{NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid error", nil),
                     NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"The action generated an unexpected error.", nil)
                     };
    }
}

@end


text:
'use strict';

BacharuApp.controller('VMGuestMetricsCtrl', function($scope) {
});


text:
"""
This check tests if a file with the same filename (ignoring the case) already exists in the repository.
"""

from repoguard.core.module import Check, ConfigSerializer, Array, String

class Config(ConfigSerializer):
    class types(ConfigSerializer.types):
        check_files = Array(String, optional=True, default=[".*"])
        ignore_files = Array(String, optional=True, default=[])

class CaseInsensitiveFilenameClash(Check):

    __config__ = Config
    pattern = "A file with the same name already exists: %r\n"

    def _run(self, config):
        files = self.transaction.get_files(config.check_files,
                                           config.ignore_files)
        msg = ""
        for filename, attribute in files.iteritems():
            if attribute in ["A"] :
                if self.transaction.file_exists(filename, ignore_case=True):
                    msg += self.pattern % filename

        if msg:
            return self.error(msg)
        else:
            return self.success()


text:
/**
 * Selfbits API V2
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: 2.0.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */
import * as models from './models';
export interface RolePermissionBulkUpdate {
    update: models.RolePermissionUpdate;
}


text:
<?php

namespace MatryoshkaModelWrapperMongoTest\Hydrator\NamingStrategy;

use Matryoshka\Model\Wrapper\Mongo\Hydrator\NamingStrategy\DefaultNamingStrategy;

/**
 * Class DefaultNamingStrategyTest
 */
class DefaultNamingStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testExtract()
    {
        $strategy = new DefaultNamingStrategy();
        $this->assertSame('_id', $strategy->extract('id'));
        $this->assertSame('foo', $strategy->extract('foo'));
    }

    public function testHydrate()
    {
        $strategy = new DefaultNamingStrategy();
        $this->assertSame('id', $strategy->hydrate('_id'));
        $this->assertSame('foo', $strategy->hydrate('foo'));
    }
}


text:
/**
 * @const
 * @suppress {const|duplicate}
 * @externs
 */
var jsts = {};

/** @const */
jsts.geom = {};

/**
 * @constructor
 */
jsts.geom.Geometry = function() {};

/**
 * @param {number} buffer Buffer in meters.
 * @return {jsts.geom.Geometry} A JSTS geometry object.
 */
jsts.geom.Geometry.prototype.buffer = function(buffer) {};

/**
 * @param {jsts.geom.Geometry} jstsGeom A JSTS geometry object.
 * @return {jsts.geom.Geometry} A JSTS geometry object.
 */
jsts.geom.Geometry.prototype.difference = function(jstsGeom) {};

/**
 * @param {jsts.geom.Geometry} jstsGeom A JSTS geometry object.
 * @return {boolean} Whether the geometries intersect with one an other.
 */
jsts.geom.Geometry.prototype.intersects = function(jstsGeom) {};

/**
 * @param {jsts.geom.Geometry} jstsGeom A JSTS geometry object.
 * @return {jsts.geom.Geometry} A JSTS geometry object.
 */
jsts.geom.Geometry.prototype.union = function(jstsGeom) {};

/** @const */
jsts.io = {};

/**
 * @constructor
 */
jsts.io.OL3Parser = function() {};

/**
 * @param {ol.geom.Geometry} ol3Geom A OL3 geometry object.
 * @return {jsts.geom.Geometry} A JSTS geometry object.
 */
jsts.io.OL3Parser.prototype.read = function(ol3Geom) {};

/**
 * @param {jsts.geom.Geometry} jstsGeom A JSTS geometry object.
 * @return {ol.geom.Geometry} A OL3 geometry object.
 */
jsts.io.OL3Parser.prototype.write = function(jstsGeom) {};


text:
import {zoneSymbol} from '../../lib/common/utils';

describe('Zone', function() {
  const rootZone = Zone.current;

  it('should have a name', function() {
    expect(Zone.current.name).toBeDefined();
  });

  describe('hooks', function() {
    it('should throw if onError is not defined', function() {
      expect(function() {
        Zone.current.run(throwError);
      }).toThrow();
    });

    it('should fire onError if a function run by a zone throws', function() {
      const errorSpy = jasmine.createSpy('error');
      const myZone = Zone.current.fork({name: 'spy', onHandleError: errorSpy});

      expect(errorSpy).not.toHaveBeenCalled();

      expect(function() {
        myZone.runGuarded(throwError);
      }).not.toThrow();

      expect(errorSpy).toHaveBeenCalled();
    });

    it('should send correct currentZone in hook method when in nested zone', function() {
      const zone = Zone.current;
      const zoneA = zone.fork({
        name: 'A',
        onInvoke: function(
            parentDelegate, currentZone, targetZone, callback, applyThis, applyArgs, source) {
          expect(currentZone.name).toEqual('A');
          return parentDelegate.invoke(targetZone, callback, applyThis, applyArgs, source);
        }
      });
      const zoneB = zoneA.fork({
        name: 'B',
        onInvoke: function(
            parentDelegate, currentZone, targetZone, callback, applyThis, applyArgs, source) {
          expect(currentZone.name).toEqual('B');
          return parentDelegate.invoke(targetZone, callback, applyThis, applyArgs, source);
        }
      });
      const zoneC = zoneB.fork({name: 'C'});
      zoneC.run(function() {});
    });

    it('should send correct currentZone in hook method when in nested zone with empty implementation',
       function() {
         const zone = Zone.current;
         const zoneA = zone.fork({
           name: 'A',
           onInvoke: function(
               parentDelegate, currentZone, targetZone, callback, applyThis, applyArgs, source) {
             expect(currentZone.name).toEqual('A');
             return parentDelegate.invoke(targetZone, callback, applyThis, applyArgs, source);
           }
         });
         const zoneB = zoneA.fork({name: 'B'});
         const zoneC = zoneB.fork({name: 'C'});
         zoneC.run(function() {});
       });
  });

  it('should allow zones to be run from within another zone', function() {
    const zone = Zone.current;
    const zoneA = zone.fork({name: 'A'});
    const zoneB = zone.fork({name: 'B'});

    zoneA.run(function() {
      zoneB.run(function() {
        expect(Zone.current).toBe(zoneB);
      });
      expect(Zone.current).toBe(zoneA);
    });
    expect(Zone.current).toBe(zone);
  });

  describe('wrap', function() {
    it('should throw if argument is not a function', function() {
      expect(function() {
        (<Function>Zone.current.wrap)(11);
      }).toThrowError('Expecting function got: 11');
    });
  });

  describe('run out side of current zone', function() {
    it('should be able to get root zone', function() {
      Zone.current.fork({name: 'testZone'}).run(function() {
        expect(Zone.root.name).toEqual('<root>');
      });
    });

    it('should be able to get run under rootZone', function() {
      Zone.current.fork({name: 'testZone'}).run(function() {
        Zone.root.run(() => {
          expect(Zone.current.name).toEqual('<root>');
        });
      });
    });

    it('should be able to get run outside of current zone', function() {
      Zone.current.fork({name: 'testZone'}).run(function() {
        Zone.root.fork({name: 'newTestZone'}).run(() => {
          expect(Zone.current.name).toEqual('newTestZone');
          expect(Zone.current.parent!.name).toEqual('<root>');
        });
      });
    });
  });

  describe('get', function() {
    it('should store properties', function() {
      const testZone = Zone.current.fork({name: 'A', properties: {key: 'value'}});
      expect(testZone.get('key')).toEqual('value');
      expect(testZone.getZoneWith('key')).toEqual(testZone);
      const childZone = testZone.fork({name: 'B', properties: {key: 'override'}});
      expect(testZone.get('key')).toEqual('value');
      expect(testZone.getZoneWith('key')).toEqual(testZone);
      expect(childZone.get('key')).toEqual('override');
      expect(childZone.getZoneWith('key')).toEqual(childZone);
    });
  });

  describe('task', () => {
    function noop() {}
    let log: any[];
    const zone: Zone = Zone.current.fork({
      name: 'parent',
      onHasTask: (delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState):
          void => {
            (hasTaskState as any)['zone'] = target.name;
            log.push(hasTaskState);
          },
      onScheduleTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task) => {
        // Do nothing to prevent tasks from being run on VM turn;
        // Tests run task explicitly.
        return task;
      }
    });

    beforeEach(() => {
      log = [];
    });

    it('task can only run in the zone of creation', () => {
      const task =
          zone.fork({name: 'createZone'}).scheduleMacroTask('test', noop, undefined, noop, noop);
      expect(() => {
        Zone.current.fork({name: 'anotherZone'}).runTask(task);
      })
          .toThrowError(
              'A task can only be run in the zone of creation! (Creation: createZone; Execution: anotherZone)');
      task.zone.cancelTask(task);
    });

    it('task can only cancel in the zone of creation', () => {
      const task =
          zone.fork({name: 'createZone'}).scheduleMacroTask('test', noop, undefined, noop, noop);
      expect(() => {
        Zone.current.fork({name: 'anotherZone'}).cancelTask(task);
      })
          .toThrowError(
              'A task can only be cancelled in the zone of creation! (Creation: createZone; Execution: anotherZone)');
      task.zone.cancelTask(task);
    });

    it('should prevent double cancellation', () => {
      const task =
          zone.scheduleMacroTask('test', () => log.push('macroTask'), undefined, noop, noop);
      zone.cancelTask(task);
      try {
        zone.cancelTask(task);
      } catch (e) {
        expect(e.message).toContain(
            'macroTask \'test\': can not transition to \'canceling\', expecting state \'scheduled\' or \'running\', was \'notScheduled\'.');
      }
    });

    it('should not decrement counters on periodic tasks', () => {
      zone.run(() => {
        const task = zone.scheduleMacroTask(
            'test', () => log.push('macroTask'), {isPeriodic: true}, noop, noop);
        zone.runTask(task);
        zone.runTask(task);
        zone.cancelTask(task);
      });
      expect(log).toEqual([
        {microTask: false, macroTask: true, eventTask: false, change: 'macroTask', zone: 'parent'},
        'macroTask', 'macroTask',
        {microTask: false, macroTask: false, eventTask: false, change: 'macroTask', zone: 'parent'}
      ]);
    });

    it('should notify of queue status change', () => {
      zone.run(() => {
        const z = Zone.current;
        z.runTask(z.scheduleMicroTask('test', () => log.push('microTask')));
        z.cancelTask(
            z.scheduleMacroTask('test', () => log.push('macroTask'), undefined, noop, noop));
        z.cancelTask(
            z.scheduleEventTask('test', () => log.push('eventTask'), undefined, noop, noop));
      });
      expect(log).toEqual([
        {microTask: true, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
        'microTask',
        {microTask: false, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
        {microTask: false, macroTask: true, eventTask: false, change: 'macroTask', zone: 'parent'},
        {microTask: false, macroTask: false, eventTask: false, change: 'macroTask', zone: 'parent'},
        {microTask: false, macroTask: false, eventTask: true, change: 'eventTask', zone: 'parent'},
        {microTask: false, macroTask: false, eventTask: false, change: 'eventTask', zone: 'parent'}
      ]);
    });

    it('should notify of queue status change on parent task', () => {
      zone.fork({name: 'child'}).run(() => {
        const z = Zone.current;
        z.runTask(z.scheduleMicroTask('test', () => log.push('microTask')));
      });
      expect(log).toEqual([
        {microTask: true, macroTask: false, eventTask: false, change: 'microTask', zone: 'child'},
        {microTask: true, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
        'microTask',
        {microTask: false, macroTask: false, eventTask: false, change: 'microTask', zone: 'child'},
        {microTask: false, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
      ]);
    });

    it('should allow rescheduling a task on a separate zone', () => {
      const log: any[] = [];
      const zone = Zone.current.fork({
        name: 'test-root',
        onHasTask:
            (delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) => {
              (hasTaskState as any)['zone'] = target.name;
              log.push(hasTaskState);
            }
      });
      const left = zone.fork({name: 'left'});
      const right = zone.fork({
        name: 'right',
        onScheduleTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task => {
          log.push(
              {pos: 'before', method: 'onScheduleTask', zone: current.name, task: task.zone.name});
          // Cancel the current scheduling of the task
          task.cancelScheduleRequest();
          // reschedule on a different zone.
          task = left.scheduleTask(task);
          log.push(
              {pos: 'after', method: 'onScheduleTask', zone: current.name, task: task.zone.name});
          return task;
        }
      });
      const rchild = right.fork({
        name: 'rchild',
        onScheduleTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task => {
          log.push(
              {pos: 'before', method: 'onScheduleTask', zone: current.name, task: task.zone.name});
          task = delegate.scheduleTask(target, task);
          log.push(
              {pos: 'after', method: 'onScheduleTask', zone: current.name, task: task.zone.name});
          expect((task as any)._zoneDelegates.map((zd: ZoneDelegate) => zd.zone.name)).toEqual([
            'left', 'test-root', 'ProxyZone'
          ]);
          return task;
        }
      });

      const task = rchild.scheduleMacroTask('testTask', () => log.push('WORK'), {}, noop, noop);
      expect(task.zone).toEqual(left);
      log.push(task.zone.name);
      task.invoke();
      expect(log).toEqual([
        {pos: 'before', method: 'onScheduleTask', zone: 'rchild', task: 'rchild'},
        {pos: 'before', method: 'onScheduleTask', zone: 'right', task: 'rchild'},
        {microTask: false, macroTask: true, eventTask: false, change: 'macroTask', zone: 'left'}, {
          microTask: false,
          macroTask: true,
          eventTask: false,
          change: 'macroTask',
          zone: 'test-root'
        },
        {pos: 'after', method: 'onScheduleTask', zone: 'right', task: 'left'},
        {pos: 'after', method: 'onScheduleTask', zone: 'rchild', task: 'left'}, 'left', 'WORK',
        {microTask: false, macroTask: false, eventTask: false, change: 'macroTask', zone: 'left'}, {
          microTask: false,
          macroTask: false,
          eventTask: false,
          change: 'macroTask',
          zone: 'test-root'
        }
      ]);
    });

    it('period task should not transit to scheduled state after being cancelled in running state',
       () => {
         const zone = Zone.current.fork({name: 'testZone'});

         const task = zone.scheduleMacroTask('testPeriodTask', () => {
           zone.cancelTask(task);
         }, {isPeriodic: true}, () => {}, () => {});

         task.invoke();
         expect(task.state).toBe('notScheduled');
       });

    it('event task should not transit to scheduled state after being cancelled in running state',
       () => {
         const zone = Zone.current.fork({name: 'testZone'});

         const task = zone.scheduleEventTask('testEventTask', () => {
           zone.cancelTask(task);
         }, undefined, () => {}, () => {});

         task.invoke();
         expect(task.state).toBe('notScheduled');
       });

    describe('assert ZoneAwarePromise', () => {
      it('should not throw when all is OK', () => {
        Zone.assertZonePatched();
      });

      // xit('should throw error if ZoneAwarePromise has been overwritten', () => {
      //   class WrongPromise {
      //     static resolve(value: any) {}

      //     then() {}
      //   }

      //   const ZoneAwarePromise = global.Promise;
      //   try {
      //     global.Promise = WrongPromise;
      //     expect(Zone.assertZonePatched()).toThrow();
      //   } finally {
      //     // restore it.
      //     global.Promise = ZoneAwarePromise;
      //   }
      //   Zone.assertZonePatched();
      // });
    });
  });

  describe('invoking tasks', () => {
    let log: string[];
    function noop() {}

    beforeEach(() => {
      log = [];
    });

    it('should not drain the microtask queue too early', () => {
      const z = Zone.current;
      const event = z.scheduleEventTask('test', () => log.push('eventTask'), undefined, noop, noop);

      z.scheduleMicroTask('test', () => log.push('microTask'));

      const macro = z.scheduleMacroTask('test', () => {
        event.invoke();
        // At this point, we should not have invoked the microtask.
        expect(log).toEqual(['eventTask']);
      }, undefined, noop, noop);

      macro.invoke();
    });

    it('should convert task to json without cyclic error', () => {
      const z = Zone.current;
      const event = z.scheduleEventTask('test', () => {}, undefined, noop, noop);
      const micro = z.scheduleMicroTask('test', () => {});
      const macro = z.scheduleMacroTask('test', () => {}, undefined, noop, noop);
      expect(function() {
        JSON.stringify(event);
      }).not.toThrow();
      expect(function() {
        JSON.stringify(micro);
      }).not.toThrow();
      expect(function() {
        JSON.stringify(macro);
      }).not.toThrow();
    });

    it('should call onHandleError callback when zoneSpec onHasTask throw error', () => {
      const spy = jasmine.createSpy('error');
      const hasTaskZone = Zone.current.fork({
        name: 'hasTask',
        onHasTask:
            (delegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
             hasTasState: HasTaskState) => {
              throw new Error('onHasTask Error');
            },
        onHandleError:
            (delegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: Error) => {
              spy(error.message);
              return delegate.handleError(targetZone, error);
            }
      });

      const microTask = hasTaskZone.scheduleMicroTask('test', () => {}, undefined, () => {});
      expect(spy).toHaveBeenCalledWith('onHasTask Error');
    });
  });
});

function throwError() {
  throw new Error();
}