text:
/**
 * @unrestricted
 */
Timeline.TimelineEventOverview = class extends PerfUI.TimelineOverviewBase {
  /**
   * @param {string} id
   * @param {?string} title
   * @param {!TimelineModel.TimelineModel} model
   */
  constructor(id, title, model) {
    super();
    this.element.id = 'timeline-overview-' + id;
    this.element.classList.add('overview-strip');
    if (title)
      this.element.createChild('div', 'timeline-overview-strip-title').textContent = title;
    this._model = model;
  }

  /**
   * @param {number} begin
   * @param {number} end
   * @param {number} position
   * @param {number} height
   * @param {string} color
   */
  _renderBar(begin, end, position, height, color) {
    var x = begin;
    var width = end - begin;
    var ctx = this.context();
    ctx.fillStyle = color;
    ctx.fillRect(x, position, width, height);
  }

  /**
   * @override
   * @param {number} windowLeft
   * @param {number} windowRight
   * @return {!{startTime: number, endTime: number}}
   */
  windowTimes(windowLeft, windowRight) {
    var absoluteMin = this._model.minimumRecordTime();
    var timeSpan = this._model.maximumRecordTime() - absoluteMin;
    return {startTime: absoluteMin + timeSpan * windowLeft, endTime: absoluteMin + timeSpan * windowRight};
  }

  /**
   * @override
   * @param {number} startTime
   * @param {number} endTime
   * @return {!{left: number, right: number}}
   */
  windowBoundaries(startTime, endTime) {
    var absoluteMin = this._model.minimumRecordTime();
    var timeSpan = this._model.maximumRecordTime() - absoluteMin;
    var haveRecords = absoluteMin > 0;
    return {
      left: haveRecords && startTime ? Math.min((startTime - absoluteMin) / timeSpan, 1) : 0,
      right: haveRecords && endTime < Infinity ? (endTime - absoluteMin) / timeSpan : 1
    };
  }
};

/**
 * @unrestricted
 */
Timeline.TimelineEventOverviewInput = class extends Timeline.TimelineEventOverview {
  /**
   * @param {!TimelineModel.TimelineModel} model
   */
  constructor(model) {
    super('input', null, model);
  }

  /**
   * @override
   */
  update() {
    super.update();
    var events = this._model.mainThreadEvents();
    var height = this.height();
    var descriptors = Timeline.TimelineUIUtils.eventDispatchDesciptors();
    /** @type {!Map.<string,!Timeline.TimelineUIUtils.EventDispatchTypeDescriptor>} */
    var descriptorsByType = new Map();
    var maxPriority = -1;
    for (var descriptor of descriptors) {
      for (var type of descriptor.eventTypes)
        descriptorsByType.set(type, descriptor);
      maxPriority = Math.max(maxPriority, descriptor.priority);
    }

    var /** @const */ minWidth = 2 * window.devicePixelRatio;
    var timeOffset = this._model.minimumRecordTime();
    var timeSpan = this._model.maximumRecordTime() - timeOffset;
    var canvasWidth = this.width();
    var scale = canvasWidth / timeSpan;

    for (var priority = 0; priority <= maxPriority; ++priority) {
      for (var i = 0; i < events.length; ++i) {
        var event = events[i];
        if (event.name !== TimelineModel.TimelineModel.RecordType.EventDispatch)
          continue;
        var descriptor = descriptorsByType.get(event.args['data']['type']);
        if (!descriptor || descriptor.priority !== priority)
          continue;
        var start = Number.constrain(Math.floor((event.startTime - timeOffset) * scale), 0, canvasWidth);
        var end = Number.constrain(Math.ceil((event.endTime - timeOffset) * scale), 0, canvasWidth);
        var width = Math.max(end - start, minWidth);
        this._renderBar(start, start + width, 0, height, descriptor.color);
      }
    }
  }
};

/**
 * @unrestricted
 */
Timeline.TimelineEventOverviewNetwork = class extends Timeline.TimelineEventOverview {
  /**
   * @param {!TimelineModel.TimelineModel} model
   */
  constructor(model) {
    super('network', Common.UIString('NET'), model);
  }

  /**
   * @override
   */
  update() {
    super.update();
    var height = this.height();
    var numBands = categoryBand(Timeline.TimelineUIUtils.NetworkCategory.Other) + 1;
    var bandHeight = Math.floor(height / numBands);
    var devicePixelRatio = window.devicePixelRatio;
    var timeOffset = this._model.minimumRecordTime();
    var timeSpan = this._model.maximumRecordTime() - timeOffset;
    var canvasWidth = this.width();
    var scale = canvasWidth / timeSpan;
    var ctx = this.context();
    var requests = this._model.networkRequests();
    /** @type {!Map<string,!{waiting:!Path2D,transfer:!Path2D}>} */
    var paths = new Map();
    requests.forEach(drawRequest);
    for (var path of paths) {
      ctx.fillStyle = path[0];
      ctx.globalAlpha = 0.3;
      ctx.fill(path[1]['waiting']);
      ctx.globalAlpha = 1;
      ctx.fill(path[1]['transfer']);
    }

    /**
     * @param {!Timeline.TimelineUIUtils.NetworkCategory} category
     * @return {number}
     */
    function categoryBand(category) {
      var categories = Timeline.TimelineUIUtils.NetworkCategory;
      switch (category) {
        case categories.HTML:
          return 0;
        case categories.Script:
          return 1;
        case categories.Style:
          return 2;
        case categories.Media:
          return 3;
        default:
          return 4;
      }
    }

    /**
     * @param {!TimelineModel.TimelineModel.NetworkRequest} request
     */
    function drawRequest(request) {
      var tickWidth = 2 * devicePixelRatio;
      var category = Timeline.TimelineUIUtils.networkRequestCategory(request);
      var style = Timeline.TimelineUIUtils.networkCategoryColor(category);
      var band = categoryBand(category);
      var y = band * bandHeight;
      var path = paths.get(style);
      if (!path) {
        path = {waiting: new Path2D(), transfer: new Path2D()};
        paths.set(style, path);
      }
      var s = Math.max(Math.floor((request.startTime - timeOffset) * scale), 0);
      var e = Math.min(Math.ceil((request.endTime - timeOffset) * scale), canvasWidth);
      path['waiting'].rect(s, y, e - s, bandHeight - 1);
      path['transfer'].rect(e - tickWidth / 2, y, tickWidth, bandHeight - 1);
      if (!request.responseTime)
        return;
      var r = Math.ceil((request.responseTime - timeOffset) * scale);
      path['transfer'].rect(r - tickWidth / 2, y, tickWidth, bandHeight - 1);
    }
  }
};

/**
 * @unrestricted
 */
Timeline.TimelineEventOverviewCPUActivity = class extends Timeline.TimelineEventOverview {
  /**
   * @param {!TimelineModel.TimelineModel} model
   */
  constructor(model) {
    super('cpu-activity', Common.UIString('CPU'), model);
    this._backgroundCanvas = this.element.createChild('canvas', 'fill background');
  }

  /**
   * @override
   */
  resetCanvas() {
    super.resetCanvas();
    this._backgroundCanvas.width = this.element.clientWidth * window.devicePixelRatio;
    this._backgroundCanvas.height = this.element.clientHeight * window.devicePixelRatio;
  }

  /**
   * @override
   */
  update() {
    super.update();
    var /** @const */ quantSizePx = 4 * window.devicePixelRatio;
    var width = this.width();
    var height = this.height();
    var baseLine = height;
    var timeOffset = this._model.minimumRecordTime();
    var timeSpan = this._model.maximumRecordTime() - timeOffset;
    var scale = width / timeSpan;
    var quantTime = quantSizePx / scale;
    var categories = Timeline.TimelineUIUtils.categories();
    var categoryOrder = ['idle', 'loading', 'painting', 'rendering', 'scripting', 'other'];
    var otherIndex = categoryOrder.indexOf('other');
    var idleIndex = 0;
    console.assert(idleIndex === categoryOrder.indexOf('idle'));
    for (var i = idleIndex + 1; i < categoryOrder.length; ++i)
      categories[categoryOrder[i]]._overviewIndex = i;

    var backgroundContext = this._backgroundCanvas.getContext('2d');
    for (var thread of this._model.virtualThreads())
      drawThreadEvents(backgroundContext, thread.events);
    applyPattern(backgroundContext);
    drawThreadEvents(this.context(), this._model.mainThreadEvents());

    /**
     * @param {!CanvasRenderingContext2D} ctx
     * @param {!Array<!SDK.TracingModel.Event>} events
     */
    function drawThreadEvents(ctx, events) {
      var quantizer = new Timeline.Quantizer(timeOffset, quantTime, drawSample);
      var x = 0;
      var categoryIndexStack = [];
      var paths = [];
      var lastY = [];
      for (var i = 0; i < categoryOrder.length; ++i) {
        paths[i] = new Path2D();
        paths[i].moveTo(0, height);
        lastY[i] = height;
      }

      /**
       * @param {!Array<number>} counters
       */
      function drawSample(counters) {
        var y = baseLine;
        for (var i = idleIndex + 1; i < categoryOrder.length; ++i) {
          var h = (counters[i] || 0) / quantTime * height;
          y -= h;
          paths[i].bezierCurveTo(x, lastY[i], x, y, x + quantSizePx / 2, y);
          lastY[i] = y;
        }
        x += quantSizePx;
      }

      /**
       * @param {!SDK.TracingModel.Event} e
       */
      function onEventStart(e) {
        var index = categoryIndexStack.length ? categoryIndexStack.peekLast() : idleIndex;
        quantizer.appendInterval(e.startTime, index);
        categoryIndexStack.push(Timeline.TimelineUIUtils.eventStyle(e).category._overviewIndex || otherIndex);
      }

      /**
       * @param {!SDK.TracingModel.Event} e
       */
      function onEventEnd(e) {
        quantizer.appendInterval(e.endTime, categoryIndexStack.pop());
      }

      TimelineModel.TimelineModel.forEachEvent(events, onEventStart, onEventEnd);
      quantizer.appendInterval(timeOffset + timeSpan + quantTime, idleIndex);  // Kick drawing the last bucket.
      for (var i = categoryOrder.length - 1; i > 0; --i) {
        paths[i].lineTo(width, height);
        ctx.fillStyle = categories[categoryOrder[i]].color;
        ctx.fill(paths[i]);
      }
    }

    /**
     * @param {!CanvasRenderingContext2D} ctx
     */
    function applyPattern(ctx) {
      var step = 4 * window.devicePixelRatio;
      ctx.save();
      ctx.lineWidth = step / Math.sqrt(8);
      for (var x = 0.5; x < width + height; x += step) {
        ctx.moveTo(x, 0);
        ctx.lineTo(x - height, height);
      }
      ctx.globalCompositeOperation = 'destination-out';
      ctx.stroke();
      ctx.restore();
    }
  }
};

/**
 * @unrestricted
 */
Timeline.TimelineEventOverviewResponsiveness = class extends Timeline.TimelineEventOverview {
  /**
   * @param {!TimelineModel.TimelineModel} model
   * @param {!TimelineModel.TimelineFrameModel} frameModel
   */
  constructor(model, frameModel) {
    super('responsiveness', null, model);
    this._frameModel = frameModel;
  }

  /**
   * @override
   */
  update() {
    super.update();
    var height = this.height();
    var timeOffset = this._model.minimumRecordTime();
    var timeSpan = this._model.maximumRecordTime() - timeOffset;
    var scale = this.width() / timeSpan;
    var frames = this._frameModel.frames();
    // This is due to usage of new signatures of fill() and storke() that closure compiler does not recognize.
    var ctx = /** @type {!Object} */ (this.context());
    var fillPath = new Path2D();
    var markersPath = new Path2D();
    for (var i = 0; i < frames.length; ++i) {
      var frame = frames[i];
      if (!frame.hasWarnings())
        continue;
      paintWarningDecoration(frame.startTime, frame.duration);
    }

    var events = this._model.mainThreadEvents();
    for (var i = 0; i < events.length; ++i) {
      if (!TimelineModel.TimelineData.forEvent(events[i]).warning)
        continue;
      paintWarningDecoration(events[i].startTime, events[i].duration);
    }

    ctx.fillStyle = 'hsl(0, 80%, 90%)';
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 2 * window.devicePixelRatio;
    ctx.fill(fillPath);
    ctx.stroke(markersPath);

    /**
     * @param {number} time
     * @param {number} duration
     */
    function paintWarningDecoration(time, duration) {
      var x = Math.round(scale * (time - timeOffset));
      var w = Math.round(scale * duration);
      fillPath.rect(x, 0, w, height);
      markersPath.moveTo(x + w, 0);
      markersPath.lineTo(x + w, height);
    }
  }
};

