<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Skywriter.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Julian Viereck (julian.viereck@gmail.com)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var StateHandler = require("ace/keyboard/state_handler").StateHandler;
var matchCharacterOnly =  require("ace/keyboard/state_handler").matchCharacterOnly;

var vimStates = {
    start: [
        {
            key:    "i",
            then:   "insertMode"
        },
        {
            key:    "o",
            exec:   "gotoright",
            then:   "insertMode"
        },
        {
            regex:  [ "([0-9]*)", "(k|up)" ],
            exec:   "golineup",
            params: [
                {
                    name:     "times",
                    match:    1,
                    type:     "number",
                    defaultValue:     1
                }
            ]
        },
        {
            regex:  [ "([0-9]*)", "(j|down|enter)" ],
            exec:   "golinedown",
            params: [
                {
                    name:    "times",
                    match:   1,
                    type:    "number",
                    defaultValue:    1
                }
            ]
        },
        {
            regex:  [ "([0-9]*)", "(l|right)" ],
            exec:   "gotoright",
            params: [
                {
                    name:   "times",
                    match:  1,
                    type:   "number",
                    defaultValue:     1
                }
            ]
        },
        {
            regex:  [ "([0-9]*)", "(h|left)" ],
            exec:   "gotoleft",
            params: [
                {
                    name:     "times",
                    match:    1,
                    type:     "number",
                    defaultValue:     1
                }
            ]
        },
        {
            comment:    "Catch some keyboard input to stop it here",
            match:      matchCharacterOnly
        }
    ],
    insertMode: [
        {
            key:      "esc",
            then:     "start"
        }
    ]
};

exports.Vim = new StateHandler(vimStates);

});
<commit_msg>vim R command<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Skywriter.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Julian Viereck (julian.viereck@gmail.com)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

var StateHandler = require("ace/keyboard/state_handler").StateHandler;
var matchCharacterOnly =  require("ace/keyboard/state_handler").matchCharacterOnly;

var vimStates = {
    start: [
        {
            key:    "i",
            then:   "insertMode"
        },
        {
            key:    "o",
            exec:   "gotoright",
            then:   "insertMode"
        },
        {
            key:    "shift-r",
            exec:   "overwrite",
            then:   "replaceMode"
        },
        {
            regex:  [ "([0-9]*)", "(k|up)" ],
            exec:   "golineup",
            params: [
                {
                    name:     "times",
                    match:    1,
                    type:     "number",
                    defaultValue:     1
                }
            ]
        },
        {
            regex:  [ "([0-9]*)", "(j|down|enter)" ],
            exec:   "golinedown",
            params: [
                {
                    name:    "times",
                    match:   1,
                    type:    "number",
                    defaultValue:    1
                }
            ]
        },
        {
            regex:  [ "([0-9]*)", "(l|right)" ],
            exec:   "gotoright",
            params: [
                {
                    name:   "times",
                    match:  1,
                    type:   "number",
                    defaultValue:     1
                }
            ]
        },
        {
            regex:  [ "([0-9]*)", "(h|left)" ],
            exec:   "gotoleft",
            params: [
                {
                    name:     "times",
                    match:    1,
                    type:     "number",
                    defaultValue:     1
                }
            ]
        },
        {
            comment:    "Catch some keyboard input to stop it here",
            match:      matchCharacterOnly
        }
    ],
    insertMode: [
        {
            key:      "esc",
            then:     "start"
        }
    ],
    replaceMode: [
        {
            key:      "esc",
            exec:     "overwrite",
            then:     "start"
        }
    ]
};

exports.Vim = new StateHandler(vimStates);

});
<|endoftext|>


<commit_before>// var log = require('_/log');
var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
var request = chai.request;
var app = require('_/app');

// Helper functions for our tests
function requestCreatePost(postJSON, callback){
  request(app)
    .post('/post')
    .send(postJSON)
    .end(callback);
}

function requestDeletePost(criteria, callback){
  request(app)
    .post('/post/' + criteria)
    .end(callback);
}

function requestGetPost(criteria, callback){
  request(app)
    .post('/post?' + criteria)
    .end(callback);
}

// Handle the Mocha specific functions
/* global describe beforeEach afterEach it */
describe('handlers', function(){
  var testPostTitle = '_posts-api-Test';

  beforeEach(function () {
    var newPostJSON = {
      title: testPostTitle,
      body: 'In at aliquet turpis. Fusce gravida arcu a eros feugiat rhoncus nec id enim. Duis commodo ornare lectus, non pretium risus mollis volutpat. Vivamus finibus est',
      published: false,
      meta: { tags: ['test', 'this', 'code'], likes: 100}
    };

    requestCreatePost(newPostJSON, function (err, res) {
      expect(err).to.be.null;
      expect(res).to.have.status(200);
    });
  });

  afterEach(function () {
    requestDeletePost(testPostTitle, function (err, res) {
      expect(err).to.be.null;
      expect(res).to.have.status(200);
    });
  });

  describe('#get-post-titles', function(){
    it('Should return a list of all the post titles', function(){
      // Use the plain post title api for this one instead of our helper
      // functions because we only use this once
      request(app)
        .get('/post-titles')
        .end(function (err, res) {
          expect(err).to.be.null;
          expect(res).to.have.status(200);
          expect(res.body).to.include(testPostTitle);
        });
    });
  });

  describe('#get-post', function(){
    it('Should return our new post when we specify the title', function(){
      requestGetPost('?title=' + testPostTitle, function (err, res) {
        expect(err).to.be.null;
        expect(res).to.have.status(200);
        expect(res.body).to.have.property('title');
        expect(res.body.title).to.equal(testPostTitle);
      });
    });
    it('Should return an error when we dont provide enough information', function(){
      requestGetPost('', function (err, res) {
        expect(err).to.exist;
        expect(res).to.have.status(404);
      });
    });
  });

  describe('#update-post', function(){
    it('Should update a post when you supply the posts title', function(){
      // Like post-titles don't use a helper function becuase we don't need
      // to make this check more than once
      request(app)
        .put('/post/' + testPostTitle)
        .end(function (err, res) {
          expect(err).to.exist;
          expect(res).to.have.status(404);
        });
    });
  });

  describe('#delete-post', function(){
    it('Should delete the post when we ask and not return the post once we search for it again', function(){
      // Build our new post's contents
      var deletePostTitle = '_posts-api-delete-Test';
      var deletePostJSON = {
        title: deletePostTitle,
        body: 'test',
        published: false,
        meta: { tags: ['test', 'this', 'code'], likes: 100}
      };

      // Create the new post
      requestCreatePost(deletePostJSON, function(err, res) {
        expect(err).to.be.null;
        expect(res).to.have.status(200);

        // Delete the post
        requestDeletePost(deletePostTitle, function(err, res) {
          expect(err).to.be.null;
          expect(res).to.have.status(200);

          // Make sure the post is deleted
          requestGetPost(deletePostTitle, function(err, res) {
            expect(err).to.exist;
            expect(res).to.have.status(404);
          });
        });
      });
    });
  });

  describe('#create-post', function(){
    it('Should create a new post that can be found when we search for it', function(){
      // Build our new post's contents
      var createPostTitle = '_posts-api-create-Test';
      var createPostJSON = {
        title: createPostTitle,
        body: 'test',
        published: false,
        meta: { tags: ['test', 'this', 'code'], likes: 100}
      };

      // Create the new post
      requestCreatePost(createPostJSON, function(err, res) {
        expect(err).to.be.null;
        expect(res).to.have.status(200);

        // Make sure the new post exists
        requestGetPost(createPostTitle, function(err, res) {
          expect(err).to.be.null;
          expect(res.body).to.have.property('title');
          expect(res.body.title).to.equal(createPostTitle);
        });
      });
    });
  });
});
<commit_msg>Use promises [BUG] test asserts dont work<commit_after>var log = require('_/log');
var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
var request = chai.request;
var app = require('_/app');

// Add promise support if this does not exist natively.
if (!global.Promise) {
  var q = require('q');
  chai.request.addPromises(q.Promise);
}

// Helper functions for our tests
function requestCreatePost(postJSON, callback){
  request(app)
    .post('/post')
    .send(postJSON)
    .then(callback)
    .catch(function (err) {
      throw err;
    });
}

function requestDeletePost(criteria, callback){
  request(app)
    .post('/post/' + criteria)
    .then(callback)
    .catch(function (err) {
      throw err;
    });
}

function requestGetPost(criteria, callback){
  request(app)
    .post('/post?' + criteria)
    .then(callback)
    .catch(function (err) {
      throw err;
    });
}

