text:
/*global $serverSide */

describe('serverSide', function() {
  var _serverSide = window.$serverSide,
      emit;
  beforeEach(function() {
    window.$serverSide = true;
    window.FruitLoops = {
      emit: emit = this.spy()
    };
  });
  afterEach(function() {
    window.$serverSide = _serverSide;
  });

  describe('emit', function() {
    it('should emit on setView for non-server views', function() {
      var view = new Thorax.View(),
          layout = new Thorax.LayoutView();

      layout.setView(view);
      expect(emit.calledOnce).to.be(true);
    });
    it('should defer emit for server-side views', function() {
      var view = new Thorax.View({template: function() { return 'bar'; }}),
          layout = new Thorax.LayoutView();

      layout.setView(view, {serverRender: true});
      expect(emit.called).to.be(false);

      view = new Thorax.View({
        serverRender: true,
        template: function() { return 'bar'; }
      });
      layout.setView(view, {async: false});
      expect(emit.called).to.be(false);
    });
  });

  describe('events', function() {
    it('should NOP DOM events in server mode', function() {
      var spy = this.spy();
      var view = new Thorax.View({
        events: {
          click: spy
        },
        template: function() {
          return 'foo';
        }
      });
      $('body').append(view.$el);

      // Success under fruit-loops is not throwing above
      // Under other environments, it's not triggering the handler
      view.$el.trigger && view.$el.trigger('click');
      expect(spy.called).to.be(false);

      view.release();
    });
    it('should NOP loading in server mode', function() {
      var start = this.spy(),
          end = this.spy(),
          context = {};

      var handler = Thorax.loadHandler(start, end, context);
      handler();
      this.clock.tick(2000);
      expect(start.called).to.be(false);
      expect(end.called).to.be(false);
    });
    it('should NOP loading in server mode', function() {
      var start = this.spy(),
          end = this.spy(),
          context = {};

      var handler = Thorax.loadHandler(start, end, context);
      handler();
      this.clock.tick(2000);
      expect(start.called).to.be(false);
      expect(end.called).to.be(false);
    });
  });

  describe('rendering', function() {
    it('should track server-side rendering vs. not', function() {
      var view = new Thorax.View({template: function() { return 'foo'; }});
      view.render();
      expect(view.$el.attr('data-view-restore')).to.equal('true');

      window.$serverSide = false;
      view = new Thorax.View({template: function() { return 'foo'; }});
      view.render();
      expect(view.$el.attr('data-view-restore')).to.not.exist;
    });
  });

  describe('restore', function() {
    if ($serverSide) {
      return;
    }

    var restoreFail = sinon.spy();
    Thorax.View.on('restore:fail', restoreFail);

    var count,
        Counter = Thorax.View.extend({
          template: function() {
            return 'foo_' + count++;
          }
        }),
        SomethingElse = Thorax.View.extend({
          _name: 'somethingelse',
          template: Handlebars.compile('somethingelse')
        }),
        render,
        fixture,
        server,
        view;

    function cleanIds(view) {
      view.$('[data-model-cid]').each(function() {
        $(this).removeAttr('data-model-cid');
      });
      view.$('[data-view-restore]').each(function() {
        $(this).removeAttr('data-view-restore');
      });
      view.$('[data-server-data]').each(function() {
        $(this).removeAttr('data-server-data');
      });
    }
    function restoreView(shouldRender, shouldFail, serverShouldFail) {
      window.$serverSide = true;

      server.render();
      expectShouldFail(serverShouldFail);
      restoreFail.reset();

      var el = server.$el.clone();
      fixture.append(el);

      window.$serverSide = false;

      render.reset();
      view.restore(el, shouldRender === 'forced');
      expect(render.called).to.equal(!!shouldRender);
      expectShouldFail(shouldFail);
    }

    function expectShouldFail(shouldFail) {
      if (shouldFail && !_.isArray(shouldFail)) {
        shouldFail = [shouldFail];
      }

      expect(restoreFail.callCount).to.equal(shouldFail ? shouldFail.length : 0);
      if (shouldFail) {
        _.each(shouldFail, function(shouldFail, index) {
          var info = restoreFail.getCall(index).args[0];
          expect(info.type).to.equal(shouldFail.type);
          if ('view' in shouldFail) {
            expect(info.view).to.equal(shouldFail.view);
          }

          delete shouldFail.count;
          delete shouldFail.view;
          expect(restoreFail.calledWith(sinon.match(shouldFail))).to.be.ok();
        });
      }
    }
    function compareViews() {
      cleanIds(view);
      cleanIds(server);
      expect(view.$el.html()).to.equal(server.$el.html());
    }

    beforeEach(function() {
      restoreFail.reset();

      window.$serverSide = false;
      count = 0;

      fixture = $('
');
      $('body').append(fixture);

      render = this.spy(Thorax.View.prototype, 'render');

      Thorax.Views.registry = Thorax.View.extend({
        name: 'registry',
        template: function() {
          return 'foo ' + count++;
        }
      });
    });
    afterEach(function() {
      fixture.remove();
    });

    it('should restore views explicitly', function() {
      var el = $('
bar
');
      fixture.append(el);

      var view = new Thorax.View({
        el: '.foo-view'
      });
      expect(view.el).to.equal(el[0]);
      expect(view._renderCount).to.equal(1);
      expect(el.html()).to.equal('bar');

      el.remove();

      el = $('
bar
');
      fixture.append(el);
      view = new Thorax.View({
        el: function() {
          return '.foo-view';
        }
      });
      expect(view.el).to.equal(el[0]);
      expect(view._renderCount).to.equal(1);
      expect(el.html()).to.equal('bar');

      expectShouldFail(false);
    });
    it('should not re-render non-server elements on restore', function() {
      var el = $('
bar
');
      fixture.append(el);

      var view = new Thorax.View({
        el: '.foo-view',
        template: function() {
          return 'bat';
        }
      });
      expect(view.el).to.equal(el[0]);
      expect(view._renderCount).to.equal(0);
      expect(el.html()).to.equal('bar');
    });

    it('should restore views with a passed el', function() {
      var el = $('
bar
');
      fixture.append(el);

      var view = new Thorax.View({});
      view.restore(el);

      expect(view.el).to.equal(el[0]);
      expect(view._renderCount).to.equal(1);
      expect(el.html()).to.equal('bar');
      expectShouldFail(false);
    });

    it('should update view attributes on restore', function() {
      var el = $('
bar
');
      fixture.append(el);

      var spy = this.spy();
      var view = new Thorax.View({
        events: {
          click: spy
        }
      });
      view.restore(el);

      expect(view.$el.attr('data-view-cid')).to.equal(view.cid);
    });

    if (!$serverSide) {
      it('should restore DOM events', function() {
        var el = $('
bar
');
        fixture.append(el);

        var spy = this.spy();
        var view = new Thorax.View({
          events: {
            click: spy
          }
        });
        view.restore(el);

        el.trigger('click');
        expect(spy.calledOnce).to.be(true);
      });
    }

    it('should replace restore of rendered view', function() {
      var el = $('
bar
');
      fixture.append(el);

      var view = new Thorax.View({});
      view.render('foo');
      view.restore(el);

      var el = fixture.find('div');
      expect(view.el).to.equal(el[0]);
      expect(view._renderCount).to.equal(1);
      expect(el.html()).to.equal('foo');
      expect(view.$el.attr('data-view-restore')).to.not.exist;

      expectShouldFail({
        type: 'previously-rendered',
        view: view
      });
    });

    describe('setView', function() {
      var layout,
          view;
      beforeEach(function() {
        layout = new Thorax.LayoutView();
        layout.render();

        view = new Thorax.View({
          name: 'winning',
          template: function() {
            return 'not winning';
          }
        });
      });
      it('should restore matching views', function() {
        var $el = $('
winning
');
        layout.$el.append($el);

        layout.setView(view);
        expect(view.$el.html()).to.equal('winning');
        expect(layout._view).to.equal(view);
        expect(layout.$el.children().length).to.equal(1);
        expect(layout.$el.text()).to.equal('winning');
      });
      it('should rerenderd matching views on forced', function() {
        var $el = $('
winning
');
        layout.$el.append($el);
        layout.restore(layout.el, true);

        layout.setView(view);
        expect(view.$el.html()).to.equal('not winning');
        expect(layout._view).to.equal(view);
        expect(layout.$el.children().length).to.equal(1);
        expect(layout.$el.text()).to.equal('not winning');
      });
      it('should rerender non-matching views', function() {
        var $el = $('
winning
');
        layout.$el.append($el);

        layout.setView(view);
        expect(view.$el.html()).to.equal('not winning');
        expect(layout._view).to.equal(view);
        expect(layout.$el.children().length).to.equal(1);
        expect(layout.$el.text()).to.equal('not winning');
      });
      it('should rerender non-server views', function() {
        var $el = $('
winning
');
        layout.$el.append($el);

        layout.setView(view);
        expect(view.$el.html()).to.equal('not winning');
        expect(layout._view).to.equal(view);
        expect(layout.$el.children().length).to.equal(1);
        expect(layout.$el.text()).to.equal('not winning');
      });
    });

    describe('view helper', function() {
      beforeEach(function() {
        window.$serverSide = true;
      });
      describe('registry', function() {
        it('should rerender anonymous block', function() {
          var View = Thorax.View.extend({
            template: Handlebars.compile('{{#view}}something{{/view}}', {trackIds: true})
          });

          server = new View();
          view = new View();
          restoreView(false);

          compareViews();
          expect(_.keys(view.children).length).to.equal(1);
          expect(_.values(view.children)[0].$el.html()).to.equal('something');
          expect(view._renderCount).to.equal(1);
        });

        it('should restore views instantiated through the registry', function() {
          server = new Thorax.View({
            template: Handlebars.compile('{{view "registry"}}')
          });
          view = new SomethingElse();
          restoreView();

          compareViews();
          expect(_.keys(view.children).length).to.equal(1);
          expect(_.values(view.children)[0]).to.be.a(Thorax.Views.registry);
        });
        it('should include view args when instantiating view', function() {
          server = new Thorax.View({
            template: Handlebars.compile('{{view "registry" key=4}}', {trackIds: true})
          });
          view = new SomethingElse();
          restoreView();

          expect(_.values(view.children)[0].key).to.equal(4);
        });
        it('should restore named complex args', function() {
          server = new Thorax.View({
            foo: {
              yes: false
            },
            template: Handlebars.compile('{{view "registry" key=4 bar=foo}}', {trackIds: true})
          });
          view = new SomethingElse({
            foo: {
              yes: true
            }
          });
          restoreView();

          expect(_.values(view.children)[0].key).to.equal(4);
          expect(_.values(view.children)[0].bar).to.equal(view.foo);
        });
        it('should restore passed classes', function() {
          var View = Thorax.View.extend({
            template: Handlebars.compile('{{view ChildClass}}', {trackIds: true})
          });

          server = new View({
            context: function() {
              return {
                ChildClass: Counter
              };
            }
          });
          view = new View({
            context: function() {
              return {
                ChildClass: SomethingElse
              };
            }
          });
          restoreView();

          compareViews();
          expect(_.keys(view.children).length).to.equal(1);
        });
      });
      it('should restore named references', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{view child}}', {trackIds: true})
        });

        server = new View({
          child: new Counter()
        });
        view = new View({
          child: new SomethingElse()
        });
        restoreView();

        compareViews();
        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.child);
      });
      it('should restore pathed named references', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{view parentObj.child}}', {trackIds: true})
        });

        server = new View({
          parentObj: {
            child: new Counter()
          }
        });
        view = new View({
          parentObj: {
            child: new SomethingElse()
          }
        });
        restoreView();

        compareViews();
        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.parentObj.child);
      });
      it('should restore context responses', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{view child}}', {trackIds: true})
        });
        var child = new SomethingElse();

        server = new View({
          context: function() {
            return {
              child: new Counter()
            };
          }
        });
        view = new View({
          context: function() {
            return {
              child: child
            };
          }
        });
        restoreView();

        compareViews();
        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(child);
      });
      it('should restore named references within iterators', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{#each parentObj}}{{view .}}{{/each}}', {trackIds: true})
        });

        server = new View({
          parentObj: {
            child: new Counter()
          }
        });
        view = new View({
          parentObj: {
            child: new SomethingElse()
          }
        });
        restoreView();

        compareViews();
        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.parentObj.child);
      });
      it('should rerender ../ depthed references', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{#each parentObj}}{{view ../parentObj.child}}{{/each}}', {trackIds: true})
        });

        server = new View({
          parentObj: {
            child: new Counter()
          }
        });
        view = new View({
          parentObj: {
            child: new SomethingElse()
          }
        });
        restoreView(true, {
          count: 1,
          type: 'remaining',
          view: view
        }, {
          count: 1,
          type: 'serialize',
          view: server.parentObj.child
        });

        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.parentObj.child);
        expect(view.parentObj.child.$el.html()).to.equal('somethingelse');
        expect(view._renderCount).to.equal(2);
      });
      it('should restore block view helpers', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{#view child}}something{{/view}}', {trackIds: true})
        });

        server = new View({
          child: new Counter()
        });
        view = new View({
          child: new SomethingElse()
        });
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.child);
        expect(server.child.$el.html()).to.equal('something');
        expect(view.child.$el.html()).to.equal('something');
        expect(view._renderCount).to.equal(1);
      });
      it('should rerender block view helper with depth', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{#view child}}{{../root}}{{/view}}', {trackIds: true}),
          root: 1
        });

        server = new View({
          child: new Counter()
        });
        view = new View({
          child: new SomethingElse(),
          root: 2
        });
        restoreView(true, {
          type: 'remaining',
          view: view
        }, {
          type: 'serialize',
          view: server.child
        });

        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.child);
        expect(server.child.$el.html()).to.equal('1');
        expect(view.child.$el.html()).to.equal('2');
        expect(view._renderCount).to.equal(2);
      });
      it('should restore block view helper with data', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{#view child}}{{@cid}}{{/view}}', {trackIds: true})
        });

        server = new View({
          child: new Counter()
        });
        view = new View({
          child: new SomethingElse()
        });
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.child);
        expect(view._renderCount).to.equal(1);
      });

      it('should handle partial restore', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{view theGoodOne}}{{view (ambiguousResponse child)}}', {trackIds: true}),
          ambiguousResponse: function(child) {
            return child;
          }
        });

        server = new View({
          theGoodOne: new Counter(),
          child: new Counter()
        });
        view = new View({
          theGoodOne: new SomethingElse(),
          child: new SomethingElse()
        });
        restoreView(true, {
          type: 'remaining',
          view: view
        }, {
          type: 'serialize',
          view: server.child
        });

        expect(_.keys(view.children).length).to.equal(2);
        expect(_.values(view.children)[0]).to.equal(view.theGoodOne);
        expect(_.values(view.children)[1]).to.equal(view.child);
        expect(view.child.$el.html()).to.equal('somethingelse');
        expect(view.theGoodOne.$el.html()).to.equal('foo_0');
        expect(view._renderCount).to.equal(2);
      });

      it('should restore nested views properly', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{view "nested"}}', {trackIds: true})
        });

        Thorax.Views.nested = Thorax.View.extend({
          name: 'nested',
          template: Handlebars.compile('{{view child}}', {trackIds: true}),

          initialize: function() {
            this.child = new Counter();
          }
        });

        server = new View();
        view = new View();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var nested = _.values(view.children)[0];
        expect(nested.name).to.equal('nested');
        expect(nested.child.$el.html()).to.equal('foo_0');
      });
      it('should rerender views using subexpressions', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{view (ambiguousResponse child)}}', {trackIds: true}),
          ambiguousResponse: function(view) {
            return view;
          }
        });

        server = new View({
          child: new Counter()
        });
        view = new View({
          child: new SomethingElse()
        });
        restoreView(true, {
          count: 1,
          type: 'remaining',
          view: view
        }, {
          count: 1,
          type: 'serialize',
          view: server.child
        });

        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(view.child);
        expect(server.child.$el.html()).to.equal('foo_0');
        expect(view.child.$el.html()).to.equal('somethingelse');
        expect(view._renderCount).to.equal(2);
      });

      it('should rerender lookup templates if lacking trackId', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{view child}}')
        });
        var child = new SomethingElse(),
            serverChild = new Counter();

        server = new View({
          context: function() {
            return {
              child: serverChild
            };
          }
        });
        view = new View({
          context: function() {
            return {
              child: child
            };
          }
        });
        restoreView(true, {
          count: 1,
          type: 'remaining',
          view: view
        }, {
          count: 1,
          type: 'serialize',
          view: serverChild
        });

        expect(_.keys(view.children).length).to.equal(1);
        expect(_.values(view.children)[0]).to.equal(child);
      });
    });
    describe('collection views', function() {
      var collection1,
          collection2,
          collectionSpy,
          itemSpy,
          emptySpy;
      beforeEach(function() {
        window.$serverSide = true;
        count = 0;

        collection1 = new Thorax.Collection([{id: 1}, {id: 2}, {id: 3}, {id: 4}]);
        collection2 = new Thorax.Collection([{id: 1}, {id: 2}, {id: 3}, {id: 4}]);
      });

      function registerEvents() {
        collectionSpy = sinon.spy();
        itemSpy = sinon.spy();
        emptySpy = sinon.spy();

        view.on('restore:collection', collectionSpy);
        view.on('restore:item', itemSpy);
        view.on('restore:empty', emptySpy);
      }
      function expectEvents(collection, item, empty) {
        expect(collectionSpy.callCount).to.equal(collection);
        expect(itemSpy.callCount).to.equal(item);
        expect(emptySpy.callCount).to.equal(empty);
      }

      it('should restore inline views', function() {
        server = new Thorax.View({
          template: Handlebars.compile('{{#collection}}something{{/collection}}', {trackIds: true}),
          collection: collection1
        });
        view = new Thorax.View({
          template: Handlebars.compile('{{#collection}}somethingelse{{/collection}}', {trackIds: true}),
          collection: collection2
        });

        registerEvents();
        restoreView();
        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(collection2);
        expect(_.keys(collectionView.children).length).to.equal(0);
        expect(collectionView.itemTemplate()).to.equal('somethingelse');

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expect(view.$el.children().text()).to.equal('somethingsomethingsomethingsomething');
        expectEvents(1, 4, 0);
        compareViews();
      });
      it('should restore referenced templates', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection tag="ul" empty-template="letter-empty" item-template="letter-item"}}')
        });
        server = new View({collection: collection1});
        view = new View({collection: collection2});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(collection2);
        expect(collectionView.itemTemplate).to.equal(Thorax.Util.getTemplate('letter-item'));
        expect(collectionView.emptyTemplate).to.equal(Thorax.Util.getTemplate('letter-empty'));

        expect(_.keys(collectionView.children).length).to.equal(0);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();
      });
      it('should restore implicit named templates', function() {
        var _ItemView = Thorax.Views['letter-item'];
        Thorax.Views['letter-item'] = undefined;

        var View = Thorax.View.extend({
          name: 'letter',
          template: Handlebars.compile('{{collection tag="ul"}}')
        });
        server = new View({collection: collection1});
        view = new View({collection: collection2});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(collection2);
        expect(collectionView.itemTemplate).to.equal(Thorax.Util.getTemplate('letter-item'));
        expect(collectionView.emptyTemplate).to.equal(Thorax.Util.getTemplate('letter-empty'));

        expect(_.keys(collectionView.children).length).to.equal(0);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();

        Thorax.Views['letter-item'] = _ItemView;
      });
      it('should restore implicit item views', function() {
        var View = Thorax.View.extend({
          name: 'letter',
          template: Handlebars.compile('{{collection tag="ul"}}')
        });
        server = new View({collection: collection1});
        view = new View({collection: collection2});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(collection2);
        expect(collectionView.itemView).to.equal(Thorax.Util.getViewClass('letter-item'));
        expect(collectionView.emptyView).to.equal(Thorax.Util.getViewClass('letter-empty'));

        expect(_.keys(collectionView.children).length).to.equal(4);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();
      });
      it('should restore referenced item-view', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection tag="ul" empty-view="letter-empty" item-view=ChildView}}', {trackIds: true}),
          ChildView: Thorax.Util.getViewClass('letter-item')
        });
        server = new View({collection: collection1});
        view = new View({collection: collection2});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.itemView).to.equal(view.ChildView);
        expect(collectionView.emptyView).to.equal('letter-empty');

        expect(_.keys(collectionView.children).length).to.equal(4);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();
      });
      it('should restore registry item-view', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection tag="ul" empty-view="letter-empty" item-view="letter-item"}}')
        });
        server = new View({collection: collection1});
        view = new View({collection: collection2});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.itemView).to.equal('letter-item');
        expect(collectionView.emptyView).to.equal('letter-empty');

        expect(_.keys(collectionView.children).length).to.equal(4);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();
      });
      it('should restore renderItem views', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection}}')
        });
        server = new View({
          collection: collection1,
          renderItem: function() {
            return new Counter();
          }
        });
        view = new View({
          collection: collection2,
          renderItem: function() {
            return new SomethingElse();
          }
        });
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(_.keys(collectionView.children).length).to.equal(4);
        expect(_.every(collectionView.children, function(value) {
          return value._name === 'somethingelse';
        })).to.be(true);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();
      });
      it('should force restore renderItem views', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection}}')
        });
        server = new View({
          collection: collection1,
          renderItem: function() {
            return new Counter();
          }
        });
        view = new View({
          collection: collection2,
          renderItem: function() {
            return new SomethingElse();
          }
        });
        registerEvents();
        restoreView('forced');

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(_.keys(collectionView.children).length).to.equal(4);
        expect(_.every(collectionView.children, function(value) {
          return value._name === 'somethingelse';
        })).to.be(true);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        expect(view.$el.text()).to.equal('somethingelsesomethingelsesomethingelsesomethingelse');
      });
      it('should restore renderItem strings', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection}}')
        });
        server = new View({
          collection: collection1,
          renderItem: function() {
            return '
foo
';
          }
        });
        view = new View({
          collection: collection2,
          renderItem: function() {
            return '
bar
';
          }
        });
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        expect(view.$el.text()).to.equal('foofoofoofoo');

        var viewCids = _.map(view.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();
      });
      it('should restore empty-template', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection tag="ul" empty-template="letter-empty" item-template="letter-item"}}')
        });
        server = new View({collection: new Thorax.Collection()});
        server.render();
        view = new View({collection: new Thorax.Collection()});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(view.collection);
        expect(collectionView.itemTemplate).to.equal(Thorax.Util.getTemplate('letter-item'));
        expect(collectionView.emptyTemplate).to.equal(Thorax.Util.getTemplate('letter-empty'));

        expect(_.keys(collectionView.children).length).to.equal(0);

        expectEvents(1, 0, 0);
        compareViews();
      });
      it('should restore empty-view', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection tag="ul" empty-view="letter-empty" item-template="letter-item"}}')
        });
        server = new View({collection: new Thorax.Collection()});
        view = new View({collection: new Thorax.Collection()});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(view.collection);
        expect(collectionView.itemTemplate).to.equal(Thorax.Util.getTemplate('letter-item'));
        expect(collectionView.emptyView).to.equal('letter-empty');

        expect(_.keys(collectionView.children).length).to.equal(1);

        expectEvents(1, 0, 1);
        compareViews();
      });
      it('should restore renderEmpty', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection tag="ul" item-template="letter-item"}}')
        });

        server = new View({
          collection: new Thorax.Collection(),
          renderEmpty: function() {
            return new Counter();
          }
        });
        view = new View({
          collection: new Thorax.Collection(),
          renderEmpty: function() {
            return new SomethingElse();
          }
        });
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(view.collection);
        expect(collectionView.itemTemplate).to.equal(Thorax.Util.getTemplate('letter-item'));

        expect(_.keys(collectionView.children).length).to.equal(1);

        expectEvents(1, 0, 1);
        compareViews();
      });
      it('should restore over non-default collection name', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('{{collection foo tag="ul" empty-view="letter-empty" item-view="letter-item"}}', {trackIds: true})
        });
        server = new View({foo: collection1});
        view = new View({foo: collection2});
        registerEvents();
        restoreView();

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.itemView).to.equal('letter-item');
        expect(collectionView.emptyView).to.equal('letter-empty');

        expect(_.keys(collectionView.children).length).to.equal(4);

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expectEvents(1, 4, 0);
        compareViews();
      });

      it('should rerender items for inline view helper with depth', function() {
        server = new Thorax.View({
          template: Handlebars.compile('
this
{{#collection}}{{../foo}}something{{/collection}}', {trackIds: true}),
          collection: collection1
        });
        view = new Thorax.View({
          template: Handlebars.compile('
that
{{#collection}}{{../foo}}somethingelse{{/collection}}', {trackIds: true}),
          collection: collection2
        });
        restoreView(true, {
          type: 'remaining',
          view: view
        }, {
          type: 'serialize',
          err: 'collection-depthed-query'
        });

        expect(view.$el.children().length).to.equal(2);
        expect(view.$el.children().eq(0).text()).to.equal('that');

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(collection2);
        expect(_.keys(collectionView.children).length).to.equal(0);
        expect(collectionView.itemTemplate()).to.equal('somethingelse');

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));

        expect(view.$el.text()).to.equal('thatsomethingelsesomethingelsesomethingelsesomethingelse');

        expectEvents(1, 4, 0);
      });
      it.skip('should rerender block view helper with data', function() {
        server = new Thorax.View({
          template: Handlebars.compile('
this
{{#collection}}{{@foo}}something{{/collection}}', {trackIds: true}),
          collection: collection1
        });
        view = new Thorax.View({
          template: Handlebars.compile('
that
{{#collection}}{{@foo}}somethingelse{{/collection}}', {trackIds: true}),
          collection: collection2
        });
        restoreView(true);

        expect(view.$el.children().length).to.equal(2);
        expect(view.$el.children().eq(0).text()).to.equal('that');

        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(collection2);
        expect(_.keys(collectionView.children).length).to.equal(0);
        expect(collectionView.itemTemplate()).to.equal('somethingelse');

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));

        expect(view.$el.text()).to.equal('thatsomethingelsesomethingelsesomethingelsesomethingelse');

        expectEvents(1, 4, 0);
      });

      it('should rerender collections where elements are missing ids', function() {
        collection2 = new Thorax.Collection([{id: 1}, {id: 6}, {id: 3}, {id: 4}]);

        server = new Thorax.View({
          template: Handlebars.compile('{{#collection}}{{id}}. something{{/collection}}', {trackIds: true}),
          collection: collection1
        });
        view = new Thorax.View({
          template: Handlebars.compile('{{#collection}}somethingelse{{/collection}}', {trackIds: true}),
          collection: collection2
        });
        registerEvents();
        restoreView(false, [
          {type: 'collection-remove'},
          {type: 'collection-missing'}
        ]);
        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(collection2);
        expect(_.keys(collectionView.children).length).to.equal(0);
        expect(collectionView.itemTemplate()).to.equal('somethingelse');

        var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expect(view.$el.children().text()).to.equal('1. somethingsomethingelse3. something4. something');

        expectEvents(1, 3, 0);
      });

      describe('data loading', function() {
        it('should defer rerender for collections loading on the client side', function() {
          collection2 = new (Thorax.Collection.extend({url: 'foo'}))();

          server = new Thorax.View({
            template: Handlebars.compile('{{#collection}}{{id}}. something{{/collection}}', {trackIds: true}),
            collection: collection1
          });
          view = new Thorax.View({
            template: Handlebars.compile('{{#collection}}somethingelse{{/collection}}', {trackIds: true}),
            collection: collection2
          });
          registerEvents();
          restoreView(false);
          expect(_.keys(view.children).length).to.equal(1);

          var collectionView = _.values(view.children)[0];
          expect(collectionView.collection).to.equal(collection2);
          expect(_.keys(collectionView.children).length).to.equal(0);
          expect(collectionView.itemTemplate()).to.equal('somethingelse');

          expect(view.$el.children().text()).to.equal('1. something2. something3. something4. something');

          expectEvents(0, 0, 0);

          collection2.reset([{id: 1}, {id: 6}, {id: 3}, {id: 4}]);

          expectEvents(1, 3, 0);

          var viewCids = _.map(collectionView.$('[data-model-cid]'), function(el) {
            return el.getAttribute('data-model-cid');
          });
          expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
          expect(view.$el.children().text()).to.equal('1. somethingsomethingelse3. something4. something');
        });
        it('render properly when collection is not loaded on the server and loaded before restore on the client', function() {
          collection1 = new Thorax.Collection();

          server = new Thorax.View({
            template: Handlebars.compile('{{#collection}}{{id}}. something{{/collection}}', {trackIds: true}),
            collection: collection1
          });
          view = new Thorax.View({
            template: Handlebars.compile('{{#collection}}somethingelse{{/collection}}', {trackIds: true}),
            collection: collection2
          });
          registerEvents();
          restoreView(false, [
            {type: 'collection-missing'},
            {type: 'collection-missing'},
            {type: 'collection-missing'},
            {type: 'collection-missing'}
          ]);
          expect(_.keys(view.children).length).to.equal(1);

          var collectionView = _.values(view.children)[0];
          expect(collectionView.collection).to.equal(collection2);
          expect(_.keys(collectionView.children).length).to.equal(0);
          expect(collectionView.itemTemplate()).to.equal('somethingelse');

          expectEvents(1, 0, 0);

          expect(view.$el.children().text()).to.equal('somethingelsesomethingelsesomethingelsesomethingelse');
        });
      });

      it('should handle nested collections', function() {
        var rootCollection1 = new Thorax.Collection([
          {id:'a', child: collection1},
          {id:'b', child: collection1}
        ]);
        var rootCollection2 = new Thorax.Collection([
          {id:'a', child: collection2},
          {id:'b', child: collection2}
        ]);

        var Child1 = Thorax.View.extend({
          template: Handlebars.compile('{{#collection child}}something{{/collection}}', {trackIds: true})
        });
        var Child2 = Thorax.View.extend({
          template: Handlebars.compile('{{#collection child}}somethingelse{{/collection}}', {trackIds: true})
        });

        server = new Thorax.View({
          template: Handlebars.compile('{{collection}}', {trackIds: true}),
          itemView: Child1,
          collection: rootCollection2
        });
        view = new Thorax.View({
          template: Handlebars.compile('{{collection}}', {trackIds: true}),
          itemView: Child2,
          collection: rootCollection2
        });

        registerEvents();
        restoreView();
        expect(_.keys(view.children).length).to.equal(1);

        var collectionView = _.values(view.children)[0];
        expect(collectionView.collection).to.equal(rootCollection2);
        expect(_.keys(collectionView.children).length).to.equal(2);

        var childView = _.values(collectionView.children)[0];
        expect(childView.model.attributes.child).to.equal(collection2);
        expect(_.keys(childView.children).length).to.equal(1);

        var childCollectionView = _.values(childView.children)[0];
        expect(childCollectionView.collection).to.equal(collection2);
        expect(_.keys(childCollectionView.children).length).to.equal(0);
        expect(childCollectionView.itemTemplate()).to.equal('somethingelse');

        var viewCids = _.map(childCollectionView.$('[data-model-cid]'), function(el) {
          return el.getAttribute('data-model-cid');
        });
        expect(viewCids).to.eql(collection2.map(function(model) { return model.cid; }));
        expect(view.$el.children().text()).to.equal('somethingsomethingsomethingsomethingsomethingsomethingsomethingsomething');
        expectEvents(1, 2, 0);
        compareViews();
      });
    });

    it('should cooperate with custom restore events', function() {
      window.$serverSide = true;

      var View = Thorax.View.extend({
        template: Handlebars.compile('{{view child}}', {trackIds: true})
      });
      var child = new SomethingElse({
        restore: function(el) {
          this.setElement(el);
          this.$el.removeAttr('data-view-restore');

          this.$el.text('winning!');
          return true;
        }
      });

      server = new View({
        child: new Counter(),
        context: function() {
          return {
            child: this.child
          };
        }
      });
      view = new View({
        context: function() {
          return {
            child: child
          };
        }
      });
      restoreView();

      expect(view.$el.text()).to.equal('winning!');
      expect(child.$el.attr('data-view-cid')).to.equal(server.child.cid);
    });

    it('should recover views on client-side parent rerender', function() {
      window.$serverSide = true;

      server = new Thorax.View({
        foo: {
          yes: false
        },
        template: Handlebars.compile('{{view "registry" key=4 bar=foo}}', {trackIds: true})
      });
      view = new SomethingElse({
        foo: {
          yes: true
        },
        template: Handlebars.compile('{{view "registry" key=4 bar=foo}}', {trackIds: true})
      });
      restoreView();

      var restored = _.values(view.children)[0];
      expect(restored.key).to.equal(4);
      expect(restored.bar).to.equal(view.foo);

      view.render();
      expect(_.values(view.children)).to.eql([restored]);
    });

    it('should handle forced restore', function() {
      var View = Thorax.View.extend({
        template: Handlebars.compile('

{{view child}}', {trackIds: true})
      });

      server = new View({
        theGoodOne: new Counter(),
        child: new Counter()
      });
      view = new View({
        events: {
          'after-restore': function() {
            this.$('.foo').addClass('bar');
          }
        },
        child: new SomethingElse()
      });

      restoreView('forced');

      expect(server.$('.foo.bar')).to.be.empty();
      expect(view.$('.foo.bar')).to.not.be.empty();

      var restored = _.values(view.children)[0];
      expect(restored.$el.html()).to.equal('somethingelse');
      expect(view._renderCount).to.equal(2);
    });

    describe('after-restore', function() {
      it('should handle restore', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('

{{view child}}', {trackIds: true})
        });

        server = new View({
          theGoodOne: new Counter(),
          child: new Counter()
        });
        view = new View({
          events: {
            'after-restore': function() {
              this.$('.foo').addClass('bar');
            }
          },
          child: new SomethingElse()
        });

        restoreView();

        expect(server.$('.foo.bar')).to.be.empty();
        expect(view.$('.foo.bar')).to.not.be.empty();
        expect(view._renderCount).to.equal(1);
      });
      it('should handle partial restore', function() {
        var View = Thorax.View.extend({
          template: Handlebars.compile('

{{view (ambiguousResponse child)}}', {trackIds: true}),
          ambiguousResponse: function(child) {
            return child;
          }
        });

        server = new View({
          theGoodOne: new Counter(),
          child: new Counter()
        });
        view = new View({
          events: {
            'after-restore': function() {
              this.$('.foo').addClass('bar');
            }
          },
          child: new SomethingElse()
        });

        restoreView(true, {
          type: 'remaining',
          view: view
        }, {
          type: 'serialize',
          view: server.child
        });

        expect(server.$('.foo.bar')).to.be.empty();
        expect(view.$('.foo.bar')).to.not.be.empty();
        expect(view._renderCount).to.equal(2);
      });
    });
  });
});


text:
{{-- Pterodactyl - Panel --}}
{{-- Copyright (c) 2015 - 2017 Dane Everitt <dane@daneeveritt.com> --}}

{{-- This software is licensed under the terms of the MIT license. --}}
{{-- https://opensource.org/licenses/MIT --}}
@extends('layouts.admin')

@section('title')
    Egg → {{ $egg->name }} → Variables
@endsection

@section('content-header')

{{ $egg->name }}Managing variables for this Egg.

Admin

Nests

nest->id) }}">{{ $egg->nest->name }}

id) }}">{{ $egg->name }}