/**
 * @unrestricted
 */
Timeline.TimelineFilmStripOverview = class extends Timeline.TimelineEventOverview {
  /**
   * @param {!TimelineModel.TimelineModel} model
   * @param {!SDK.FilmStripModel} filmStripModel
   */
  constructor(model, filmStripModel) {
    super('filmstrip', null, model);
    this._filmStripModel = filmStripModel;
    this.reset();
  }

  /**
   * @override
   */
  update() {
    super.update();
    var frames = this._filmStripModel.frames();
    if (!frames.length)
      return;

    var drawGeneration = Symbol('drawGeneration');
    this._drawGeneration = drawGeneration;
    this._imageByFrame(frames[0]).then(image => {
      if (this._drawGeneration !== drawGeneration)
        return;
      if (!image.naturalWidth || !image.naturalHeight)
        return;
      var imageHeight = this.height() - 2 * Timeline.TimelineFilmStripOverview.Padding;
      var imageWidth = Math.ceil(imageHeight * image.naturalWidth / image.naturalHeight);
      var popoverScale = Math.min(200 / image.naturalWidth, 1);
      this._emptyImage = new Image(image.naturalWidth * popoverScale, image.naturalHeight * popoverScale);
      this._drawFrames(imageWidth, imageHeight);
    });
  }

  /**
   * @param {!SDK.FilmStripModel.Frame} frame
   * @return {!Promise<!HTMLImageElement>}
   */
  _imageByFrame(frame) {
    var imagePromise = this._frameToImagePromise.get(frame);
    if (!imagePromise) {
      imagePromise = frame.imageDataPromise().then(createImage);
      this._frameToImagePromise.set(frame, imagePromise);
    }
    return imagePromise;

    /**
     * @param {?string} data
     * @return {!Promise<!HTMLImageElement>}
     */
    function createImage(data) {
      var fulfill;
      var promise = new Promise(f => fulfill = f);

      var image = /** @type {!HTMLImageElement} */ (createElement('img'));
      if (data) {
        image.src = 'data:image/jpg;base64,' + data;
        image.addEventListener('load', () => fulfill(image));
        image.addEventListener('error', () => fulfill(image));
      } else {
        fulfill(image);
      }
      return promise;
    }
  }

  /**
   * @param {number} imageWidth
   * @param {number} imageHeight
   */
  _drawFrames(imageWidth, imageHeight) {
    if (!imageWidth)
      return;
    if (!this._filmStripModel.frames().length)
      return;
    var padding = Timeline.TimelineFilmStripOverview.Padding;
    var width = this.width();
    var zeroTime = this._filmStripModel.zeroTime();
    var spanTime = this._filmStripModel.spanTime();
    var scale = spanTime / width;
    var context = this.context();
    var drawGeneration = this._drawGeneration;

    context.beginPath();
    for (var x = padding; x < width; x += imageWidth + 2 * padding) {
      var time = zeroTime + (x + imageWidth / 2) * scale;
      var frame = this._filmStripModel.frameByTimestamp(time);
      if (!frame)
        continue;
      context.rect(x - 0.5, 0.5, imageWidth + 1, imageHeight + 1);
      this._imageByFrame(frame).then(drawFrameImage.bind(this, x));
    }
    context.strokeStyle = '#ddd';
    context.stroke();

    /**
     * @param {number} x
     * @param {!HTMLImageElement} image
     * @this {Timeline.TimelineFilmStripOverview}
     */
    function drawFrameImage(x, image) {
      // Ignore draws deferred from a previous update call.
      if (this._drawGeneration !== drawGeneration)
        return;
      context.drawImage(image, x, 1, imageWidth, imageHeight);
    }
  }

  /**
   * @override
   * @param {number} x
   * @return {!Promise<?Element>}
   */
  popoverElementPromise(x) {
    if (!this._filmStripModel.frames().length)
      return Promise.resolve(/** @type {?Element} */ (null));

    var time = this.calculator().positionToTime(x);
    var frame = this._filmStripModel.frameByTimestamp(time);
    if (frame === this._lastFrame)
      return Promise.resolve(this._lastElement);
    var imagePromise = frame ? this._imageByFrame(frame) : Promise.resolve(this._emptyImage);
    return imagePromise.then(createFrameElement.bind(this));

    /**
     * @this {Timeline.TimelineFilmStripOverview}
     * @param {!HTMLImageElement} image
     * @return {?Element}
     */
    function createFrameElement(image) {
      var element = createElementWithClass('div', 'frame');
      element.createChild('div', 'thumbnail').appendChild(image);
      UI.appendStyle(element, 'timeline/timelinePanel.css');
      this._lastFrame = frame;
      this._lastElement = element;
      return element;
    }
  }

  /**
   * @override
   */
  reset() {
    this._lastFrame = undefined;
    this._lastElement = null;
    /** @type {!Map<!SDK.FilmStripModel.Frame,!Promise<!HTMLImageElement>>} */
    this._frameToImagePromise = new Map();
    this._imageWidth = 0;
  }
};

Timeline.TimelineFilmStripOverview.Padding = 2;

/**
 * @unrestricted
 */
Timeline.TimelineEventOverviewFrames = class extends Timeline.TimelineEventOverview {
  /**
   * @param {!TimelineModel.TimelineModel} model
   * @param {!TimelineModel.TimelineFrameModel} frameModel
   */
  constructor(model, frameModel) {
    super('framerate', Common.UIString('FPS'), model);
    this._frameModel = frameModel;
  }

  /**
   * @override
   */
  update() {
    super.update();
    var height = this.height();
    var /** @const */ padding = 1 * window.devicePixelRatio;
    var /** @const */ baseFrameDurationMs = 1e3 / 60;
    var visualHeight = height - 2 * padding;
    var timeOffset = this._model.minimumRecordTime();
    var timeSpan = this._model.maximumRecordTime() - timeOffset;
    var scale = this.width() / timeSpan;
    var frames = this._frameModel.frames();
    var baseY = height - padding;
    var ctx = this.context();
    var bottomY = baseY + 10 * window.devicePixelRatio;
    var x = 0;
    var y = bottomY;
    if (!frames.length)
      return;

    var lineWidth = window.devicePixelRatio;
    var offset = lineWidth & 1 ? 0.5 : 0;
    var tickDepth = 1.5 * window.devicePixelRatio;
    ctx.beginPath();
    ctx.moveTo(0, y);
    for (var i = 0; i < frames.length; ++i) {
      var frame = frames[i];
      x = Math.round((frame.startTime - timeOffset) * scale) + offset;
      ctx.lineTo(x, y);
      ctx.lineTo(x, y + tickDepth);
      y = frame.idle ? bottomY :
                       Math.round(baseY - visualHeight * Math.min(baseFrameDurationMs / frame.duration, 1)) - offset;
      ctx.lineTo(x, y + tickDepth);
      ctx.lineTo(x, y);
    }
    if (frames.length) {
      var lastFrame = frames.peekLast();
      x = Math.round((lastFrame.startTime + lastFrame.duration - timeOffset) * scale) + offset;
      ctx.lineTo(x, y);
    }
    ctx.lineTo(x, bottomY);
    ctx.fillStyle = 'hsl(110, 50%, 88%)';
    ctx.strokeStyle = 'hsl(110, 50%, 60%)';
    ctx.lineWidth = lineWidth;
    ctx.fill();
    ctx.stroke();
  }
};

/**
 * @unrestricted
 */
Timeline.TimelineEventOverviewMemory = class extends Timeline.TimelineEventOverview {
  /**
   * @param {!TimelineModel.TimelineModel} model
   */
  constructor(model) {
    super('memory', Common.UIString('HEAP'), model);
    this._heapSizeLabel = this.element.createChild('div', 'memory-graph-label');
  }

  resetHeapSizeLabels() {
    this._heapSizeLabel.textContent = '';
  }

  /**
   * @override
   */
  update() {
    super.update();
    var ratio = window.devicePixelRatio;

    var events = this._model.mainThreadEvents();
    if (!events.length) {
      this.resetHeapSizeLabels();
      return;
    }

    var lowerOffset = 3 * ratio;
    var maxUsedHeapSize = 0;
    var minUsedHeapSize = 100000000000;
    var minTime = this._model.minimumRecordTime();
    var maxTime = this._model.maximumRecordTime();
    /**
     * @param {!SDK.TracingModel.Event} event
     * @return {boolean}
     */
    function isUpdateCountersEvent(event) {
      return event.name === TimelineModel.TimelineModel.RecordType.UpdateCounters;
    }
    events = events.filter(isUpdateCountersEvent);
    /**
     * @param {!SDK.TracingModel.Event} event
     */
    function calculateMinMaxSizes(event) {
      var counters = event.args.data;
      if (!counters || !counters.jsHeapSizeUsed)
        return;
      maxUsedHeapSize = Math.max(maxUsedHeapSize, counters.jsHeapSizeUsed);
      minUsedHeapSize = Math.min(minUsedHeapSize, counters.jsHeapSizeUsed);
    }
    events.forEach(calculateMinMaxSizes);
    minUsedHeapSize = Math.min(minUsedHeapSize, maxUsedHeapSize);

    var lineWidth = 1;
    var width = this.width();
    var height = this.height() - lowerOffset;
    var xFactor = width / (maxTime - minTime);
    var yFactor = (height - lineWidth) / Math.max(maxUsedHeapSize - minUsedHeapSize, 1);

    var histogram = new Array(width);

    /**
     * @param {!SDK.TracingModel.Event} event
     */
    function buildHistogram(event) {
      var counters = event.args.data;
      if (!counters || !counters.jsHeapSizeUsed)
        return;
      var x = Math.round((event.startTime - minTime) * xFactor);
      var y = Math.round((counters.jsHeapSizeUsed - minUsedHeapSize) * yFactor);
      histogram[x] = Math.max(histogram[x] || 0, y);
    }
    events.forEach(buildHistogram);

    var ctx = this.context();
    var heightBeyondView = height + lowerOffset + lineWidth;

    ctx.translate(0.5, 0.5);
    ctx.beginPath();
    ctx.moveTo(-lineWidth, heightBeyondView);
    var y = 0;
    var isFirstPoint = true;
    var lastX = 0;
    for (var x = 0; x < histogram.length; x++) {
      if (typeof histogram[x] === 'undefined')
        continue;
      if (isFirstPoint) {
        isFirstPoint = false;
        y = histogram[x];
        ctx.lineTo(-lineWidth, height - y);
      }
      var nextY = histogram[x];
      if (Math.abs(nextY - y) > 2 && Math.abs(x - lastX) > 1)
        ctx.lineTo(x, height - y);
      y = nextY;
      ctx.lineTo(x, height - y);
      lastX = x;
    }
    ctx.lineTo(width + lineWidth, height - y);
    ctx.lineTo(width + lineWidth, heightBeyondView);
    ctx.closePath();

    ctx.fillStyle = 'hsla(220, 90%, 70%, 0.2)';
    ctx.fill();
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = 'hsl(220, 90%, 70%)';
    ctx.stroke();

    this._heapSizeLabel.textContent =
        Common.UIString('%s \u2013 %s', Number.bytesToString(minUsedHeapSize), Number.bytesToString(maxUsedHeapSize));
  }
};

