text:
(function() {
  var Contrib,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  if (typeof Giraffe === 'undefined') {
    throw new Error('Can\'t find Giraffe');
  }

  Contrib = Giraffe.Contrib = {
    version: '0.2.1'
  };

  /*
  * A __Controller__ is a simple evented class that can participate in appEvents.
  * It demonstrates the usage of `Giraffe.configure` which extends any function
  * instance with [features including lifecycle management, app events, and more.]
  * (http://barc.github.io/backbone.giraffe/backbone.giraffe.html#configure)
  *
  * @param {Object} options
  *
  * - all options get merged into object like models and views.
  *
  * @example
  *
  *  var SfxController = Giraffe.Contrib.Controller.extend({
  *    appEvents: {
  *      'process:complete': 'playDingSound'
  *    },
  *
  *    playDingSound: function() {
  *      // Code for playing sound...
  *    }
  *  });
  *
  *  // Options get merged into object like views and models.
  *  var sfxController = new SfxController({
  *    basePath: 'media/audio',
  *  });
  *
  * @author darthapo <github.com/darthapo>
  */

  Contrib.Controller = (function() {
    _.extend(Controller.prototype, Backbone.Events);

    function Controller(options) {
      Giraffe.configure(this, options);
    }

    return Controller;

  })();

  /*
  * `Backbone.Giraffe.Contrib` is a collection of officially supported classes that are
  * built on top of `Backbone.Giraffe`. These classes should be considered
  * experimental as their APIs are subject to undocumented changes.
  */

  /*
  * A __CollectionView__ mirrors a `Collection`, rendering a view for each model.
  *
  * @param {Object} options
  *
  * - [collection] - {Collection} The collection instance for the `CollectionView`. Defaults to a new __Giraffe.Collection__.
  * - [modelView] - {ViewClass} The view created per model in `collection.models`. Defaults to __Giraffe.View__.
  * - [modelViewArgs] - {Array} The arguments passed to the `modelView` constructor. Can be a function returning an array.
  * - [modelViewEl] - {Selector,Giraffe.View#ui} The container for the model views. Can be a function returning the same. Defaults to `collectionView.$el`.
  *
  * @example
  *
  *  var FruitView = Giraffe.View.extend({});
  *
  *  var FruitsView = Giraffe.Contrib.CollectionView.extend({
  *    modelView: FruitView
  *  });
  *
  *  var view = new FruitsView({
  *    collection: [{name: 'apple'}],
  *  });
  *
  *  view.children.length; // => 1
  *
  *  view.collection.add({name: 'banana'});
  *
  *  view.children.length; // => 2
  */

  Contrib.CollectionView = (function(_super) {
    __extends(CollectionView, _super);

    CollectionView.getDefaults = function(ctx) {
      return {
        collection: ctx.collection ? null : new Giraffe.Collection,
        modelView: Giraffe.View,
        modelViewArgs: null,
        modelViewEl: null,
        renderOnChange: false
      };
    };

    function CollectionView() {
      var _ref, _ref1;
      CollectionView.__super__.constructor.apply(this, arguments);
      _.defaults(this, this.constructor.getDefaults(this));
      if (_.isArray(this.collection)) {
        this.collection = new Giraffe.Collection(this.collection);
      }
      if (!this.modelView) {
        throw new Error('`modelView` is required');
      }
      if (!((_ref = this.collection) != null ? _ref.model : void 0)) {
        throw new Error('`collection.model` is required');
      }
      this.listenTo(this.collection, 'add', this.addOne);
      this.listenTo(this.collection, 'remove', this.removeOne);
      this.listenTo(this.collection, 'reset sort', this.render);
      if (this.renderOnChange) {
        this.listenTo(this.collection, 'change', this._onChangeModel);
      }
      if (this.modelViewEl) {
        this.modelViewEl = ((_ref1 = this.ui) != null ? _ref1[this.modelViewEl] : void 0) || this.modelViewEl;
      }
    }

    CollectionView.prototype._onChangeModel = function(model) {
      var view;
      view = this.findByModel(model);
      return view.render();
    };

    CollectionView.prototype.findByModel = function(model) {
      var view, _i, _len, _ref;
      _ref = this.children;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        view = _ref[_i];
        if (view.model === model) {
          return view;
        }
      }
      return null;
    };

    CollectionView.prototype._calcAttachOptions = function(model) {
      var i, index, options, prevModel, prevView;
      options = {
        el: null,
        method: 'prepend'
      };
      index = this.collection.indexOf(model);
      i = 1;
      while (prevModel = this.collection.at(index - i)) {
        prevView = this.findByModel(prevModel);
        if (prevView != null ? prevView._isAttached : void 0) {
          options.method = 'after';
          options.el = prevView.$el;
          break;
        }
        i++;
      }
      if (!options.el && this.modelViewEl) {
        options.el = this.$(this.modelViewEl);
        if (!options.el.length) {
          throw new Error('`modelViewEl` not found in this view');
        }
      }
      return options;
    };

    CollectionView.prototype._cloneModelViewArgs = function() {
      var args;
      args = this.modelViewArgs || [{}];
      if (_.isFunction(args)) {
        args = args.call(this);
      }
      if (!_.isArray(args)) {
        args = [args];
      }
      args = _.map(args, _.clone);
      if (!(_.isArray(args) && _.isObject(args[0]))) {
        throw new Error('`modelViewArgs` must be an array with an object as the first value');
      }
      return args;
    };

    CollectionView.prototype.afterRender = function() {
      var model, _i, _len, _ref;
      _ref = this.collection.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        model = _ref[_i];
        this.addOne(model);
      }
      return this;
    };

    CollectionView.prototype.removeOne = function(model, options) {
      var modelView;
      if (this.collection.contains(model)) {
        this.collection.remove(model);
      } else {
        modelView = _.findWhere(this.children, {
          model: model
        });
        if (modelView != null) {
          modelView.dispose();
        }
      }
      return this;
    };

    CollectionView.prototype.addOne = function(model) {
      var attachOptions, modelView, modelViewArgs;
      if (!this.collection.contains(model)) {
        this.collection.add(model);
      } else if (!this._renderedOnce) {
        this.render();
      } else {
        attachOptions = this._calcAttachOptions(model);
        modelViewArgs = this._cloneModelViewArgs();
        modelViewArgs[0].model = model;
        modelView = (function(func, args, ctor) {
          ctor.prototype = func.prototype;
          var child = new ctor, result = func.apply(child, args);
          return Object(result) === result ? result : child;
        })(this.modelView, modelViewArgs, function(){});
        this.attach(modelView, attachOptions);
      }
      return this;
    };

    return CollectionView;

  })(Giraffe.View);

  /*
  * A __FastCollectionView__ is a __CollectionView__ that _doesn't create a view
  * per model_. Performance should generally be improved, especially when the
  * entire collection must be rendered, as string concatenation is used to touch
  * the DOM once. [Here's a jsPerf with more.](http://jsperf.com/collection-views-in-giraffe-and-marionette/5)
  *
  * The option `modelEl` can be used to specify where to insert the model html.
  * It defaults to `view.$el` and cannot contain any DOM elemenets other
  * than those automatically created per model by the `FastCollectionView`.
  *
  * The option `modelTemplate` is the only required one and it is used to create
  * the html per model. ___`modelTemplate` must return a single top-level DOM node
  * per call.___ The __FVC__ uses a similar templating system to the
  * __Giraffe.View__, but instead of defining `template` and an optional
  * `serialize` and templateStrategy`, __FVC__ takes  `modelTemplate` and optional
  * `modelSerialize` and `modelTemplateStrategy`. As in __Giraffe.View__,
  * setting `modelTemplateStrategy` to a function bypasses Giraffe's usage
  * of `modelTemplate` and `modelSerialize` to directly return a string of html.
  *
  * The __FVC__ reacts to the events `'add'`, `'remove'`, `'reset`', and `'sort'`.
  * It should keep `modelEl` in sync wih the collection with a template per model.
  * The __FVC__ API also exposes a shortcut to manipulating the collection with
  * `addOne` and `removeOne`.
  *
  * @param {Object} options
  *
  * - [collection] - {Collection} The collection instance for the `FastCollectionView`. Defaults to a new __Giraffe.Collection__.
  * - modelTemplate - {String,Function} Required. The template for each model. Must return exactly 1 top level DOM element per call. Is actually not required if `modelTemplateStrategy` is a function, signaling circumvention of Giraffe's templating help.
  * - [modelTemplateStrategy] - {String} The template strategy used for the `modelTemplate`. Can be a function returning a string of HTML to override the need for `modelTemplate` and `modelSerialize`. Defaults to inheriting from the view.
  * - [modelSerialize] - {Function} Used to get the data passed to `modelTemplate`. Returns the model by default. Customize by passing as an option or override globally at `Giraffe.Contrib.FastCollectionView.prototype.modelSerialize`.
  * - [modelEl] - {Selector,Giraffe.View#ui} The selector or Giraffe.View#ui name for the model template container. Can be a function returning the same. Do not put html in here manually with the current design. Defaults to `view.$el`.
  *
  * @example
  *
  *  var FruitsView = Giraffe.Contrib.CollectionView.extend({
  *    modelTemplate: 'my-fcv-template-id'
  *  });
  *
  *  var view = new FruitsView({
  *    collection: [{name: 'apple'}],
  *  });
  *
  *  view.render();
  *
  *  view.$el.children().length; // => 1
  *
  *  var banana = new Backbone.Model({name: 'banana'});
  *
  *  view.collection.add(banana);
  *  // or
  *  // view.addOne(banana);
  *
  *  view.$el.children().length; // => 2
  *
  *  view.collection.remove(banana);
  *  // or
  *  // view.removeOne(banana);
  *
  *  view.$el.children().length; // => 1
  */

  Contrib.FastCollectionView = (function(_super) {
    __extends(FastCollectionView, _super);

    FastCollectionView.getDefaults = function(ctx) {
      return {
        collection: ctx.collection ? null : new Giraffe.Collection,
        modelTemplate: null,
        modelSerialize: ctx.modelSerialize ? null : function() {
          return this.model;
        },
        modelTemplateStrategy: ctx.templateStrategy,
        modelEl: null,
        renderOnChange: true
      };
    };

    function FastCollectionView() {
      var _ref;
      FastCollectionView.__super__.constructor.apply(this, arguments);
      if ((this.modelTemplate == null) && !_.isFunction(this.modelTemplateStrategy)) {
        throw new Error('`modelTemplate` or a `modelTemplateStrategy` function is required');
      }
      _.defaults(this, this.constructor.getDefaults(this));
      if (_.isArray(this.collection)) {
        this.collection = new Giraffe.Collection(this.collection);
      }
      this.listenTo(this.collection, 'add', this.addOne);
      this.listenTo(this.collection, 'remove', this.removeOne);
      this.listenTo(this.collection, 'reset sort', this.render);
      if (this.renderOnChange) {
        this.listenTo(this.collection, 'change', this.addOne);
      }
      if (this.modelEl) {
        this.modelEl = ((_ref = this.ui) != null ? _ref[this.modelEl] : void 0) || this.modelEl;
      }
      this.modelTemplateCtx = {
        serialize: this.modelSerialize,
        template: this.modelTemplate
      };
      Giraffe.View.setTemplateStrategy(this.modelTemplateStrategy, this.modelTemplateCtx);
    }

    FastCollectionView.prototype.afterRender = function() {
      this.$modelEl = this.modelEl ? this.$(this.modelEl) : this.$el;
      if (!this.$modelEl.length) {
        throw new Error('`$modelEl` not found after rendering');
      }
      this.addAll();
      return this;
    };

    /*
    * Removes `model` from the collection if present and removes its DOM elements.
    */

    FastCollectionView.prototype.removeOne = function(model, collection, options) {
      var index, _ref;
      if (this.collection.contains(model)) {
        this.collection.remove(model);
      } else {
        index = (_ref = options != null ? options.index : void 0) != null ? _ref : options;
        this.removeByIndex(index);
      }
      return this;
    };

    /*
    * Adds `model` to the collection if not present and renders it to the DOM.
    */

    FastCollectionView.prototype.addOne = function(model) {
      var html;
      if (!this.collection.contains(model)) {
        this.collection.add(model);
      } else if (!this._renderedOnce) {
        this.render();
      } else {
        html = this._renderModel(model);
        this._insertModelHTML(html, model);
      }
      return this;
    };

    /*
    * Adds all of the models to the DOM at once. Is destructive to `modelEl`.
    */

    FastCollectionView.prototype.addAll = function() {
      var html, model, _i, _len, _ref;
      html = '';
      _ref = this.collection.models;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        model = _ref[_i];
        html += this._renderModel(model);
      }
      this.$modelEl.empty()[0].innerHTML = html;
      return this;
    };

    /*
    * Removes children of `modelEl` by index.
    *
    * @param {Integer} index
    */

    FastCollectionView.prototype.removeByIndex = function(index) {
      var $el;
      $el = this.findElByIndex(index);
      if (!$el.length) {
        throw new Error('Unable to find el with index ' + index);
      }
      $el.remove();
      return this;
    };

    /*
    * Finds the element for `model`.
    *
    * @param {Model} model
    */

    FastCollectionView.prototype.findElByModel = function(model) {
      return this.findElByIndex(this.collection.indexOf(model));
    };

    /*
    * Finds the element inside `modelEl` at `index`.
    *
    * @param {Integer} index
    */

    FastCollectionView.prototype.findElByIndex = function(index) {
      return $(this.$modelEl.children()[index]);
    };

    /*
    * Finds the corresponding model in the collection by a DOM element.
    * Is especially useful in DOM handlers - pass `event.target` to get the model.
    *
    * @param {String/Element/$/Giraffe.View} el
    */

    FastCollectionView.prototype.findModelByEl = function(el) {
      var index;
      index = $(el).closest(this.$modelEl.children()).index();
      return this.collection.at(index);
    };

    /*
    * Generates a model's html string using `modelTemplateCtx` and its options.
    */

    FastCollectionView.prototype._renderModel = function(model) {
      this.modelTemplateCtx.model = model;
      return this.modelTemplateCtx.templateStrategy();
    };

    /*
    * Inserts a model's html into the DOM.
    */

    FastCollectionView.prototype._insertModelHTML = function(html, model) {
      var $children, $existingEl, $prevModel, index, numChildren;
      $children = this.$modelEl.children();
      numChildren = $children.length;
      index = this.collection.indexOf(model);
      if (numChildren === this.collection.length) {
        $existingEl = $($children[index]);
        $existingEl.replaceWith(html);
      } else if (index >= numChildren) {
        this.$modelEl.append(html);
      } else {
        $prevModel = $($children[index - 1]);
        if ($prevModel.length) {
          $prevModel.after(html);
        } else {
          this.$modelEl.prepend(html);
        }
      }
      return this;
    };

    return FastCollectionView;

  })(Giraffe.View);

  if (_.isObject(typeof module !== "undefined" && module !== null ? module.exports : void 0)) {
    module.exports = Contrib;
  } else if (typeof define === 'function' && define.amd) {
    define('backbone.giraffe.contrib', [], function() {
      return Contrib;
    });
  }

}).call(this);


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Tests;