Variables

@endsection

@section('content')

id) }}">Configuration

id) }}">Variables

id) }}">Install Script

                Create New Variable

    @foreach($egg->variables as $variable)

{{ $variable->name }}

                <form action="{{ route('admin.nests.egg.variables.edit', ['egg' => $egg->id, 'variable' => $variable->id]) }}" method="POST">

                            Name
                            <input type="text" name="name" value="{{ $variable->name }}" class="form-control" />

                            Description
                            <textarea name="description" class="form-control" rows="3">{{ $variable->description }}</textarea>

                                Environment Variable
                                <input type="text" name="env_variable" value="{{ $variable->env_variable }}" class="form-control" />

                                Default Value
                                <input type="text" name="default_value" value="{{ $variable->default_value }}" class="form-control" />

This variable can be accessed in the startup command by using {{ $variable->env_variable }}.

                            Permissions
                            <select name="options[]" class="pOptions form-control" multiple>
                                <option value="user_viewable" {{ (! $variable->user_viewable) ?: 'selected' }}>Users Can View</option>
                                <option value="user_editable" {{ (! $variable->user_editable) ?: 'selected' }}>Users Can Edit</option>
                            </select>

                            Input Rules
                            <input type="text" name="rules" class="form-control" value="{{ $variable->rules }}" />