/**
 * @unrestricted
 */
Timeline.Quantizer = class {
  /**
   * @param {number} startTime
   * @param {number} quantDuration
   * @param {function(!Array<number>)} callback
   */
  constructor(startTime, quantDuration, callback) {
    this._lastTime = startTime;
    this._quantDuration = quantDuration;
    this._callback = callback;
    this._counters = [];
    this._remainder = quantDuration;
  }

  /**
   * @param {number} time
   * @param {number} group
   */
  appendInterval(time, group) {
    var interval = time - this._lastTime;
    if (interval <= this._remainder) {
      this._counters[group] = (this._counters[group] || 0) + interval;
      this._remainder -= interval;
      this._lastTime = time;
      return;
    }
    this._counters[group] = (this._counters[group] || 0) + this._remainder;
    this._callback(this._counters);
    interval -= this._remainder;
    while (interval >= this._quantDuration) {
      var counters = [];
      counters[group] = this._quantDuration;
      this._callback(counters);
      interval -= this._quantDuration;
    }
    this._counters = [];
    this._counters[group] = interval;
    this._lastTime = time;
    this._remainder = this._quantDuration - interval;
  }
};


text:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BitBucket.REST.API.Helpers;
using BitBucket.REST.API.Interfaces;
using BitBucket.REST.API.Mappings;
using BitBucket.REST.API.Models.Enterprise;
using BitBucket.REST.API.Models.Standard;
using BitBucket.REST.API.Wrappers;

namespace BitBucket.REST.API.Clients.Enterprise
{
    public class EnterpriseTeamsClient : ApiClient, ITeamsClient
    {
        public EnterpriseTeamsClient(IEnterpriseBitbucketRestClient restClient, Connection connection) : base(restClient, connection)
        {

        }

        public Task<IEnumerable<Team>> GetTeams() // not needed
        {
            IEnumerable<Team> coll = new List<Team>();
            return Task.FromResult(coll);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using Carrotware.CMS.Core;
using Carrotware.CMS.UI.Controls;
using System;
using System.Collections.Generic;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace Carrotware.CMS.UI.Admin.c3_admin {

	public partial class UserGroupAddEdit : AdminBasePage {
		public Guid groupID = Guid.Empty;

		protected void Page_Load(object sender, EventArgs e) {
			Master.ActivateTab(AdminBaseMasterPage.SectionID.GroupAdmin);

			groupID = GetGuidIDFromQuery();

			btnApply.Visible = SecurityData.IsAdmin;
			btnAddUsers.Visible = SecurityData.IsAdmin;
			btnRemove.Visible = SecurityData.IsAdmin;

			if (groupID == Guid.Empty) {
				btnApply.Text = "Add";
			} else {
				pnlUsers.Visible = true;
			}

			if (!IsPostBack) {
				if (groupID != Guid.Empty) {
					MembershipRole role = getCurrentGroup();

					txtRoleName.Text = role.RoleName;
					txtRoleName.Enabled = CheckValidEditing(role.RoleName);

					btnApply.Visible = CheckValidEditing(role.RoleName);

					GetUserList(role.RoleName);
				}
			}
		}

		protected void GetUserList(string roleName) {
			List<MembershipUser> usrs = SecurityData.GetUsersInRole(roleName);
			GeneralUtilities.BindDataBoundControl(gvUsers, usrs);

			if (usrs.Count < 1) {
				btnRemove.Visible = false;
			}
		}

		protected MembershipRole getCurrentGroup() {
			MembershipRole role = SecurityData.FindMembershipRole(groupID);

			return role;
		}

		protected void btnAddUsers_Click(object sender, EventArgs e) {
			if (!String.IsNullOrEmpty(hdnUserID.Value)) {
				MembershipRole role = getCurrentGroup();

				ExtendedUserData exUsr = new ExtendedUserData(hdnUserID.Value);
				exUsr.AddToRole(role.RoleName);
			}

			Response.Redirect(SiteData.CurrentScriptName + "?id=" + groupID.ToString());
		}

		protected void btnRemove_Click(object sender, EventArgs e) {
			HiddenField hdnUserName = null;
			CheckBox chkSelected = null;

			MembershipRole role = getCurrentGroup();

			string currentRoleName = role.RoleName;

			foreach (GridViewRow dgItem in gvUsers.Rows) {
				hdnUserName = (HiddenField)dgItem.FindControl("hdnUserName");

				if (!String.IsNullOrEmpty(hdnUserName.Value)) {
					chkSelected = (CheckBox)dgItem.FindControl("chkSelected");
					if (chkSelected.Checked) {
						Roles.RemoveUserFromRole(hdnUserName.Value, currentRoleName);
					}
				}
			}

			Response.Redirect(SiteData.CurrentScriptName + "?id=" + groupID.ToString());
		}

		protected void btnApply_Click(object sender, EventArgs e) {
			MembershipRole role = new MembershipRole(txtRoleName.Text, groupID);

			if (!Roles.RoleExists(txtRoleName.Text) && groupID == Guid.Empty) {
				Roles.CreateRole(txtRoleName.Text);
			}

			if (Roles.RoleExists(txtRoleName.Text) || groupID != Guid.Empty) {
				if (groupID == Guid.Empty) {
					role = SecurityData.FindMembershipRole(txtRoleName.Text);

					groupID = role.RoleId;
				} else {
					role = SecurityData.FindMembershipRole(groupID);
				}

				if (role != null && groupID != Guid.Empty) {
					if (CheckValidEditing(role.LoweredRoleName)
							&& CheckValidEditing(txtRoleName.Text)) {
						role.RoleName = txtRoleName.Text;
						role.Save();
					}

					if (CheckValidEditing(role.LoweredRoleName)
							&& !CheckValidEditing(txtRoleName.Text)) {
						txtRoleName.Text = role.RoleName;
					}
				}

				Response.Redirect(SiteData.CurrentScriptName + "?id=" + groupID.ToString());
			}
		}

		private bool CheckValidEditing(string sLoweredRoleName) {
			sLoweredRoleName = sLoweredRoleName.ToLowerInvariant();

			if (groupID != Guid.Empty
						&& sLoweredRoleName != SecurityData.CMSGroup_Admins.ToLowerInvariant()
						&& sLoweredRoleName != SecurityData.CMSGroup_Editors.ToLowerInvariant()
						&& sLoweredRoleName != SecurityData.CMSGroup_Users.ToLowerInvariant()) {
				return true;
			}

			return false;
		}
	}
}


text:
<?php

namespace Zend\Mvc\Service;

use Zend\Filter\FilterPluginManager;

class FilterManagerFactory extends AbstractPluginManagerFactory
{
    const PLUGIN_MANAGER_CLASS = FilterPluginManager::class;
}


text:
package imdb

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/StalkR/goircbot/bot"
	"github.com/StalkR/imdb"
)

func search(e *bot.Event) {
	q := strings.TrimSpace(e.Args)
	if len(q) == 0 {
		return
	}
	titles, err := imdb.SearchTitle(http.DefaultClient, q)
	if err != nil {
		e.Bot.Privmsg(e.Target, fmt.Sprintf("error: %s", err))
		return
	}
	if len(titles) == 0 {
		e.Bot.Privmsg(e.Target, "No results found.")
		return
	}
	title, err := imdb.NewTitle(http.DefaultClient, titles[0].ID)
	if err != nil {
		e.Bot.Privmsg(e.Target, fmt.Sprintf("error: %s", err))
		return
	}
	e.Bot.Privmsg(e.Target, title.String())
}

// Register registers the plugin with a bot.
func Register(b bot.Bot) {
	b.Commands().Add("imdb", bot.Command{
		Help:    "imdb <title> - search a Title on IMDb",
		Handler: search,
		Pub:     true,
		Priv:    true,
		Hidden:  false})
}


text:
define(function (require, exports, module) {
    // require('./some-mock');
});


text:
int main(int argc, char** argv)
{

	SMTPClient mailc("localhost",25,"m1@example.com","miner1");
	int rc  = mailc.Send("m1@example.com","m1@example.com","subject","Hello from C++ SMTP Client!");
	std::cout << "rc : " << rc << "\n";
	return 0;
}


text:
from thinglang.lexer.lexical_token import LexicalToken

class LexicalDeclarationConstructor(LexicalToken):
    """
    Declares a constructor.

    Examples:
        setup
        setup with number size
    """

class LexicalDeclarationStatic(LexicalToken):
    """
    Tags a definition as static.

    Examples:
        does static hello_message
        has static text count
    """

class LexicalDeclarationReturnType(LexicalToken):
    """
    Tags a method's return type.

    Examples:
        does get_text returns text
    """

class LexicalArgumentListIndicator(LexicalToken):
    """
    Tags a method's arguments.

    Examples:
        does add with number lhs, number rhs
    """

class LexicalInheritanceTag(LexicalToken):
    """
    Tags a thing definition's parent type.
    """

class LexicalPrivateTag(LexicalToken):
    """
    Tags a method or member as private
    """

class LexicalImplicitTag(LexicalToken):
    """
    Marks a cast operation as implicitly callable
    TODO: demote to Identifier if no parser rule matches?
    """


text:
package com.jamonapi.jmx;

import com.jamonapi.MonKey;
import com.jamonapi.MonKeyImp;
import com.jamonapi.MonitorFactory;
import com.sun.management.GarbageCollectionNotificationInfo;
import com.sun.management.GcInfo;

import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Class that can listen to any jmx notifications. It listens to gc collections from a sun jvm only and that is
 * only versions at 1.7 and after (unfortunately). JAMon monitors are created for

 *     * gc duration as well as...

 *     * memory used in each of the memory pools after the gc has fired.

 *
 * http://www.fasterj.com/articles/gcnotifs.shtml
 */
public class GcMXBeanImp implements GcMXBean, NotificationListener {
    private String gcInfoString="";
    private long duration;
    private Date when;
    private static final String PREFIX = GcMXBeanImp.class.getPackage().getName();
    private Set<String> gcNames = new HashSet<String>();

    public static ObjectName getObjectName() {
        return JmxUtils.getObjectName( PREFIX + ":type=current,name=Jamon.Gc.MostRecent");
    }

    /** This is called automatically when a gc is fired */
    public void handleNotification(Notification notification, Object handback) {
        String notifyType = notification.getType();
        if (notifyType.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
            // retrieve the garbage collection notification information
            CompositeData cd = (CompositeData) notification.getUserData();
            GarbageCollectionNotificationInfo gcNotifyInfo = GarbageCollectionNotificationInfo.from(cd);
            monitor(gcNotifyInfo);
            if (!gcNames.contains(gcNotifyInfo.getGcName())) {
                registerDependentGcMbeans(gcNotifyInfo.getGcName());
            }
        }
    }

    /* This method is visible for testing purposes */
    void monitor(GarbageCollectionNotificationInfo gcNotifyInfo) {
        // http://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/GcInfo.html
        // for each type count: times fired, duration, and used memory
        GcInfo gcInfo = gcNotifyInfo.getGcInfo();
        duration = gcInfo.getDuration();
        when = new Date();
        String details = toString(gcNotifyInfo);
        String labelPrefix = getGcPrefix(gcNotifyInfo.getGcName());

        // create jamon gc monitors
        monitorDuration(labelPrefix, details);
        monitorUsedMemory(labelPrefix, gcInfo, details);
    }

    // gcName would be something like: PS Scavenge, or PS MarkSweep
    private String getGcPrefix(String gcName) {
        return PREFIX + ".gc." + gcName;
    }

    private void monitorDuration(String labelPrefix, String details) {
        MonKey key = new MonKeyImp(labelPrefix+".time", details, "ms.");
        MonitorFactory.add(key, duration); // ms. duration of gc
    }