using Xunit;

namespace System.Net.Tests
{
    public partial class WebHeaderCollectionTest
    {
        [Fact]
        public void Ctor_Success()
        {
            new WebHeaderCollection();
        }

        [Fact]
        public void DefaultPropertyValues_ReturnEmptyAfterConstruction_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            Assert.Equal(0, w.AllKeys.Length);
            Assert.Equal(0, w.Count);
            Assert.Equal("\r\n", w.ToString());
            Assert.Empty(w);
            Assert.Empty(w.AllKeys);
        }

        [Fact]
        public void HttpRequestHeader_Add_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[HttpRequestHeader.Connection] = "keep-alive";

            Assert.Equal(1, w.Count);
            Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]);
            Assert.Equal("Connection", w.AllKeys[0]);
        }

        [Theory]
        [InlineData((HttpRequestHeader)int.MinValue)]
        [InlineData((HttpRequestHeader)(-1))]
        [InlineData((HttpRequestHeader)int.MaxValue)]
        public void HttpRequestHeader_AddInvalid_Throws(HttpRequestHeader header)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo");
        }

        [Theory]
        [InlineData((HttpResponseHeader)int.MinValue)]
        [InlineData((HttpResponseHeader)(-1))]
        [InlineData((HttpResponseHeader)int.MaxValue)]
        public void HttpResponseHeader_AddInvalid_Throws(HttpResponseHeader header)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            Assert.Throws<IndexOutOfRangeException>(() => w[header] = "foo");
        }

        [Fact]
        public void CustomHeader_AddQuery_Success()
        {
            string customHeader = "Custom-Header";
            string customValue = "Custom;.-Value";
            WebHeaderCollection w = new WebHeaderCollection();
            w[customHeader] = customValue;

            Assert.Equal(1, w.Count);
            Assert.Equal(customValue, w[customHeader]);
            Assert.Equal(customHeader, w.AllKeys[0]);
        }

        [Fact]
        public void HttpResponseHeader_AddQuery_CommonHeader_Success()
        {
            string headerValue = "value123";
            WebHeaderCollection w = new WebHeaderCollection();
            w[HttpResponseHeader.ProxyAuthenticate] = headerValue;
            w[HttpResponseHeader.WwwAuthenticate] = headerValue;

            Assert.Equal(headerValue, w[HttpResponseHeader.ProxyAuthenticate]);
            Assert.Equal(headerValue, w[HttpResponseHeader.WwwAuthenticate]);
        }

        [Fact]
        public void HttpRequest_AddQuery_CommonHeader_Success()
        {
            string headerValue = "value123";
            WebHeaderCollection w = new WebHeaderCollection();
            w[HttpRequestHeader.Accept] = headerValue;

            Assert.Equal(headerValue, w[HttpRequestHeader.Accept]);
        }

        [Fact]
        public void RequestThenResponseHeaders_Add_Throws()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[HttpRequestHeader.Accept] = "text/json";
            Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength] = "123");
        }

        [Fact]
        public void ResponseThenRequestHeaders_Add_Throws()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[HttpResponseHeader.ContentLength] = "123";
            Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept] = "text/json");
        }

        [Fact]
        public void ResponseHeader_QueryRequest_Throws()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[HttpResponseHeader.ContentLength] = "123";
            Assert.Throws<InvalidOperationException>(() => w[HttpRequestHeader.Accept]);
        }

        [Fact]
        public void RequestHeader_QueryResponse_Throws()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[HttpRequestHeader.Accept] = "text/json";
            Assert.Throws<InvalidOperationException>(() => w[HttpResponseHeader.ContentLength]);
        }

        [Fact]
        public void Setter_ValidName_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w["Accept"] = "text/json";
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        public void Setter_NullOrEmptyName_Throws(string name)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentNullException>("name", () => w[name] = "test");
        }

        public static object[][] InvalidNames = {
            new object[] { "(" },
            new object[] { "\u1234" },
            new object[] { "\u0019" }
        };

        [Theory, MemberData(nameof(InvalidNames))]
        public void Setter_InvalidName_Throws(string name)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentException>("name", () => w[name] = "test");
        }

        public static object[][] InvalidValues = {
            new object[] { "value1\rvalue2\r" },
            new object[] { "value1\nvalue2\r" },
            new object[] { "value1\u007fvalue2" },
            new object[] { "value1\r\nvalue2" },
            new object[] { "value1\u0019value2" }
        };

        [Theory, MemberData(nameof(InvalidValues))]
        public void Setter_InvalidValue_Throws(string value)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentException>("value", () => w["custom"] = value);
        }

        public static object[][] ValidValues = {
            new object[] { null },
            new object[] { "" },
            new object[] { "value1\r\n" },
            new object[] { "value1\tvalue2" },
            new object[] { "value1\r\n\tvalue2" },
            new object[] { "value1\r\n value2" }
        };

        [Theory, MemberData(nameof(ValidValues))]
        public void Setter_ValidValue_Success(string value)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w["custom"] = value;
        }

        [Theory]
        [InlineData("name", "name")]
        [InlineData("name", "NaMe")]
        [InlineData("nAmE", "name")]
        public void Setter_SameHeaderTwice_Success(string firstName, string secondName)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[firstName] = "first";
            w[secondName] = "second";
            Assert.Equal(1, w.Count);
            Assert.NotEmpty(w);
            Assert.NotEmpty(w.AllKeys);
            Assert.Equal(new[] { firstName }, w.AllKeys);
            Assert.Equal("second", w[firstName]);
            Assert.Equal("second", w[secondName]);
        }

        [Theory]
        [InlineData("name")]
        [InlineData("nAMe")]
        public void Remove_HeaderExists_RemovesFromCollection(string name)
        {
            var headers = new WebHeaderCollection()
            {
                { "name", "value" }
            };
            headers.Remove(name);
            Assert.Empty(headers);

            headers.Remove(name);
            Assert.Empty(headers);
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        public void Remove_NullOrEmptyHeader_ThrowsArgumentNullException(string name)
        {
            var headers = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentNullException>("name", () => headers.Remove(name));
        }

        [Theory]
        [InlineData(" \r \t \n")]
        [InlineData("  name  ")]
        [MemberData(nameof(InvalidValues))]
        public void Remove_InvalidHeader_ThrowsArgumentException(string name)
        {
            var headers = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentException>("name", () => headers.Remove(name));
        }

        [Fact]
        public void Remove_IllegalCharacter_Throws()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentException>("name", () => w.Remove("{"));
        }

        [Fact]
        public void Remove_EmptyCollection_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Remove("foo");
            Assert.Equal(0, w.Count);
            Assert.Empty(w);
            Assert.Empty(w.AllKeys);
        }

        [Theory]
        [InlineData("name", "name")]
        [InlineData("name", "NaMe")]
        public void Remove_SetThenRemove_Success(string setName, string removeName)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[setName] = "value";
            w.Remove(removeName);
            Assert.Equal(0, w.Count);
            Assert.Empty(w);
            Assert.Empty(w.AllKeys);
        }

        [Theory]
        [InlineData("name", "name")]
        [InlineData("name", "NaMe")]
        public void Remove_SetTwoThenRemoveOne_Success(string setName, string removeName)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w[setName] = "value";
            w["foo"] = "bar";
            w.Remove(removeName);
            Assert.Equal(1, w.Count);
            Assert.NotEmpty(w);
            Assert.NotEmpty(w.AllKeys);
            Assert.Equal(new[] { "foo" }, w.AllKeys);
            Assert.Equal("bar", w["foo"]);
        }

        [Fact]
        public void Getter_EmptyCollection_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            Assert.Null(w["name"]);
            Assert.Equal(0, w.Count);
            Assert.Empty(w);
            Assert.Empty(w.AllKeys);
        }

        [Fact]
        public void Getter_NonEmptyCollectionNonExistentHeader_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w["name"] = "value";
            Assert.Null(w["foo"]);
            Assert.Equal(1, w.Count);
            Assert.NotEmpty(w);
            Assert.NotEmpty(w.AllKeys);
            Assert.Equal(new[] { "name" }, w.AllKeys);
            Assert.Equal("value", w["name"]);
        }

        [Fact]
        public void Getter_Success()
        {
            string[] keys = { "Accept", "uPgRaDe", "Custom" };
            string[] values = { "text/plain, text/html", " HTTP/2.0 , SHTTP/1.3,  , RTA/x11 ", "\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"" };
            WebHeaderCollection w = new WebHeaderCollection();

            for (int i = 0; i < keys.Length; ++i)
            {
                string key = keys[i];
                string value = values[i];
                w[key] = value;
            }

            for (int i = 0; i < keys.Length; ++i)
            {
                string key = keys[i];
                string expected = values[i].Trim();
                Assert.Equal(expected, w[key]);
                Assert.Equal(expected, w[key.ToUpperInvariant()]);
                Assert.Equal(expected, w[key.ToLowerInvariant()]);
            }
        }

        [Fact]
        public void ToString_Empty_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            Assert.Equal("\r\n", w.ToString());
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        public void ToString_SingleHeaderWithEmptyValue_Success(string value)
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w["name"] = value;
            Assert.Equal("name: \r\n\r\n", w.ToString());
        }

        [Fact]
        public void ToString_NotEmpty_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w["Accept"] = "text/plain";
            w["Content-Length"] = "123";
            Assert.Equal(
                "Accept: text/plain\r\nContent-Length: 123\r\n\r\n",
                w.ToString());
        }

        [Fact]
        public void IterateCollection_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w["Accept"] = "text/plain";
            w["Content-Length"] = "123";

            string result = "";
            foreach (var item in w)
            {
                result += item;
            }

            Assert.Equal("AcceptContent-Length", result);
        }

        [Fact]
        public void Enumerator_Success()
        {
            string item1 = "Accept";
            string item2 = "Content-Length";
            string item3 = "Name";

            WebHeaderCollection w = new WebHeaderCollection();
            w[item1] = "text/plain";
            w[item2] = "123";
            w[item3] = "value";

            IEnumerable collection = w;
            IEnumerator e = collection.GetEnumerator();

            for (int i = 0; i < 2; i++)
            {
                // Not started
                Assert.Throws<InvalidOperationException>(() => e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(item1, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(item2, e.Current);

                Assert.True(e.MoveNext());
                Assert.Same(item3, e.Current);

                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());
                Assert.False(e.MoveNext());

                // Ended
                Assert.Throws<InvalidOperationException>(() => e.Current);

                e.Reset();
            }
        }

        public static IEnumerable<object[]> SerializeDeserialize_Roundtrip_MemberData()
        {
            for (int i = 0; i < 10; i++)
            {
                var wc = new WebHeaderCollection();
                for (int j = 0; j < i; j++)
                {
                    wc[$"header{j}"] = $"value{j}";
                }
                yield return new object[] { wc };
            }
        }

        public static IEnumerable<object[]> Add_Value_TestData()
        {
            yield return new object[] { null, string.Empty };
            yield return new object[] { string.Empty, string.Empty };
            yield return new object[] { "VaLue", "VaLue" };
            yield return new object[] { "  value  ", "value" };

            // Documentation says this should fail but it does not.
            string longString = new string('a', 65536);
            yield return new object[] { longString, longString };
        }

        [Theory]
        [MemberData(nameof(Add_Value_TestData))]
        public void Add_ValidValue_Success(string value, string expectedValue)
        {
            var headers = new WebHeaderCollection
            {
                { "name", value }
            };

            Assert.Equal(expectedValue, headers["name"]);
        }

        [Fact]
        public void Add_HeaderAlreadyExists_AppendsValue()
        {
            var headers = new WebHeaderCollection
            {
                { "name", "value1" },
                { "name", null },
                { "name", "value2" },
                { "NAME", "value3" },
                { "name", "" }
            };
            Assert.Equal("value1,,value2,value3,", headers["name"]);
        }

        [Fact]
        public void Add_NullName_ThrowsArgumentNullException()
        {
            var headers = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentNullException>("name", () => headers.Add(null, "value"));
        }

        [Theory]
        [InlineData("")]
        [InlineData("(")]
        [InlineData("\r \t \n")]
        [InlineData("  name  ")]
        [MemberData(nameof(InvalidValues))]
        public void Add_InvalidName_ThrowsArgumentException(string name)
        {
            var headers = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentException>("name", () => headers.Add(name, "value"));
        }

        [Theory]
        [MemberData(nameof(InvalidValues))]
        public void Add_InvalidValue_ThrowsArgumentException(string value)
        {
            var headers = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentException>("value", () => headers.Add("name", value));
        }

        [Fact]
        public void Add_ValidHeader_AddsToHeaders()
        {
            var headers = new WebHeaderCollection()
            {
                "name:value1",
                "name:",
                "NaMe:value2",
                "name:  ",
            };
            Assert.Equal("value1,,value2,", headers["name"]);
        }

        [Theory]
        [InlineData(null)]
        [InlineData("")]
        public void Add_NullHeader_ThrowsArgumentNullException(string header)
        {
            var headers = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentNullException>("header", () => headers.Add(header));
        }

        [Theory]
        [InlineData(" \r \t \n", "header")]
        [InlineData("nocolon", "header")]
        [InlineData("  :value", "name")]
        [InlineData("name  :value", "name")]
        [InlineData("name:va\rlue", "value")]
        public void Add_InvalidHeader_ThrowsArgumentException(string header, string paramName)
        {
            var headers = new WebHeaderCollection();
            AssertExtensions.Throws<ArgumentException>(paramName, () => headers.Add(header));
        }

        [Fact]
        public void HttpRequestHeader_Add_Rmemove_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add(HttpRequestHeader.Warning, "Warning1");

            Assert.Equal(1, w.Count);
            Assert.Equal("Warning1", w[HttpRequestHeader.Warning]);
            Assert.Equal("Warning", w.AllKeys[0]);

            w.Remove(HttpRequestHeader.Warning);
            Assert.Equal(0, w.Count);
        }

        [Fact]
        public void HttpRequestHeader_Get_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add("header1", "value1");
            w.Add("header1", "value2");
            string[] values = w.GetValues(0);
            Assert.Equal("value1", values[0]);
            Assert.Equal("value2", values[1]);
        }

        [Fact]
        public void HttpRequestHeader_ToByteArray_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add("header1", "value1");
            w.Add("header1", "value2");
            byte[] byteArr = w.ToByteArray();
            Assert.NotEmpty(byteArr);
        }

        [Fact]
        public void HttpRequestHeader_GetKey_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add("header1", "value1");
            w.Add("header1", "value2");
            Assert.NotEmpty(w.GetKey(0));
        }

        [Fact]
        public void HttpRequestHeader_GetValues_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add("header1", "value1");
            Assert.Equal("value1", w.GetValues("header1")[0]);
        }

        [Fact]
        public void HttpRequestHeader_Clear_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add("header1", "value1");
            w.Add("header1", "value2");
            w.Clear();
            Assert.Equal(0, w.Count);
        }

        [Fact]
        public void HttpRequestHeader_IsRestricted_Success()
        {
            Assert.True(WebHeaderCollection.IsRestricted("Accept"));
            Assert.False(WebHeaderCollection.IsRestricted("Age"));
            Assert.False(WebHeaderCollection.IsRestricted("Accept", true));
        }

        [Fact]
        public void HttpRequestHeader_AddHeader_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add(HttpRequestHeader.ContentLength, "10");
            w.Add(HttpRequestHeader.ContentType, "text/html");
            Assert.Equal(2,w.Count);
        }

        [Fact]
        public void WebHeaderCollection_Keys_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Add(HttpRequestHeader.ContentLength, "10");
            w.Add(HttpRequestHeader.ContentType, "text/html");
            Assert.Equal(2, w.Keys.Count);
        }

        [Fact]
        public void HttpRequestHeader_AddHeader_Failure()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            char[] arr = new char[ushort.MaxValue + 1];
            string maxStr = new string(arr);
            AssertExtensions.Throws<ArgumentException>("value", () => w.Add(HttpRequestHeader.ContentLength,maxStr));
            AssertExtensions.Throws<ArgumentException>("value", () => w.Add("ContentLength", maxStr));
        }

        [Fact]
        public void HttpResponseHeader_Set_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Set(HttpResponseHeader.ProxyAuthenticate, "value123");

            Assert.Equal("value123", w[HttpResponseHeader.ProxyAuthenticate]);
        }

        [Fact]
        public void HttpRequestHeader_Set_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Set(HttpRequestHeader.Connection, "keep-alive");

            Assert.Equal(1, w.Count);
            Assert.Equal("keep-alive", w[HttpRequestHeader.Connection]);
            Assert.Equal("Connection", w.AllKeys[0]);
        }

        [Fact]
        public void NameValue_Set_Success()
        {
            WebHeaderCollection w = new WebHeaderCollection();
            w.Set("firstName", "first");
            Assert.Equal(1, w.Count);
            Assert.NotEmpty(w);
            Assert.NotEmpty(w.AllKeys);
            Assert.Equal(new[] { "firstName" }, w.AllKeys);
            Assert.Equal("first", w["firstName"]);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Payum\Paypal\ExpressCheckout\Nvp\Tests\Action;

use Payum\Core\Request\Sync;
use Payum\Paypal\ExpressCheckout\Nvp\Action\PaymentDetailsSyncAction;
use Payum\Paypal\ExpressCheckout\Nvp\Api;
use Payum\Paypal\ExpressCheckout\Nvp\Request\Api\GetExpressCheckoutDetails;
use Payum\Paypal\ExpressCheckout\Nvp\Request\Api\GetTransactionDetails;

class PaymentDetailsSyncActionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldBeSubClassOfPaymentAwareAction()
    {
        $rc = new \ReflectionClass('Payum\Paypal\ExpressCheckout\Nvp\Action\PaymentDetailsSyncAction');

        $this->assertTrue($rc->isSubclassOf('Payum\Core\Action\PaymentAwareAction'));
    }

    /**
     * @test
     */
    public function couldBeConstructedWithoutAnyArguments()
    {
        new PaymentDetailsSyncAction();
    }

    /**
     * @test
     */
    public function shouldSupportSyncAndArrayAsModelWhichHasPaymentRequestAmountSet()
    {
        $action = new PaymentDetailsSyncAction();

        $paymentDetails = array(
            'PAYMENTREQUEST_0_AMT' => 12,
        );

        $request = new Sync($paymentDetails);

        $this->assertTrue($action->supports($request));
    }

    /**
     * @test
     */
    public function shouldSupportSyncAndArrayAsModelWhichHasPaymentRequestAmountSetToZero()
    {
        $action = new PaymentDetailsSyncAction();

        $paymentDetails = array(
            'PAYMENTREQUEST_0_AMT' => 0,
        );

        $request = new Sync($paymentDetails);

        $this->assertTrue($action->supports($request));
    }

    /**
     * @test
     */
    public function shouldNotSupportAnythingNotSync()
    {
        $action = new PaymentDetailsSyncAction();

        $this->assertFalse($action->supports(new \stdClass()));
    }

    /**
     * @test
     *
     * @expectedException \Payum\Core\Exception\RequestNotSupportedException
     */
    public function throwIfNotSupportedRequestGivenAsArgumentForExecute()
    {
        $action = new PaymentDetailsSyncAction();

        $action->execute(new \stdClass());
    }

    /**
     * @test
     */
    public function shouldDoNothingIfTokenNotSet()
    {
        $paymentMock = $this->createPaymentMock();
        $paymentMock
            ->expects($this->never())
            ->method('execute')
        ;

        $action = new PaymentDetailsSyncAction();
        $action->setPayment($paymentMock);

        $request = new Sync(array(
            'PAYMENTREQUEST_0_AMT' => 12,
        ));

        $action->execute($request);
    }

    /**
     * @test
     */
    public function shouldRequestGetExpressCheckoutDetailsAndUpdateModelIfTokenSetInModel()
    {
        $paymentMock = $this->createPaymentMock();
        $paymentMock
            ->expects($this->once())
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Paypal\ExpressCheckout\Nvp\Request\Api\GetExpressCheckoutDetails'))
            ->will($this->returnCallback(function (GetExpressCheckoutDetails $request) {
                $model = $request->getModel();
                $model['foo'] = 'fooVal';
                $model['PAYMENTREQUEST_0_AMT'] = 33;
            }))
        ;

        $action = new PaymentDetailsSyncAction();
        $action->setPayment($paymentMock);

        $details = new \ArrayObject(array(
            'PAYMENTREQUEST_0_AMT' => 11,
            'TOKEN' => 'aToken',
        ));

        $action->execute($sync = new Sync($details));

        $this->assertArrayHasKey('foo', (array) $details);
        $this->assertEquals('fooVal', $details['foo']);

        $this->assertArrayHasKey('PAYMENTREQUEST_0_AMT', (array) $details);
        $this->assertEquals(33, $details['PAYMENTREQUEST_0_AMT']);
    }

    /**
     * @test
     */
    public function shouldRequestGetExpressCheckoutDetailsAndDoNotUpdateModelIfSessionExpired()
    {
        $paymentMock = $this->createPaymentMock();
        $paymentMock
            ->expects($this->once())
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Paypal\ExpressCheckout\Nvp\Request\Api\GetExpressCheckoutDetails'))
            ->will($this->returnCallback(function (GetExpressCheckoutDetails $request) {
                $model = $request->getModel();
                $model['foo'] = 'fooVal';
                $model['PAYMENTREQUEST_0_AMT'] = 33;
                $model['L_ERRORCODE0'] = Api::L_ERRORCODE_SESSION_HAS_EXPIRED;
            }))
        ;

        $action = new PaymentDetailsSyncAction();
        $action->setPayment($paymentMock);

        $details = new \ArrayObject(array(
            'PAYMENTREQUEST_0_AMT' => 11,
            'TOKEN' => 'aToken',
        ));

        $action->execute($sync = new Sync($details));

        $this->assertArrayNotHasKey('foo', (array) $details);

        $this->assertArrayHasKey('PAYMENTREQUEST_0_AMT', (array) $details);
        $this->assertEquals(11, $details['PAYMENTREQUEST_0_AMT']);
    }

    /**
     * @test
     */
    public function shouldRequestGetTransactionDetailsTwice()
    {
        $paymentMock = $this->createPaymentMock();
        $paymentMock
            ->expects($this->at(1))
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Paypal\ExpressCheckout\Nvp\Request\Api\GetTransactionDetails'))
            ->will($this->returnCallback(function (GetTransactionDetails $request) {
                $model = $request->getModel();
                $model['foo'] = 'fooVal';
            }))
        ;
        $paymentMock
            ->expects($this->at(2))
            ->method('execute')
            ->with($this->isInstanceOf('Payum\Paypal\ExpressCheckout\Nvp\Request\Api\GetTransactionDetails'))
            ->will($this->returnCallback(function (GetTransactionDetails $request) {
                $model = $request->getModel();
                $model['bar'] = 'barVal';
            }))
        ;

        $action = new PaymentDetailsSyncAction();
        $action->setPayment($paymentMock);

        $details = new \ArrayObject(array(
            'PAYMENTREQUEST_0_AMT' => 12,
            'TOKEN' => 'aToken',
            'PAYMENTREQUEST_0_TRANSACTIONID' => 'zeroTransId',
            'PAYMENTREQUEST_9_TRANSACTIONID' => 'nineTransId',
        ));

        $action->execute(new Sync($details));

        $this->assertArrayHasKey('foo', (array) $details);
        $this->assertEquals('fooVal', $details['foo']);

        $this->assertArrayHasKey('bar', (array) $details);
        $this->assertEquals('barVal', $details['bar']);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject|\Payum\Core\PaymentInterface
     */
    protected function createPaymentMock()
    {
        return $this->getMock('Payum\Core\PaymentInterface');
    }
}


text:
title: A Target Attribute
---
## A Target Attribute

The `<a target>` attribute specifies where to open the linked document in an `a` (anchor) tag.

#### Examples:

A target attribute with the value of "_blank" opens the linked document in a new window or tab.

```html
	<a href="https://www.freecodecamp.org" target="_blank">freeCodeCamp</a>
```

A target attribute with the value of "_self" opens the linked document in the same frame as it was clicked (this is the default and usually does not need to be specified).

```html
	<a href="https://www.freecodecamp.org" target="_self">freeCodeCamp</a>
```

```html
	<a href="https://www.freecodecamp.org">freeCodeCamp</a>
```

A target attribute with the value of "_parent" opens the linked document in the parent frame.

```html
	<a href="https://www.freecodecamp.org" target="_parent">freeCodeCamp</a>
```

A target attribute with the value of "_top" opens the linked document in the full body of the window.

```html
	<a href="https://www.freecodecamp.org" target="_top">freeCodeCamp</a>
```

A target attribute with the value of _"framename"_ opens the linked document in a specified named frame.

```html
	<a href="https://www.freecodecamp.org" target="framename">freeCodeCamp</a>
```

#### More Information:

Target Attribute: w3schools


text:
#ifndef BOOST_INTERPROCESS_CONTAINERS_ALLOCATION_TYPE_HPP
#define BOOST_INTERPROCESS_CONTAINERS_ALLOCATION_TYPE_HPP

#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/container/detail/allocation_type.hpp>

namespace boost {
namespace interprocess {

#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
typedef int allocation_type;
#endif   //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
static const allocation_type allocate_new       = boost::container::allocate_new;
static const allocation_type expand_fwd         = boost::container::expand_fwd;
static const allocation_type expand_bwd         = boost::container::expand_bwd;
static const allocation_type shrink_in_place    = boost::container::shrink_in_place;
static const allocation_type try_shrink_in_place= boost::container::try_shrink_in_place;
static const allocation_type nothrow_allocation = boost::container::nothrow_allocation;
static const allocation_type zero_memory        = boost::container::zero_memory;

}  //namespace interprocess {
}  //namespace boost {

#include <boost/interprocess/detail/config_end.hpp>

#endif //   #ifndef  BOOST_INTERPROCESS_CONTAINERS_ALLOCATION_TYPE_HPP


text:
package org.apache.flink.kubernetes.kubeclient.decorators;

import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkPod;
import org.apache.flink.kubernetes.kubeclient.KubernetesJobManagerTestBase;
import org.apache.flink.kubernetes.kubeclient.parameters.KubernetesJobManagerParameters;
import org.apache.flink.kubernetes.utils.Constants;

import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerPort;
import io.fabric8.kubernetes.api.model.ContainerPortBuilder;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.api.model.Toleration;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

/**
 * General tests for the {@link InitJobManagerDecorator}.
 */
public class InitJobManagerDecoratorTest extends KubernetesJobManagerTestBase {

	private static final String SERVICE_ACCOUNT_NAME = "service-test";
	private static final List<String> IMAGE_PULL_SECRETS = Arrays.asList("s1", "s2", "s3");
	private static final Map<String, String> ANNOTATIONS = new HashMap<String, String>() {
		{
			put("a1", "v1");
			put("a2", "v2");
		}
	};
	private static final String TOLERATION_STRING = "key:key1,operator:Equal,value:value1,effect:NoSchedule;" +
		"KEY:key2,operator:Exists,Effect:NoExecute,tolerationSeconds:6000";
	private static final List<Toleration> TOLERATION = Arrays.asList(
		new Toleration("NoSchedule", "key1", "Equal", null, "value1"),
		new Toleration("NoExecute", "key2", "Exists", 6000L, null));

	private Pod resultPod;
	private Container resultMainContainer;

	@Before
	public void setup() throws Exception {
		super.setup();
		this.flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT, SERVICE_ACCOUNT_NAME);
		this.flinkConfig.set(KubernetesConfigOptions.CONTAINER_IMAGE_PULL_SECRETS, IMAGE_PULL_SECRETS);
		this.flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_ANNOTATIONS, ANNOTATIONS);
		this.flinkConfig.setString(KubernetesConfigOptions.JOB_MANAGER_TOLERATIONS.key(), TOLERATION_STRING);

		final InitJobManagerDecorator initJobManagerDecorator =
			new InitJobManagerDecorator(this.kubernetesJobManagerParameters);
		final FlinkPod resultFlinkPod = initJobManagerDecorator.decorateFlinkPod(this.baseFlinkPod);

		this.resultPod = resultFlinkPod.getPod();
		this.resultMainContainer = resultFlinkPod.getMainContainer();
	}

	@Test
	public void testApiVersion() {
		assertEquals(Constants.API_VERSION, this.resultPod.getApiVersion());
	}

	@Test
	public void testMainContainerName() {
		assertEquals(KubernetesJobManagerParameters.JOB_MANAGER_MAIN_CONTAINER_NAME, this.resultMainContainer.getName());
	}

	@Test
	public void testMainContainerImage() {
		assertEquals(CONTAINER_IMAGE, this.resultMainContainer.getImage());
		assertEquals(CONTAINER_IMAGE_PULL_POLICY.name(), this.resultMainContainer.getImagePullPolicy());
	}

	@Test
	public void testMainContainerResourceRequirements() {
		final ResourceRequirements resourceRequirements = this.resultMainContainer.getResources();

		final Map<String, Quantity> requests = resourceRequirements.getRequests();
		assertEquals(Double.toString(JOB_MANAGER_CPU), requests.get("cpu").getAmount());
		assertEquals(JOB_MANAGER_MEMORY + "Mi", requests.get("memory").getAmount());

		final Map<String, Quantity> limits = resourceRequirements.getLimits();
		assertEquals(Double.toString(JOB_MANAGER_CPU), limits.get("cpu").getAmount());
		assertEquals(JOB_MANAGER_MEMORY + "Mi", limits.get("memory").getAmount());
	}

	@Test
	public void testMainContainerPorts() {
		final List<ContainerPort> expectedContainerPorts = Arrays.asList(
			new ContainerPortBuilder()
				.withName(Constants.REST_PORT_NAME)
				.withContainerPort(REST_PORT)
			.build(),
			new ContainerPortBuilder()
				.withName(Constants.JOB_MANAGER_RPC_PORT_NAME)
				.withContainerPort(RPC_PORT)
			.build(),
			new ContainerPortBuilder()
				.withName(Constants.BLOB_SERVER_PORT_NAME)
				.withContainerPort(BLOB_SERVER_PORT)
			.build());

		assertEquals(expectedContainerPorts, this.resultMainContainer.getPorts());
	}

	@Test
	public void testMainContainerEnv() {
		final List<EnvVar> envVars = this.resultMainContainer.getEnv();

		final Map<String, String> envs = new HashMap<>();
		envVars.forEach(env -> envs.put(env.getName(), env.getValue()));
		this.customizedEnvs.forEach((k, v) -> assertEquals(envs.get(k), v));

		assertTrue(envVars.stream().anyMatch(env -> env.getName().equals(Constants.ENV_FLINK_POD_IP_ADDRESS)
			&& env.getValueFrom().getFieldRef().getApiVersion().equals(Constants.API_VERSION)
			&& env.getValueFrom().getFieldRef().getFieldPath().equals(Constants.POD_IP_FIELD_PATH)));
	}

	@Test
	public void testPodLabels() {
		final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
		expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
		expectedLabels.putAll(userLabels);

		assertEquals(expectedLabels, this.resultPod.getMetadata().getLabels());
	}

	@Test
	public void testPodAnnotations() {
		final Map<String, String> resultAnnotations = kubernetesJobManagerParameters.getAnnotations();
		assertThat(resultAnnotations, is(equalTo(ANNOTATIONS)));
	}

	@Test
	public void testPodServiceAccountName() {
		assertEquals(SERVICE_ACCOUNT_NAME, this.resultPod.getSpec().getServiceAccountName());
	}

	@Test
	public void testImagePullSecrets() {
		final List<String> resultSecrets = this.resultPod.getSpec().getImagePullSecrets()
			.stream()
			.map(LocalObjectReference::getName)
			.collect(Collectors.toList());

		assertEquals(IMAGE_PULL_SECRETS, resultSecrets);
	}

	@Test
	public void testNodeSelector() {
		assertThat(this.resultPod.getSpec().getNodeSelector(), is(equalTo(nodeSelector)));
	}

	@Test
	public void testPodTolerations() {
		assertThat(this.resultPod.getSpec().getTolerations(), Matchers.containsInAnyOrder(TOLERATION.toArray()));
	}
}