These rules are defined using standard Laravel Framework validation rules.

                        {!! csrf_field() !!}
                        <button class="btn btn-sm btn-primary pull-right" name="_method" value="PATCH" type="submit">Save</button>
                        <button class="btn btn-sm btn-danger pull-left muted muted-hover" data-action="delete" name="_method" value="DELETE" type="submit"></button>

                </form>

    @endforeach

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Create New Egg Variable

            <form action="{{ route('admin.nests.egg.variables', $egg->id) }}" method="POST">

                        Name
                        <input type="text" name="name" class="form-control" value="{{ old('name') }}"/>

                        Description
                        <textarea name="description" class="form-control" rows="3">{{ old('description') }}</textarea>

                            Environment Variable
                            <input type="text" name="env_variable" class="form-control" value="{{ old('env_variable') }}" />

                            Default Value
                            <input type="text" name="default_value" class="form-control" value="{{ old('default_value') }}" />

This variable can be accessed in the startup command by entering @{{environment variable value}}.

                        Permissions
                        <select name="options[]" class="pOptions form-control" multiple>
                            <option value="user_viewable">Users Can View</option>
                            <option value="user_editable">Users Can Edit</option>
                        </select>

                        Input Rules
                        <input type="text" name="rules" class="form-control" value="{{ old('rules', 'required|string|max:20') }}" placeholder="required|string|max:20" />