    /**
     * Loop through different memory pools and determine how much memory is used (bytes) after this
     * gc firing.   Example data follows:
     *
     *  before: PS Survivor Space=... used = 1589320(1552K)...,
     *  after: PS Survivor Space=... used = 0(0K)...
     *
     * @param labelPrefix
     * @param gcInfo
     * @param details
     */
    private void monitorUsedMemory(String labelPrefix, GcInfo gcInfo, String details) {
        for (Map.Entry<String, MemoryUsage> entry : gcInfo.getMemoryUsageAfterGc().entrySet()) {
            MonKey key = new MonKeyImp(labelPrefix+".usedMemory."+entry.getKey(), details, "bytes");
            MonitorFactory.add(key, entry.getValue().getUsed()); // memory used in pool.
        }
    }

    /**
     * This will be placed in the details part of the MonKey which is used for display in the mondetails.jsp page.
     *
     * Sample returned string:
     *  Name: PS MarkSweep
     *  Cause: System.gc()
     *  Action: end of major GC
     *  Duration: 43
     *  Sequence: 1
     *  When: Fri Nov 28 13:10:31 EST 2014
     *  BeforeGc: {PS Survivor Space=init = 2621440(2560K) used = 2242248(2189K) committed = 2621440(2560K) max = 2621440(2560K), PS Eden Space=init = 17301504(16896K) used = 0(0K) committed = 17301504(16896K) max = 352845824(344576K), PS Old Gen=init = 44564480(43520K) used = 8192(8K) committed = 44564480(43520K) max = 715653120(698880K), Code Cache=init = 2555904(2496K) used = 531712(519K) committed = 2555904(2496K) max = 50331648(49152K), PS Perm Gen=init = 22020096(21504K) used = 7591192(7413K) committed = 22020096(21504K) max = 85983232(83968K)}
     *  AfterGc: {PS Survivor Space=init = 2621440(2560K) used = 0(0K) committed = 2621440(2560K) max = 2621440(2560K), PS Eden Space=init = 17301504(16896K) used = 0(0K) committed = 17301504(16896K) max = 352845824(344576K), PS Old Gen=init = 44564480(43520K) used = 2075448(2026K) committed = 44564480(43520K) max = 715653120(698880K), Code Cache=init = 2555904(2496K) used = 531712(519K) committed = 2555904(2496K) max = 50331648(49152K), PS Perm Gen=init = 22020096(21504K) used = 7589328(7411K) committed = 22020096(21504K) max = 85983232(83968K)}
     *
     * @param gcNotifyInfo
     * @return
     */
    private String toString(GarbageCollectionNotificationInfo gcNotifyInfo) {
        GcInfo gcInfo = gcNotifyInfo.getGcInfo();
        StringBuilder sb = new StringBuilder();
        sb.append("Name: ").append(gcNotifyInfo.getGcName()).append("\n");
        sb.append("Cause: ").append(gcNotifyInfo.getGcCause()).append("\n");
        sb.append("Action: ").append(gcNotifyInfo.getGcAction()).append("\n");
        sb.append("Duration: ").append(gcInfo.getDuration()).append("\n");
        sb.append("Sequence: ").append(gcInfo.getId()).append("\n");
        sb.append("When: ").append(when).append("\n\n");
        sb.append("BeforeGc: ").append(formatGcData(gcInfo.getMemoryUsageBeforeGc())).append("\n\n");
        sb.append("AfterGc: ").append(formatGcData(gcInfo.getMemoryUsageAfterGc())).append("\n");
        gcInfoString = sb.toString();
        return gcInfoString;
    }

    // register the custom gc monitors for each gcName (for example Scavenge, and MarkSweep
    private void registerDependentGcMbeans(String gcName) {
        String label = getGcPrefix(gcName)+".time";
        String jmxName = "Jamon.Gc."+gcName;

        try {
          // register current
          MonitorMXBean mXbean = MonitorMXBeanFactory.create(label, "ms.", jmxName);
          ObjectName current =  MonitorMXBeanFactory.getObjectName(mXbean);
          ManagementFactory.getPlatformMBeanServer().registerMBean(mXbean, current);

          // register delta
          MonitorMXBean  mXbeanDelta = MonitorMXBeanFactory.createDelta(label, "ms.", jmxName);
          ObjectName delta =  MonitorMXBeanFactory.getDeltaObjectName(mXbeanDelta);
          ManagementFactory.getPlatformMBeanServer().registerMBean(mXbeanDelta, delta);
          gcNames.add(gcName);
        } catch (Exception e) {
           e.printStackTrace(); // shouldn't happen.
        }
    }

    private String formatGcData(Map map) {
        String str = map.toString();
        return str.replace(",", ",\n").replace("{","{\n");
    }

    @Override
    public String getGcInfo() {
        return gcInfoString;
    }

    @Override
    public Date getWhen() {
        return when;
    }