text:
.. _label-exceptions:

Error handling
==============

In this section we will cover the various mechanisms Parsl provides to add resiliency
and robustness to workflows.

Exceptions
----------

Parsl provides support for capturing, tracking, and handling a variety of
errors. It also provides functionality to appropriately respond to failures during
workflow execution.
If a task is unable to complete execution within a specified time limit or if it
is unable to produce the specified set of outputs it is considered to have failed.

Failures might occur for various reasons:

1. Task exceeded specified walltime.
2. Formatting error while formatting the command-line string in Bash apps.
3. Task failed during execution.
4. Task completed execution but failed to produce one or more of its specified
   outputs.
5. Task failed to launch, for example if an input dependency is not met.

Since Parsl tasks are executed asynchronously, it can be difficult to determine
where to place exception handling code in the workflow.
In Parsl all exceptions are associated with the task futures.
These exceptions are raised only when a result is called on the future
of a failed task. For example:

.. code-block:: python

      @python_app
      def bad_divide(x):
          return 6 / x

      # Call bad divide with 0, to cause a divide by zero exception
      doubled_x = bad_divide(0)

      # Catch and handle the exception.
      try:
           doubled_x.result()
      except ZeroDivisionError as e:
           print('Oops! You tried to divide by 0.')
      except Exception as e:
           print('Oops! Something really bad happened.')