These rules are defined using standard Laravel Framework validation rules.

                    {!! csrf_field() !!}
                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Create Variable</button>

            </form>

@endsection

@section('footer-scripts')
    @parent

@endsection

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file
 *
 * This template class provides reference counting based heap allocation
 * for objects.
 */

/******************************************************************************
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/
#ifndef _QCC_MANAGEDOBJ_H
#define _QCC_MANAGEDOBJ_H

#include <qcc/platform.h>

#if defined(QCC_OS_ANDROID)
// This must be included before #include <new> for building on Froyo with
// certain versions of STLPort.
#include <stdlib.h>
#endif

#include <new>

#include <stdlib.h>
#include <assert.h>

#include <qcc/atomic.h>

namespace qcc {
#if defined(QCC_OS_GROUP_WINDOWS)
/*
 * pragmas in the code should be avoided.  This pragma is only being used in
 * this specific situation because. When compiling code on Visual Studio the
 * fact that ManagedObj has two copy constructors will cause the compiler to
 * generate two 4521 errors everytime a ManagedObj is used in the code.
 * Resulting in hundreds of warnings. The extra copy constructor exists to avoid
 * ambiguity with the ManagedObj<T>(A1& arg) constructor and can not be removed
 * without breaking the code.
 */
#pragma warning(push)
#pragma warning(disable: 4521)
#endif
/**
 * ManagedObj manages heap allocation and reference counting for a template parameter type T.
 * ManagedObj@<T@> allocates T and sets its reference count to 1 when it is created. Each time the
 * managed object is passed by value or otherwise copied (which is an inexpensive operation), the
 * underlying heap allocated T's reference count is incremented. Each time a ManagedObj instance
 * is destructed, the underlying T reference count is decremented. When the reference count reaches
 * zero, T itself is deallocated using delete.
 */