    @Override
    public long getDuration() {
        return duration;
    }

}


text:
package net2

type IPProtocol struct {
	Keyword  string
	Protocol string
}

var IPProtocolMap = map[int]IPProtocol{
	0:   IPProtocol{"HOPOPT", "IPv6 Hop-by-Hop Option"},
	1:   IPProtocol{"ICMP", "Internet Control Message Protocol"},
	2:   IPProtocol{"IGMP", "Internet Group Management Protocol"},
	3:   IPProtocol{"GGP", "Gateway-to-Gateway Protocol"},
	4:   IPProtocol{"IP-in-IP", "IP-in-IP"},
	5:   IPProtocol{"ST", "Internet Stream Protocol"},
	6:   IPProtocol{"TCP", "Transmission Control Protocol"},
	7:   IPProtocol{"CBT", "Core-based trees"},
	8:   IPProtocol{"EGP", "Exterior Gateway Protocol"},
	9:   IPProtocol{"IGP", "Interior Gateway Protocol"},
	10:  IPProtocol{"BBN-RCC-MON", "BBN RCC Monitoring"},
	11:  IPProtocol{"NVP-II", "Network Voice Protocol"},
	12:  IPProtocol{"PUP", "Xerox PUP"},
	13:  IPProtocol{"ARGUS", "ARGUS"},
	14:  IPProtocol{"EMCON", "EMCON"},
	15:  IPProtocol{"XNET", "Cross Net Debugger"},
	16:  IPProtocol{"CHAOS", "Chaos"},
	17:  IPProtocol{"UDP", "User Datagram Protocol"},
	18:  IPProtocol{"MUX", "Multiplexing"},
	19:  IPProtocol{"DCN-MEAS", "DCN Measurement Subsystems"},
	20:  IPProtocol{"HMP", "Host Monitoring Protocol"},
	21:  IPProtocol{"PRM", "Packet Radio Measurement"},
	22:  IPProtocol{"XNS-IDP", "XEROX NS IDP"},
	23:  IPProtocol{"TRUNK-1", "Trunk-1"},
	24:  IPProtocol{"TRUNK-2", "Trunk-2"},
	25:  IPProtocol{"LEAF-1", "Leaf-1"},
	26:  IPProtocol{"LEAF-2", "Leaf-2"},
	27:  IPProtocol{"RDP", "Reliable Datagram Protocol"},
	28:  IPProtocol{"IRTP", "Internet Reliable Transaction Protocol"},
	29:  IPProtocol{"ISO-TP4", "ISO Transport Protocol Class 4"},
	30:  IPProtocol{"NETBLT", "Bulk Data Transfer Protocol"},
	31:  IPProtocol{"MFE-NSP", "MFE Network Services Protocol"},
	32:  IPProtocol{"MERIT-INP", "MERIT Internodal Protocol"},
	33:  IPProtocol{"DCCP", "Datagram Congestion Control Protocol"},
	34:  IPProtocol{"3PC", "Third Party Connect Protocol"},
	35:  IPProtocol{"IDPR", "Inter-Domain Policy Routing Protocol"},
	36:  IPProtocol{"XTP", "Xpress Transport Protocol"},
	37:  IPProtocol{"DDP", "Datagram Delivery Protocol"},
	38:  IPProtocol{"IDPR-CMTP", "IDPR Control Message Transport Protocol"},
	39:  IPProtocol{"TP++", "TP++ Transport Protocol"},
	40:  IPProtocol{"IL", "IL Transport Protocol"},
	41:  IPProtocol{"IPv6", "IPv6 Encapsulation"},
	42:  IPProtocol{"SDRP", "Source Demand Routing Protocol"},
	43:  IPProtocol{"IPv6-Route", "Routing Header for IPv6"},
	44:  IPProtocol{"IPv6-Frag", "Fragment Header for IPv6"},
	45:  IPProtocol{"IDRP", "Inter-Domain Routing Protocol"},
	46:  IPProtocol{"RSVP", "Resource Reservation Protocol"},
	47:  IPProtocol{"GRE", "Generic Routing Encapsulation"},
	48:  IPProtocol{"MHRP", "Mobile Host Routing Protocol"},
	49:  IPProtocol{"BNA", "BNA"},
	50:  IPProtocol{"ESP", "Encapsulating Security Payload"},
	51:  IPProtocol{"AH", "Authentication Header"},
	52:  IPProtocol{"I-NLSP", "Integrated Net Layer Security Protocol"},
	53:  IPProtocol{"SWIPE", "SwIPe"},
	54:  IPProtocol{"NARP", "NBMA Address Resolution Protocol"},
	55:  IPProtocol{"MOBILE", "IP Mobility"},
	56:  IPProtocol{"TLSP", "Transport Layer Security Protocol"},
	57:  IPProtocol{"SKIP", "Simple Key-Management for Internet Protocol"},
	58:  IPProtocol{"IPv6-ICMP", "ICMP for IPv6"},
	59:  IPProtocol{"IPv6-NoNxt", "No Next Header for IPv6"},
	60:  IPProtocol{"IPv6-Opts", "Destination Options for IPv6"},
	61:  IPProtocol{"", "Any host internal protocol"},
	62:  IPProtocol{"CFTP", "CFTP"},
	63:  IPProtocol{"", "Any local network"},
	64:  IPProtocol{"SAT-EXPAK", "SATNET and Backroom EXPAK"},
	65:  IPProtocol{"KRYPTOLAN", "Kryptolan"},
	66:  IPProtocol{"RVD", "MIT Remote Virtual Disk Protocol"},
	67:  IPProtocol{"IPPC", "Internet Pluribus Packet Core"},
	68:  IPProtocol{"", "Any distributed file system"},
	69:  IPProtocol{"SAT-MON", "SATNET Monitoring"},
	70:  IPProtocol{"VISA", "VISA Protocol"},
	71:  IPProtocol{"IPCU", "Internet Packet Core Utility"},
	72:  IPProtocol{"CPNX", "Computer Protocol Network Executive"},
	73:  IPProtocol{"CPHB", "Computer Protocol Heart Beat"},
	74:  IPProtocol{"WSN", "Wang Span Network"},
	75:  IPProtocol{"PVP", "Packet Video Protocol"},
	76:  IPProtocol{"BR-SAT-MON", "Backroom SATNET Monitoring"},
	77:  IPProtocol{"SUN-ND", "SUN ND PROTOCOL-Temporary"},
	78:  IPProtocol{"WB-MON", "WIDEBAND Monitoring"},
	79:  IPProtocol{"WB_EXPAK", "WIDEBAND EXPAK"},
	80:  IPProtocol{"ISO-IP", "International Organization for Standardization Internet Protocol"},
	81:  IPProtocol{"VMTP", "Versatile Message Transaction Protocol"},
	82:  IPProtocol{"SECURE-VMTP", "Secure Versatile Message Transaction Protocol"},
	83:  IPProtocol{"VINES", "VINES"},
	84:  IPProtocol{"TTP/IPTM", "TTP/Internet Protocol Traffic Manager"},
	85:  IPProtocol{"NSFNET-IGP", "NSFNET-IGP"},
	86:  IPProtocol{"DGP", "Dissimilar Gateway Protocol"},
	87:  IPProtocol{"TCF", "TCF"},
	88:  IPProtocol{"EIGRP", "EIGRP"},
	89:  IPProtocol{"OSPF", "OSPF"},
	90:  IPProtocol{"Sprite-RPC", "Sprite RPC Protocol"},
	91:  IPProtocol{"LARP", "Locus Address Resolution Protocol"},
	92:  IPProtocol{"MTP", "Multicast Transport Protocol"},
	93:  IPProtocol{"AX.25", "AX.25"},
	94:  IPProtocol{"IPIP", "IP-within-IP Encapsulation Protocol"},
	95:  IPProtocol{"MICP", "Mobile Internetworking Control Protocol"},
	96:  IPProtocol{"SCC-SP", "Semaphore Communications Sec. Pro"},
	97:  IPProtocol{"ETHERIP", "Ethernet-within-IP Encapsulation"},
	98:  IPProtocol{"ENCAP", "Encapsulation Header"},
	99:  IPProtocol{"", "Any private encryption scheme"},
	100: IPProtocol{"GMTP", "GMTP"},
	101: IPProtocol{"IFMP", "Ipsilon Flow Management Protocol"},
	102: IPProtocol{"PNNI", "PNNI over IP"},
	103: IPProtocol{"PIM", "Protocol Independent Multicast"},
	104: IPProtocol{"ARIS", "IBM's ARIS (Aggregate Route IP Switching) Protocol"},
	105: IPProtocol{"SCPS", "Space Communications Protocol Standards"},
	106: IPProtocol{"QNX", "QNX"},
	107: IPProtocol{"A/N", "Active Networks"},
	108: IPProtocol{"IPComp", "IP Payload Compression Protocol"},
	109: IPProtocol{"SNP", "Sitara Networks Protocol"},
	110: IPProtocol{"Compaq-Peer", "Compaq Peer Protocol"},
	111: IPProtocol{"IPX-in-IP", "IPX in IP"},
	112: IPProtocol{"VRRP", "Virtual Router Redundancy Protocol, Common Address Redundancy Protocol"},
	113: IPProtocol{"PGM", "PGM Reliable Transport Protocol"},
	114: IPProtocol{"", "Any 0-hop protocol"},
	115: IPProtocol{"L2TP", "Layer Two Tunning Protocol Version 3"},
	116: IPProtocol{"DDX", "D-II Data Exchange"},
	117: IPProtocol{"IATP", "Interactive Agent Transfer Protocol"},
	118: IPProtocol{"STP", "Schedule Transfer Protocol"},
	119: IPProtocol{"SRP", "SpectraLink Radio Protocol"},
	120: IPProtocol{"UTI", "Universal Transport Interface Protocol"},
	121: IPProtocol{"SMP", "Simple Message Protocol"},
	122: IPProtocol{"SM", "Simple Multicast Protocol"},
	123: IPProtocol{"PTP", "Performance Transparency Protocol"},
	124: IPProtocol{"IS-IS over IPv4", "Intermediate System to Intermediate System (IS-IS) Protocol over IPv4"},
	125: IPProtocol{"FIRE", "Flexible Intra-AS Routing Environment"},
	126: IPProtocol{"CRTP", "Combat Radio Transport Protocol"},
	127: IPProtocol{"CRUDP", "Combat Radio User Datagram"},
	128: IPProtocol{"SSCOPMCE", "Service-Specific Connection-Oriented Protocol in a Multilink and Connectionless Environment"},
	129: IPProtocol{"IPLT", ""},
	130: IPProtocol{"SPS", "Secure Packet Shield"},
	131: IPProtocol{"PIPE", "Private IP Encapsulation within IP"},
	132: IPProtocol{"SCTP", "Stream Control Transmission Protocol"},
	133: IPProtocol{"FC", "Fibre Channel"},
	134: IPProtocol{"RSVP-E2E-IGNORE", "Reservation Protocol (RSVP) End-to-End Ignore"},
	135: IPProtocol{"Mobility Header", "Mobility Extension Header for IPv6"},
	136: IPProtocol{"UDPLite", "Lightweight User Datagram Protocol"},
	137: IPProtocol{"MPLS-in-IP", "Multiprotocol Label Switching Ecapsulated in IP"},
	138: IPProtocol{"manet", "MANET Protocols"},
	139: IPProtocol{"HIP", "Host Identity Protocol"},
	140: IPProtocol{"Shim6", "Site Multihoming by IPv6 Intermediation"},
	141: IPProtocol{"WESP", "Wrapped Encapsulating Security Payload"},
	142: IPProtocol{"ROHC", "Robust Header Compression"},
}

// TODO: fill..
var TCPUDPPortMap = map[int]map[string]string{
	0: {
		"TCP": "Programming technique for specifying system-allocated (dynamic) ports",
		"UDP": "Reserved",
	},
	1: {
		"TCP": "TCPMUX",
		"UDP": "TCPMUX",
	},
	7: {
		"TCP": "Echo Protocol",
		"UDP": "Echo Protocol",
	},
	20: {
		"TCP": "FTP data transfer",
		"UDP": "FTP data transfer",
	},
	21: {
		"TCP": "FTP control",
	},
	22: {
		"TCP": "SSH/SCP/SFTP",
		"UDP": "SSH/SCP/SFTP",
	},
	23: {
		"TCP": "Telnet",
		"UDP": "Telnet",
	},
	25: {
		"TCP": "SMTP",
	},
	42: {
		"TCP": "ARPA Host Name Server Protocol",
		"UDP": "ARPA Host Name Server Protocol",
	},
	43: {
		"TCP": "WHOIS",
	},
	53: {
		"TCP": "DNS",
		"UDP": "DNS",
	},
	69: {
		"UDP": "TFTP",
	},
	80: {
		"TCP": "HTTP",
		"UDP": "QUIC",
	},
	123: {
		"TCP": "NTP",
		"UDP": "NTP",
	},
	143: {
		"TCP": "IMAP",
	},
	161: {
		"UDP": "SNMP",
	},
	177: {
		"TCP": "XDMCP",
		"UDP": "XDMCP",
	},
	179: {
		"TCP": "BGP",
	},
	194: {
		"TCP": "IRC",
		"UDP": "IRC",
	},
	443: {
		"TCP": "HTTPS",
		"UDP": "QUIC",
	},
	554: {
		"TCP": "RTSP",
		"UDP": "RTSP",
	},
	944: {
		"UDP": "NFS",
	},
}


text:
#include "config.h"

#if defined(LIBC_SCCS) && !defined(lint)
static const char sccsid[] = "@(#)bsearch.c	8.1 (Berkeley) 6/4/93";
#endif /* LIBC_SCCS and not lint */
#else
__RCSID("$NetBSD: bsearch.c,v 1.2 2014/01/26 21:43:45 christos Exp $");
#endif

#include <stddef.h>
#include <stdlib.h>

#include "port.h"

/*
 * Perform a binary search.
 *
 * The code below is a bit sneaky.  After a comparison fails, we
 * divide the work in half by moving either left or right. If lim
 * is odd, moving left simply involves halving lim: e.g., when lim
 * is 5 we look at item 2, so we change lim to 2 so that we will
 * look at items 0 & 1.  If lim is even, the same applies.  If lim
 * is odd, moving right again involes halving lim, this time moving
 * the base up one item past p: e.g., when lim is 5 we change base
 * to item 3 and make lim 2 so that we will look at items 3 and 4.
 * If lim is even, however, we have to shrink it by one before
 * halving: e.g., when lim is 4, we still looked at item 2, so we
 * have to make lim 3, then halve, obtaining 1, so that we will only
 * look at item 3.
 *
 * PUBLIC: #ifndef HAVE_BSEARCH
 * PUBLIC: void	*bsearch __P((const void *, const void *, size_t,
 * PUBLIC:    size_t, int (*)(const void *, const void *)));
 * PUBLIC: #endif
 */
void *
bsearch(register const void *key, const void *base0, size_t nmemb, register size_t size, register int (*compar) (const void *, const void *))
{
	register const char *base = base0;
	register size_t lim;
	register int cmp;
	register const void *p;

	for (lim = nmemb; lim != 0; lim >>= 1) {
		p = base + (lim >> 1) * size;
		cmp = (*compar)(key, p);
		if (cmp == 0)
			return ((void *)p);
		if (cmp > 0) {	/* key > p: move right */
			base = (char *)p + size;
			lim--;
		}		/* else move left */
	}
	return (NULL);
}


text:
import smtplib
import logging

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

class EncodingFormatter(logging.Formatter):

    def __init__(self, fmt, datefmt=None, encoding=None):
        logging.Formatter.__init__(self, fmt, datefmt)
        self.encoding = encoding

    def format(self, record):
        result = logging.Formatter.format(self, record)
        if isinstance(result, unicode):
            result = result.encode(self.encoding or 'utf-8')
            return result

class EmailUtil(object):
    def __init__(self, smtp_config):
        self.smtp_config = smtp_config

    def send_reply_mail(self, receiver, title, content, did, username, diary_title):
        sender = self.smtp_config.USER
        password = self.smtp_config.PASSWORD
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(title, "UTF-8")
        msg['From'] = sender
        msg['To'] = receiver
        content = self.generateHtml(content, did, username, diary_title)
        part = MIMEText(content, 'html', _charset='UTF-8')
        msg.attach(part)

        server = smtplib.SMTP(self.smtp_config.SERVER, self.smtp_config.PORT)
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, receiver, msg.as_string())
        server.quit()

    def generateHtml(self, content, did, username, diary_title):
        avatar = ''
        html = u'
<thead style=" width: 100%;color: #FFF; height: 75px; background-color: #bdcadf; -webkit-box-shadow: 0 1px 1px rgba(255,255,255,.5), inset 0 1px 3px #183357; -moz-box-shadow: 0 1px 1px rgba(255,255,255,.5), inset 0 1px 3px #183357; box-shadow: 0 1px 1px rgba(255,255,255,.5), inset 0 1px 3px #183357; background-image: -webkit-linear-gradient(bottom, #647792, #8d9baf); background-image: -moz-linear-gradient(bottom, #647792, #8d9baf); background-image: -o-linear-gradient(bottom, #647792, #8d9baf); background-image: -ms-linear-gradient(bottom, #647792, #8d9baf); background-image: linear-gradient(to top, #647792, #8d9baf);">
'
        html += self.smtp_config.MAIN_TITLE
        html += u'

'
        html += u'	'
        html += username
        html += u':
'
        html += content
        html += u'

'
        html += '<a style="-webkit-transform: translateY(0); -webkit-transition: -webkit-transform .2s ease-out; -moz-transform: translateY(0); -moz-transition: -moz-transform .2s ease-out; transform: translateY(0); transition: -moz-transform .2s ease-out; position: relative; top: 0; background-image: -webkit-linear-gradient(#6389C1, #4369A1); background-image: -moz-linear-gradient(#6389C1, #4369A1); background-image: -linear-gradient(#6389C1, #4369A1); height: 24px; box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 5px 1px; border: 1px solid rgba(53, 85, 131, 0.9); border-radius: 2px; text-shadow: 0 1px rgba(0, 0, 0, 0.5); margin-top: 0px; cursor: pointer; font-size: 13px; font-family: Vavont, Helvetica, sans-serif; text-align: center; line-height: 20px; color: rgba(255, 255, 255, 0.99); box-sizing: border-box; margin-bottom: 5px; display: block; padding: 2px 6px 3px; overflow: hidden; text-decoration: none;width:70px;" href="'
        html += self.smtp_config.SITE_URL
        html += u'/diary/'
        html += str(did)
        html += u'/'
        html += diary_title
        html += u'">返回原文

'
        html += u'

Copyright © 2012-2013 Dev_Blog 博客评论邮件提醒。 Written By Scen(he.kang@dev-engine.com)

'
        return html