Retries
-------

Often errors in distributed/parallel environments are transient. Retrying
a task is a common method for adding resiliency to a workflow.
By retrying failed apps, transient failures (e.g., machine failure,
network failure) and intermittent failures within applications can be overcome.
When ``retries`` are enabled (and set to an integer > 0), Parsl will automatically
re-launch applications that have failed, until the retry limit is reached.

By default ``retries = 0``.

The following example shows how the number of retries can be set to 2:

.. code-block:: python

   from parsl import load
   from parsl.tests.configs.local_threads import config
   config.retries = 2

   load(config)

Lazy fail
---------

.. warning::
   Due to a known bug (`issue#282 <https://github.com/Parsl/parsl/issues/282>`_),
   disabling lazy_errors with ``lazy_errors=False`` is **not** supported in Parsl 0.6.0.

Parsl implements a lazy failure model through which a workload will continue
to execute in the case that some tasks fail. That is, the workflow
does not halt as soon as it encounters a failure, but continues execution of every
app that is unaffected.

For example:

.. code-block:: python

    Here's a workflow graph, where
         (X)  is runnable,
         [X]  is completed,
         (X*) is failed.
         (!X) is dependency failed

      (A)           [A]           (A)
      / \           / \           / \
    (B) (C)       [B] (C*)      [B] (C*)
     |   |   =>    |   |   =>    |   |
    (D) (E)       (D) (E)       [D] (!E)
      \ /           \ /           \ /
      (F)           (F)           (!F)

      time ----->