template <typename T>
class ManagedObj {
  private:

    static const uint32_t ManagedCtxMagic = (('M') | ('C' << 8) | (('T' << 16)  + ('X' << 24)));

    struct ManagedCtx {
        ManagedCtx(int32_t refCount) : refCount(refCount), magic(ManagedCtxMagic) { }
        volatile int32_t refCount;
        uint32_t magic;
    };

    ManagedCtx* context;
    T* object;

  public:

    /** The underlying type that is being managed */
    typedef T ManagedType;

    /** Copy constructor */
    ManagedObj<T>(const ManagedObj<T>&copyMe)
    {
        context = copyMe.context;
        object = copyMe.object;
        IncRef();
    }

    /** non-const Copy constructor needed to avoid ambiguity with ManagedObj<T>(A1& arg) constructor */
    ManagedObj<T>(ManagedObj<T>&copyMe)
    {
        context = copyMe.context;
        object = copyMe.object;
        IncRef();
    }

    /**
     * Create a copy of managed object T.
     *
     * If isDeep is true
     * Create a deep (clone) copy of a managed object.
     * A ManagedObject created using this constructor copies the underlying T
     * object and wraps it in a new ManagedObject with 1 reference.
     *
     * if isDeep is false
     * Do not make a deep copy of the managed object instead make a new reference
     * to the existing object and increment the reference counter by +1.
     *
     * @param other   ManagedObject to make a copy of.
     * @param isDeep  Specify if this is a deep (clone) copy or a normal copy
     */
    ManagedObj<T>(const ManagedObj<T>&other, bool isDeep)
    {
        if (isDeep) {
            /* Deep copy */
            const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
            context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
            if (NULL == context) {
                abort();
            }
            context = new (context) ManagedCtx(1);
            object = new ((char*)context + offset)T(*other);
        } else {
            /* Normal copy constructor (inc ref) of existing object */
            context = other.context;
            object = other.object;
            IncRef();
        }
    }

    /** Allocate T() on the heap and set its reference count to 1. */
    ManagedObj<T>()
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T();
    }

    /**
     * Static method to wrap an existing T that is already managed in its managed object type.
     * This method is typically called from within a method of the inner T class to provide
     * a managed object instance that can be passed to methods that required that type.
     *
     * @param naked  A unwrapped managed object instance.
     * @returns      The managed object instance re-wrapped in a ManageObj template class
     */
    static ManagedObj<T> wrap(T* naked)
    {
        static const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        return ManagedObj<T>((ManagedCtx*)((char*)naked - offset), naked);
    }

    /**
     * Static method to convert between managed objects of related types.
     *
     * @param other  A managed object instance of a related type.
     * @returns      A managed object cast to the required type
     */
    template <class T2> static ManagedObj<T> cast(T2& other)
    {
        static const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        return ManagedObj<T>((ManagedCtx*)((char*)other.unwrap() - offset), static_cast<T*>(other.unwrap()));
    }

    /**
     * Allocate T(arg1) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     */
    template <typename A1> ManagedObj<T>(A1 & arg1)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1);
    }

    /**
     * Allocate T(arg1, arg2) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     */
    template <typename A1, typename A2> ManagedObj<T>(A1 & arg1, A2 & arg2)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2);
    }

    /**
     * Allocate T(arg1, arg2, arg3) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     */
    template <typename A1, typename A2, typename A3> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3);
    }

    /**
     * Allocate T(arg1, arg2, arg3, arg4) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     * @param arg4   Fourth arg to T constructor.
     */
    template <typename A1, typename A2, typename A3, typename A4> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3, A4 & arg4)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3, arg4);
    }

    /**
     * Allocate T(arg1, arg2, arg3, arg4, arg5) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     * @param arg4   Fourth arg to T constructor.
     * @param arg5   Fifth arg to T constructor.
     */
    template <typename A1, typename A2, typename A3, typename A4, typename A5> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3, A4 & arg4, A5 & arg5)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3, arg4, arg5);
    }

    /**
     * Allocate T(arg1, arg2, arg3, arg4, arg5, arg6) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     * @param arg4   Fourth arg to T constructor.
     * @param arg5   Fifth arg to T constructor.
     * @param arg6   Sixth arg to T constructor.
     */
    template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3, A4 & arg4, A5 & arg5, A6 & arg6)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3, arg4, arg5, arg6);
    }

    /**
     * Allocate T(arg1, arg2, arg3, arg4, arg5, arg6, arg7) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     * @param arg4   Fourth arg to T constructor.
     * @param arg5   Fifth arg to T constructor.
     * @param arg6   Sixth arg to T constructor.
     * @param arg7   Seventh arg to T constructor.
     */
    template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3, A4 & arg4, A5 & arg5, A6 & arg6, A7 & arg7)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
    }

    /**
     * Allocate T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     * @param arg4   Fourth arg to T constructor.
     * @param arg5   Fifth arg to T constructor.
     * @param arg6   Sixth arg to T constructor.
     * @param arg7   Seventh arg to T constructor.
     * @param arg8   Eight arg to T constructor.
     */
    template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3, A4 & arg4, A5 & arg5, A6 & arg6, A7 & arg7, A8 & arg8)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
    }

    /**
     * Allocate T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     * @param arg4   Fourth arg to T constructor.
     * @param arg5   Fifth arg to T constructor.
     * @param arg6   Sixth arg to T constructor.
     * @param arg7   Seventh arg to T constructor.
     * @param arg8   Eight arg to T constructor.
     * @param arg9   Ninth arg to T constructor.
     */
    template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3, A4 & arg4, A5 & arg5, A6 & arg6, A7 & arg7, A8 & arg8, A9 & arg9)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
    }

    /**
     * Allocate T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) on the heap and set its reference count to 1.
     * @param arg1   First arg to T constructor.
     * @param arg2   Second arg to T constructor.
     * @param arg3   Third arg to T constructor.
     * @param arg4   Fourth arg to T constructor.
     * @param arg5   Fifth arg to T constructor.
     * @param arg6   Sixth arg to T constructor.
     * @param arg7   Seventh arg to T constructor.
     * @param arg8   Eight arg to T constructor.
     * @param arg9   Ninth arg to T constructor.
     * @param arg10  Tenth arg to T constructor.
     */
    template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> ManagedObj<T>(A1 & arg1, A2 & arg2, A3 & arg3, A4 & arg4, A5 & arg5, A6 & arg6, A7 & arg7, A8 & arg8, A9 & arg9, A10 & arg10)
    {
        const size_t offset = (sizeof(ManagedCtx) + 7) & ~0x07;
        context = reinterpret_cast<ManagedCtx*>(malloc(offset + sizeof(T)));
        if (NULL == context) {
            abort();
        }
        context = new (context) ManagedCtx(1);
        object = new ((char*)context + offset)T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
    }

    /**
     * ManagedObj destructor.
     * Decrement T's reference count and deallocate if zero.
     */
    ~ManagedObj<T>()
    {
        DecRef();
    }

    /**
     * Assign a ManagedObj<T> to an existing ManagedObj<T>
     * @param assignFromMe   ManagedObj<T> to copy from.
     * @return reference to this MangedObj<T>.
     */
    ManagedObj<T>& operator=(const ManagedObj<T>& assignFromMe)
    {
        if (object != assignFromMe.object) {
            /* Decrement ref of current context */
            DecRef();

            /* Reassign this Managed Obj */
            context = assignFromMe.context;
            object = assignFromMe.object;

            /* Increment the ref */
            IncRef();
        }

        return *this;
    }

    /**
     * Equality for managed objects is whatever equality means for @<T@>
     * @param other  The other managed object to compare.
     * @return  true if the managed objects are equal.
     */
    bool operator==(const ManagedObj<T>& other) const { return (object == other.object) || (*object == *other.object); }

    /**
     * Returns true if the two managed objects managed the same object. This is a more strict
     * comparison thant the equality operator.
     *
     * @param other  The other managed object to compare.
     * @return  true if the managed objects refer to the same underlying object.
     */
    template <class T2> bool iden(const ManagedObj<T2>& other) const { return ((ptrdiff_t)object == (ptrdiff_t)other.unwrap()); }

    /**
     * Inequality for managed objects is whatever inequality means for @<T@>
     * @param other  The other managed object to compare.
     * @return  true if the managed objects are equal.
     */
    bool operator!=(const ManagedObj<T>& other) const { return !(*this == other); }

    /**
     * Less-than for managed objects is whatever less-than means for @<T@>
     * @param other  The other managed object to compare.
     * @return  true if the managed objects are equal.
     */
    bool operator<(const ManagedObj<T>& other) const { return (object != other.object) && (*object < *other.object); }

    /**
     * Get a reference to T.
     * @return A reference to the managed object T.
     */
    T& operator*() { return *object; }

    /**
     * Get a pointer to the managed object T.
     */
    T* unwrap() { return object; }

    /**
     * Get a pointer to the managed object T.
     */
    const T* unwrap() const { return object; }

    /**
     * Get a pointer to T using the dereference operator
     * @return A reference to the managed object T.
     */
    T* operator->() { return object; }

    /**
     * Get a const reference to T.
     * @return A const reference to the managed object T.
     */
    const T& operator*() const { return *object; }

    /**
     * Get a const pointer to T.
     * @return A const pointer to the managed object T.
     */
    const T* operator->() const { return object; }

    /** Increment the ref count */
    void IncRef()
    {
#ifndef NDEBUG
        int32_t refs =
#endif
        IncrementAndFetch(&context->refCount);

#ifndef NDEBUG
        assert(refs != 1 && "IncRef(): Incrementing from zero reference count!");
#endif

    }

    /** Decrement the ref count and deallocate if necessary. */
    void DecRef()
    {
        int32_t refs = DecrementAndFetch(&context->refCount);
        if (0 == refs) {
            /* Call the overriden destructor */
            object->~T();
            context->ManagedCtx::~ManagedCtx();
            free(context);
            context = NULL;
        }
    }

    /**
     * Get the reference count
     */
    int32_t GetRefCount() const { return context ? context->refCount : 0; }

  private:

    ManagedObj<T>(ManagedCtx* context, T* object) : context(context), object(object)
    {
        assert(context->magic == ManagedCtxMagic);
        IncRef();
    }
};
#if defined(QCC_OS_GROUP_WINDOWS)
#pragma warning(pop)
#endif

}