    def send_error_email(self, title, error_log):
        sender = self.smtp_config.USER
        password = self.smtp_config.PASSWORD
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(title, "UTF-8")
        msg['From'] = sender
        msg['To'] = self.smtp_config.EMAIL
        part = MIMEText(str(error_log), 'html', _charset='UTF-8')
        msg.attach(part)

        server = smtplib.SMTP(self.smtp_config.SERVER, self.smtp_config.PORT)
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, self.smtp_config.EMAIL, msg.as_string())
        server.quit()


text:
<?php
    /**
     * XPHP - PHP Framework
     *
     * This project is licensed
     * under MIT. Please use it
     * under the license and law.
     *
     * @category Framework
     * @package  XPHP
     * @author   Tianle Xu <xtl@xtlsoft.top>
     * @license  MIT
     * @link     https://github.com/xtlsoft/XPHP
     *
     */

    namespace X\Database;

    use \NonDB\NonDB as NDB;

    class NonDB implements \X\Interfaces\Database, \X\Interfaces\NeedApplication, \X\Interfaces\Bootable {

        protected $db;

        public function bootup(){

            $config = $this->app->config['Database']['Driver'];

            $this->db = new NDB(NDB::driver($config));

        }

        public function getTable($table){

            return $this->db->table($table);

        }

    }


text:
Renderer::Renderer()
{

}


text:
<application>
  <component name="StatisticsApplicationUsages">
    <group name="run-configuration-type-temp">
      <project id="JDK8Demo" values="Application" collectionTime="1440512301383" />
    </group>
    <group name="language-level">
      <project id="main" values="JDK_1_7,JDK_1_5" collectionTime="1440789092032" />
      <project id="JDK8Demo" values="JDK_1_8" collectionTime="1440512301524" />
    </group>
    <group name="file-type">
      <project id="main" values="IDEA_MODULE,JAVA,Eclipse,UNKNOWN,XML,PLAIN_TEXT" collectionTime="1440789092022" />
      <project id="JDK8Demo" values="JAVA,HTML,IDEA_MODULE,UNKNOWN,XML" collectionTime="1440512301509" />
    </group>
    <group name="vcs">
      <project id="JDK8Demo" values="Git" collectionTime="1440512301382" />
    </group>
    <group name="module type">
      <project id="main" values="JAVA_MODULE" collectionTime="1440789091952" />
      <project id="JDK8Demo" values="JAVA_MODULE" collectionTime="1440512301382" />
    </group>
  </component>
  <component name="UsageTrigger">
    <counts>
      <entry feature="execute.Application.Run" count="2" />
      <entry feature="ide.settings.Appearance" count="1" />
      <entry feature="ide.settings.Colors_&_Fonts" count="1" />
      <entry feature="ide.settings.Console_Font" count="3" />
      <entry feature="ide.settings.Copyright" count="1" />
      <entry feature="ide.settings.Copyright_Profiles" count="2" />
      <entry feature="ide.settings.File_and_Code_Templates" count="5" />
      <entry feature="ide.settings.Font" count="5" />
      <entry feature="ide.settings.HTML" count="1" />
      <entry feature="ide.settings.Inspections" count="1" />
      <entry feature="ide.settings.JSON" count="1" />
      <entry feature="ide.settings.Java" count="1" />
      <entry feature="ide.settings.Keymap" count="2" />
      <entry feature="ide.settings.Language_Defaults" count="1" />
      <entry feature="ide.settings.Live_Templates" count="3" />
      <entry feature="ide.settings.Properties" count="1" />
      <entry feature="ide.settings.RegExp" count="1" />
      <entry feature="ide.settings.Scopes" count="1" />
      <entry feature="ide.settings.XML" count="1" />
      <entry feature="ide.settings.XPath" count="2" />
      <entry feature="ideaapp.started" count="8" />
      <entry feature="welcome.screen.WelcomeScreen.Configure" count="2" />
      <entry feature="welcome.screen.WelcomeScreen.CreateNewProject" count="3" />
      <entry feature="welcome.screen.WelcomeScreen.GetFromVcs" count="3" />
      <entry feature="welcome.screen.WelcomeScreen.Plugins" count="1" />
    </counts>
  </component>
</application>


text:
A Flux app that allows users to manage a shopping cart.

Based on the tutorial found at
https://scotch.io/tutorials/creating-a-simple-shopping-cart-with-react-js-and-flux.

## Demo

View a live demo at https://flux-shopping-cart.herokuapp.com/.

## How to use

```
git clone git@github.com:thinkswan/flux-shopping-cart.git
npm install
npm start
```

This will start a server at http://localhost:5000/.

## How to deploy

Click the button below to spin up your own copy of the app in a Heroku
instance.

[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy)

## How it works

The app is bootstrapped by loading mock data into local storage, then using a
mock API to retrieve the data and use it to initialize the `ProductStore`.

Following the Flux architecture, React views trigger actions, which are then
sent to the dispatcher, which notifies any stores who have registered callbacks.

When the affected stores modify their data, they emit a `change` event, which
causes the `FluxCartApp` controller view to update its state. Changes are then
passed to child components via props.

The app is stateless, so refreshing the page will clear all items from the cart.

## License

MIT


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

package com.thomsonreuters.corptech.charts;

import java.util.List;

/**
 *

 * Fade the targeted drawables into view (opacity from 0% to 100%)
 *

 *

 * WARNING: This is an automatically generated wrapper around a
 * native object; overriding methods will not work as expected.
 *

 */

@SuppressWarnings("all")
public class FadeInEffect extends BaseObject implements AnimationEffect
{
	/**
	 * Default constructor
	 */

	public FadeInEffect()
	{
		this(true);
		setHandle(nativeCreate());
	}

	/**
	 * Get the drawableList.
	 *

	 * Targeted drawables
	 *

	 * @return The current drawableList.
	 */

	public List<Drawable> getDrawableList()
	{
		return (List<Drawable>)nativeGetDrawableList(getHandle());
	}

	/**
	 * Set the drawableList.
	 *

	 * Targeted drawables
	 *

	 * @param value The new drawableList.
	 */

	public void setDrawableList(final List<Drawable> value)
	{
		nativeSetDrawableList(getHandle(), value);
	}

	/**
	 *

	 * Apply the next step of the animation.
	 *

	 * @param position Position of the animation (in seconds)
	 * @param duration Duration of the animation (in seconds)
	 */

	public void apply(final double position, final double duration)
	{
		nativeApply(getHandle(), position, duration);
	}

	// need this to prevent default constructor in base classes
	/*package*/ FadeInEffect(boolean dummy)
	{
		super(dummy);
	}

	protected void onFinalize()
	{
		nativeDestroy(getHandle());
	}

	private final native long nativeCreate();
	private final native void nativeDestroy(long ptr);
	private final native Object nativeGetDrawableList(long ptr);
	private final native void nativeSetDrawableList(long ptr, Object value);
	private final native void nativeApply(long ptr, double position, double duration);
}


text:
<TITLE>Review for Eve of Destruction (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Eve of Destruction (1991)

reviewed by
Mark R. Leeper

                              EVE OF DESTRUCTION
                       A film review by Mark R. Leeper
                        Copyright 1991 Mark R. Leeper

          Capsule review:  A few interesting ideas are lost in the
     mindless action and violence in this less than stellar story
     of a distaff "Terminator" with a bomb in her chest.  Rating:
     -1 (-4 to +4).

     EVE OF DESTRUCTION is the sort of science fiction film that nobody
minds if you call "sci-fi."  It is an action film with a poorly thought-out
science fiction premise that happens on a few nice ideas, but generally
wastes them.  It seems that missiles are not a very subtle way to place a
nuclear bomb.  Instead, the government is going to use a robot who, short of
surgery, cannot be distinguished from an attractive blonde.  Inside the
robot's chest is a nuclear bomb about the size of a soup can.  Inside the
robot's head are many of its inventor's memories, experiences, and
attitudes.  In front of this head is the inventor's face.  The inventor is
Dr. Eve Simmons and the robot's name is Eve VIII.  So the robot really is
the Eve of Destruction (get it?).  Baghdad would know something was up if we
shot a nuclear missile at them, I guess, but would never notice anything
strange if a tall, leggy blond walked into town.  Eve VIII is being tested-
-with full nuclear capability!--in real world situations such as going to
the bank.  Suddenly she runs into the unexpected, her temporary controller
is killed, and she starts running lose in the real world like a female
Terminator.  She is following instructions programmed into her head but also
enjoying new-found toys such as Uzi machine guns.  Anti-terrorist Jim
McQuade (played by Gregory Hines) and Eve Simmons (played by Renee
Soutendijk) must team up to out-fight and out-think the robot.

     Nice things could still be done with this idea, but nothing really
interesting comes out of it.  A little if made of the idea that the woman
and the robot will have some of the same thoughts, but mostly it is a
contrivance to make the needle a little easier to find in the haystack and
at the same time to make it a little more dangerous.  Eve VIII takes
particular exception to being called "bitch" and always uses it as a trigger
to go violent.  The audience knows that via repetitions, but Dr. Simmons
shows no sign of knowing it.  And when late in the film, McQuade seems to
know the trigger, we can only conclude that he learned it reading the
script.

     The robot is made of some material that is not greatly damaged in a
seventy-mile-per-hour impact, but still feels real in a slow breast fondle.
That's the material rocket scientists have been looking for for years!

     There is occasionally a little fun here, but overall the film is mostly
for a drive-in-style audience.  I rate it a -1 on the -4 to +4 scale.

                                        Mark R. Leeper
                                        att!mtgzy!leeper
                                        leeper@mtgzy.att.com
                                        Copyright 1991 Mark R. Leeper
.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text: """Unit tests for the `temppydemo` package."""


text:
const ObjectId = require('mongodb').ObjectID;
const Bulk = require('./bulk');
const crypto = require('crypto');

module.exports = class BasicCollection {
  constructor(db, schema) {
    this.db = db;
    this.mongo = db.db;
    this.schema = schema;
    this.name = schema.name;
  }

  bulk() {
    return new Bulk(this);
  }

  extractKey(object, to) {
    let key = to || {};
    for(let name in this.schema.key) {
      key[name] = object[name];
    }
    return key;
  }

  buildKeyString(object) {
    if (this.schema.syntheticKey) {
      return object[Object.keys(this.schema.key)[0]];
    } else {
      return this.buildHash(this.extractKey(object));
    }
  }

  buildHash(object) {
    let key = (typeof object === 'string') ? object : JSON.stringify(object);
    let hash = crypto.createHash('md5');
    hash.update(key);
    return hash.digest('hex');
  }

  async autoIndex(filter) {
    try {
      if (!this.indexes) {
        let allCollections = await this.mongo.collections();
        if (!allCollections.find(c => c.name === this.name)) {
          return;
        }
        let indexes = await this.mongo.collection(this.name).indexes();
        this.indexes = {};
        for(let index of indexes) {
          let key = index.key;
          let fields = Object.keys(key);
          fields.sort();
          this.indexes[fields.join(',')] = true;
        }
        //console.log(this.indexes);
      }

      let filterKeys = Object.keys(filter);
      filterKeys.sort();
      let filterSpec = filterKeys.join(',');

      if (!filter._bsontype && filterKeys.length > 0 && !this.indexes[filterSpec]) {
        let indexSpec = Object.assign({}, filter);
        for(let key in indexSpec) {
          indexSpec[key] = 1;
        }
        console.log('collection:', this.name, 'creating index', indexSpec);
        await this.mongo.collection(this.name).createIndex(indexSpec);
        this.indexes[filterSpec] = true;
      }
    } catch(e) {
      console.log(e);
    }
  }

  async read(filter) {
    await this.autoIndex(filter);
    let result = await this._read(filter);
    return result;
  }

  async _read(filter) {
    let data = await this.mongo.collection(this.name).find(filter).toArray();
    return data || [];
  }

  async update(filter, data) {
    let result = await this.mongo.collection(this.name).updateOne(filter, { $set:data});
    return result;
  }

  async remove(filter) {
    await this.mongo.collection(this.name).remove(filter);
  }

  async clear() {
    await this.remove({});
  }

  async insert(data) {
    let result = await this.mongo.collection(this.name).insertOne(data);
    return result;
  }

  async connect() {

  }

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember;
using Microsoft.CodeAnalysis.Host.Mef;

namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateEnumMember
{
    [ExportLanguageService(typeof(IGenerateEnumMemberService), LanguageNames.CSharp), Shared]
    internal partial class CSharpGenerateEnumMemberService :
        AbstractGenerateEnumMemberService<CSharpGenerateEnumMemberService, SimpleNameSyntax, ExpressionSyntax>
    {
        protected override bool IsIdentifierNameGeneration(SyntaxNode node)
        {
            return node is IdentifierNameSyntax;
        }

        protected override bool TryInitializeIdentifierNameState(
            SemanticDocument document, SimpleNameSyntax identifierName, CancellationToken cancellationToken,
            out SyntaxToken identifierToken, out ExpressionSyntax simpleNameOrMemberAccessExpression)
        {
            identifierToken = identifierName.Identifier;
            if (identifierToken.ValueText != string.Empty &&
                !identifierName.IsVar)
            {
                var memberAccess = identifierName.Parent as MemberAccessExpressionSyntax;
                simpleNameOrMemberAccessExpression = memberAccess != null && memberAccess.Name == identifierName
                    ? (ExpressionSyntax)memberAccess
                    : identifierName;

                // If we're being invoked, then don't offer this, offer generate method instead.
                // Note: we could offer to generate a field with a delegate type.  However, that's
                // very esoteric and probably not what most users want.
                if (simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression) ||
                    simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
                    simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.GotoStatement) ||
                    simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.AliasQualifiedName))
                {
                    return false;
                }

                return true;
            }

            identifierToken = default;
            simpleNameOrMemberAccessExpression = null;
            return false;
        }
    }
}