text:
using System.Collections.Generic;
using reexjungle.xcal.domain.models;

namespace reexjungle.xcal.tests.contracts.services
{
    public interface ICalendarTestService
    {
        VCALENDAR RandomlySchedule(VCALENDAR calendar, IEnumerable<VEVENT> events);

        IEnumerable<VCALENDAR> RandomlySchedule(IEnumerable<VCALENDAR> calendars, IEnumerable<VEVENT> events);
    }
}


text:
const EditCardDate = BlazeComponent.extendComponent({
  template() {
    return 'editCardDate';
  },

  onCreated() {
    this.error = new ReactiveVar('');
    this.card = this.data();
    this.date = new ReactiveVar(moment.invalid());
  },

  onRendered() {
    const $picker = this.$('.js-datepicker').datepicker({
      todayHighlight: true,
      todayBtn: 'linked',
      language: TAPi18n.getLanguage(),
    }).on('changeDate', function(evt) {
      this.find('#date').value = moment(evt.date).format('L');
      this.error.set('');
      this.find('#time').focus();
    }.bind(this));

    if (this.date.get().isValid()) {
      $picker.datepicker('update', this.date.get().toDate());
    }
  },

  showDate() {
    if (this.date.get().isValid())
      return this.date.get().format('L');
    return '';
  },
  showTime() {
    if (this.date.get().isValid())
      return this.date.get().format('LT');
    return '';
  },
  dateFormat() {
    return moment.localeData().longDateFormat('L');
  },
  timeFormat() {
    return moment.localeData().longDateFormat('LT');
  },

  events() {
    return [{
      'keyup .js-date-field'() {
        // parse for localized date format in strict mode
        const dateMoment = moment(this.find('#date').value, 'L', true);
        if (dateMoment.isValid()) {
          this.error.set('');
          this.$('.js-datepicker').datepicker('update', dateMoment.toDate());
        }
      },
      'keyup .js-time-field'() {
        // parse for localized time format in strict mode
        const dateMoment = moment(this.find('#time').value, 'LT', true);
        if (dateMoment.isValid()) {
          this.error.set('');
        }
      },
      'submit .edit-date'(evt) {
        evt.preventDefault();

        // if no time was given, init with 12:00
        const time = evt.target.time.value || moment(new Date().setHours(12, 0, 0)).format('LT');

        const dateString = `${evt.target.date.value} ${time}`;
        const newDate = moment(dateString, 'L LT', true);
        if (newDate.isValid()) {
          this._storeDate(newDate.toDate());
          Popup.close();
        }
        else {
          this.error.set('invalid-date');
          evt.target.date.focus();
        }
      },
      'click .js-delete-date'(evt) {
        evt.preventDefault();
        this._deleteDate();
        Popup.close();
      },
    }];
  },
});