#endif


text:
from ._pyimports import levenshtein, fast_comp

def ilevenshtein(seq1, seqs, max_dist=-1):
	"""Compute the Levenshtein distance between the sequence `seq1` and the series
	of	sequences `seqs`.

		`seq1`: the reference sequence
		`seqs`: a series of sequences (can be a generator)
		`max_dist`: if provided and > 0, only the sequences which distance from
		the reference sequence is lower or equal to this value will be returned.

	The return value is a series of pairs (distance, sequence).

	The sequence objects in `seqs` are expected to be of the same kind than
	the reference sequence in the C implementation; the same holds true for
	`ifast_comp`.
	"""
	for seq2 in seqs:
		dist = levenshtein(seq1, seq2, max_dist=max_dist)
		if dist != -1:
			yield dist, seq2

def ifast_comp(seq1, seqs, transpositions=False):
	"""Return an iterator over all the sequences in `seqs` which distance from
	`seq1` is lower or equal to 2. The sequences which distance from the
	reference sequence is higher than that are dropped.

		`seq1`: the reference sequence.
		`seqs`: a series of sequences (can be a generator)
		`transpositions` has the same sense than in `fast_comp`.

	The return value is a series of pairs (distance, sequence).

	You might want to call `sorted()` on the iterator to get the results in a
	significant order:

		>>> g = ifast_comp("foo", ["fo", "bar", "foob", "foo", "foobaz"])
		>>> sorted(g)
		[(0, 'foo'), (1, 'fo'), (1, 'foob')]
	"""
	for seq2 in seqs:
		dist = fast_comp(seq1, seq2, transpositions)
		if dist != -1:
			yield dist, seq2


text: New web authentication system for AscendTech


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiscordBot.Util
{
    static class TimeConverter
    {
        public static int MinToMS(double min)
        {
            return (int)(min * 1000 * 60);
        }
        public static int MSToMin(double ms)
        {
            return (int)((ms / 1000) / 60);
        }

        public static int SecToMS(double sec)
        {
            return (int)(sec * 1000);
        }
        public static int MSToSec(double ms)
        {
            return (int)(ms / 1000);
        }
    }
}


text:
import { A as emberA } from '@ember/array';
import { get, set } from '@ember/object';
import { resolve } from 'rsvp';
import {
  array as promiseArray,
  resolve as promiseResolve
} from 'ember-awesome-macros/promise';
import { module, test } from 'qunit';
import { compute } from 'ember-macro-helpers/test-support';

let array;