text:
'use strict';

// Articles controller
angular.module('courses').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles',
  function ($scope, $stateParams, $location, Authentication, Articles) {
    $scope.authentication = Authentication;

    // Create new Course
    $scope.create = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'articleForm');

        return false;
      }

      // Create new Course object
      var course = new Articles({
        title: this.title,
        content: this.content
      });

      // Redirect after save
      course.$save(function (response) {
        $location.path('courses/' + response._id);

        // Clear form fields
        $scope.title = '';
        $scope.content = '';
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Remove existing Course
    $scope.remove = function (course) {
      if (course) {
        course.$remove();

        for (var i in $scope.courses) {
          if ($scope.courses[i] === course) {
            $scope.courses.splice(i, 1);
          }
        }
      } else {
        $scope.course.$remove(function () {
          $location.path('courses');
        });
      }
    };

    // Update existing Course
    $scope.update = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'articleForm');

        return false;
      }

      var course = $scope.course;

      course.$update(function () {
        $location.path('courses/' + course._id);
      }, function (errorResponse) {
        $scope.error = errorResponse.data.message;
      });
    };

    // Find a list of Articles
    $scope.find = function () {
      $scope.courses = Articles.query();
    };

    // Find existing Course
    $scope.findOne = function () {
      $scope.course = Articles.get({
        articleId: $stateParams.articleId
      });
    };
  }
]);


text:
<?php

/*
 * GENERATED CODE WARNING
 * This file was automatically generated - do not edit!
 */

require_once __DIR__ . '/../../../vendor/autoload.php';

// [START dlp_v2_generated_DlpService_ListStoredInfoTypes_sync]
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\StoredInfoType;

/**
 * Lists stored infoTypes.
 * See https://cloud.google.com/dlp/docs/creating-stored-infotypes to
 * learn more.
 *
 * @param string $formattedParent Parent resource name.
 *
 *                                The format of this value varies depending on the scope of the request
 *                                (project or organization) and whether you have [specified a processing
 *                                location](https://cloud.google.com/dlp/docs/specifying-location):
 *
 *                                + Projects scope, location specified:

 *                                `projects/`<var>PROJECT_ID</var>`/locations/`<var>LOCATION_ID</var>
 *                                + Projects scope, no location specified (defaults to global):

 *                                `projects/`<var>PROJECT_ID</var>
 *
 *                                The following example `parent` string specifies a parent project with the
 *                                identifier `example-project`, and specifies the `europe-west3` location
 *                                for processing data:
 *
 *                                parent=projects/example-project/locations/europe-west3
 *                                Please see {@see DlpServiceClient::organizationLocationName()} for help formatting this field.
 */
function list_stored_info_types_sample(string $formattedParent): void
{
    // Create a client.
    $dlpServiceClient = new DlpServiceClient();

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $dlpServiceClient->listStoredInfoTypes($formattedParent);

        /** @var StoredInfoType $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = DlpServiceClient::organizationLocationName('[ORGANIZATION]', '[LOCATION]');

    list_stored_info_types_sample($formattedParent);
}
// [END dlp_v2_generated_DlpService_ListStoredInfoTypes_sync]


text:
import deepEqual from 'deep-equal';
import * as models from './index';
import * as db from '../common/database';
import {compressObject, decompressObject} from '../common/misc';
export const name = 'Request Version';
export const type = 'RequestVersion';
export const prefix = 'rvr';
export const canDuplicate = false;

const FIELDS_TO_IGNORE = [
  '_id',
  'type',
  'created',
  'modified',
  'metaSortKey',
  'description',
  'parentId',
  'name'
];

export function init () {
  return {
    compressedRequest: null
  };
}

export function migrate (doc) {
  return doc;
}

export function getById (id) {
  return db.get(type, id);
}

export async function create (request) {
  if (!request.type === models.request.type) {
    throw new Error(`New ${type} was not given a valid ${models.request.type} instance`);
  }

  const parentId = request._id;
  const latestRequestVersion = await getLatestByParentId(parentId);
  const latestRequest = latestRequestVersion
    ? decompressObject(latestRequestVersion.compressedRequest)
    : null;

  const hasChanged = _diffRequests(latestRequest, request);
  if (hasChanged) {
    // Create a new version if the request has been modified
    const compressedRequest = compressObject(request);
    return db.docCreate(type, {parentId, compressedRequest});
  } else {
    // Re-use the latest version if not modified since
    return latestRequestVersion;
  }
}

export function getLatestByParentId (parentId) {
  return db.getMostRecentlyModified(type, {parentId});
}

export async function restore (requestVersionId) {
  const requestVersion = await getById(requestVersionId);

  // Older responses won't have versions saved with them
  if (!requestVersion) {
    return null;
  }

  const requestPatch = decompressObject(requestVersion.compressedRequest);
  const originalRequest = await models.request.getById(requestPatch._id);

  // Only restore fields that aren't blacklisted
  for (const field of FIELDS_TO_IGNORE) {
    delete requestPatch[field];
  }

  return models.request.update(originalRequest, requestPatch);
}

function _diffRequests (rOld, rNew) {
  if (!rOld) {
    return true;
  }

  for (const key of Object.keys(rOld)) {
    // Skip fields that aren't useful
    if (FIELDS_TO_IGNORE.includes(key)) {
      continue;
    }

    if (!deepEqual(rOld[key], rNew[key])) {
      return true;
    }
  }

  return false;
}


text:
"""
api_utils.auth
~~~~~~~~~~~~~~

This module provides API authentication based on Hawk scheme and
Flask-Login extension.

"""
from functools import wraps

from flask import request, session, current_app
from werkzeug.exceptions import BadRequest, Unauthorized
try:
    import mohawk
    from flask.ext.login import current_user
except ImportError:
    pass

from . import compat

__all__ = ('Hawk',)

class Hawk(object):
    """HTTP authentication scheme using a message authentication code
    (MAC) algorithm.

    Instances are *not* bound to specific apps.

    """
    def __init__(self, app=None):
        self._client_key_loader_func = None

        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        app.config.setdefault('HAWK_ENABLED', True)
        app.config.setdefault('HAWK_SIGN_RESPONSE', False)
        app.config.setdefault('HAWK_ALLOW_COOKIE_AUTH', False)
        app.config.setdefault('HAWK_ALGORITHM', 'sha256')
        app.config.setdefault('HAWK_ACCEPT_UNTRUSTED_CONTENT', False)
        app.config.setdefault('HAWK_LOCALTIME_OFFSET_IN_SECONDS', 0)
        app.config.setdefault('HAWK_TIMESTAMP_SKEW_IN_SECONDS', 60)

        if app.config['HAWK_SIGN_RESPONSE']:
            app.after_request(self._sign_response)

    def client_key_loader(self, f):
        """Registers a function to be called to find a client key.

        Function you set has to take a client id and return a client key::

            @hawk.client_key_loader
            def get_client_key(client_id):
                if client_id == 'Alice':
                    return 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn'
                else:
                    raise LookupError()

        :param f: The callback for retrieving a client key.

        """
        @wraps(f)
        def wrapped_f(client_id):
            client_key = f(client_id)
            return {
                'id': client_id,
                'key': client_key,
                'algorithm': current_app.config['HAWK_ALGORITHM']
            }

        self._client_key_loader_func = wrapped_f
        return wrapped_f

    def auth_required(self, view_func):
        """Decorator that provides an access to view function for
        authenticated users only.

        Note that we don't run authentication when `HAWK_ENABLED` is `False`.

        """
        @wraps(view_func)
        def wrapped_view_func(*args, **kwargs):
            if current_app.config['HAWK_ENABLED']:
                if current_app.config['HAWK_ALLOW_COOKIE_AUTH'] and session:
                    self._auth_by_cookie()
                else:
                    self._auth_by_signature()
            return view_func(*args, **kwargs)

        return wrapped_view_func

    def _auth_by_cookie(self):
        if not compat.is_user_authenticated(current_user):
            raise Unauthorized()

    def _auth_by_signature(self):
        if self._client_key_loader_func is None:
            raise RuntimeError('Client key loader function was not defined')
        if 'Authorization' not in request.headers:
            raise Unauthorized()

        try:
            mohawk.Receiver(
                credentials_map=self._client_key_loader_func,
                request_header=request.headers['Authorization'],
                url=request.url,
                method=request.method,
                content=request.get_data(),
                content_type=request.mimetype,
                accept_untrusted_content=current_app.config['HAWK_ACCEPT_UNTRUSTED_CONTENT'],
                localtime_offset_in_seconds=current_app.config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'],
                timestamp_skew_in_seconds=current_app.config['HAWK_TIMESTAMP_SKEW_IN_SECONDS']
            )
        except mohawk.exc.MacMismatch:
            # mohawk exception contains computed MAC.
            # We should not expose it in response.
            raise Unauthorized()
        except (
            mohawk.exc.CredentialsLookupError,
            mohawk.exc.AlreadyProcessed,
            mohawk.exc.MisComputedContentHash,
            mohawk.exc.TokenExpired
        ) as e:
            raise Unauthorized(str(e))
        except mohawk.exc.HawkFail as e:
            raise BadRequest(str(e))
        except KeyError:
            raise BadRequest()

    def _sign_response(self, response):
        """Signs a response if it's possible."""
        if 'Authorization' not in request.headers:
            return response

        try:
            mohawk_receiver = mohawk.Receiver(
                credentials_map=self._client_key_loader_func,
                request_header=request.headers['Authorization'],
                url=request.url,
                method=request.method,
                content=request.get_data(),
                content_type=request.mimetype,
                accept_untrusted_content=current_app.config['HAWK_ACCEPT_UNTRUSTED_CONTENT'],
                localtime_offset_in_seconds=current_app.config['HAWK_LOCALTIME_OFFSET_IN_SECONDS'],
                timestamp_skew_in_seconds=current_app.config['HAWK_TIMESTAMP_SKEW_IN_SECONDS']
            )
        except mohawk.exc.HawkFail:
            return response

        response.headers['Server-Authorization'] = mohawk_receiver.respond(
            content=response.data,
            content_type=response.mimetype
        )
        return response


text:
require "baseapi/version"

# ActiveRecord::Relation Extension
require 'baseapi/active_record/relation_extension'
ActiveRecord::Relation.send(:include, ActiveRecordRelationExtension)

# ActiveRecord::Base Extension
require 'baseapi/active_record/base_extension'
ActiveRecord::Base.send(:include, ActiveRecordBaseExtension)

# ActionController::Base Extension
require 'baseapi/app/controllers/base_api_controller'

# baseapi module
require 'baseapi/app/controllers/concerns/base_api'


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__int_connect_socket_divide_42.c
Label Definition File: CWE369_Divide_by_Zero__int.label.xml
Template File: sources-sinks-42.tmpl.c
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: connect_socket Read data using a connect socket (client side)
 * GoodSource: Non-zero
 * Sinks: divide
 *    GoodSink: Check for zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 42 Data flow: data returned from one function to another in the same source file
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

#ifndef OMITBAD

static int badSource(int data)
{
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate the string */
            inputBuffer[recvResult] = '\0';
            /* Convert to int */
            data = atoi(inputBuffer);
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    return data;
}