Template.dateBadge.helpers({
  canModifyCard() {
    return Meteor.user() && Meteor.user().isBoardMember() && !Meteor.user().isCommentOnly();
  },
});

// editCardStartDatePopup
(class extends EditCardDate {
  onCreated() {
    super.onCreated();
    this.data().startAt && this.date.set(moment(this.data().startAt));
  }

  _storeDate(date) {
    this.card.setStart(date);
  }

  _deleteDate() {
    this.card.unsetStart();
  }
}).register('editCardStartDatePopup');

// editCardDueDatePopup
(class extends EditCardDate {
  onCreated() {
    super.onCreated();
    this.data().dueAt && this.date.set(moment(this.data().dueAt));
  }

  onRendered() {
    super.onRendered();
    if (moment.isDate(this.card.startAt)) {
      this.$('.js-datepicker').datepicker('setStartDate', this.card.startAt);
    }
  }

  _storeDate(date) {
    this.card.setDue(date);
  }

  _deleteDate() {
    this.card.unsetDue();
  }
}).register('editCardDueDatePopup');

// Display start & due dates
const CardDate = BlazeComponent.extendComponent({
  template() {
    return 'dateBadge';
  },

  onCreated() {
    const self = this;
    self.date = ReactiveVar();
    self.now = ReactiveVar(moment());
    window.setInterval(() => {
      self.now.set(moment());
    }, 60000);
  },

  showDate() {
    // this will start working once mquandalle:moment
    // is updated to at least moment.js 2.10.5
    // until then, the date is displayed in the "L" format
    return this.date.get().calendar(null, {
      sameElse: 'llll',
    });
  },

  showISODate() {
    return this.date.get().toISOString();
  },
});

class CardStartDate extends CardDate {
  onCreated() {
    super.onCreated();
    const self = this;
    self.autorun(() => {
      self.date.set(moment(self.data().startAt));
    });
  }

  classes() {
    if (this.date.get().isBefore(this.now.get(), 'minute') &&
        this.now.get().isBefore(this.data().dueAt)) {
      return 'current';
    }
    return '';
  }

  showTitle() {
    return `${TAPi18n.__('card-start-on')} ${this.date.get().format('LLLL')}`;
  }

  events() {
    return super.events().concat({
      'click .js-edit-date': Popup.open('editCardStartDate'),
    });
  }
}
CardStartDate.register('cardStartDate');

class CardDueDate extends CardDate {
  onCreated() {
    super.onCreated();
    const self = this;
    self.autorun(() => {
      self.date.set(moment(self.data().dueAt));
    });
  }

  classes() {
    if (this.now.get().diff(this.date.get(), 'days') >= 2)
      return 'long-overdue';
    else if (this.now.get().diff(this.date.get(), 'minute') >= 0)
      return 'due';
    else if (this.now.get().diff(this.date.get(), 'days') >= -1)
      return 'almost-due';
    return '';
  }