// Handle the Mocha specific functions
/* global describe beforeEach afterEach it */
describe('handlers', function(){
  var testPostTitle = '_posts-api-Test';

  beforeEach(function () {
    var newPostJSON = {
      title: testPostTitle,
      body: 'In at aliquet turpis. Fusce gravida arcu a eros feugiat rhoncus nec id enim. Duis commodo ornare lectus, non pretium risus mollis volutpat. Vivamus finibus est',
      published: false,
      meta: { tags: ['test', 'this', 'code'], likes: 100}
    };

    requestCreatePost(newPostJSON, function (res) {
      expect(err).to.be.null;
      expect(res).to.have.status(200);
    });
  });

  afterEach(function () {
    requestDeletePost(testPostTitle, function (res) {
      expect(err).to.be.null;
      expect(res).to.have.status(200);
    });
  });

  describe('#get-post-titles', function(){
    it('Should return a list of all the post titles', function(){
      log.info('IM HERE');
      var test = 'OH NOSE';
      // Use the plain post title api for this one instead of our helper
      // functions because we only use this once
      request(app)
        .get('/post-titles')
        .then(function (res) {
          expect(res).to.have.status(200);
          expect(res.body).to.include(testPostTitle);
          test = 'poodle';
        })
        .catch(function (err) {
          throw err;
        });
      log.info(test);
    });
  });

  describe('#get-post', function(){
    it('Should return our new post when we specify the title', function(){
      requestGetPost('?title=' + testPostTitle, function (res) {
        log.info('I MADE IT HERE BUT I DONT KNOW HOWWWWWWWWWWWWWWW');
        expect('FAILLLL').to.be.null;
        // expect(err).to.be.null;
        expect(res).to.have.status(200);
        expect(res.body).to.have.property('title');
        expect(res.body.title).to.equal(testPostTitle);
      });
    });
    it('Should return an error when we dont provide enough information', function(){
      requestGetPost('', function (res) {
        expect(err).to.exist;
        expect(res).to.have.status(404);
      });
    });
  });

  describe('#update-post', function(){
    it('Should update a post when you supply the posts title', function(){
      // Like post-titles don't use a helper function becuase we don't need
      // to make this check more than once
      request(app)
        .put('/post/' + testPostTitle)
        .then(function (res) {
          expect(res).to.have.status(404);
        })
        .catch(function (err) {
          throw err;
        });
    });
  });

  describe('#delete-post', function(){
    it('Should delete the post when we ask and not return the post once we search for it again', function(){
      // Build our new post's contents
      var deletePostTitle = '_posts-api-delete-Test';
      var deletePostJSON = {
        title: deletePostTitle,
        body: 'test',
        published: false,
        meta: { tags: ['test', 'this', 'code'], likes: 100}
      };

      // Create the new post
      requestCreatePost(deletePostJSON, function(res) {
        expect(err).to.be.null;
        expect(res).to.have.status(200);

        // Delete the post
        requestDeletePost(deletePostTitle, function(res) {
          expect(err).to.be.null;
          expect(res).to.have.status(200);

          // Make sure the post is deleted
          requestGetPost(deletePostTitle, function(res) {
            expect(err).to.exist;
            expect(res).to.have.status(404);
          });
        });
      });
    });
  });

  describe('#create-post', function(){
    it('Should create a new post that can be found when we search for it', function(){
      // Build our new post's contents
      var createPostTitle = '_posts-api-create-Test';
      var createPostJSON = {
        title: createPostTitle,
        body: 'test',
        published: false,
        meta: { tags: ['test', 'this', 'code'], likes: 100}
      };

      // Create the new post
      requestCreatePost(createPostJSON, function(res) {
        expect(err).to.be.null;
        expect(res).to.have.status(200);

        // Make sure the new post exists
        requestGetPost(createPostTitle, function(res) {
          expect(err).to.be.null;
          expect(res.body).to.have.property('title');
          expect(res.body.title).to.equal(createPostTitle);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/*
	Arcana by Pixelarity
	html5up.net | @ajlkn
	License: pixelarity.com/license
*/

(function($) {

	skel.breakpoints({
		wide: '(max-width: 1680px)',
		normal: '(max-width: 1280px)',
		narrow: '(max-width: 980px)',
		narrower: '(max-width: 840px)',
		mobile: '(max-width: 736px)',
		mobilep: '(max-width: 480px)'
	});

	$(function() {

		var	$window = $(window),
			$body = $('body');

		// Disable animations/transitions until the page has loaded.
			$body.addClass('is-loading');

			$window.on('load', function() {
				$body.removeClass('is-loading');
			});

		// Fix: Placeholder polyfill.
			$('form').placeholder();

		// Prioritize "important" elements on narrower.
			skel.on('+narrower -narrower', function() {
				$.prioritize(
					'.important\\28 narrower\\29',
					skel.breakpoint('narrower').active
				);
			});

		// Dropdowns.
			$('#nav > ul').dropotron({
				offsetY: -15,
				hoverDelay: 0,
				alignment: 'center'
			});

		// Off-Canvas Navigation.

			// Title Bar.
				$(
					'
' +
						'' +
						'' +
					'
'
				)
					.appendTo($body);

			// Navigation Panel.
				$(
					'
' +
						'' +
							$('#nav').navList() +
						'' +
					'
'
				)
					.appendTo($body)
					.panel({
						delay: 500,
						hideOnClick: true,
						hideOnSwipe: true,
						resetScroll: true,
						resetForms: true,
						side: 'left',
						target: $body,
						visibleClass: 'navPanel-visible'
					});

			// Fix: Remove navPanel transitions on WP<10 (poor/buggy performance).
				if (skel.vars.os == 'wp' && skel.vars.osVersion < 10)
					$('#titleBar, #navPanel, #page-wrapper')
						.css('transition', 'none');

	});

})(jQuery);

//Slick slider
$(document).ready(function(){
    //Drug page slider, no autoplay
      $('.slider').slick({
        dots: true,
        slidesToShow: 1,
          cssEase: 'linear'
      });
    //Home page slider, autoplay
      $('.slider-home').slick({
        dots: true,
        slidesToShow: 1,
          autoplay: true,
        autoplaySpeed: 5000,
          cssEase: 'linear'
      });
    });

//Navigation
$("#nav").html("

Home

General Medication Info

Rejection

Vaccination After Transplant

Over-the-Counter Medication

Cytotoxic Safety Precautions

Dental Protocol

Cancer Risks

Anti-Rejection Medication

Tacrolimus

Mycophenolate

Azathioprine

Cyclosporine

Prednisone

Sirolimus

Anti-Infection Medication

Bacterial Infection

Fungal  Infection

Sulfamethoxazole / Trimethoprim

Pentamidine

Dapsone

Fluconazole

Viral  Infection

Valganciclovir

Valacyclovir

Lamivudine

About Us

Contact Us

");

//Footer social icons
//$(".icons").html("

Twitter

Facebook

GitHub

LinkedIn

Google+

");

//Footer copyright content
$(".copyright").html("

© EMIT 2016. All rights reserved.

The information on this website is intended to supplement the advice given to you by your transplant team. There may be side effects or instructions that are not listed on this website. If you feel you need more information, please contact your transplant physician or clinical pharmacist.

");<commit_msg>Main nav current class<commit_after>/*
	Arcana by Pixelarity
	html5up.net | @ajlkn
	License: pixelarity.com/license
*/

(function($) {

	skel.breakpoints({
		wide: '(max-width: 1680px)',
		normal: '(max-width: 1280px)',
		narrow: '(max-width: 980px)',
		narrower: '(max-width: 840px)',
		mobile: '(max-width: 736px)',
		mobilep: '(max-width: 480px)'
	});

	$(function() {

		var	$window = $(window),
			$body = $('body');

		// Disable animations/transitions until the page has loaded.
			$body.addClass('is-loading');

			$window.on('load', function() {
				$body.removeClass('is-loading');
			});

		// Fix: Placeholder polyfill.
			$('form').placeholder();

		// Prioritize "important" elements on narrower.
			skel.on('+narrower -narrower', function() {
				$.prioritize(
					'.important\\28 narrower\\29',
					skel.breakpoint('narrower').active
				);
			});

		// Dropdowns.
			$('#nav > ul').dropotron({
				offsetY: -15,
				hoverDelay: 0,
				alignment: 'center'
			});

		// Off-Canvas Navigation.

			// Title Bar.
				$(
					'
' +
						'' +
						'' +
					'
'
				)
					.appendTo($body);

			// Navigation Panel.
				$(
					'
' +
						'' +
							$('#nav').navList() +
						'' +
					'
'
				)
					.appendTo($body)
					.panel({
						delay: 500,
						hideOnClick: true,
						hideOnSwipe: true,
						resetScroll: true,
						resetForms: true,
						side: 'left',
						target: $body,
						visibleClass: 'navPanel-visible'
					});

			// Fix: Remove navPanel transitions on WP<10 (poor/buggy performance).
				if (skel.vars.os == 'wp' && skel.vars.osVersion < 10)
					$('#titleBar, #navPanel, #page-wrapper')
						.css('transition', 'none');

	});

})(jQuery);

//Slick slider
$(document).ready(function(){
    //Drug page slider, no autoplay
      $('.slider').slick({
        dots: true,
        slidesToShow: 1,
          cssEase: 'linear'
      });
    //Home page slider, autoplay
      $('.slider-home').slick({
        dots: true,
        slidesToShow: 1,
          autoplay: true,
        autoplaySpeed: 5000,
          cssEase: 'linear'
      });
    });

//Navigation
$("#nav").html("

Home
" +
"
General Medication Info
" +
"
Rejection
" +
"
Vaccination After Transplant
" +
"
Over-the-Counter Medication
" +
"
Cytotoxic Safety Precautions
" +
"
Dental Protocol
" +
"
Cancer Risks

" +
"
Anti-Rejection Medication
" +
"
Tacrolimus
" +
"
Mycophenolate
" +
"
Azathioprine
" +
"
Cyclosporine
" +
"
Prednisone
" +
"
Sirolimus

" +
"
Anti-Infection Medication
" +
"
Bacterial Infection
" +
"
Fungal  Infection
" +
"
Sulfamethoxazole / Trimethoprim
" +
"
Pentamidine
" +
"
Dapsone
" +
"
Fluconazole

" +
"
Viral  Infection
" +
"
Valganciclovir
" +
"
Valacyclovir
" +
"
Lamivudine

" +
"
About Us

Contact Us

");

(function() {
	var nav = document.getElementById('nav'),
	anchor = nav.getElementsByTagName('a'),
	current = window.location.pathname.split('/')[1];
	for (var i = 0; i < anchor.length; i++) {
		var anchorMenu = anchor[i].pathname.split('/')[1] //anchor[i].href.split('/')[3]
		if(anchorMenu == current) {
			anchor[i].parentElement.className = "current";
		}
	}
})();

//Footer social icons
//$(".icons").html("

Twitter

Facebook

GitHub

LinkedIn

Google+

");

//Footer copyright content
$(".copyright").html("

© EMIT 2016. All rights reserved.

The information on this website is intended to supplement the advice given to you by your transplant team. There may be side effects or instructions that are not listed on this website. If you feel you need more information, please contact your transplant physician or clinical pharmacist.

");
<|endoftext|>


<commit_before>doQuery = function(query){
    var collection = [],
        query = document.querySelectorAll(query);
    if(query.length > 0) {
        query.map(function(e) {
            collection.push(e);
        });
    }
    return collection;
}

isArray = function(obj){
    if(obj.constructor == Array)
        return true;
    return false;
}

// retorna a quantidade de um item
Array.prototype.occurrences = function(comparison) {
    var
        _arr = this.sort();
        count = 0;
    ;

    // talvez fosse interessante não usar o map para otimizar, testando até determinado item se diferente do próximo
    _arr.map(function(item) {
        if(item === comparison) { count++; }
    });
    return count;
}

Array.prototype.css = function(attr, value) {
    var collection = this;
    if(attr.constructor === Object) {
        var attrs = attr;
        collection.map(function(e) {
            for(i in attrs){
                if( attrs.hasOwnProperty(i) ){
                    e.style[i] = attr[i];
                }
            }
        });
    } else {
        collection.map(function(e) {
            e.style[attr] = value;
        });
    }
    return this;
}

Array.prototype.item = function(index) {
    var _a = this;
    if(_a.hasOwnProperty(index)) {
        return this[index];
    }
    return null;
}

Array.prototype.without = function(items) {
    var _a = this;

    if( isString(items) ){
        items = items.split(",");
    }

    items.map(function (v) {
        if ( isString(v) ) {
            _a = removeItem(_a, v.trim());
        } else {
            _a = removeItem(_a, v);
        }
    });

    return _a;
}

var removeItem = function(array, item) {
    var _new = [];

    array.map(function (v){
        if (! v === item ){
            _new.push(v);
        }
    });

    return _new;
}

Array.prototype.compressed = function() {
    var
        _a = this,
        _new = []
    ;

    _a.map(function(v) {
        if( !(v === null || v === undefined) ) {
            _new.push(v);
        }
    });

    return _new;
}

HTMLElement.prototype.next = function() {
    return this.nextElementSibling;
}

Array.prototype.prev = function(selector) {
    var collection = [];

    this.map(function(e) {
        if(e.previousElementSibling){
            collection.push(e.previousElementSibling);
        }
    });
    return collection;
}

//
HTMLElement.prototype.is = function(selector) {
    var obj = this;

    if(selector.charAt(0) === ':'){
        switch(selector) {
            case ':hidden':
                if(obj.style.display === 'none') {
                    return true;
                }
                break;
        }
    } else {
        if(document.querySelector(selector)) {
            return true;
        }
    }

    return false;
}

Array.prototype.parents = function(nodeName){
    var _parents = [],
        collection = this,
        parent = null;

    collection.map(function(e) {
        parent = e.parentNode;
        if(nodeName) {
            if(parent.nodeName.toLowerCase() === nodeName) {
                _parents.push(parent);
            } else {
                while(true) {
                    parent = parent.parentNode;
                    if(parent){
                        if(parent.nodeName.toLowerCase() === nodeName) {
                            _parents.push(parent);
                            break;
                        }
                    } else {
                        break;
                    }
                }
            }
        } else {
            if(parent){
                _parents.push(parent);
            }
        }
    });
    return _parents;
}
<commit_msg>refatora código without mudando seu nome para destroy pois agora ele, efetivamente remove o item<commit_after>doQuery = function(query){
    var collection = [],
        query = document.querySelectorAll(query);
    if(query.length > 0) {
        query.map(function(e) {
            collection.push(e);
        });
    }
    return collection;
}

isArray = function(obj){
    if(obj.constructor == Array)
        return true;
    return false;
}

// retorna a quantidade de um item
Array.prototype.occurrences = function(comparison) {
    var
        _arr = this.sort();
        count = 0;
    ;

    // talvez fosse interessante não usar o map para otimizar, testando até determinado item se diferente do próximo
    _arr.map(function(item) {
        if(item === comparison) { count++; }
    });
    return count;
}

Array.prototype.css = function(attr, value) {
    var collection = this;
    if(attr.constructor === Object) {
        var attrs = attr;
        collection.map(function(e) {
            for(i in attrs){
                if( attrs.hasOwnProperty(i) ){
                    e.style[i] = attr[i];
                }
            }
        });
    } else {
        collection.map(function(e) {
            e.style[attr] = value;
        });
    }
    return this;
}

Array.prototype.item = function(index) {
    var _a = this;
    if(_a.hasOwnProperty(index)) {
        return this[index];
    }
    return null;
}

Array.prototype.detroy = function(items) {
    var
        _a = this,
        i = 0,
        index = -1
    ;

    if(arguments.length > 1) {
        for(i in arguments) {
            while(true) {
                index = _a.indexOf(arguments[i]);
                if(index > -1) {
                    _a.splice(index, 1);
                } else {
                    break;
                }
            }
        }
    }

    return _a;
}

var removeItem = function(array, item) {
    var _new = [];

    array.map(function (v){
        if (! v === item ){
            _new.push(v);
        }
    });

    return _new;
}

Array.prototype.compressed = function() {
    var
        _a = this,
        _new = []
    ;

    _a.map(function(v) {
        if( !(v === null || v === undefined) ) {
            _new.push(v);
        }
    });

    return _new;
}

HTMLElement.prototype.next = function() {
    return this.nextElementSibling;
}

Array.prototype.prev = function(selector) {
    var collection = [];

    this.map(function(e) {
        if(e.previousElementSibling){
            collection.push(e.previousElementSibling);
        }
    });
    return collection;
}

//
HTMLElement.prototype.is = function(selector) {
    var obj = this;

    if(selector.charAt(0) === ':'){
        switch(selector) {
            case ':hidden':
                if(obj.style.display === 'none') {
                    return true;
                }
                break;
        }
    } else {
        if(document.querySelector(selector)) {
            return true;
        }
    }

    return false;
}

Array.prototype.parents = function(nodeName){
    var _parents = [],
        collection = this,
        parent = null;

    collection.map(function(e) {
        parent = e.parentNode;
        if(nodeName) {
            if(parent.nodeName.toLowerCase() === nodeName) {
                _parents.push(parent);
            } else {
                while(true) {
                    parent = parent.parentNode;
                    if(parent){
                        if(parent.nodeName.toLowerCase() === nodeName) {
                            _parents.push(parent);
                            break;
                        }
                    } else {
                        break;
                    }
                }
            }
        } else {
            if(parent){
                _parents.push(parent);
            }
        }
    });
    return _parents;
}
<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var Config;

Config = function() {
  return this.host = "http://192.168.9.191:12345";
};

module.exports = new Config();

},{}],2:[function(require,module,exports){
var Course, CourseListController, config,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

config = require('../config');

Course = require('../models/courses');

CourseListController = (function(superClass) {
  extend(CourseListController, superClass);

  CourseListController.prototype.url = config.host + "/api/v2/courses";

  CourseListController.prototype.el = '#course-list';

  CourseListController.prototype.className = 'courses';

  function CourseListController() {
    this.render = bind(this.render, this);
    CourseListController.__super__.constructor.apply(this, arguments);
    Course.bind("refresh change", this.render);
    Course.fetch();
  }

  CourseListController.prototype.template = function(items) {
    return require('../views/course')(items);
  };

  CourseListController.prototype.render = function() {
    return this.html(this.template(Course.all()));
  };

  return CourseListController;

})(Spine.Controller);

module.exports = CourseListController;

},{"../config":1,"../models/courses":4,"../views/course":5}],3:[function(require,module,exports){
var App, CourseListController, config,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

config = require("./config.coffee");

Spine.Model.host = config.host;

CourseListController = require('./controllers/courses');

App = (function(superClass) {
  extend(App, superClass);

  App.prototype.el = 'body';

  App.prototype.className = 'app';

  function App() {
    App.__super__.constructor.apply(this, arguments);
    this.courseListController = new CourseListController();
    Spine.Route.setup();
  }

  return App;

})(Spine.Controller);

$(function() {
  return new App();
});

},{"./config.coffee":1,"./controllers/courses":2}],4:[function(require,module,exports){
var Course,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Course = (function(superClass) {
  extend(Course, superClass);

  function Course() {
    return Course.__super__.constructor.apply(this, arguments);
  }

  Course.configure("Course", "name");

  Course.extend(Spine.Model.Ajax);

  Course.url = "/api/v2/courses";

  Course.beforeFromJSON = function(data) {
    console.log('beforeFromJSON');
    console.log(data['courses']);
    return data['courses'];
  };

  return Course;

})(Spine.Model);

module.exports = Course;

},{}],5:[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [], __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  }, __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  }, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
  __safe = __obj.safe = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else {
      if (!(typeof value !== 'undefined' && value != null)) value = '';
      var result = new String(value);
      result.ecoSafe = true;
      return result;
    }
  };
  if (!__escape) {
    __escape = __obj.escape = function(value) {
      return ('' + value)
        .replace(/&/g, '&')
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"');
    };
  }
  (function() {
    (function() {
      var course, i, len;

      __out.push('\n  course list\n\n\n
\n  ');

      for (i = 0, len = this.length; i < len; i++) {
        course = this[i];
        __out.push('\n
');
        __out.push(__sanitize(course.name));
        __out.push('
\n  ');
      }

      __out.push('\n
\n');

    }).call(this);

  }).call(__obj);
  __obj.safe = __objSafe, __obj.escape = __escape;
  return __out.join('');
}
},{}]},{},[3])
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi9yb290L3Byb2plY3RzL2xlYW5pbmctZnJvbnRlbmQvbm9kZV9tb2R1bGVzL2d1bHAtYnJvd3NlcmlmeS9ub2RlX21vZHVsZXMvYnJvd3NlcmlmeS9ub2R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5wdXNoKCdcXG48L2Rpdj5cXG4nKTtcbiAgICBcbiAgICB9KS5jYWxsKHRoaXMpO1xuICAgIFxuICB9KS5jYWxsKF9fb2JqKTtcbiAgX19vYmouc2FmZSA9IF9fb2JqU2FmZSwgX19vYmouZXNjYXBlID0gX19lc2NhcGU7XG4gIHJldHVybiBfX291dC5qb2luKCcnKTtcbn0iXX0=
<commit_msg>删除这个文件，ignore之<commit_after><|endoftext|>


<commit_before>var Node = require('../Node').Node;

exports.UseStatement = function (identifiers) {
  var self = this;
  Node.call(self);

  self.type = 'UseStatement';

  self.identifiers = identifiers;
  self.identifiers.forEach(function (id) {
    id.parent = self;
  });
};

exports.UseStatement.predefinedCollections = {
  'browser': [
    'document',
    'window',
    'screen',
    'location',
    'navigator',
    'alert',
    'console'
  ]
};

exports.UseStatement.prototype = Object.create(Node);

exports.UseStatement.prototype.codegen = function () {
  if (!Node.prototype.codegen.call(this)) {
    return;
  }

  var context = this.getContext().node;

  this.identifiers.forEach(function (id) {
    if (id.predefinedCollection) {
      exports.UseStatement.predefinedCollections[id.name]
        .forEach(function (p) {
          context.defineIdentifier({ name: p });
        });
    } else {
      context.defineIdentifier(id);
    }
  });

  return null;
};<commit_msg>add support for :node in use statement<commit_after>var Node = require('../Node').Node;

exports.UseStatement = function (identifiers) {
  var self = this;
  Node.call(self);

  self.type = 'UseStatement';

  self.identifiers = identifiers;
  self.identifiers.forEach(function (id) {
    id.parent = self;
  });
};

exports.UseStatement.predefinedCollections = {
  'browser': [
    'document',
    'window',
    'screen',
    'location',
    'navigator',
    'alert',
    'console'
  ],

  'node': [
    'require',
    'exports',
    'module',
    'global',
    'console',
    'process'
  ]
};

exports.UseStatement.prototype = Object.create(Node);

exports.UseStatement.prototype.codegen = function () {
  if (!Node.prototype.codegen.call(this)) {
    return;
  }

  var context = this.getContext().node;

  this.identifiers.forEach(function (id) {
    if (id.predefinedCollection) {
      exports.UseStatement.predefinedCollections[id.name]
        .forEach(function (p) {
          context.defineIdentifier({ name: p });
        });
    } else {
      context.defineIdentifier(id);
    }
  });

  return null;
};<|endoftext|>


<commit_before>// Add all the ES6 library features that my be missing.
require ("babel-polyfill");

// Get our browser up to date with polyfills.
let Modernizr = require("modernizr");
if (!Modernizr.classlist) {
  require('classlist-polyfill'); // DOM element classList support.
}
if (!Modernizr.dataset) {
  require('dataset');  // dataSet accessort support.
}

// Bring in foundation and custom libraries.
require('foundation/js/foundation/foundation');
let WOW = require('wow.js/src/wow.coffee');
new WOW().init();
require('./components.js');

// Things that run on document.ready().
require('./vendor/jquery-accessible-simple-tooltip-aria.js'); // Only used in facility-locator index and some playbook examples.
require('./vendor/menu.js');

// Poor-man's client-side router. If more than the healthcare-app
// starts using this functionality, then replace with a real client-side
// routing library.
if (window.location.pathname === '/health-care/form.html') {
  if (__DEV__) {
    // Use code chunking because most pages do not need this piece of JS.
    require.ensure([], function(require) {
      let HealthApp = require('../../_health-care/_js/_form.js');
      $(document).ready(HealthApp.initForm);
      window.HealthApp = HealthApp;  // Attach to window for easy debugging.
    });
  }
}
<commit_msg>remove extra space.<commit_after>// Add all the ES6 library features that my be missing.
require("babel-polyfill");

// Get our browser up to date with polyfills.
let Modernizr = require("modernizr");
if (!Modernizr.classlist) {
  require('classlist-polyfill'); // DOM element classList support.
}
if (!Modernizr.dataset) {
  require('dataset');  // dataSet accessort support.
}

// Bring in foundation and custom libraries.
require('foundation/js/foundation/foundation');
let WOW = require('wow.js/src/wow.coffee');
new WOW().init();
require('./components.js');

// Things that run on document.ready().
require('./vendor/jquery-accessible-simple-tooltip-aria.js'); // Only used in facility-locator index and some playbook examples.
require('./vendor/menu.js');

// Poor-man's client-side router. If more than the healthcare-app
// starts using this functionality, then replace with a real client-side
// routing library.
if (window.location.pathname === '/health-care/form.html') {
  if (__DEV__) {
    // Use code chunking because most pages do not need this piece of JS.
    require.ensure([], function(require) {
      let HealthApp = require('../../_health-care/_js/_form.js');
      $(document).ready(HealthApp.initForm);
      window.HealthApp = HealthApp;  // Attach to window for easy debugging.
    });
  }
}
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from "react-router-dom";

import {
  DASHBOARD_INDEX_URL,
  LOGIN_URL,
  HOME_URL,
  LOGOUT_URL
} from "./urls/constants";
import { Authenticator } from "./authentication/auth";
import LoginView from "./authentication/login";
import Header from "./fragments/header";
import Footer from "./fragments/footer";
import { HomePage } from "./home/home";
import { Dashboard } from "./dashboard";
import { LogoutView } from "./authentication/logout";

const BetterSelfRouter = () => (
  <Router>

      {/*Public Routes*/}
      <Route exact path={HOME_URL} component={HomePage} />

      <Route path={LOGIN_URL} component={LoginView} />
      <Route path={LOGOUT_URL} component={LogoutView} />

      {/* TODO Routes and Components */}
      {/*<Route path={SETTINGS_URL} component={LoggedOutView} />*/}
      {/*<Route path={DASHBOARD_OVERVIEW_URL} component={LoggedOutView} />*/}

      {/*Private Routes*/}
      <PrivateRoute path={DASHBOARD_INDEX_URL} component={Dashboard} />

  </Router>
);

const PrivateRoute = ({ component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      (Authenticator.isAuthenticated
        ? React.createElement(component, props)
        : <Redirect
            to={{
              pathname: LOGIN_URL,
              state: { from: props.location }
            }}
          />)}
  />
);

ReactDOM.render(<BetterSelfRouter />, document.getElementById("root"));
<commit_msg>[REFACTOR] Switch over to exact path instead<commit_after>import React, { PropTypes, Component } from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from "react-router-dom";

import {
  DASHBOARD_INDEX_URL,
  LOGIN_URL,
  HOME_URL,
  LOGOUT_URL
} from "./urls/constants";
import { Authenticator } from "./authentication/auth";
import LoginView from "./authentication/login";
import Header from "./fragments/header";
import Footer from "./fragments/footer";
import { HomePage } from "./home/home";
import { Dashboard } from "./dashboard";
import { LogoutView } from "./authentication/logout";

const BetterSelfRouter = () => (
  <Router>

      {/*Public Routes*/}
      <Route exact path={HOME_URL} component={HomePage} />

      <Route exact path={LOGIN_URL} component={LoginView} />
      <Route exact path={LOGOUT_URL} component={LogoutView} />

      {/* TODO Routes and Components */}
      {/*<Route exact path={SETTINGS_URL} component={LoggedOutView} />*/}
      {/*<Route exact path={DASHBOARD_OVERVIEW_URL} component={LoggedOutView} />*/}

      {/*Private Routes*/}
      <PrivateRoute path={DASHBOARD_INDEX_URL} component={Dashboard} />

  </Router>
);

const PrivateRoute = ({ component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      (Authenticator.isAuthenticated
        ? React.createElement(component, props)
        : <Redirect
            to={{
              pathname: LOGIN_URL,
              state: { from: props.location }
            }}
          />)}
  />
);

ReactDOM.render(<BetterSelfRouter />, document.getElementById("root"));
<|endoftext|>


<commit_before>if (typeof jQuery === "undefined") { throw new Error("Marky requires jQuery") }

// Global variables
var links = [
    [
        "intro-link",
        "basics-link",
        "headers-link",
        "links-link",
        "codes-link",
        "lists-link",
        "quotes-link",
        "images-link",
        "paragraphs-link",
        "play-link"
    ],
    [
        "subtopic-1",
        "subtopic-2",
        "subtopic-3",
        "subtopic-4",
        "subtopic-5",
        "subtopic-6"
    ]
];

// Functions
function resetThenColor(element) {
    var listIndex = 0;

    // Check which nav list is the selected element in
    if (element.indexOf("subtopic") > -1) { listIndex = 1; } // Selected element is in the subtopic nav list

    for (var counter = 0; counter < links[listIndex].length; counter++) {
        $("#" + links[listIndex][counter]).css("border-bottom-color", "#ffffff");
        $("#" + links[listIndex][counter]).css("cursor", "pointer");
    }

    $(element).css("border-bottom-color", "#1c9041");
    $(element).css("cursor", "initial");
}

function initPage() {
    resetThenColor("#intro-link");
    $("#topic-title").html("IntroductionWhat is Markdown?");
    $("span#info-text > ul li").css("display", "none");
    $("p#topic-instructions").html("According to Wikipedia, Markdown is a markup language with plain text formatting syntax designed so that it can be converted to HTML and many other formats using a tool by the same name. Markdown is often used to format readme files, for writing messages in online discussion forums, and to create rich text using a plain text editor.

To start learning about markdown, press the 'Next' button on the lower right.");
    $("div#markdown-playground").css("display", "none");
    $("button#submit-md").prop("class", "btn btn-primary disabled");
}

// User interactions with Marky
$(document).ready(function() {
    initPage(); // Initial set-up

    // Make the selected
 'active'
    $("li").click(function() {
        var li_ID = $(this).attr("id");
        resetThenColor("#" + li_ID);
    });
});<commit_msg>Added the content for 'intro' and 'basics'. No code evaluation yet.<commit_after>if (typeof jQuery === "undefined") { throw new Error("Marky requires jQuery") }

// Global variables
var links = [
    [
        "intro-link",
        "basics-link",
        "headers-link",
        "links-link",
        "codes-link",
        "lists-link",
        "quotes-link",
        "images-link",
        "paragraphs-link",
        "play-link"
    ],
    [
        "subtopic-1",
        "subtopic-2",
        "subtopic-3",
        "subtopic-4",
        "subtopic-5",
        "subtopic-6"
    ]
];

var currentPage = "intro";
var subtopicPage = "";

// Functions
function resetThenColor(element) {
    var listIndex = 0;

    // Check which nav list is the selected element in
    if (element.indexOf("subtopic") > -1) { listIndex = 1; } // Selected element is in the subtopic nav list

    for (var counter = 0; counter < links[listIndex].length; counter++) {
        $("#" + links[listIndex][counter]).css("border-bottom-color", "#ffffff");
        $("#" + links[listIndex][counter]).css("cursor", "pointer");
    }

    $(element).css("border-bottom-color", "#1c9041");
    $(element).css("cursor", "initial");
}

function initPage() {
    resetThenColor("#intro-link");
    $("#topic-title").html("IntroductionWhat is Markdown?");
    $("span#info-text > ul li").css("display", "none");
    $("p#topic-instructions").html("According to Wikipedia, Markdown is a markup language with plain text formatting syntax designed so that it can be converted to HTML and many other formats using a tool by the same name. Markdown is often used to format readme files, for writing messages in online discussion forums, and to create rich text using a plain text editor.

To start learning about markdown, press the 'Next' button on the lower right.");
    $("div#markdown-playground").css("display", "none");
    $("button#submit-md").attr("class", "btn btn-primary disabled");
    currentPage = "intro";
}

function initBasics() {
    resetThenColor("#basics-link");
    $("#topic-title").html("BasicsBold");
    $("span#info-text > ul li#subtopic-1").css("display", "inline");
    $("span#info-text > ul li#subtopic-2").css("display", "inline");
    $("span#info-text > ul li#subtopic-3").css("display", "inline");
    $("span#info-text > ul li#subtopic-1").html("Bold");
    $("span#info-text > ul li#subtopic-2").html("Italic");
    $("span#info-text > ul li#subtopic-3").html("Strikethrough");
    $("div#markdown-playground").css("display", "inline");
    $("button#submit-md").attr("class", "btn btn-primary disabled");
    basicsPage("subtopic-1");
    currentPage = "basics";
}

function basicsPage(subtopic) {
    resetThenColor("#" + subtopic);
    $("button#next-md").attr("class", "btn btn-info disabled");
    $("button#submit-md").attr("class", "btn btn-primary");

    switch(subtopic) {
        case "subtopic-1":
            $("#topic-title").html("BasicsBold");
            $("p#topic-instructions").html("Bold words in text emphasize a remark or comment. To turn a word or group of words into bold, place two stars (*) before and after the word/s.

For example:
Marky is awesome
in markdown is
**Marky is awesome**.

Now try it on your own.");
            subtopicPage = "bold";
            break;
        case "subtopic-2":
            $("#topic-title").html("BasicsItalic");
            $("p#topic-instructions").html("Italicized words in text emphasize a key point or, according to Wikipedia, quote a speaker as a way to show which words they stressed. To turn a word or group of words into italicized text, place one stars (*) before and after the word/s.

For example:
\"It's not called being gay, it's called being FABULOUS!\"
in markdown is
*\"It's not called being gay, it's called being FABULOUS!\"*.

Now try it on your own.");
            subtopicPage = "italic";
            break;
        case "subtopic-3":
            $("#topic-title").html("BasicsStrikethrough");
            $("p#topic-instructions").html("Strikethrough words in text meant that those words are not meant for inclusion. To strikethrough a word or words, place two tildes (~) before and after the word/s.

For example:
<s>A MacBook Pro costs $199.99</s>
in markdown is
~~A MacBook Pro costs $199.99~~.

Now try it on your own.");
            subtopicPage = "strikethrough";
            break;
    }

    console.log("Passed by basicsPage()");
}

// User interactions with Marky
$(document).ready(function() {
    initPage(); // Initial set-up

    // Make the selected
 'active'
    $("li").click(function() {
        var li_ID = $(this).attr("id");
        li_ID = "#" + li_ID;
        resetThenColor(li_ID);
    });

    /******************************************************/
    /*   Events to handle events with the "Basics" page   */
    /******************************************************/
    $("li#basics-link").click(function() {
        initBasics();

        if (subtopicPage == "") {
            basicsPage("bold");
        }

        resetThenColor("#basics-link");
        console.log("Basics");
    });

    $("li#subtopic-1").click(function() { // Points to "bold"
        if (currentPage == "basics") {
            basicsPage("subtopic-1");
        }

        resetThenColor("#subtopic-1");
        console.log("Bold");
    });

    $("li#subtopic-2").click(function() { // Points to "bold"
        if (currentPage == "basics") {
            basicsPage("subtopic-2");
        }

        resetThenColor("#subtopic-2");
        console.log("Italic");
    });

    $("li#subtopic-3").click(function() { // Points to "bold"
        if (currentPage == "basics") {
            basicsPage("subtopic-3");
        }

        resetThenColor("#subtopic-3");
        console.log("Strikethrough");
    });

    /******************************************************/
});<|endoftext|>


<commit_before>import ExtractTextPlugin from 'extract-text-webpack-plugin'
import { defaults, cloneDeep } from 'lodash'
import { join, resolve } from 'path'
import webpack from 'webpack'
import { isUrl, urlJoin } from 'utils'
import autoprefixer from 'autoprefixer'
import vueLoaderConfig from './vue-loader.config'
import { styleLoader, extractStyles } from './helpers'

/*
|--------------------------------------------------------------------------
| Webpack Shared Config
|
| This is the config which is extended by the server and client
| webpack config files
|--------------------------------------------------------------------------
*/
export default function webpackBaseConfig ({ isClient, isServer }) {
  const nodeModulesDir = join(__dirname, '..', 'node_modules')

  /* istanbul ignore if */
  if (!Array.isArray(this.options.build.postcss)) {
    this.options.build.postcss = [
      autoprefixer({
        browsers: ['last 3 versions']
      })
    ]
  }

  const config = {
    devtool: this.options.dev ? 'cheap-module-source-map' : 'nosources-source-map',
    entry: {
      vendor: ['vue', 'vue-router', 'vue-meta']
    },
    output: {
      path: resolve(this.options.buildDir, 'dist'),
      filename: this.options.build.filenames.app,
      publicPath: (isUrl(this.options.build.publicPath)
        ? this.options.build.publicPath
        : urlJoin(this.options.router.base, this.options.build.publicPath))
    },
    performance: {
      maxEntrypointSize: 1000000,
      maxAssetSize: 300000,
      hints: this.options.dev ? false : 'warning'
    },
    resolve: {
      extensions: ['.js', '.json', '.vue', '.ts'],
      alias: {
        '~': join(this.options.srcDir),
        '~~': join(this.options.rootDir),
        '@': join(this.options.srcDir),
        '@@': join(this.options.rootDir),
        'static': join(this.options.srcDir, 'static'), // use in template with
        'assets': join(this.options.srcDir, 'assets') // use in template with
      },
      modules: [
        join(this.options.rootDir, 'node_modules'),
        nodeModulesDir
      ]
    },
    resolveLoader: {
      modules: [
        join(this.options.rootDir, 'node_modules'),
        nodeModulesDir
      ]
    },
    module: {
      noParse: /es6-promise\.js$/, // avoid webpack shimming process
      rules: [
        {
          test: /\.vue$/,
          loader: 'vue-loader',
          query: vueLoaderConfig.call(this, { isClient, isServer })
        },
        {
          test: /\.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: defaults(this.options.build.babel, {
            presets: ['vue-app'],
            babelrc: false,
            cacheDirectory: !!this.options.dev
          })
        },
        { test: /\.css$/, use: styleLoader.call(this, 'css') },
        { test: /\.less$/, use: styleLoader.call(this, 'less', 'less-loader') },
        { test: /\.sass$/, use: styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax&sourceMap') },
        { test: /\.scss$/, use: styleLoader.call(this, 'sass', 'sass-loader?sourceMap') },
        { test: /\.styl(us)?$/, use: styleLoader.call(this, 'stylus', 'stylus-loader') },
        {
          test: /\.(png|jpe?g|gif|svg)$/,
          loader: 'url-loader',
          query: {
            limit: 1000, // 1KO
            name: 'img/[name].[hash:7].[ext]'
          }
        },
        {
          test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
          loader: 'url-loader',
          query: {
            limit: 1000, // 1 KO
            name: 'fonts/[name].[hash:7].[ext]'
          }
        },
        {
          test: /\.(webm|mp4)$/,
          loader: 'file'
        }
      ]
    },
    plugins: this.options.build.plugins
  }

  // CSS extraction
  if (extractStyles.call(this)) {
    config.plugins.push(
      new ExtractTextPlugin({ filename: this.options.build.filenames.css })
    )
  }

  // Workaround for hiding Warnings about plugins without a default export (#1179)
  config.plugins.push({
    apply (compiler) {
      compiler.plugin('done', stats => {
        stats.compilation.warnings = stats.compilation.warnings.filter(warn => {
          if (warn.name === 'ModuleDependencyWarning' && warn.message.includes(`export 'default'`) && warn.message.includes('plugin')) {
            return false
          }
          return true
        })
      })
    }
  })

  // --------------------------------------
  // Dev specific config
  // --------------------------------------
  if (this.options.dev) {
    //
  }

  // --------------------------------------
  // Production specific config
  // --------------------------------------
  if (!this.options.dev) {
    // This is needed in webpack 2 for minify CSS
    config.plugins.push(
      new webpack.LoaderOptionsPlugin({
        minimize: true
      })
    )

    // Scope Hoisting
    // config.plugins.push(
    //   new webpack.optimize.ModuleConcatenationPlugin()
    // )
  }

  // Clone deep avoid leaking config between Client and Server
  return cloneDeep(config)
}
<commit_msg>Update base.config.js<commit_after>import ExtractTextPlugin from 'extract-text-webpack-plugin'
import { defaults, cloneDeep } from 'lodash'
import { join, resolve } from 'path'
import webpack from 'webpack'
import { isUrl, urlJoin } from 'utils'
import autoprefixer from 'autoprefixer'
import vueLoaderConfig from './vue-loader.config'
import { styleLoader, extractStyles } from './helpers'

/*
|--------------------------------------------------------------------------
| Webpack Shared Config
|
| This is the config which is extended by the server and client
| webpack config files
|--------------------------------------------------------------------------
*/
export default function webpackBaseConfig ({ isClient, isServer }) {
  const nodeModulesDir = join(__dirname, '..', 'node_modules')

  /* istanbul ignore if */
  if (!Array.isArray(this.options.build.postcss)) {
    this.options.build.postcss = [
      autoprefixer({
        browsers: ['last 3 versions']
      })
    ]
  }

  const config = {
    devtool: this.options.dev ? 'cheap-module-source-map' : 'nosources-source-map',
    entry: {
      vendor: ['vue', 'vue-router', 'vue-meta']
    },
    output: {
      path: resolve(this.options.buildDir, 'dist'),
      filename: this.options.build.filenames.app,
      publicPath: (isUrl(this.options.build.publicPath)
        ? this.options.build.publicPath
        : urlJoin(this.options.router.base, this.options.build.publicPath))
    },
    performance: {
      maxEntrypointSize: 1000000,
      maxAssetSize: 300000,
      hints: this.options.dev ? false : 'warning'
    },
    resolve: {
      extensions: ['.js', '.json', '.vue', '.ts'],
      alias: {
        '~': join(this.options.srcDir),
        '~~': join(this.options.rootDir),
        '@': join(this.options.srcDir),
        '@@': join(this.options.rootDir),
        'static': join(this.options.srcDir, 'static'), // use in template with
        'assets': join(this.options.srcDir, 'assets') // use in template with
      },
      modules: [
        join(this.options.rootDir, 'node_modules'),
        nodeModulesDir
      ]
    },
    resolveLoader: {
      modules: [
        join(this.options.rootDir, 'node_modules'),
        nodeModulesDir
      ]
    },
    module: {
      noParse: /es6-promise\.js$/, // avoid webpack shimming process
      rules: [
        {
          test: /\.vue$/,
          loader: 'vue-loader',
          query: vueLoaderConfig.call(this, { isClient, isServer })
        },
        {
          test: /\.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: defaults(this.options.build.babel, {
            presets: ['vue-app'],
            babelrc: false,
            cacheDirectory: !!this.options.dev
          })
        },
        { test: /\.css$/, use: styleLoader.call(this, 'css') },
        { test: /\.less$/, use: styleLoader.call(this, 'less', 'less-loader') },
        { test: /\.sass$/, use: styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax&sourceMap') },
        { test: /\.scss$/, use: styleLoader.call(this, 'sass', 'sass-loader?sourceMap') },
        { test: /\.styl(us)?$/, use: styleLoader.call(this, 'stylus', 'stylus-loader') },
        {
          test: /\.(png|jpe?g|gif|svg)$/,
          loader: 'url-loader',
          query: {
            limit: 1000, // 1KO
            name: 'img/[name].[hash:7].[ext]'
          }
        },
        {
          test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
          loader: 'url-loader',
          query: {
            limit: 1000, // 1 KO
            name: 'fonts/[name].[hash:7].[ext]'
          }
        },
        {
          test: /\.(webm|mp4)$/,
          loader: 'file',
          query: {
            name: 'videos/[name].[hash:7].[ext]'
          }
        }
      ]
    },
    plugins: this.options.build.plugins
  }

  // CSS extraction
  if (extractStyles.call(this)) {
    config.plugins.push(
      new ExtractTextPlugin({ filename: this.options.build.filenames.css })
    )
  }

  // Workaround for hiding Warnings about plugins without a default export (#1179)
  config.plugins.push({
    apply (compiler) {
      compiler.plugin('done', stats => {
        stats.compilation.warnings = stats.compilation.warnings.filter(warn => {
          if (warn.name === 'ModuleDependencyWarning' && warn.message.includes(`export 'default'`) && warn.message.includes('plugin')) {
            return false
          }
          return true
        })
      })
    }
  })

  // --------------------------------------
  // Dev specific config
  // --------------------------------------
  if (this.options.dev) {
    //
  }

  // --------------------------------------
  // Production specific config
  // --------------------------------------
  if (!this.options.dev) {
    // This is needed in webpack 2 for minify CSS
    config.plugins.push(
      new webpack.LoaderOptionsPlugin({
        minimize: true
      })
    )

    // Scope Hoisting
    // config.plugins.push(
    //   new webpack.optimize.ModuleConcatenationPlugin()
    // )
  }

  // Clone deep avoid leaking config between Client and Server
  return cloneDeep(config)
}
<|endoftext|>


<commit_before>EvtPerJobPerDate = new Mongo.Collection('evtPerJobPerDate');

var numLPad = function(number, length){
  var ns = number.toString();
  if (typeof length == 'undefined') length = 2;
  while(ns.length < length)
    ns = "0" + ns;
  return ns;
}
/*
 * Mongo aggregation is not available in mini-mongo (on client).
 */
if (Meteor.isServer) {
  Meteor.methods({
    compileYearTotal: function (breakdownType, selectedJobs, period) {
      return compileTotal(breakdownType, selectedJobs, period, "P1Y");
    },
    compileMonthTotal: function (breakdownType, selectedJobs, period) {
      return compileTotal(breakdownType, selectedJobs, period, "P1M");
    },
    compileDayTotal: function (breakdownType, selectedJobs, period) {
      return compileTotal(breakdownType, selectedJobs, period, "P1D");
    },
    compileDailyAgg: function(breakdownType, selectedJobs, date, tzOffset) {
      //FIXME 1. date filter (in range date-1y)
      var all;
      var tzOffsetMs = tzOffset * 60 * 1000; //from min to ms
      //FIXME: $substract applied 3 times, but one should be sufficient (using projection?)
      switch(breakdownType) {
        case "rtBreakdown":
          all = Events.aggregate(
            [
              {$match: {jobId : {$in: selectedJobs}}},
              {$group: {
                  _id:  {
                      "year": { $year:[{ $subtract: [ "$etime", tzOffsetMs ]}]},
                      "month": { $month:[{ $subtract: [ "$etime", tzOffsetMs ]}]},
                      "day": { $dayOfMonth:[{ $subtract: [ "$etime", tzOffsetMs ]}]}
                  },
                  val: {$avg: "$responseTime"}
                  }
              }
            ]
          );
        break;
        case "errorBreakdown":
          all = Events.aggregate(
            [
              {$match: {jobId : {$in: selectedJobs}}},
              { $project: {
                jobId: "$jobId",
                etime: "$etime",
                prob: {$cond: [{$eq: ['$isProblematic', true]}, 1, 0]},
              }},
              {$group: {
                  _id:  {
                      "year": { $year:[{ $subtract: [ "$etime", tzOffsetMs ]}]},
                      "month": { $month:[{ $subtract: [ "$etime", tzOffsetMs ]}]},
                      "day": { $dayOfMonth:[{ $subtract: [ "$etime", tzOffsetMs ]}]}
                  },
                  valAll: {$sum: 1},
                  valProb: {$sum: "$prob"}
                  }
              }
            ]
          );
        break;
      }

      // [ { _id: { year: 2015, month: 4, day: 23 },
      //   count: 2064,
      //   avgRT: 258.6075581395349 },
      //   ...]
      //   to
      //   {
      //    "2014-04-29": 123.7,
      //    "2014-04-30: 153.4,
      //    ...
      //    }
      var dat = {};
      all.forEach(function(elem){
        var date = elem._id.year + "-" + numLPad(elem._id.month) + "-" + numLPad(elem._id.day);
        dat[date] = breakdownType === "rtBreakdown"?elem.val:(elem.valProb/elem.valAll)*100;
      });

      return dat;
    }

  });
}

function compileTotal(breakdownType, selectedJobs, period, range) {
  var indicator;
  var periodEnd = period;
  var periodStart;
  var total;

  if (!selectedJobs || selectedJobs.length === 0) {
    return 0;
  }

  switch(range) {
    default:
    case "P1Y":
      periodStart = new Date(periodEnd.getFullYear() -1, periodEnd.getMonth(), periodEnd.getDate());
      break;
    case "P1M":
      periodStart = new Date(periodEnd.getFullYear(), periodEnd.getMonth()-1, periodEnd.getDate());
      break;
    case "P1D":
      periodStart = new Date(periodEnd.getFullYear(), periodEnd.getMonth(), periodEnd.getDate(), 0, 0, 0, 0);
      break;
  }

  switch(breakdownType) {
    case "rtBreakdown":
      var agg = Events.aggregate(
        [
          {
            $match: {
              jobId : {$in: selectedJobs},
              etime: {
                $gte: periodStart
              }
            }
          },
          {$group: {
              _id:  0,
              avgRT: {$avg: "$responseTime"},
              count: {$sum: 1}
            }
          }
        ]
      );
      indicator = 0 < agg.length ? agg[0].avgRT : null;
      total = 0 < agg.length ? agg[0].count : null;
      break;
    case "errorBreakdown":
      indicator = Events.find({
        jobId : {$in: selectedJobs},
        isProblematic: true,
        etime: {
          $gte: periodStart
        }
      }).count();
      total = Events.find({
        jobId: {$in: selectedJobs},
        etime: {
          $gte: periodStart
        }
      }).count();
      break;
  }

  return {val: indicator, total: total};
}
<commit_msg>Optimization of compileDailyAgg<commit_after>EvtPerJobPerDate = new Mongo.Collection('evtPerJobPerDate');

var numLPad = function(number, length){
  var ns = number.toString();
  if (typeof length == 'undefined') length = 2;
  while(ns.length < length)
    ns = "0" + ns;
  return ns;
}
/*
 * Mongo aggregation is not available in mini-mongo (on client).
 */
if (Meteor.isServer) {
  Meteor.methods({
    compileYearTotal: function (breakdownType, selectedJobs, period) {
      return compileTotal(breakdownType, selectedJobs, period, "P1Y");
    },
    compileMonthTotal: function (breakdownType, selectedJobs, period) {
      return compileTotal(breakdownType, selectedJobs, period, "P1M");
    },
    compileDayTotal: function (breakdownType, selectedJobs, period) {
      return compileTotal(breakdownType, selectedJobs, period, "P1D");
    },
    compileDailyAgg: function(breakdownType, selectedJobs, date, tzOffset) {
      //FIXME 1. date filter (in range date-1y)
      var all;
      var tzOffsetMs = tzOffset * 60 * 1000; //from min to ms
      switch(breakdownType) {
        case "rtBreakdown":
          all = Events.aggregate(
            [
              {$match: {jobId : {$in: selectedJobs}}},
              {$group: {
                  _id: { $dateToString: { format: "%Y-%m-%d", date: { $subtract: [ "$etime", tzOffsetMs ]} } },
                  val: {$avg: "$responseTime"}
                  }
              }
            ]
          );
        break;
        case "errorBreakdown":
          all = Events.aggregate(
            [
              {$match: {jobId : {$in: selectedJobs}}},
              { $project: {
                jobId: "$jobId",
                etime: "$etime",
                prob: {$cond: [{$eq: ['$isProblematic', true]}, 1, 0]},
              }},
              {$group: {
                  _id: { $dateToString: { format: "%Y-%m-%d", date: { $subtract: [ "$etime", tzOffsetMs ]} } },
                  valAll: {$sum: 1},
                  valProb: {$sum: "$prob"}
                  }
              }
            ]
          );
        break;
      }

      // [ { _id: { year: 2015, month: 4, day: 23 },
      //   count: 2064,
      //   avgRT: 258.6075581395349 },
      //   ...]
      //   to
      //   {
      //    "2014-04-29": 123.7,
      //    "2014-04-30: 153.4,
      //    ...
      //    }
      var dat = {};
      all.forEach(function(elem){
        var date = elem._id;
        dat[date] = breakdownType === "rtBreakdown"?elem.val:(elem.valProb/elem.valAll)*100;
      });

      return dat;
    }

  });
}

function compileTotal(breakdownType, selectedJobs, period, range) {
  var indicator;
  var periodEnd = period;
  var periodStart;
  var total;

  if (!selectedJobs || selectedJobs.length === 0) {
    return 0;
  }

  switch(range) {
    default:
    case "P1Y":
      periodStart = new Date(periodEnd.getFullYear() -1, periodEnd.getMonth(), periodEnd.getDate());
      break;
    case "P1M":
      periodStart = new Date(periodEnd.getFullYear(), periodEnd.getMonth()-1, periodEnd.getDate());
      break;
    case "P1D":
      periodStart = new Date(periodEnd.getFullYear(), periodEnd.getMonth(), periodEnd.getDate(), 0, 0, 0, 0);
      break;
  }

  switch(breakdownType) {
    case "rtBreakdown":
      var agg = Events.aggregate(
        [
          {
            $match: {
              jobId : {$in: selectedJobs},
              etime: {
                $gte: periodStart
              }
            }
          },
          {$group: {
              _id:  0,
              avgRT: {$avg: "$responseTime"},
              count: {$sum: 1}
            }
          }
        ]
      );
      indicator = 0 < agg.length ? agg[0].avgRT : null;
      total = 0 < agg.length ? agg[0].count : null;
      break;
    case "errorBreakdown":
      indicator = Events.find({
        jobId : {$in: selectedJobs},
        isProblematic: true,
        etime: {
          $gte: periodStart
        }
      }).count();
      total = Events.find({
        jobId: {$in: selectedJobs},
        etime: {
          $gte: periodStart
        }
      }).count();
      break;
  }

  return {val: indicator, total: total};
}
<|endoftext|>


<commit_before>var mongoose = require('../config/mongoose').instance();
var _ = require('lodash');
var apiOptions = require('../config/options');

var AcceptanceTest = mongoose.model('AcceptanceTest');

exports.find = function(req, res, next, id) {
    AcceptanceTest
        .findById(id)
        .populate('user', '-password')
        .populate('lastExecution', '-acceptanceTest')
        .exec(function(err, acceptanceTest) {
            if (err) return next(err);
            if (!acceptanceTest) return res.sendStatus(404);
            req.acceptanceTest = acceptanceTest;
            next();
        });
};

function list(query, req, res, next) {
    if (req.query.keyword) {
        var keywords = _.isArray(req.query.keyword) ? req.query.keyword : [req.query.keyword];
        query.where('keywords').all(keywords);
    }

    return query
        .select('-__v')
        .populate('lastExecution', '-acceptanceTest')
        .exec(function(err, acceptanceTests) {
            if (err) return next(err);
            if (req.query.organization) {
                var organizations = _.isArray(req.query.organization) ? req.query.organization : [req.query.organization];
                acceptanceTests = _.filter(acceptanceTests, function(acceptanceTest) {
                    return acceptanceTest.user && _.contains(organizations, acceptanceTest.user.organization);
                });
            }
            res.send(acceptanceTests);
        });
}

exports.list = function (req, res, next) {
    var query = AcceptanceTest.find();

    query.populate('user', '-password -isAdmin -email')
         .where('state').in(req.query.state ? _.flatten([req.query.state]) : ['validated', 'pending'])
         .where(_.pick(req.query, 'priority', 'user'));

    return list(query, req, res, next);
};

exports.listPublic = function (req, res, next) {
    var query = AcceptanceTest.find();

    query.select('-rejectionMessage -state -user -priority')
         .where('state', 'validated');

    return list(query, req, res, next);
};

exports.create = function (req, res, next) {
    var attributes = req.body;

    attributes.user = req.user._id;

    AcceptanceTest.createNew(attributes, function (err, acceptanceTest) {
        if (err) return next(err);
        res.send(acceptanceTest);
    });
};

exports.createPublic = function (req, res, next) {
    var attributes = req.body;

    delete attributes.priority;
    attributes.state = 'unclaimed';

    AcceptanceTest.createNew(attributes, function (err, acceptanceTest) {
        if (err) return next(err);
        res.send(acceptanceTest);
    });
};

exports.show = function (req, res) {
    res.send(req.acceptanceTest);
};

exports.update = function (req, res, next) {
    var expectedResults = _.map(req.body.expectedResults, function (expectedResult) {
        return _.pick(expectedResult, 'code', 'expectedValue');
    });

    if (req.acceptanceTest.state === 'unclaimed') {
        req.acceptanceTest.set('state', 'pending');
        req.acceptanceTest.set('user', req.user._id);
    }

    req.acceptanceTest
        .set('expectedResults', expectedResults)
        .set(_.pick(req.body, 'name', 'description', 'keywords'));

    if (req.user.isAdmin) {
        req.acceptanceTest.set(_.pick(req.body, 'priority'));
    }

    req.acceptanceTest.saveUpdate(req.user, function(err) {
        if (err) return next(err);
        res.send(req.acceptanceTest);
    });
};

exports.delete = function (req, res, next) {
    req.acceptanceTest.removeAll(function(err) {
        if (err) return next(err);
        res.sendStatus(204);
    });
};

exports.updateValidation = function (req, res, next) {
    req.acceptanceTest.updateValidationState(req.body.state, req.user, req.body.rejectionMessage, function(err) {
        if (err) return next(err);
        res.sendStatus(200);
    });
};

exports.showTimeline = function (req, res, next) {
    req.acceptanceTest.timeline(function (err, activities) {
        if (err) return next(err);
        res.send(activities);
    });
};

exports.showKeywords = function (req, res, next) {
    AcceptanceTest.distinct('keywords', function (err, keywords) {
        if (err) return next(err);
        res.send(keywords);
    });
};

exports.simulate = function (req, res, next) {
    req.acceptanceTest.simulate(function(err, result) {
        if (err) return next(err);
        res.send(result);
    });
};

exports.showOrganizations = function (req, res) {
    var organizations = {};

    AcceptanceTest
        .find()
        .select('user')
        .populate('user', 'organization')
        .stream()
        .on('data', function (acceptanceTest) {
            if (acceptanceTest.user && acceptanceTest.user.organization) {
                organizations[acceptanceTest.user.organization] = true;
            }
        })
        .on('end', function () {
            res.send(_.keys(organizations));
        });
};

exports.possibleValues = function(req, res) {
    res.status(200).json(apiOptions.possibleValues);
};

<commit_msg>Fix whitespace<commit_after>var mongoose = require('../config/mongoose').instance();
var _ = require('lodash');
var apiOptions = require('../config/options');

var AcceptanceTest = mongoose.model('AcceptanceTest');

exports.find = function(req, res, next, id) {
    AcceptanceTest
        .findById(id)
        .populate('user', '-password')
        .populate('lastExecution', '-acceptanceTest')
        .exec(function(err, acceptanceTest) {
            if (err) return next(err);
            if (!acceptanceTest) return res.sendStatus(404);
            req.acceptanceTest = acceptanceTest;
            next();
        });
};

function list(query, req, res, next) {
    if (req.query.keyword) {
        var keywords = _.isArray(req.query.keyword) ? req.query.keyword : [req.query.keyword];
        query.where('keywords').all(keywords);
    }

    return query
        .select('-__v')
        .populate('lastExecution', '-acceptanceTest')
        .exec(function(err, acceptanceTests) {
            if (err) return next(err);
            if (req.query.organization) {
                var organizations = _.isArray(req.query.organization) ? req.query.organization : [req.query.organization];
                acceptanceTests = _.filter(acceptanceTests, function(acceptanceTest) {
                    return acceptanceTest.user && _.contains(organizations, acceptanceTest.user.organization);
                });
            }
            res.send(acceptanceTests);
        });
}

exports.list = function (req, res, next) {
    var query = AcceptanceTest.find();

    query.populate('user', '-password -isAdmin -email')
         .where('state').in(req.query.state ? _.flatten([req.query.state]) : ['validated', 'pending'])
         .where(_.pick(req.query, 'priority', 'user'));

    return list(query, req, res, next);
};

exports.listPublic = function (req, res, next) {
    var query = AcceptanceTest.find();

    query.select('-rejectionMessage -state -user -priority')
         .where('state', 'validated');

    return list(query, req, res, next);
};

exports.create = function (req, res, next) {
    var attributes = req.body;

    attributes.user = req.user._id;

    AcceptanceTest.createNew(attributes, function (err, acceptanceTest) {
        if (err) return next(err);
        res.send(acceptanceTest);
    });
};

exports.createPublic = function (req, res, next) {
    var attributes = req.body;

    delete attributes.priority;
    attributes.state = 'unclaimed';

    AcceptanceTest.createNew(attributes, function (err, acceptanceTest) {
        if (err) return next(err);
        res.send(acceptanceTest);
    });
};

exports.show = function (req, res) {
    res.send(req.acceptanceTest);
};

exports.update = function (req, res, next) {
    var expectedResults = _.map(req.body.expectedResults, function (expectedResult) {
        return _.pick(expectedResult, 'code', 'expectedValue');
    });

    if (req.acceptanceTest.state === 'unclaimed') {
        req.acceptanceTest.set('state', 'pending');
        req.acceptanceTest.set('user', req.user._id);
    }

    req.acceptanceTest
        .set('expectedResults', expectedResults)
        .set(_.pick(req.body, 'name', 'description', 'keywords'));

    if (req.user.isAdmin) {
        req.acceptanceTest.set(_.pick(req.body, 'priority'));
    }

    req.acceptanceTest.saveUpdate(req.user, function(err) {
        if (err) return next(err);
        res.send(req.acceptanceTest);
    });
};

exports.delete = function (req, res, next) {
    req.acceptanceTest.removeAll(function(err) {
        if (err) return next(err);
        res.sendStatus(204);
    });
};

exports.updateValidation = function (req, res, next) {
    req.acceptanceTest.updateValidationState(req.body.state, req.user, req.body.rejectionMessage, function(err) {
        if (err) return next(err);
        res.sendStatus(200);
    });
};

exports.showTimeline = function (req, res, next) {
    req.acceptanceTest.timeline(function (err, activities) {
        if (err) return next(err);
        res.send(activities);
    });
};

exports.showKeywords = function (req, res, next) {
    AcceptanceTest.distinct('keywords', function (err, keywords) {
        if (err) return next(err);
        res.send(keywords);
    });
};

exports.simulate = function (req, res, next) {
    req.acceptanceTest.simulate(function(err, result) {
        if (err) return next(err);
        res.send(result);
    });
};

exports.showOrganizations = function (req, res) {
    var organizations = {};

    AcceptanceTest
        .find()
        .select('user')
        .populate('user', 'organization')
        .stream()
        .on('data', function (acceptanceTest) {
            if (acceptanceTest.user && acceptanceTest.user.organization) {
                organizations[acceptanceTest.user.organization] = true;
            }
        })
        .on('end', function () {
            res.send(_.keys(organizations));
        });
};

exports.possibleValues = function(req, res) {
    res.status(200).json(apiOptions.possibleValues);
};
<|endoftext|>