void CWE369_Divide_by_Zero__int_connect_socket_divide_42_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    data = badSource(data);
    /* POTENTIAL FLAW: Possibly divide by zero */
    printIntLine(100 / data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
static int goodG2BSource(int data)
{
    /* FIX: Use a value not equal to zero */
    data = 7;
    return data;
}

static void goodG2B()
{
    int data;
    /* Initialize data */
    data = -1;
    data = goodG2BSource(data);
    /* POTENTIAL FLAW: Possibly divide by zero */
    printIntLine(100 / data);
}

/* goodB2G uses the BadSource with the GoodSink */
static int goodB2GSource(int data)
{
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        SOCKET connectSocket = INVALID_SOCKET;
        char inputBuffer[CHAR_ARRAY_SIZE];
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a connect socket */
            connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (connectSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
            service.sin_port = htons(TCP_PORT);
            if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed, make sure to recv one
             * less char than is in the recv_buf in order to append a terminator */
            recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* NUL-terminate the string */
            inputBuffer[recvResult] = '\0';
            /* Convert to int */
            data = atoi(inputBuffer);
        }
        while (0);
        if (connectSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(connectSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    return data;
}

static void goodB2G()
{
    int data;
    /* Initialize data */
    data = -1;
    data = goodB2GSource(data);
    /* FIX: test for a zero denominator */
    if( data != 0 )
    {
        printIntLine(100 / data);
    }
    else
    {
        printLine("This would result in a divide by zero");
    }
}

void CWE369_Divide_by_Zero__int_connect_socket_divide_42_good()
{
    goodB2G();
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE369_Divide_by_Zero__int_connect_socket_divide_42_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE369_Divide_by_Zero__int_connect_socket_divide_42_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
from __future__ import unicode_literals

from django.utils import six

from reviewboard.hostingsvcs.service import (get_hosting_services,
                                             get_hosting_service)
from reviewboard.webapi.resources import resources
from reviewboard.webapi.tests.base import BaseWebAPITestCase
from reviewboard.webapi.tests.mimetypes import (hosting_service_item_mimetype,
                                                hosting_service_list_mimetype)
from reviewboard.webapi.tests.mixins import BasicTestsMetaclass
from reviewboard.webapi.tests.urls import (get_hosting_service_item_url,
                                           get_hosting_service_list_url)

def _compare_item(self, item_rsp, hosting_service):
    self.assertEqual(item_rsp['id'], hosting_service.hosting_service_id)
    self.assertEqual(item_rsp['name'], hosting_service.name)
    self.assertEqual(item_rsp['needs_authorization'],
                     hosting_service.needs_authorization)
    self.assertEqual(item_rsp['supports_bug_trackers'],
                     hosting_service.supports_bug_trackers)
    self.assertEqual(item_rsp['supports_repositories'],
                     hosting_service.supports_repositories)
    self.assertEqual(item_rsp['supports_two_factor_auth'],
                     hosting_service.supports_two_factor_auth)
    self.assertEqual(item_rsp['supported_scmtools'],
                     hosting_service.supported_scmtools)

    plans_rsp = item_rsp['plans']
    plan_keys = set(six.iterkeys(plans_rsp))

    if plan_keys == {''}:
        self.assertIsNone(hosting_service.plans)

        plan_rsp = plans_rsp['']
        self.assertEqual(plan_rsp['name'], 'Default')
        self.assertEqual(set(plan_rsp['fields']),
                         set(hosting_service.form.base_fields))
    else:
        plans = hosting_service.plans
        self.assertEqual(len(plans), len(plan_keys))

        for plan_id, plan in plans:
            self.assertIn(plan_id, plans_rsp)

            plan_rsp = plans_rsp[plan_id]
            self.assertEqual(plan_rsp['name'], plan['name'])
            self.assertEqual(set(plan_rsp['fields']),
                             set(plan['form'].base_fields))

    self.assertEqual(item_rsp['supported_scmtools'],
                     hosting_service.supported_scmtools)

    # Compute the base URL for links.
    url_base = 'http://testserver/'

    if '/s/local-site-1/' in item_rsp['links']['self']['href']:
        url_base += 's/local-site-1/'

    url_base += 'api/'

    # Check the links.
    accounts_url = url_base + ('hosting-service-accounts/?service=%s'
                               % hosting_service.hosting_service_id)
    self.assertIn('accounts', item_rsp['links'])
    self.assertEqual(item_rsp['links']['accounts']['href'], accounts_url)

    accounts_url = url_base + ('repositories/?hosting-service=%s'
                               % hosting_service.hosting_service_id)
    self.assertIn('repositories', item_rsp['links'])
    self.assertEqual(item_rsp['links']['repositories']['href'], accounts_url)

@six.add_metaclass(BasicTestsMetaclass)
class ResourceListTests(BaseWebAPITestCase):
    """Testing the HostingServiceResource list APIs."""
    fixtures = ['test_users']
    sample_api_url = 'hosting-services/'
    resource = resources.hosting_service

    compare_item = _compare_item

    def setup_http_not_allowed_list_test(self, user):
        return get_hosting_service_list_url()

    #
    # HTTP GET tests
    #

    def setup_basic_get_test(self, user, with_local_site, local_site_name,
                             populate_items):
        return (get_hosting_service_list_url(local_site_name),
                hosting_service_list_mimetype,
                get_hosting_services())

@six.add_metaclass(BasicTestsMetaclass)
class ResourceItemTests(BaseWebAPITestCase):
    """Testing the HostingServiceResource item APIs."""
    fixtures = ['test_users']
    sample_api_url = 'hosting-services/<id>/'
    resource = resources.hosting_service

    compare_item = _compare_item

    def setup_http_not_allowed_item_test(self, user):
        hosting_service = get_hosting_service('github')

        return get_hosting_service_item_url(hosting_service)

    #
    # HTTP GET tests
    #

    def setup_basic_get_test(self, user, with_local_site, local_site_name):
        hosting_service = get_hosting_service('github')

        return (get_hosting_service_item_url(hosting_service, local_site_name),
                hosting_service_item_mimetype,
                hosting_service)


text:
package com.jeeplus.weixin.fastweixin.handle.impl;

import com.jeeplus.weixin.fastweixin.handle.EventHandle;
import com.jeeplus.weixin.fastweixin.message.BaseMsg;
import com.jeeplus.weixin.fastweixin.message.req.BaseEvent;

/**
 * @author:yuzp17311
 * @version:v1.0
 * @date: 2016-10-12 18:41.
 */
public class WeiXinEventHandle implements EventHandle {
    /**
     * 处理微信事件
     *
     * @param event 微信事件
     * @return 回复用户的消息
     */
    @Override
    public BaseMsg handle(BaseEvent event) {
        return null;
    }

    /**
     * 在处理之前,判断本事件是否符合处理的条件
     *
     * @param event 事件
     * @return 是否需要处理
     */
    @Override
    public boolean beforeHandle(BaseEvent event) {
        return false;
    }
}


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

<title>O-Index</title>
<meta name="date" content="2016-10-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D G H I N O P Q R U

O

opaque(String) - Method in class org.barebonesdigest.DigestChallengeResponse

Sets the opaque directive, which must be the same as the opaque directive of
 the challenge.

org.barebonesdigest - package org.barebonesdigest

A C D G H I N O P Q R U

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Quadrant Hybrid Settings</title>
 <link rel='stylesheet' type='text/css' href='slate.min.css'>
 <link rel='stylesheet' type='text/css' href='style.css'>

Quadrant Hybrid Watchface
Configuration Page

    Choose the settings to apply.

Configurable items

    Invert colors
    <input id='invertCheckbox' type='checkbox' class='item-checkbox'>

   Settings only change on the watch after you click save.

    <input id='submitButton' type='button' class='item-button' value='SUBMIT'>

    <input id='cancelButton' type='button' class='item-button' value='CANCEL'>


text:
<link rel="import" href="/sys/polymer/polymer.html">

<template>

This is ViewKeeper test subject

            TOP LEFT
            BOTTOM RIGHT

    <dom-bind><template is="dom-bind">

            This is a shared thing: <input type="text" value="{{model.SharedValue.Description$::input}}" class="ViewKeeper-subject-input">

    </template></dom-bind>

        Go to ViewKeeper test distraction (Acceptance Helper 2)

</template>


text:
package checkspec.api;

/**
 * Way for setting each modifier for a given specification. Modifiers that are
 * not supported on a specific element (i.e. {@code abstract} for a field) are
 * being ignored.
 *
 * @author Florian Cramer
 *
 */
public @interface Modifiers {

	/**
	 * Returns whether or not the element has modifier {@code abstract}.
	 *
	 * @return whether or not the element is abstract
	 */
	State isAbstract() default State.NOT_SPECIFIED;

	/**
	 * Returns whether or not the element has modifier {@code final}.
	 *
	 * @return whether or not the element is final
	 */
	State isFinal() default State.NOT_SPECIFIED;

	/**
	 * Returns whether or not the element has modifier {@code native}.
	 *
	 * @return whether or not the element is native
	 */
	State isNative() default State.NOT_SPECIFIED;

	/**
	 * Returns whether or not the element has modifier {@code static}.
	 *
	 * @return whether or not the element is static
	 */
	State isStatic() default State.NOT_SPECIFIED;

	/**
	 * Returns whether or not the element has modifier {@code strictfp}.
	 *
	 * @return whether or not the element is strict
	 */
	State isStrict() default State.NOT_SPECIFIED;

	/**
	 * Returns whether or not the element has modifier {@code synchronized}.
	 *
	 * @return whether or not the element is synchronized
	 */
	State isSynchronized() default State.NOT_SPECIFIED;

	/**
	 * Returns whether or not the element has modifier {@code volatile}.
	 *
	 * @return whether or not the element is volatile
	 */
	State isVolatile() default State.NOT_SPECIFIED;

	/**
	 * Returns whether or not the element has modifier {@code transient}.
	 *
	 * @return whether or not the element is transient
	 */
	State isTransient() default State.NOT_SPECIFIED;
}


text:
a [Sails 0.10.x](http://beta.sailsjs.org) application
that demonstrates that `Sails.js` does not properly support
the `i18n-node`'s `objectNotation` flag.

More Info

* See [Github Issue](https://github.com/balderdashy/sails/issues/1878)
* or [Stackoverlfow Question](http://stackoverflow.com/questions/24342509/how-can-get-a-non-trivial-i18n-translation-to-work-using-sails-js/24343184#24343184)