  showTitle() {
    return `${TAPi18n.__('card-due-on')} ${this.date.get().format('LLLL')}`;
  }

  events() {
    return super.events().concat({
      'click .js-edit-date': Popup.open('editCardDueDate'),
    });
  }
}
CardDueDate.register('cardDueDate');

(class extends CardStartDate {
  showDate() {
    return this.date.get().format('l');
  }
}).register('minicardStartDate');

(class extends CardDueDate {
  showDate() {
    return this.date.get().format('l');
  }
}).register('minicardDueDate');


text:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;

namespace System.Runtime.Remoting.Metadata.W3cXsd2001
{
    public static class __SoapMonth
    {
        public static IObservable<System.String> GetXsdType(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth> SoapMonthValue)
        {
            return Observable.Select(SoapMonthValue, (SoapMonthValueLambda) => SoapMonthValueLambda.GetXsdType());
        }

        public static IObservable<System.String> ToString(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth> SoapMonthValue)
        {
            return Observable.Select(SoapMonthValue, (SoapMonthValueLambda) => SoapMonthValueLambda.ToString());
        }

        public static IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth> Parse(
            IObservable<System.String> value)
        {
            return Observable.Select(value,
                (valueLambda) => System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth.Parse(valueLambda));
        }

        public static IObservable<System.String> get_XsdType()
        {
            return ObservableExt.Factory(() => System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth.XsdType);
        }

        public static IObservable<System.DateTime> get_Value(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth> SoapMonthValue)
        {
            return Observable.Select(SoapMonthValue, (SoapMonthValueLambda) => SoapMonthValueLambda.Value);
        }

        public static IObservable<System.Reactive.Unit> set_Value(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapMonth> SoapMonthValue,
            IObservable<System.DateTime> value)
        {
            return ObservableExt.ZipExecute(SoapMonthValue, value,
                (SoapMonthValueLambda, valueLambda) => SoapMonthValueLambda.Value = valueLambda);
        }
    }
}


text:
<!DOCTYPE html>

    <title>jakartaDEV – Daily discoveries</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1'>

    <meta name="description" content="Daily discoveries">
    <meta property="og:description" content="Daily discoveries" />

    <meta name="author" content="jakartaDEV" />

    <meta property="og:title" content="Home" />
    <meta property="twitter:title" content="Home" />

    <meta property="og:title" content="Daily discoveries dan newsletter mingguan untuk developer dan Open source enthusias"/>
    <meta property="og:locale" content="id_ID" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="http://jakartadev.org/" />
    <meta property="og:site_name" content="JakartaDEV: developement news, tech news dan open source" />
    <meta property="og:image" content="http://localhost:4000/images/logo.png" />
    <meta name="twitter:card" content="summary"/>
    <meta name="twitter:title" content="Daily discoveries dan newsletter mingguan untuk developer dan Open source enthusias"/>
    <meta name="twitter:site" content="@JakartaDev"/>
    <meta name="twitter:image" content="http://localhost:4000/images/logo.png"/>
    <meta name="twitter:creator" content="@JakartaDev"/>

    <link rel="canonical" href="http://jakartadev.org/" />
    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="jakartaDEV - Daily discoveries" href="/feed.xml" />

    <link href="https://fonts.googleapis.com/css?family=Saira+Condensed|Roboto|Lobster|Patua+One|Open+Sans|PT+Mono" rel="stylesheet">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://localhost:4000/images/apple-touch-icon-precomposed.png">
    <link rel="icon" type="image/png" href="http://localhost:4000/images/favicon.png">

jakartaDEV

Daily discoveries

            Archives
            Newsletter
            About

Daily Digest #7  <time datetime="September  5, 2016"> ‐ September  5, 2016</time>

exclusive inside look at how artificial intelligence and machine learning work at Apple

(Not) Shipping is a Virtue

The Web Methodology Project

Protecting your embedded content with subresource integrity (SRI)

Itsy Bitsy Data Structures
panduan yang mudah dibaca mengenai struktur data di javascript

The State Of JavaScript: JavaScript Flavors

Open Source Ruby Software The Slashdot Interview With Ruby on Rails Creator David Heinemeier Hansson

Examining The Internals Of The Rails Request/Response Cycle

The Duel: React Native vs. Cordova

How to set up read-write split in Galera Cluster using ProxySQL

11 Simple npm Tricks That Will Knock Your Wombat Socks Off

Installing AMP in WordPress

Tools

Appium, App Automation testing

Insomnia, Rest Client

React Components Catalog

Daily Digest #6  <time datetime="August 23, 2016"> ‐ August 23, 2016</time>

Rilis PHP 7.1.0

Rilis PHP 5.6.25

PowerShell di Linux
Microsoft merilis PowerShell di Linux, dan juga meng-_opensource_-kan PowerShell, lihat projectnya di GitHub.

Free Coding School
Dengan banyaknya e-learning, dan orang menjadi menjauh dari sisi sosial, berkurangnya human interaction, menjadikan awal mula ide sekolah ini dan di sini juga digerakkan untuk saling belajar, saling melakukan code review dan lainnya.

AWS Summit Series 2016 Video

Running Jenkins on top of a Flocker Cluster using Docker and Ansible
Cara menggunakan Flocker untuk me-manage Docker dan data secara bersamaan.

Advanced SQL in Rails - Part 1

Understanding and Hardening Linux Containers

Trello Android Schema Upgrades
Cara Trello untuk skema SQLite database tabel update di app Android Trello

Testing Your Drupal Site with Behat

ProxySQL
sekarang versi 1.2.1 General Availability.

ARQ
Job queues and RPC in python with asyncio, redis and msgpack.

Cleave.js
<input> formatting

Slate.js
Javascript framework untuk rich text editor

      ←

        →

© Copyright 2018 -- jakartadev.org -- made with ♥ by @dedenf


text:
import { BrowserClient, Transports } from '@sentry/browser';
import { Hub } from '@sentry/hub';

import {
  DEFAULT_IDLE_TIMEOUT,
  HEARTBEAT_INTERVAL,
  IdleTransaction,
  IdleTransactionSpanRecorder,
} from '../src/idletransaction';
import { Span } from '../src/span';

export class SimpleTransport extends Transports.BaseTransport {}

const dsn = 'https://123@sentry.io/42';
let hub: Hub;
beforeEach(() => {
  hub = new Hub(new BrowserClient({ dsn, tracesSampleRate: 1, transport: SimpleTransport }));
});