module('Integration | Macro | promise | array', function(hooks) {
  hooks.beforeEach(function() {
    array = emberA([null]);
  });

  test('it returns an empty array', function(assert) {
    let { result } = compute({
      computed: promiseArray('promise'),
      properties: {
        promise: resolve(array)
      }
    });

    assert.strictEqual(get(result, 'length'), 0);
  });

  test('it resolves to a full array', function(assert) {
    let { result } = compute({
      computed: promiseArray('promise'),
      properties: {
        promise: resolve(array)
      }
    });

    return result.then(() => {
      assert.strictEqual(get(result, 'length'), 1);
    });
  });

  test('resolved value is an array', function(assert) {
    let { result } = compute({
      computed: promiseArray('promise'),
      properties: {
        promise: resolve(array)
      }
    });

    return result.then(result => {
      assert.strictEqual(get(result, 'length'), 1);
    });
  });

  test('it responds to reassigns', function(assert) {
    let { subject } = compute({
      computed: promiseArray('promise'),
      properties: {
        promise: resolve(array)
      }
    });

    set(subject, 'promise', resolve(emberA([null, null])));

    let result = get(subject, 'computed');

    return result.then(result => {
      assert.strictEqual(get(result, 'length'), 2);
    });
  });

  test('it responds to pushes', function(assert) {
    let { subject } = compute({
      computed: promiseArray('promise'),
      properties: {
        promise: resolve(array)
      }
    });

    array.pushObject(null);

    let result = get(subject, 'computed');

    return result.then(result => {
      assert.strictEqual(get(result, 'length'), 2);
    });
  });

  test('value: resolved value is an array', function(assert) {
    let { result } = compute({
      computed: promiseArray(resolve(array))
    });

    return result.then(result => {
      assert.strictEqual(get(result, 'length'), 1);
    });
  });

  test('composing: resolved value is an array', function(assert) {
    let { result } = compute({
      computed: promiseArray(promiseResolve(array))
    });

    return result.then(result => {
      assert.strictEqual(get(result, 'length'), 1);
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<job-suggestions>
	<jobs total="50" count="10" start="0">
		<job>
			<id>1577323</id>
			<company>
				<id>1281</id>
				<name>Unisys</name>
			</company>
			<job-poster>
				<id>OHYinXGMKT</id>
				<first-name>Joanne</first-name>
				<last-name>Rawls</last-name>
				<headline>Recruiting Lead at Unisys Corporation</headline>
			</job-poster>
			<description-snippet>Unisys is expanding our Federal Proposal Development Center and looking for talented professionals to join our team. As a Senior Technical Writer, you will be responsible for: Analyzing Request for Proposals (RFP) and work with Solution Architects to package company services into a technical proposal response; write technical proposals that spell out what the company can offer to the agency seek</description-snippet>
			<location-description>Reston, VA  </location-description>
		</job>
		<job>
			<id>1579926</id>
			<company>
				<id>15759</id>
				<name>Velti</name>
			</company>
			<salary>Negotiable</salary>
			<job-poster>
				<id>UlfGF2nmYN</id>
				<first-name>Maria</first-name>
				<last-name>Maragoudakis-Gregoriou</last-name>
				<headline>Experienced Business Manager with extensive international and start-up experience</headline>
			</job-poster>
			<description-snippet>Senior Technical Writer (Job Code: SF-SRTCR) Velti is a leading global provider of mobile marketing and advertising software solutions that enable brands, advertising agencies, mobile operators, and media companies to implement highly targeted, interactive, and measurable campaigns by communicating with and engaging consumers via their mobile devices. Job DescriptionThe Senior Technical Writer pos</description-snippet>
			<location-description>San Francisco</location-description>
		</job>
		<job>
			<id>1609091</id>
			<company>
			</company>
			<salary>Annual Salary, Bonus</salary>
			<job-poster>
				<id>VLhDZNHMmG</id>
				<first-name>Ties</first-name>
				<last-name>van de Voort</last-name>
				<headline>International Corporate Recruiter at SDL Tridion</headline>
			</job-poster>
			<description-snippet>The Senior Technical Support Engineer works in a team of support engineers and reports to the Manager Customer Support. The Senior Technical Support Engineer is guarding and meeting service levels as agreed with customers, partners and the internal organization. The Senior Technical Support Engineer independently provides complex technical support to customers and partners, provides onsite support</description-snippet>
			<location-description>New York</location-description>
		</job>
	</jobs>
</job-suggestions>


text:
require "pathname"

require File.expand_path("../../base", __FILE__)

describe Vagrant::MachineState do
  include_context "unit"

  let(:id) { :some_state }
  let(:short) { "foo" }
  let(:long) { "I am a longer foo" }

  it "should give access to the id" do
    instance = described_class.new(id, short, long)
    expect(instance.id).to eq(id)
  end

  it "should give access to the short description" do
    instance = described_class.new(id, short, long)
    expect(instance.short_description).to eq(short)
  end

  it "should give access to the long description" do
    instance = described_class.new(id, short, long)
    expect(instance.long_description).to eq(long)
  end
end


text:
package com.smoketurner.pipeline.application.managed;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import com.amazonaws.services.sqs.AmazonSQSClient;
import org.junit.Test;

public class AmazonSQSClientManagerTest {

  private final AmazonSQSClient client = mock(AmazonSQSClient.class);
  private final AmazonSQSClientManager manager = new AmazonSQSClientManager(client);

  @Test
  public void testStop() throws Exception {
    manager.stop();
    verify(client).shutdown();
  }
}


text:
package cz.metacentrum.perun.wui.consolidator.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Image;
import cz.metacentrum.perun.wui.client.resources.PerunConfiguration;
import cz.metacentrum.perun.wui.model.common.WayfGroup;
import org.gwtbootstrap3.client.ui.Heading;
import org.gwtbootstrap3.client.ui.Panel;
import org.gwtbootstrap3.client.ui.PanelBody;
import org.gwtbootstrap3.client.ui.PanelFooter;
import org.gwtbootstrap3.client.ui.constants.HeadingSize;
import org.gwtbootstrap3.client.ui.html.Paragraph;

/**
 * WAYF Group button widget. Displays one option for wayf (type of authentication).
 *
 * @author Pavel Zlámal <zlamal@cesnet.cz>
 */
public class WayfGroupButton extends Panel implements HasClickHandlers {

	private Panel widget;
	private Image image;

	@UiField PanelBody panelBody;
	@UiField PanelFooter panelFooter;
	@UiField Paragraph description;

	interface WayfGroupButtonUiBinder extends UiBinder<Panel, WayfGroupButton> {
	}

	private static WayfGroupButtonUiBinder ourUiBinder = GWT.create(WayfGroupButtonUiBinder.class);

	public WayfGroupButton(WayfGroup group) {

		widget = ourUiBinder.createAndBindUi(this);

		String locale = PerunConfiguration.getCurrentLocaleName();

		if (group.getIconUrl() != null) {
			image = new Image(group.getIconUrl());
			panelBody.add(image);
		} else {
			panelBody.add(new Heading(HeadingSize.H4, group.getName(locale)));
		}

		description.setText(group.getDescription(locale));

	}

	/**
	 * Add ClickHandler to the whole Panel widget
	 *
	 * @param handler handler to add
	 * @return handler registration
	 */
	public HandlerRegistration addClickHandler(ClickHandler handler) {

		return widget.addDomHandler(handler, ClickEvent.getType());

	}

	/**
	 * Return WayfGroupButton widget itself
	 *
	 * @return
	 */
	public Panel getWidget() {
		return widget;
	}

}


text:
/* globals require module */
"use strict";

const _ = require("lodash");

module.exports = function (db) {
    function get(req, res) {
        let articles = _.chain(db("articles"))
            .sortBy(article => -article.CreatedOn);

        res.send({
            result: articles
        });
    }

    function getById(req, res) {

        let articleId = req.params.id;
        let article = db("articles").find({
            ArticleId: articleId
        });

        if (!article) {
            return res.status(404)
                .send("Invalid article ID");
        }

        res.send({
            result: article
        });
    }

    function post(req, res) {
        let article = req.body;
        if (!article.author) {
            return res.status(401)
                .send("User not authorized");
        }

        var dbArticle = {};
        dbArticle.Title = article.title;
        dbArticle.CreatedOn = new Date();
        dbArticle.Author = article.author.username;
        dbArticle.Content = article.content;

        db("articles").insert(dbArticle);
        dbArticle.ArticleId = dbArticle.id;

        return res.status(201)
        .send({
            result: dbArticle
        });
    }

    function put(req, res) {
        let user = req.user;

        if (!user) {
            return res.status(401)
                .send("User not authorized");
        }

        let articleId = req.params.id;
        let article = db("articles").find({
            ArticleId: articleId
        });

        if (!article) {
            return res.status(404)
                .send("Invalid article ID");
        }

        // let type = req.body.type;
        // if (["like", "dislike"].indexOf(type) < 0) {
        //     return res.status(400)
        //         .send("Request type must be either like or dislike");
        // }

        // if (req.body.type === "like") {
        //     cookie.likes += 1;
        // } else {
        //     cookie.dislikes += 1;
        // }

        db.save();

        return res.send({
            result: article
        });
    }

    return { get, getById, post, put };
};


text:
module Admin::Views::Moments
  class Destroy
    include Admin::View
  end
end


text:
module Api
  module V1
    class PersonSerializer < ::Api::V1::BaseSerializer
      set_type :people

      PRIVATE_ATTRIBUTES = [:phone,
                            :email,
                            :birthdate].freeze

      attributes :id,
                 :first_name,
                 :last_name,
                 :full_name,
                 :gender,
                 :current_age,
                 :city,
                 :state_code,
                 :country_code

      PRIVATE_ATTRIBUTES.each do |att|
        attribute att, if: proc { |effort, params|
          current_user = params[:current_user]
          current_user&.authorized_to_edit?(effort)
        }
      end

      link :self, :api_v1_url

      has_many :efforts
    end
  end
end


text:
function getCenterMuchScreen(element)
{var width=$(element).width();var height=$(element).height();var screenWidth=$(window).width();var screenHeight=$(window).height();var screenTop=$(window).scrollTop();var left=(screenWidth/2)-(width/2);var top=(screenHeight/2+screenTop)-(height/2);if(top<10)
{top=10;}
return{"left":left+"px","top":top+"px"};}
var opCookie={set:function(name,value,expires,path,domain,secure,httponly)
{var result='';if(value==undefined||(value instanceof String&&!value))
{var expires=new Date();expires.setTime((new Date()).getTime()-(12*30*24*60*60*1000));result=name+'=deleted; expires='+expires.toUTCString();}
else
{if(!expires||!(expires instanceof Date))
{var expires=new Date();console.debug(expires);expires.setTime((new Date()).getTime()+(60*60*1000));}
value=encodeURIComponent(value);result=name+"="+value+"; expires="+expires.toUTCString();}
if(path&&path.length)
{result=result+"; path="+path;}
if(domain&&domain.length)
{result=result+"; domain="+domain;}
if(secure)
{result=result+"; secure";}
if(httponly)
{result=result+"; secure";}
document.cookie=result;},get:function(name)
{var value=null;if(document.cookie&&document.cookie.length)
{var _cookie=document.cookie;var cookies=_cookie.split(';');for(var i=0;i<cookies.length;i++)
{var _cookie=$.trim(cookies[i]);if(_cookie.indexOf(name+'=')==0)
{value=$.trim(decodeURIComponent(_cookie.substr(name.length+1)));break;}}}
return value;}};function pne_url2a(url)
{var urlstr;if(url.length>57)
{var _url=url.replace("&","&");if(_url.length>57)
{_url=_url.substr(0,57)+'...';urlstr=_url.replace("&","&");}}
if(!urlstr)
{urlstr=url;}
document.write(''+urlstr+'');}


text:
apt-get update
apt-get install vim git preload htop xchat lm-sensors pepperflashplugin-nonfree chromium-browser openssh-server ubuntu-restricted-extras


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DynThings.Data.Models;
using DynThings.Data.Repositories;
using DynThings.Core;
using ResultInfo;

namespace DynThings.WebPortal.Controllers
{
    [Authorize(Roles = "Admin")]
    public class ConfigController : Controller
    {
        UnitOfWork_Repositories uof_repos = new UnitOfWork_Repositories();

        // GET: Config
        public ActionResult Index()
        {
            DynSetting config = uof_repos.repoDynSettings.GetConfig();
            return View("Index", config);
        }

        public PartialViewResult MainPV()
        {
            DynSetting config = uof_repos.repoDynSettings.GetConfig();
            return PartialView("_Main", config);
        }

        #region GridsPV
        [HttpGet]
        public PartialViewResult GridsPV()
        {
            DynSetting config = uof_repos.repoDynSettings.GetConfig();
            ViewBag.DefaultRecordsPerMaster = new SelectList(StaticMenus.GetGridRowsCount(), config.DefaultRecordsPerMaster.ToString());
            ViewBag.DefaultRecordsPerChild = new SelectList(StaticMenus.GetGridRowsCount(), config.DefaultRecordsPerChild.ToString());
            return PartialView("_Grids", config);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GridsPV([Bind(Include = "DefaultRecordsPerMaster,DefaultRecordsPerChild")] DynSetting config)
        {
            Result res = Result.GenerateFailedResult();
            if (ModelState.IsValid)
            {
                res = uof_repos.repoDynSettings.SetGridRowsCount(config.DefaultRecordsPerMaster, config.DefaultRecordsPerChild);
                return Json(res);
            }
            return Json(res);
        }
        #endregion

        #region DevModePV
        [HttpGet]
        public PartialViewResult DevModePV()
        {
            DynSetting config = uof_repos.repoDynSettings.GetConfig();
            return PartialView("_DevMode", config);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DevModePV(DynSetting config)
        {
            Result res = Result.GenerateFailedResult();
            res = uof_repos.repoDynSettings.SetDevelopmentMode(config.DevelopmentMode, config.MapKey, config.GoogleAnalytics);
            return Json(res);
        }
        #endregion

        #region ResetPV
        [HttpGet]
        public PartialViewResult ResetPV()
        {
            DynSetting config = uof_repos.repoDynSettings.GetConfig();
            return PartialView("_Reset", config);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ResetPV([Bind(Include = "PlatformKey")] DynSetting config)
        {
            Result res = Result.GenerateFailedResult();
            if (ModelState.IsValid)
            {
                Session.Clear();
                res = uof_repos.repoDynSettings.ResetPlatform();
                return Json(res);
            }
            return Json(res);
        }
        #endregion

    }
}


text:
%%
%% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
%%
%% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
%%

$project=Qt5xHb
$module=QtCharts

$header

$includes=5,7,0

$beginSlotsClass
$slot=5,7,0|barsetsAdded( QList<QBarSet*> sets )
$slot=5,7,0|barsetsRemoved( QList<QBarSet*> sets )
$slot=5,7,0|clicked( int index, QBarSet * barset )
$slot=5,7,0|countChanged()
$slot=5,7,0|doubleClicked( int index, QBarSet * barset )
$slot=5,7,0|hovered( bool status, int index, QBarSet * barset )
$slot=5,7,0|labelsAngleChanged( qreal angle )
$slot=5,7,0|labelsFormatChanged( const QString & format )
$slot=5,7,0|labelsPositionChanged( QAbstractBarSeries::LabelsPosition position )
$slot=5,7,0|labelsVisibleChanged()
$slot=5,7,0|pressed( int index, QBarSet * barset )
$slot=5,7,0|released( int index, QBarSet * barset )
$endSlotsClass


text:
package trigger

import (
	"fmt"
	"strings"

	"github.com/sirupsen/logrus"

	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/github"
	"k8s.io/test-infra/prow/kube"
	"k8s.io/test-infra/prow/pluginhelp"
	"k8s.io/test-infra/prow/plugins"
)

const (
	pluginName = "trigger"
	lgtmLabel  = "lgtm"
)

func init() {
	plugins.RegisterIssueCommentHandler(pluginName, handleIssueComment, helpProvider)
	plugins.RegisterPullRequestHandler(pluginName, handlePullRequest, helpProvider)
	plugins.RegisterPushEventHandler(pluginName, handlePush, helpProvider)
}

func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) {
	configInfo := map[string]string{}
	for _, repo := range enabledRepos {
		parts := strings.Split(repo, "/")
		if len(parts) != 2 {
			return nil, fmt.Errorf("invalid repo in enabledRepos: %q", repo)
		}
		trusted, _ := trustedOrgForRepo(config, parts[0], parts[1])
		configInfo[repo] = fmt.Sprintf("The trusted Github organization for this repository is %q.", trusted)
	}
	pluginHelp := &pluginhelp.PluginHelp{
		Description: `The trigger plugin starts tests in reaction to commands and pull request events. It is responsible for ensuring that test jobs are only run on trusted PRs. A PR is considered trusted if the author is a member of the 'trusted organization' for the repository or if such a member has left an '/ok-to-test' command on the PR.

Trigger starts jobs automatically when a new trusted PR is created or when an untrusted PR becomes trusted, but it can also be used to start jobs manually via the '/test' command.

The '/retest' command can be used to rerun jobs that have reported failure.`,
		Config: configInfo,
	}
	pluginHelp.AddCommand(pluginhelp.Command{
		Usage:       "/ok-to-test",
		Description: "Marks a PR as 'trusted' and starts tests.",
		Featured:    false,
		WhoCanUse:   "Members of the trusted organization for the repo.",
		Examples:    []string{"/ok-to-test"},
	})
	pluginHelp.AddCommand(pluginhelp.Command{
		Usage:       "/test (<job name>|all)",
		Description: "Manually starts a/all test job(s).",
		Featured:    true,
		WhoCanUse:   "Anyone can trigger this command on a trusted PR.",
		Examples:    []string{"/test all", "/test pull-bazel-test"},
	})
	pluginHelp.AddCommand(pluginhelp.Command{
		Usage:       "/retest",
		Description: "Rerun test jobs that have failed.",
		Featured:    true,
		WhoCanUse:   "Anyone can trigger this command on a trusted PR.",
		Examples:    []string{"/retest"},
	})
	return pluginHelp, nil
}

type githubClient interface {
	AddLabel(org, repo string, number int, label string) error
	BotName() (string, error)
	IsMember(org, user string) (bool, error)
	GetPullRequest(org, repo string, number int) (*github.PullRequest, error)
	GetRef(org, repo, ref string) (string, error)
	CreateComment(owner, repo string, number int, comment string) error
	ListIssueComments(owner, repo string, issue int) ([]github.IssueComment, error)
	CreateStatus(owner, repo, ref string, status github.Status) error
	GetCombinedStatus(org, repo, ref string) (*github.CombinedStatus, error)
	GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
	RemoveLabel(org, repo string, number int, label string) error
	DeleteStaleComments(org, repo string, number int, comments []github.IssueComment, isStale func(github.IssueComment) bool) error
}

type kubeClient interface {
	CreateProwJob(kube.ProwJob) (kube.ProwJob, error)
}

type client struct {
	GitHubClient githubClient
	KubeClient   kubeClient
	Config       *config.Config
	Logger       *logrus.Entry
}

func getClient(pc plugins.PluginClient) client {
	return client{
		GitHubClient: pc.GitHubClient,
		Config:       pc.Config,
		KubeClient:   pc.KubeClient,
		Logger:       pc.Logger,
	}
}

func handlePullRequest(pc plugins.PluginClient, pr github.PullRequestEvent) error {
	trustedOrg, joinOrgURL := trustedOrgForRepo(pc.PluginConfig, pr.Repo.Owner.Login, pr.Repo.Name)
	return handlePR(getClient(pc), trustedOrg, joinOrgURL, pr)
}

func handleIssueComment(pc plugins.PluginClient, ic github.IssueCommentEvent) error {
	trustedOrg, _ := trustedOrgForRepo(pc.PluginConfig, ic.Repo.Owner.Login, ic.Repo.Name)
	return handleIC(getClient(pc), trustedOrg, ic)
}

func handlePush(pc plugins.PluginClient, pe github.PushEvent) error {
	return handlePE(getClient(pc), pe)
}

// trustedOrgForRepo returns the configured trusted organization and a URL for it
// for the provided org and repo combination.
func trustedOrgForRepo(config *plugins.Configuration, org, repo string) (string, string) {
	if trigger := config.TriggerFor(org, repo); trigger != nil && trigger.TrustedOrg != "" {
		return trigger.TrustedOrg, trigger.JoinOrgURL
	}
	return org, fmt.Sprintf("https://github.com/orgs/%s/people", org)
}

func isUserTrusted(ghc githubClient, user, trustedOrg, org string) (bool, error) {
	orgMember, err := ghc.IsMember(trustedOrg, user)
	if err != nil {
		return false, err
	} else if orgMember {
		return true, nil
	}
	if org != trustedOrg {
		orgMember, err = ghc.IsMember(org, user)
		if err != nil {
			return false, err
		}
	}
	return orgMember, nil
}


text:
[Grayscale](http://startbootstrap.com/template-overviews/grayscale/) is a multipurpose, one page HTML theme for [Bootstrap](http://getbootstrap.com/) created by [Start Bootstrap](http://startbootstrap.com/). This template features various content sections and a Google Maps section with a custom map marker.

Start Bootstrap was created by and is maintained by **David Miller**, Managing Parter at [Iron Summit Media Strategies](http://www.ironsummitmedia.com/).

* https://twitter.com/davidmillerskt
* https://github.com/davidtmiller

Start Bootstrap is based on the [Bootstrap](http://getbootstrap.com/) framework created by [Mark Otto](https://twitter.com/mdo) and [Jacob Thorton](https://twitter.com/fat).

## Copyright and License

Copyright 2013-2017 Blackrock Digital LLC. Code released under the [MIT](https://github.com/BlackrockDigital/startbootstrap-full-width-pics/blob/gh-pages/LICENSE) license.