describe('IdleTransaction', () => {
  describe('onScope', () => {
    it('sets the transaction on the scope on creation if onScope is true', () => {
      const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT, true);
      transaction.initSpanRecorder(10);

      hub.configureScope(s => {
        expect(s.getTransaction()).toBe(transaction);
      });
    });

    it('does not set the transaction on the scope on creation if onScope is falsey', () => {
      const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
      transaction.initSpanRecorder(10);

      hub.configureScope(s => {
        expect(s.getTransaction()).toBe(undefined);
      });
    });

    it('removes sampled transaction from scope on finish if onScope is true', () => {
      const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT, true);
      transaction.initSpanRecorder(10);

      transaction.finish();
      jest.runAllTimers();

      hub.configureScope(s => {
        expect(s.getTransaction()).toBe(undefined);
      });
    });

    it('removes unsampled transaction from scope on finish if onScope is true', () => {
      const transaction = new IdleTransaction({ name: 'foo', sampled: false }, hub, DEFAULT_IDLE_TIMEOUT, true);

      transaction.finish();
      jest.runAllTimers();

      hub.configureScope(s => {
        expect(s.getTransaction()).toBe(undefined);
      });
    });
  });

  beforeEach(() => {
    jest.useFakeTimers();
  });

  it('push and pops activities', () => {
    const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
    const mockFinish = jest.spyOn(transaction, 'finish');
    transaction.initSpanRecorder(10);
    expect(transaction.activities).toMatchObject({});

    const span = transaction.startChild();
    expect(transaction.activities).toMatchObject({ [span.spanId]: true });

    expect(mockFinish).toHaveBeenCalledTimes(0);

    span.finish();
    expect(transaction.activities).toMatchObject({});

    jest.runOnlyPendingTimers();
    expect(mockFinish).toHaveBeenCalledTimes(1);
  });

  it('does not push activities if a span already has an end timestamp', () => {
    const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
    transaction.initSpanRecorder(10);
    expect(transaction.activities).toMatchObject({});

    transaction.startChild({ startTimestamp: 1234, endTimestamp: 5678 });
    expect(transaction.activities).toMatchObject({});
  });

  it('does not finish if there are still active activities', () => {
    const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
    const mockFinish = jest.spyOn(transaction, 'finish');
    transaction.initSpanRecorder(10);
    expect(transaction.activities).toMatchObject({});

    const span = transaction.startChild();
    const childSpan = span.startChild();

    expect(transaction.activities).toMatchObject({ [span.spanId]: true, [childSpan.spanId]: true });
    span.finish();
    jest.runOnlyPendingTimers();

    expect(mockFinish).toHaveBeenCalledTimes(0);
    expect(transaction.activities).toMatchObject({ [childSpan.spanId]: true });
  });

  it('calls beforeFinish callback before finishing', () => {
    const mockCallback1 = jest.fn();
    const mockCallback2 = jest.fn();
    const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
    transaction.initSpanRecorder(10);
    transaction.registerBeforeFinishCallback(mockCallback1);
    transaction.registerBeforeFinishCallback(mockCallback2);

    expect(mockCallback1).toHaveBeenCalledTimes(0);
    expect(mockCallback2).toHaveBeenCalledTimes(0);

    const span = transaction.startChild();
    span.finish();

    jest.runOnlyPendingTimers();
    expect(mockCallback1).toHaveBeenCalledTimes(1);
    expect(mockCallback1).toHaveBeenLastCalledWith(transaction, expect.any(Number));
    expect(mockCallback2).toHaveBeenCalledTimes(1);
    expect(mockCallback2).toHaveBeenLastCalledWith(transaction, expect.any(Number));
  });

  it('filters spans on finish', () => {
    const transaction = new IdleTransaction({ name: 'foo', startTimestamp: 1234 }, hub, DEFAULT_IDLE_TIMEOUT);
    transaction.initSpanRecorder(10);

    // regular child - should be kept
    const regularSpan = transaction.startChild({ startTimestamp: transaction.startTimestamp + 2 });

    // discardedSpan - startTimestamp is too large
    transaction.startChild({ startTimestamp: 645345234 });

    // Should be cancelled - will not finish
    const cancelledSpan = transaction.startChild({ startTimestamp: transaction.startTimestamp + 4 });

    regularSpan.finish(regularSpan.startTimestamp + 4);
    transaction.finish(transaction.startTimestamp + 10);

    expect(transaction.spanRecorder).toBeDefined();
    if (transaction.spanRecorder) {
      const spans = transaction.spanRecorder.spans;
      expect(spans).toHaveLength(3);
      expect(spans[0].spanId).toBe(transaction.spanId);

      // Regular Span - should not modified
      expect(spans[1].spanId).toBe(regularSpan.spanId);
      expect(spans[1].endTimestamp).not.toBe(transaction.endTimestamp);

      // Cancelled Span - has endtimestamp of transaction
      expect(spans[2].spanId).toBe(cancelledSpan.spanId);
      expect(spans[2].status).toBe('cancelled');
      expect(spans[2].endTimestamp).toBe(transaction.endTimestamp);
    }
  });

  it('should record dropped transactions', async () => {
    const transaction = new IdleTransaction({ name: 'foo', startTimestamp: 1234, sampled: false }, hub, 1000);

    const transport = hub.getClient()?.getTransport();

    const spy = jest.spyOn(transport!, 'recordLostEvent');

    transaction.initSpanRecorder(10);
    transaction.finish(transaction.startTimestamp + 10);

    expect(spy).toHaveBeenCalledWith('sample_rate', 'transaction');
  });

  describe('_initTimeout', () => {
    it('finishes if no activities are added to the transaction', () => {
      const transaction = new IdleTransaction({ name: 'foo', startTimestamp: 1234 }, hub, DEFAULT_IDLE_TIMEOUT);
      transaction.initSpanRecorder(10);

      jest.advanceTimersByTime(DEFAULT_IDLE_TIMEOUT);
      expect(transaction.endTimestamp).toBeDefined();
    });

    it('does not finish if a activity is started', () => {
      const transaction = new IdleTransaction({ name: 'foo', startTimestamp: 1234 }, hub, DEFAULT_IDLE_TIMEOUT);
      transaction.initSpanRecorder(10);
      transaction.startChild({});

      jest.advanceTimersByTime(DEFAULT_IDLE_TIMEOUT);
      expect(transaction.endTimestamp).toBeUndefined();
    });
  });

  describe('heartbeat', () => {
    it('does not mark transaction as `DeadlineExceeded` if idle timeout has not been reached', () => {
      // 20s to exceed 3 heartbeats
      const transaction = new IdleTransaction({ name: 'foo' }, hub, 20000);
      const mockFinish = jest.spyOn(transaction, 'finish');

      expect(transaction.status).not.toEqual('deadline_exceeded');
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 1
      jest.advanceTimersByTime(HEARTBEAT_INTERVAL);
      expect(transaction.status).not.toEqual('deadline_exceeded');
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 2
      jest.advanceTimersByTime(HEARTBEAT_INTERVAL);
      expect(transaction.status).not.toEqual('deadline_exceeded');
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 3
      jest.advanceTimersByTime(HEARTBEAT_INTERVAL);
      expect(transaction.status).not.toEqual('deadline_exceeded');
      expect(mockFinish).toHaveBeenCalledTimes(0);
    });

    it('finishes a transaction after 3 beats', () => {
      const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
      const mockFinish = jest.spyOn(transaction, 'finish');
      transaction.initSpanRecorder(10);

      expect(mockFinish).toHaveBeenCalledTimes(0);
      transaction.startChild({});

      // Beat 1
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 2
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 3
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(1);
    });

    it('resets after new activities are added', () => {
      const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
      const mockFinish = jest.spyOn(transaction, 'finish');
      transaction.initSpanRecorder(10);

      expect(mockFinish).toHaveBeenCalledTimes(0);
      transaction.startChild({});

      // Beat 1
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      const span = transaction.startChild(); // push activity

      // Beat 1
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 2
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      transaction.startChild(); // push activity
      transaction.startChild(); // push activity

      // Beat 1
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 2
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      span.finish(); // pop activity

      // Beat 1
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 2
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(0);

      // Beat 3
      jest.runOnlyPendingTimers();
      expect(mockFinish).toHaveBeenCalledTimes(1);

      // Heartbeat does not keep going after finish has been called
      jest.runAllTimers();
      expect(mockFinish).toHaveBeenCalledTimes(1);
    });
  });
});

describe('IdleTransactionSpanRecorder', () => {
  it('pushes and pops activities', () => {
    const mockPushActivity = jest.fn();
    const mockPopActivity = jest.fn();
    const spanRecorder = new IdleTransactionSpanRecorder(mockPushActivity, mockPopActivity, undefined, 10);
    expect(mockPushActivity).toHaveBeenCalledTimes(0);
    expect(mockPopActivity).toHaveBeenCalledTimes(0);

    const span = new Span({ sampled: true });

    expect(spanRecorder.spans).toHaveLength(0);
    spanRecorder.add(span);
    expect(spanRecorder.spans).toHaveLength(1);

    expect(mockPushActivity).toHaveBeenCalledTimes(1);
    expect(mockPushActivity).toHaveBeenLastCalledWith(span.spanId);
    expect(mockPopActivity).toHaveBeenCalledTimes(0);

    span.finish();
    expect(mockPushActivity).toHaveBeenCalledTimes(1);
    expect(mockPopActivity).toHaveBeenCalledTimes(1);
    expect(mockPushActivity).toHaveBeenLastCalledWith(span.spanId);
  });

  it('does not push activities if a span has a timestamp', () => {
    const mockPushActivity = jest.fn();
    const mockPopActivity = jest.fn();
    const spanRecorder = new IdleTransactionSpanRecorder(mockPushActivity, mockPopActivity, undefined, 10);

    const span = new Span({ sampled: true, startTimestamp: 765, endTimestamp: 345 });
    spanRecorder.add(span);

    expect(mockPushActivity).toHaveBeenCalledTimes(0);
  });

  it('does not push or pop transaction spans', () => {
    const mockPushActivity = jest.fn();
    const mockPopActivity = jest.fn();

    const transaction = new IdleTransaction({ name: 'foo' }, hub, DEFAULT_IDLE_TIMEOUT);
    const spanRecorder = new IdleTransactionSpanRecorder(mockPushActivity, mockPopActivity, transaction.spanId, 10);

    spanRecorder.add(transaction);
    expect(mockPushActivity).toHaveBeenCalledTimes(0);
    expect(mockPopActivity).toHaveBeenCalledTimes(0);
  });
});


text:
NAME="Boot Mouse Input Report"
UUID=0x2A33


text:
package com.navercorp.pinpoint.plugin.jboss;

import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.common.trace.MethodType;
import com.navercorp.pinpoint.common.util.LineNumber;

/**
 * The Class ContextInvocationMethodDescriptor.
 *
 * @author Suraj Raturi
 */
public class ContextInvocationMethodDescriptor implements MethodDescriptor {

    /** The api id. */
    private int apiId = 0;

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getMethodName()
     */
    @Override
    public String getMethodName() {
        return "";
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getClassName()
     */
    @Override
    public String getClassName() {
        return "";
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getParameterTypes()
     */
    @Override
    public String[] getParameterTypes() {
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getParameterVariableName()
     */
    @Override
    public String[] getParameterVariableName() {
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getParameterDescriptor()
     */
    @Override
    public String getParameterDescriptor() {
        return "()";
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getLineNumber()
     */
    @Override
    public int getLineNumber() {
        return LineNumber.NO_LINE_NUMBER;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getFullName()
     */
    @Override
    public String getFullName() {
        return ContextInvocationMethodDescriptor.class.getName();
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#setApiId(int)
     */
    @Override
    public void setApiId(final int apiId) {
        this.apiId = apiId;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getApiId()
     */
    @Override
    public int getApiId() {
        return apiId;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getApiDescriptor()
     */
    @Override
    public String getApiDescriptor() {
        return "Jboss Context Invocation Process";
    }

    /*
     * (non-Javadoc)
     *
     * @see com.navercorp.pinpoint.bootstrap.context.MethodDescriptor#getType()
     */
    @Override
    public int getType() {
        return MethodType.WEB_REQUEST;
    }

}