<commit_before>/*! Tappy! - a lightweight normalized tap event. Copyright 2013 @scottjehl, Filament Group, Inc. Licensed MIT */
(function( w, $, undefined ){

	var tap = function( $els ){
		return $els.each(function(){

			var $el = $( this ),
				lastE,
				resetTimer,
				lastScroll,
				scrollTolerance = 15,
				href;

			function trigger( e ){
				e.preventDefault();
				$( e.target ).trigger( "tap", [ e ] );
			}

			function start( e ){
				lastScroll = w.document.body.scrollTop;
				if( $el.is( "a" ) ){
					// set href to null hash during tap. this prevents the address bar from dropping down in iOS
					href = $el[ 0 ].href;
					console.log(href);
					$el[ 0 ].href = "#";
				}
			}

			function end( e ){

				e.preventDefault();

				// this part prevents a double callback from touch and mouse on the same tap
				if( lastE && lastE !== e.type ){
					return false;
				}

				lastE = e.type;
				clearTimeout( resetTimer );
				resetTimer = setTimeout( function(){
					lastE = null;
				}, 1000 );

				// if a scroll happened between touchstart and touchend
				if( e.type === "touchend" && Math.abs( w.document.body.scrollTop - lastScroll ) > scrollTolerance ){
					return false;
				}

				// set href back
				if( href ){
					$el[ 0 ].href = href;
				}
				href = null;

				trigger( e );
			}

			$el
				.bind( "touchstart", start )
				.bind( "touchend", end )
				.bind( "click", end );
		});
	};

	// monkeybind
	var oldBind = $.fn.bind;
	$.fn.bind = function( evt, callback ){
		if( evt === "tap" ){
			tap( this );
		}
		return oldBind.apply( this, [evt, callback] );
	};

}( this, jQuery ));<commit_msg>removed a console loggins<commit_after>/*! Tappy! - a lightweight normalized tap event. Copyright 2013 @scottjehl, Filament Group, Inc. Licensed MIT */
(function( w, $, undefined ){

	var tap = function( $els ){
		return $els.each(function(){

			var $el = $( this ),
				lastE,
				resetTimer,
				lastScroll,
				scrollTolerance = 15,
				href;

			function trigger( e ){
				e.preventDefault();
				$( e.target ).trigger( "tap", [ e ] );
			}

			function start( e ){
				lastScroll = w.document.body.scrollTop;
				if( $el.is( "a" ) ){
					// set href to null hash during tap. this prevents the address bar from dropping down in iOS
					href = $el[ 0 ].href;
					$el[ 0 ].href = "#";
				}
			}

			function end( e ){

				e.preventDefault();

				// this part prevents a double callback from touch and mouse on the same tap
				if( lastE && lastE !== e.type ){
					return false;
				}

				lastE = e.type;
				clearTimeout( resetTimer );
				resetTimer = setTimeout( function(){
					lastE = null;
				}, 1000 );

				// if a scroll happened between touchstart and touchend
				if( e.type === "touchend" && Math.abs( w.document.body.scrollTop - lastScroll ) > scrollTolerance ){
					return false;
				}

				// set href back
				if( href ){
					$el[ 0 ].href = href;
				}
				href = null;

				trigger( e );
			}

			$el
				.bind( "touchstart", start )
				.bind( "touchend", end )
				.bind( "click", end );
		});
	};

	// monkeybind
	var oldBind = $.fn.bind;
	$.fn.bind = function( evt, callback ){
		if( evt === "tap" ){
			tap( this );
		}
		return oldBind.apply( this, [evt, callback] );
	};

}( this, jQuery ));<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Like = mongoose.model('Like'),
  Poll = mongoose.model('Poll'),
  User = mongoose.model('User'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('underscore');

/**
 * Create a Like
 */
exports.create = function (req, res) {
  var like = new Like(req.body);
  var cnt = (like.type === 1) ? 1 : -1;
  like.user = req.user._id;

  like.save()
    .then(_like => {
      like = _like;
      like.user = _like.user._id || _like.user;
      return User.countUpLike(like.user);
    }, handleError)
    .then(() => {
      var pollId = like.poll._id || like.poll;
      return Poll.countLike(pollId, cnt);
    }, handleError)
    .then(_poll => {
      res.jsonp({ like: like, likeCnt: _poll.likeCnt });
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Like
 */
exports.read = function (req, res) {
  // convert mongoose document to JSON
  var like = req.like ? req.like.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  like.isCurrentUserOwner = req.user && like.user && like.user._id.toString() === req.user._id.toString();

  res.jsonp(like);
};

/**
 * Update a Like
 */
exports.update = function (req, res) {
  var like = req.like;
  // Hoán đổi 2 đơn vị
  var cnt = (like.type === 1) ? -2 : 2;

  like = _.extend(like, req.body);

  like.save()
    .then(_like => {
      like = _like;
      like.user = _like.user._id || _like.user;
      var pollId = _like.poll._id || _like.poll;
      return Poll.countLike(pollId, cnt);
    }, handleError)
    .then(_poll => {
      res.jsonp({ like: like, likeCnt: _poll.likeCnt });
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Like
 */
exports.delete = function (req, res) {
  var like = req.like;
  var cnt = (like.type === 1) ? -1 : 1;

  like.remove()
    .then(() => {
      var userId = like.user._id || like.user;
      return User.countLike(userId);
    }, handleError)
    .then(() => {
      var pollId = like.poll._id || like.poll;
      return Poll.countLike(pollId, cnt);
    }, handleError)
    .then(_poll => {
      res.jsonp({ likeCnt: _poll.likeCnt });
    }, handleError);

  function handleError(err) {
    console.log(err);
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Likes
 */
exports.list = function (req, res) {
  Like.find().sort('-created').populate('user', 'displayName slug').exec(function (err, likes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(likes);
    }
  });
};

/**
 * Like middleware
 */
exports.likeByID = function (req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Like is invalid'
    });
  }

  Like.findById(id).populate('user', 'displayName slug').exec(function (err, like) {
    if (err) {
      return next(err);
    } else if (!like) {
      return res.status(404).send({
        message: 'No Like with that identifier has been found'
      });
    }
    req.like = like;
    next();
  });
};
<commit_msg>Commited from lenh at Wed, Oct 11, 2017 10:42:33 AM<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Like = mongoose.model('Like'),
  Poll = mongoose.model('Poll'),
  User = mongoose.model('User'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('underscore');

/**
 * Create a Like
 */
exports.create = function (req, res) {
  var like = new Like(req.body);
  var cnt = (like.type === 1) ? 1 : -1;
  like.user = req.user._id;

  like.save()
    .then(_like => {
      like = _like;
      like.user = _like.user._id || _like.user;
      return User.countUpLike(like.user);
    }, handleError)
    .then(() => {
      var pollId = like.poll._id || like.poll;
      return Poll.countLike(pollId, cnt);
    }, handleError)
    .then(_poll => {
      res.jsonp({ like: like, likeCnt: _poll.likeCnt });
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Like
 */
exports.read = function (req, res) {
  // convert mongoose document to JSON
  var like = req.like ? req.like.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  like.isCurrentUserOwner = req.user && like.user && like.user._id.toString() === req.user._id.toString();

  res.jsonp(like);
};

/**
 * Update a Like
 */
exports.update = function (req, res) {
  var like = req.like;
  // Hoán đổi 2 đơn vị
  var cnt = (like.type === 1) ? -2 : 2;

  like = _.extend(like, req.body);

  like.save()
    .then(_like => {
      like = _like;
      like.user = _like.user._id || _like.user;
      var pollId = _like.poll._id || _like.poll;
      return Poll.countLike(pollId, cnt);
    }, handleError)
    .then(_poll => {
      res.jsonp({ like: like, likeCnt: _poll.likeCnt });
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Like
 */
exports.delete = function (req, res) {
  var like = req.like;
  var cnt = (like.type === 1) ? -1 : 1;

  like.remove()
    .then(() => {
      var userId = like.user._id || like.user;
      return User.countDownLike(userId);
    }, handleError)
    .then(() => {
      var pollId = like.poll._id || like.poll;
      return Poll.countLike(pollId, cnt);
    }, handleError)
    .then(_poll => {
      res.jsonp({ likeCnt: _poll.likeCnt });
    }, handleError);

  function handleError(err) {
    console.log(err);
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Likes
 */
exports.list = function (req, res) {
  Like.find().sort('-created').populate('user', 'displayName slug').exec(function (err, likes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(likes);
    }
  });
};

/**
 * Like middleware
 */
exports.likeByID = function (req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Like is invalid'
    });
  }

  Like.findById(id).populate('user', 'displayName slug').exec(function (err, like) {
    if (err) {
      return next(err);
    } else if (!like) {
      return res.status(404).send({
        message: 'No Like with that identifier has been found'
      });
    }
    req.like = like;
    next();
  });
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Page = mongoose.model('Page'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Page
 */
exports.create = function(req, res) {
  var page = new Page(req.body);
  page.user = req.user;

  page.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(page);
    }
  });
};

/**
 * Show the current Page
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var page = req.page ? req.page.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  page.isCurrentUserOwner = req.user && page.user && page.user._id.toString() === req.user._id.toString();

  res.jsonp(page);
};

/**
 * Update a Page
 */
exports.update = function(req, res) {
  var page = req.page;

  page = _.extend(page, req.body);

  page.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(page);
    }
  });
};

/**
 * Delete an Page
 */
exports.delete = function(req, res) {
  var page = req.page;

  page.remove(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(page);
    }
  });
};

/**
 * List of Pages
 */
exports.list = function(req, res) {
  Page.find().sort('-created').populate('user', 'displayName').populate('sidebar').exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};

/**
 * List by tag
 */
exports.listByTag = function(req, res) {
  Page.find({ tag: { $in: req.params.tag } }).sort('-created').populate('sidebar').exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};

/**
 * List events
 */
exports.listEvents = function(req, res) {
  Page.find({ isEvent: true }).sort('-created').populate('sidebar').exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};

/**
 * Page middleware
 */
exports.pageByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Page is invalid'
    });
  }

  Page.findById(id).populate('sidebar').exec(function (err, page) {
    if (err) {
      return next(err);
    } else if (!page) {
      return res.status(404).send({
        message: 'No Page with that identifier has been found'
      });
    }
    req.page = page;
    next();
  });
};

/**
 * Page middleware
 */
exports.pageBySlug = function(req, res, next, id) {

  Page.findOne({ slug: id }).populate('sidebar').exec(function (err, page) {
    if (err) {
      return next(err);
    } else if (!page) {
      return res.status(404).send({
        message: 'No Page with that identifier has been found'
      });
    }
    req.page = page;
    next();
  });
};

/**
 * Fetch pages to be shown on menu
 */
exports.pagesOnMenu = function(req, res) {
  Page.find({ showOnMenu: true }).exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};
<commit_msg>Set events limit<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Page = mongoose.model('Page'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Page
 */
exports.create = function(req, res) {
  var page = new Page(req.body);
  page.user = req.user;

  page.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(page);
    }
  });
};

/**
 * Show the current Page
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var page = req.page ? req.page.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  page.isCurrentUserOwner = req.user && page.user && page.user._id.toString() === req.user._id.toString();

  res.jsonp(page);
};

/**
 * Update a Page
 */
exports.update = function(req, res) {
  var page = req.page;

  page = _.extend(page, req.body);

  page.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(page);
    }
  });
};

/**
 * Delete an Page
 */
exports.delete = function(req, res) {
  var page = req.page;

  page.remove(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(page);
    }
  });
};

/**
 * List of Pages
 */
exports.list = function(req, res) {
  Page.find().sort('-created').populate('user', 'displayName').populate('sidebar').exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};

/**
 * List by tag
 */
exports.listByTag = function(req, res) {
  Page.find({ tag: { $in: req.params.tag } }).sort('-created').populate('sidebar').exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};

/**
 * List events
 */
exports.listEvents = function(req, res) {
  Page.find({ isEvent: true }).sort('-created').populate('sidebar').limit(6).exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};

/**
 * Page middleware
 */
exports.pageByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Page is invalid'
    });
  }

  Page.findById(id).populate('sidebar').exec(function (err, page) {
    if (err) {
      return next(err);
    } else if (!page) {
      return res.status(404).send({
        message: 'No Page with that identifier has been found'
      });
    }
    req.page = page;
    next();
  });
};

/**
 * Page middleware
 */
exports.pageBySlug = function(req, res, next, id) {

  Page.findOne({ slug: id }).populate('sidebar').exec(function (err, page) {
    if (err) {
      return next(err);
    } else if (!page) {
      return res.status(404).send({
        message: 'No Page with that identifier has been found'
      });
    }
    req.page = page;
    next();
  });
};

/**
 * Fetch pages to be shown on menu
 */
exports.pagesOnMenu = function(req, res) {
  Page.find({ showOnMenu: true }).exec(function(err, pages) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(pages);
    }
  });
};
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('dpShared')
        .constant('TAB_HEADER_CONFIG', {
            'data-datasets': {
                data: {
                    title: 'Data',
                    action: 'FETCH_SEARCH_RESULTS_BY_QUERY',
                    getPayload: query => query,
                    tip: 'maak de zoekcriteria minder specifiek (bijv. een straat i.p.v. specifiek adres)'
                },
                datasets: {
                    title: 'Datasets',
                    action: 'FETCH_DATA_SELECTION',
                    getPayload: query => {
                        return {dataset: 'catalogus', view: 'CARDS', query, filters: {}, page: 1};
                    },
                    tip: 'gebruik in plaats van een zoekvraag de mogelijkheid om op thema te filteren'
                }
            }
        });
})();
<commit_msg>Adjust dataset tip<commit_after>(function () {
    'use strict';

    angular
        .module('dpShared')
        .constant('TAB_HEADER_CONFIG', {
            'data-datasets': {
                data: {
                    title: 'Data',
                    action: 'FETCH_SEARCH_RESULTS_BY_QUERY',
                    getPayload: query => query,
                    tip: 'maak de zoekcriteria minder specifiek (bijv. een straat i.p.v. specifiek adres)'
                },
                datasets: {
                    title: 'Datasets',
                    action: 'FETCH_DATA_SELECTION',
                    getPayload: query => {
                        return {dataset: 'catalogus', view: 'CARDS', query, filters: {}, page: 1};
                    },
                    tip: 'in datasets kun je momenteel alleen zoeken op hele woorden (dus zoek niet op \'zonne\' ' +
                        'maar op \'zonnepanelen\' of \'zonnepaneel\'). Alternatief is de optie \'Alle datasets ' +
                        'tonen\' en filteren op thema.'
                }
            }
        });
})();
<|endoftext|>


<commit_before>
$(document).ready(init);

var data;

function init(){

	loadContent();
};

function initMedia(){

	$('audio,video').mediaelementplayer();
}

function initSidebar(){
	var $window = $(window)

	//TOC
	$('.bs-docs-sidenav').affix
	(
		{
			offset:
			{
				top: function () { return $window.width() <= 980 ? 290 : 210 },
				bottom: 270
			}
		}
	)
}

function loadContent(){

	$.ajax({

		type: "GET",
		url: projectXML,
		dataType: "xml",
		success: function(xml) {

			if (typeof data == 'string'){

				//in IE we need to turn the string into xml
				data = $.parseXML(xml);

			} else {

				data = xml;

			}

			//step one - libraries?
			loadLibraries();

		}

	});

}

function loadLibraries(){

	//load stylesheet and libraries...

	if ( $(data).find('learningObject').attr('stylesheet') != undefined){

		$('head').append('<link rel="stylesheet" href="' + eval( $(data).find('learningObject').attr('stylesheet') ) + '" type="text/css" />');

	}

	if ( $(data).find('learningObject').attr('libs') != undefined){

		var libs = $(data).find('learningObject').attr('libs').split('||');

		var libCount = libs.length;
		var loaded = 0;

		for (var i = 0; i< libCount; i++){

			$.getScript(libs[i], function(){

				loaded++;

				if (loaded == libs.length){

					//step two
					setup();
					//step three
					parseContent(0);

				}

			});

		}

	} else {

		setup();

		parseContent(0);

	}

}

function setup(){

	//add all the pages to the pages menu: this links bak to the same page
	$(data).find('page').each( function(index, value){

		$('#nav').append('
' + $(this).attr('name') + '
');

	});

	//set the header image, if defined
	if ($(data).find('learningObject').attr('header') != undefined){

		$('#overview').css({filter:''}); //for IE8

		$('#overview').css('background-image', "url(" + eval( $(data).find('learningObject').attr('header'))+ ")");
	}

	if ($(data).find('learningObject').attr('headerColour') != undefined){

		var col = $(data).find('learningObject').attr('headerColour');

		//one or two?
		if (col.substr(',') != -1){
			col = col.split(',');
		} else {
			col = [col,col];
		}

		$('#overview').css('background', col[0]);
		$('#overview').css('background', '-moz-linear-gradient(45deg,  ' + col[0] + ' 0%, ' + col[1] + ' 100%)');
		$('#overview').css('background', '-webkit-gradient(linear, left bottom, right top, color-stop(0%,' + col[0] + '), color-stop(100%,' + col[1] + '))');
		$('#overview').css('background', '-webkit-linear-gradient(45deg,  ' + col[0] + ' 0%,' + col[1] + ' 100%)');
		$('#overview').css('background', '-o-linear-gradient(45deg,  ' + col[0] + ' 0%,' + col[1] + ' 100%)');
		$('#overview').css('background', '-ms-linear-gradient(45deg,  ' + col[0] + ' 0%,' + col[1] + ' 100%)');
		$('#overview').css('background', 'linear-gradient(45deg,  ' + + ' 0%,' + col[1]+ ' 100%)');
		$('#overview').css('filter', 'progid:DXImageTransform.Microsoft.gradient( startColorstr=' + col[0] + ', endColorstr=' + col[1] + ',GradientType=1 )');

	}

	if ($(data).find('learningObject').attr('headerTextColour') != undefined){

		$('#overview').css('color', $(data).find('learningObject').attr('headerTextColour'));

	}

}

function parseContent(index){

	//clear out existing content
	$('#mainContent').empty();
	$('#toc').empty();

	//which page is this from the document?
	var page = $(data).find('page').eq(index);

	//set the main page title and subtitle
	$('#pageTitle').text( page.attr('name') );
	$('#pageSubTitle').text( page.attr('subtitle') );

	//create the sections
	page.find('section').each( function(index, value){

		var sectionIndex = index;

		//add a TOC entry
		$('#toc').append('
' + $(this).attr('name') + '
');

		//add the section header
		var section = $('

' + $(this).attr('name') + '

');

		//add the section contents
		$(this).children().each( function(index, value){

			var itemIndex = index;

			if (this.nodeName == 'text'){
				section.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'script'){
				section.append( '');
			}

			if (this.nodeName == 'image'){
				section.append('

');
			}

			if (this.nodeName == 'audio'){
				section.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				section.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}

			if (this.nodeName == 'navigator'){

				if ($(this).attr('type') == 'Tabs'){
					makeNav( $(this), section, 'tabs', sectionIndex, itemIndex );
				}

				if ($(this).attr('type') == 'Accordion'){
					makeAccordion( $(this), section, sectionIndex, itemIndex );
				}

				if ($(this).attr('type') == 'Pills'){
					makeNav( $(this), section, 'pills', sectionIndex, itemIndex);
				}

				if ($(this).attr('type') == 'Carousel'){
					makeCarousel(  $(this), section, sectionIndex, itemIndex );
				}
			}

		});

		//a return to top button
		section.append( $('

Top
'));

		//add the section to the document
		$('#mainContent').append(section);

	});

	//finish initialising the piece now we have the content loaded
	initMedia();

	initSidebar();

	window.scroll(0,0);

	MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

	//$('body').scrollSpy('refresh'); //seems to cause a bunch of errors with tabs
	$('#toc a:first').tab('show');

	//an event for user defined code to know when loading is done
	$(document).trigger('contentLoaded');

	//force facebook / twitter objects to initialise
	twttr.widgets.load();

	FB.XFBML.parse();

}

function makeNav(node,section,type, sectionIndex, itemIndex){

	var sectionIndex = sectionIndex;

	var itemIndex = itemIndex;

	var tabDiv = $( '
' );

	if (type == 'tabs'){

		var tabs = $( '
' );

	}

	if (type == 'pills'){

		var tabs = $( '
' );
	}

	var content = $( '
' );

	node.children().each( function(index, value){

		if (index == 0){

			tabs.append( $('
' + $(this).attr('name') + '
') );

			var tab = $('
')

		} else {

			tabs.append( $('
' + $(this).attr('name') + '
') );

			var tab = $('
')

		}

		$(this).children().each( function(index, value){

			if (this.nodeName == 'text'){
				tab.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'image'){
				tab.append('

');
			}

			if (this.nodeName == 'audio'){
				tab.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				tab.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}

		});

		content.append(tab);
	});

	tabDiv.append(tabs);

	tabDiv.append(content);

	section.append(tabDiv);

	setTimeout( function(){ $('#tab' + sectionIndex + '_' + itemIndex + ' a:first').tab('show'); }, 0);

}

function makeAccordion(node,section, sectionIndex, itemIndex){

	var accDiv = $( '
' );

	node.children().each( function(index, value){

		var group = $('
');

		var header = $('
' + $(this).attr('name') + '
');

		group.append(header);

		if (index == 0){

			var outer = $('
');

		} else {

			var outer = $('
');

		}

		var inner = $('
');

		$(this).children().each( function(index, value){

			if (this.nodeName == 'text'){
				inner.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'image'){
				inner.append('

');
			}

			if (this.nodeName == 'audio'){
				inner.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				inner.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}
		});

		outer.append(inner);

		group.append(outer);

		accDiv.append(group);
	});

	section.append(accDiv);

}

function makeCarousel(node, section, sectionIndex, itemIndex){

	var sectionIndex = sectionIndex;

	var itemIndex = itemIndex;

	var carDiv = $('
');

	var indicators = $('
');

	var items = $('
');

	node.children().each( function(index, value){

		var pane;

		if (index == 0){

			indicators.append( $('

') );

			pane = $('
');

		} else {

			indicators.append( $('

') );

			pane = $('
');
		}

		$(this).children().each( function(index, value){

			if (this.nodeName == 'text'){
				pane.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'image'){
				pane.append('

');
			}

			if (this.nodeName == 'audio'){
				pane.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				pane.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}

		});

		items.append(pane);

	});

	carDiv.append(indicators);

	carDiv.append(items);

	carDiv.append( $('‹') );
	carDiv.append( $('›') );

	section.append(carDiv);

}

<commit_msg><commit_after>
$(document).ready(init);

var data;

function init(){

	loadContent();
};

function initMedia(){

	$('audio,video').mediaelementplayer();
}

function initSidebar(){
	var $window = $(window)

	//TOC
	$('.bs-docs-sidenav').affix
	(
		{
			offset:
			{
				top: function () { return $window.width() <= 980 ? 290 : 210 },
				bottom: 270
			}
		}
	)
}

function loadContent(){

	$.ajax({

		type: "GET",
		url: projectXML,
		dataType: "xml",
		success: function(xml) {

			if (typeof data == 'string'){

				//in IE we need to turn the string into xml
				data = $.parseXML(xml);

			} else {

				data = xml;

			}

			//step one - libraries?
			loadLibraries();

		}

	});

}

function loadLibraries(){

	//load stylesheet and libraries...

	if ( $(data).find('learningObject').attr('stylesheet') != undefined){

		$('head').append('<link rel="stylesheet" href="' + eval( $(data).find('learningObject').attr('stylesheet') ) + '" type="text/css" />');

	}

	if ( $(data).find('learningObject').attr('libs') != undefined){

		var libs = $(data).find('learningObject').attr('libs').split('||');

		var libCount = libs.length;
		var loaded = 0;

		for (var i = 0; i< libCount; i++){

			$.getScript(libs[i], function(){

				loaded++;

				if (loaded == libs.length){

					//step two
					setup();
					//step three
					parseContent(0);

				}

			});

		}

	} else {

		setup();

		parseContent(0);

	}

}

function setup(){

	//add all the pages to the pages menu: this links bak to the same page
	$(data).find('page').each( function(index, value){

		$('#nav').append('
' + $(this).attr('name') + '
');

	});

	//set the header image, if defined
	if ($(data).find('learningObject').attr('header') != undefined){

		$('#overview').css({filter:''}); //for IE8

		$('#overview').css('background-image', "url(" + eval( $(data).find('learningObject').attr('header'))+ ")");
	}

	if ($(data).find('learningObject').attr('headerColour') != undefined){

		var col = $(data).find('learningObject').attr('headerColour');

		//one or two?
		if (col.substr(',') != -1){
			col = col.split(',');
		} else {
			col = [col,col];
		}

		$('#overview').css('background', col[0]);
		$('#overview').css('background', '-moz-linear-gradient(45deg,  ' + col[0] + ' 0%, ' + col[1] + ' 100%)');
		$('#overview').css('background', '-webkit-gradient(linear, left bottom, right top, color-stop(0%,' + col[0] + '), color-stop(100%,' + col[1] + '))');
		$('#overview').css('background', '-webkit-linear-gradient(45deg,  ' + col[0] + ' 0%,' + col[1] + ' 100%)');
		$('#overview').css('background', '-o-linear-gradient(45deg,  ' + col[0] + ' 0%,' + col[1] + ' 100%)');
		$('#overview').css('background', '-ms-linear-gradient(45deg,  ' + col[0] + ' 0%,' + col[1] + ' 100%)');
		$('#overview').css('background', 'linear-gradient(45deg,  ' + + ' 0%,' + col[1]+ ' 100%)');
		$('#overview').css('filter', 'progid:DXImageTransform.Microsoft.gradient( startColorstr=' + col[0] + ', endColorstr=' + col[1] + ',GradientType=1 )');

	}

	if ($(data).find('learningObject').attr('headerTextColour') != undefined){

		$('#overview').css('color', $(data).find('learningObject').attr('headerTextColour'));

	}

}

function parseContent(index){

	//clear out existing content
	$('#mainContent').empty();
	$('#toc').empty();

	//which page is this from the document?
	var page = $(data).find('page').eq(index);

	//set the main page title and subtitle
	$('#pageTitle').text( page.attr('name') );
	$('#pageSubTitle').text( page.attr('subtitle') );

	//create the sections
	page.find('section').each( function(index, value){

		var sectionIndex = index;

		//add a TOC entry
		$('#toc').append('
' + $(this).attr('name') + '
');

		//add the section header
		var section = $('

' + $(this).attr('name') + '

');

		//add the section contents
		$(this).children().each( function(index, value){

			var itemIndex = index;

			if (this.nodeName == 'text'){
				section.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'script'){

				section.append( '');
			}

			if (this.nodeName == 'image'){
				section.append('

');
			}

			if (this.nodeName == 'audio'){
				section.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				section.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}

			if (this.nodeName == 'navigator'){

				if ($(this).attr('type') == 'Tabs'){
					makeNav( $(this), section, 'tabs', sectionIndex, itemIndex );
				}

				if ($(this).attr('type') == 'Accordion'){
					makeAccordion( $(this), section, sectionIndex, itemIndex );
				}

				if ($(this).attr('type') == 'Pills'){
					makeNav( $(this), section, 'pills', sectionIndex, itemIndex);
				}

				if ($(this).attr('type') == 'Carousel'){
					makeCarousel(  $(this), section, sectionIndex, itemIndex );
				}
			}

		});

		//a return to top button
		section.append( $('

Top
'));

		//add the section to the document
		$('#mainContent').append(section);

	});

	//finish initialising the piece now we have the content loaded
	initMedia();

	initSidebar();

	window.scroll(0,0);

	MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

	//$('body').scrollSpy('refresh'); //seems to cause a bunch of errors with tabs
	$('#toc a:first').tab('show');

	//an event for user defined code to know when loading is done
	$(document).trigger('contentLoaded');

	//force facebook / twitter objects to initialise
	twttr.widgets.load();

	FB.XFBML.parse();

}

function makeNav(node,section,type, sectionIndex, itemIndex){

	var sectionIndex = sectionIndex;

	var itemIndex = itemIndex;

	var tabDiv = $( '
' );

	if (type == 'tabs'){

		var tabs = $( '
' );

	}

	if (type == 'pills'){

		var tabs = $( '
' );
	}

	var content = $( '
' );

	node.children().each( function(index, value){

		if (index == 0){

			tabs.append( $('
' + $(this).attr('name') + '
') );

			var tab = $('
')

		} else {

			tabs.append( $('
' + $(this).attr('name') + '
') );

			var tab = $('
')

		}

		$(this).children().each( function(index, value){

			if (this.nodeName == 'text'){
				tab.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'image'){
				tab.append('

');
			}

			if (this.nodeName == 'audio'){
				tab.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				tab.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}

		});

		content.append(tab);
	});

	tabDiv.append(tabs);

	tabDiv.append(content);

	section.append(tabDiv);

	setTimeout( function(){ $('#tab' + sectionIndex + '_' + itemIndex + ' a:first').tab('show'); }, 0);

}

function makeAccordion(node,section, sectionIndex, itemIndex){

	var accDiv = $( '
' );

	node.children().each( function(index, value){

		var group = $('
');

		var header = $('
' + $(this).attr('name') + '
');

		group.append(header);

		if (index == 0){

			var outer = $('
');

		} else {

			var outer = $('
');

		}

		var inner = $('
');

		$(this).children().each( function(index, value){

			if (this.nodeName == 'text'){
				inner.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'image'){
				inner.append('

');
			}

			if (this.nodeName == 'audio'){
				inner.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				inner.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}
		});

		outer.append(inner);

		group.append(outer);

		accDiv.append(group);
	});

	section.append(accDiv);

}

function makeCarousel(node, section, sectionIndex, itemIndex){

	var sectionIndex = sectionIndex;

	var itemIndex = itemIndex;

	var carDiv = $('
');

	var indicators = $('
');

	var items = $('
');

	node.children().each( function(index, value){

		var pane;

		if (index == 0){

			indicators.append( $('

') );

			pane = $('
');

		} else {

			indicators.append( $('

') );

			pane = $('
');
		}

		$(this).children().each( function(index, value){

			if (this.nodeName == 'text'){
				pane.append( '
' + $(this).text() + '
');
			}

			if (this.nodeName == 'image'){
				pane.append('

');
			}

			if (this.nodeName == 'audio'){
				pane.append('
' + $(this).attr('name') + '

<audio src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none" width="100%"></audio>
')
			}

			if (this.nodeName == 'video'){
				pane.append('
' + $(this).attr('name') + '

<video style="max-width: 100%" class="fullPageVideo" src="' + eval( $(this).attr('url') ) + '" type="video/mp4" id="player1" controls="controls" preload="none"></video>
');
			}

		});

		items.append(pane);

	});

	carDiv.append(indicators);

	carDiv.append(items);

	carDiv.append( $('‹') );
	carDiv.append( $('›') );

	section.append(carDiv);

}

<|endoftext|>


<commit_before>import * as Yup from 'yup'

import CheckboxInput from 'src/components/inputs/formik/Checkbox'
import TextInputFormik from 'src/components/inputs/formik/TextInput'

export default {
  code: 'blockcypher',
  name: 'Blockcypher',
  title: 'Blockcypher (Payments)',
  elements: [
    {
      code: 'token',
      display: 'API Token',
      component: TextInputFormik,
      face: true,
      long: true
    },
    {
      code: 'confidenceFactor',
      display: 'Confidence Factor',
      component: TextInputFormik,
      face: true
    },
    {
      code: 'rbf',
      component: CheckboxInput,
      settings: {
        field: 'wallets_BTC_wallet',
        enabled: true,
        disabledMessage:
          'Lower the confidence of RBF transactions (Available when using bitcoind.)',
        label: 'Lower the confidence of RBF transactions',
        requirement: 'bitcoind',
        rightSideLabel: true
      },
      face: true
    }
  ],
  getValidationSchema: () => {
    return Yup.object().shape({
      token: Yup.string('The token must be a string')
        .max(100, 'The token is too long')
        .required('The token is required'),
      confidenceFactor: Yup.number('The confidence factor must be a number')
        .integer('The confidence factor must be an integer')
        .positive('The confidence factor must be positive')
        .required('The confidence factor is required')
    })
  }
}
<commit_msg>fix: check confidence level in [0,100]<commit_after>import * as Yup from 'yup'

import CheckboxInput from 'src/components/inputs/formik/Checkbox'
import TextInputFormik from 'src/components/inputs/formik/TextInput'

export default {
  code: 'blockcypher',
  name: 'Blockcypher',
  title: 'Blockcypher (Payments)',
  elements: [
    {
      code: 'token',
      display: 'API Token',
      component: TextInputFormik,
      face: true,
      long: true
    },
    {
      code: 'confidenceFactor',
      display: 'Confidence Factor',
      component: TextInputFormik,
      face: true
    },
    {
      code: 'rbf',
      component: CheckboxInput,
      settings: {
        field: 'wallets_BTC_wallet',
        enabled: true,
        disabledMessage:
          'Lower the confidence of RBF transactions (Available when using bitcoind.)',
        label: 'Lower the confidence of RBF transactions',
        requirement: 'bitcoind',
        rightSideLabel: true
      },
      face: true
    }
  ],
  getValidationSchema: () => {
    return Yup.object().shape({
      token: Yup.string('The token must be a string')
        .max(100, 'The token is too long')
        .required('The token is required'),
      confidenceFactor: Yup.number('The confidence factor must be a number')
        .integer('The confidence factor must be an integer')
        .min(0, 'The confidence factor must be non-negative')
        .max(100, 'The confidence factor must be less than or equal to 100')
        .required('The confidence factor is required')
    })
  }
}
<|endoftext|>


<commit_before>const sinon = require("sinon");
const assert = require("better-assert");
const equal = require("deep-eql");
const inspect = require("util").inspect;
const format = require("util").format;
require('source-map-support').install();

const debug = false;
const logfn = debug ? console.log.bind(console) : function () {};

const Subscriber = require("../subscriber");
const EventEmitter = require("events").EventEmitter;

describe "Prefix Event Subscriber" {
    var subscriber, defaultEmitter, bangEmitter;

    beforeEach {
        logfn(/* newline */);
        subscriber = new Subscriber();
        defaultEmitter = new EventEmitter();
        bangEmitter = new EventEmitter();
    }

    describe "The Default Emitter" {
        beforeEach {
            subscriber.addEmitter(Subscriber.defaultPrefix, defaultEmitter);
        }

        it "is a catch-all" {
            var spy = sinon.spy();
            subscriber.on("x", spy)
            defaultEmitter.emit("x");
            assert(spy.called);
        }

        it "is shadowed by every other emitter" {
            var spy = sinon.spy();
            subscriber.addEmitter("!", bangEmitter);
            subscriber.on("!x", spy);
            defaultEmitter.emit("!x");
            assert(!spy.called);
            bangEmitter.emit("x");
            assert(spy.called);
        }

        it "is shadowed by every other emitter except when they don't match" {
            var spy = sinon.spy();
            subscriber.addEmitter("!", bangEmitter);
            subscriber.on("x", spy);
            defaultEmitter.emit("x");
            assert(spy.called);
        }
    }

    describe "dispatching" {
        beforeEach {
            subscriber.addEmitter(Subscriber.defaultPrefix, defaultEmitter);
            subscriber.addEmitter("!", bangEmitter);
        }

        it "can take a string of event names" {
            var spy = sinon.spy();

            subscriber.on("!x x", spy);

            defaultEmitter.emit("x");
            assert(spy.calledOnce);
            bangEmitter.emit("x");
            assert(spy.calledTwice);
        }

        it "can take an object of event names to listener" {
            var defaultSpy = sinon.spy();
            var bangSpy = sinon.spy();

            subscriber.on({
                "x": defaultSpy,
                "!x": bangSpy
            });

            defaultEmitter.emit("x");
            assert(defaultSpy.calledOnce);
            assert(!bangSpy.called);

            bangEmitter.emit("x");
            assert(defaultSpy.calledOnce);
            assert(bangSpy.calledOnce);
        }
    }
}<commit_msg>Tests: Bugfix: Actual file location<commit_after>const sinon = require("sinon");
const assert = require("better-assert");
const equal = require("deep-eql");
const inspect = require("util").inspect;
const format = require("util").format;
require('source-map-support').install();

const debug = false;
const logfn = debug ? console.log.bind(console) : function () {};

const Subscriber = require("./subscriber");
const EventEmitter = require("events").EventEmitter;

describe "Prefix Event Subscriber" {
    var subscriber, defaultEmitter, bangEmitter;

    beforeEach {
        logfn(/* newline */);
        subscriber = new Subscriber();
        defaultEmitter = new EventEmitter();
        bangEmitter = new EventEmitter();
    }

    describe "The Default Emitter" {
        beforeEach {
            subscriber.addEmitter(Subscriber.defaultPrefix, defaultEmitter);
        }

        it "is a catch-all" {
            var spy = sinon.spy();
            subscriber.on("x", spy)
            defaultEmitter.emit("x");
            assert(spy.called);
        }

        it "is shadowed by every other emitter" {
            var spy = sinon.spy();
            subscriber.addEmitter("!", bangEmitter);
            subscriber.on("!x", spy);
            defaultEmitter.emit("!x");
            assert(!spy.called);
            bangEmitter.emit("x");
            assert(spy.called);
        }

        it "is shadowed by every other emitter except when they don't match" {
            var spy = sinon.spy();
            subscriber.addEmitter("!", bangEmitter);
            subscriber.on("x", spy);
            defaultEmitter.emit("x");
            assert(spy.called);
        }
    }

    describe "dispatching" {
        beforeEach {
            subscriber.addEmitter(Subscriber.defaultPrefix, defaultEmitter);
            subscriber.addEmitter("!", bangEmitter);
        }

        it "can take a string of event names" {
            var spy = sinon.spy();

            subscriber.on("!x x", spy);

            defaultEmitter.emit("x");
            assert(spy.calledOnce);
            bangEmitter.emit("x");
            assert(spy.calledTwice);
        }

        it "can take an object of event names to listener" {
            var defaultSpy = sinon.spy();
            var bangSpy = sinon.spy();

            subscriber.on({
                "x": defaultSpy,
                "!x": bangSpy
            });

            defaultEmitter.emit("x");
            assert(defaultSpy.calledOnce);
            assert(!bangSpy.called);

            bangEmitter.emit("x");
            assert(defaultSpy.calledOnce);
            assert(bangSpy.calledOnce);
        }
    }
}<|endoftext|>


<commit_before>module.exports = Object.assign(
  {},
  require('./default.config.js'),
  {
    "roots": [
      "server/graphql"
    ]
  }
);
<commit_msg>Update integration.config.js<commit_after>module.exports = Object.assign(
  {},
  require('./default.config.js'),
  {
    "roots": [
      "src/graphql"
    ]
  }
);
<|endoftext|>


<commit_before>;jQuery(document).ready(function($){

	var i = 0;

	$('.github-widget').each(function(){

		if(i == 0) $('head').append('');
		i++;

		var $container = $(this);
		var repo = $container.data('repo');

		$.ajax({
			url: 'https://api.github.com/repos/' + repo,
			dataType: 'jsonp',

			success: function(results){
				var repo = results.data;

				var date = new Date(repo.pushed_at);
				var pushed_at = (date.getMonth()+1) + '-' + date.getDate() + '-' + date.getFullYear();

				var $widget = $(' \

  \

 \

 \
					            ' + repo.owner.login  + ' \
					            /  \
					            ' + repo.name + ' \

 \

 \
					            ' + repo.watchers + ' \
					            ' + repo.forks + ' \

 \

 \

 \

' + repo.description + ' — Read More
 \

' + repo.homepage + '
 \

 \

 \

Latest commit to the master branch on ' + pushed_at + '
 \
					        Download as zip \

 \

 \
				');

				$widget.appendTo($container);
			}
		})

	});

});<commit_msg>js line continuation is flaky. merged #6 and fixes #5.<commit_after>;jQuery(document).ready(function($){

	var i = 0;
	var box_title_png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAXCAMAAAAx3e/WAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpEQjIyNkJERkM0NjYxMUUxOEFDQzk3ODcxRDkzRjhCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpEQjIyNkJFMEM0NjYxMUUxOEFDQzk3ODcxRDkzRjhCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkRCMjI2QkREQzQ2NjExRTE4QUNDOTc4NzFEOTNGOEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkRCMjI2QkRFQzQ2NjExRTE4QUNDOTc4NzFEOTNGOEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+dka2KgAAAEVQTFRFxMTEyMjI0tLSvb29vr6+zc3Ny8vLxcXFz8/P6enp3t7ex8fH0dHR1NTUw8PDwMDAzs7OvLy8wcHBu7u7v7+/zMzM////budQFwAAABd0Uk5T/////////////////////////////wDmQOZeAAAAcklEQVR42tSQSQ7DMAwD6chOukWs5eX/Ty2coo0T9wOdEzEgdRBuzNmnDofgja52JDyz5TCqUp0O6kfrb4bzSXkRiTviEZZ6JKLMJ5VQ2v8iGbtbfEwXmjFMG0VwdQo10hQNxYqtLMv9O6xvpZ/QeAkwAKjwHiJLaJc3AAAAAElFTkSuQmCC';
	var stats_png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAqCAMAAACEJ4viAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIE1hY2ludG9zaCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpEQjIyNkJEQkM0NjYxMUUxOEFDQzk3ODcxRDkzRjhCRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpEQjIyNkJEQ0M0NjYxMUUxOEFDQzk3ODcxRDkzRjhCRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkRCMjI2QkQ5QzQ2NjExRTE4QUNDOTc4NzFEOTNGOEJFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkRCMjI2QkRBQzQ2NjExRTE4QUNDOTc4NzFEOTNGOEJFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+h1kA9gAAAK5QTFRF+fn5sbGx8fHx09PTmpqa2dnZ/f3919fX9PT00NDQ1dXVpKSk+vr6+/v7vb298vLyycnJ8/PztLS0zc3N6enp/v7+q6ur2NjY9/f3srKy/Pz8p6en7u7uoaGhnJyc4eHhtbW1pqam6Ojo9fX17e3toqKirKys1NTUzs7Ox8fHwcHBwMDA5eXlnZ2dpaWl0dHR9vb25ubm4uLi3d3dqqqqwsLCv7+/oKCgmZmZ////8yEsbwAAAMBJREFUeNrE0tcOgjAUBuDSliUoMhTEvfdef9//xUQjgaLX0Ium/ZLT/+SkRPxZpGykvuf5VMJogy5jY9yjDHcWFhqlcRuHc4o6B1QK0BDg+hcZgNDh3NWTwzItH/bRrhvT+g3zSxZkNGCZpoWGIbU0a3Y6zV5VA6keyeDxiw62P0gUqEW0FbDim4nVikFJbU2zZXybUEaxhCqOQqyh5/G0wpWICUwthyqwD4InOMuXJ7/gs7WkoPdVg1vykF8CDACEFanKO3aSYwAAAABJRU5ErkJggg==';

	$('.github-widget').each(function(){

		if(i == 0) $('head').append(
			''
		);
		i++;

		var $container = $(this), $widget,
			repo = $container.data('repo'),
			vendorName = repo.split('/')[0],
			repoName = repo.split('/')[1],
			vendorUrl = "http://github.com/" + vendorName,
			repoUrl = "http://github.com/" + vendorName + '/' + repoName;

		$widget = $(
			'
'
			+'
'
			+'
'
			+'' + vendorName + ''
			+'/'
			+'' + repoName + ''
			+'
'
			+'
'
			+'?'
			+'?'
			+'
'
			+'
'
			+'
'
			+'
 — Read More
'
			+'

'
			+'
'
			+'
'
			+'

'
			+'Download as zip'
			+'
'
			+'
'
		);

		$widget.appendTo($container);

		$.ajax({
			url: 'https://api.github.com/repos/' + repo,
			dataType: 'jsonp',
			success: function(results) {
				var repo = results.data, date, pushed_at = 'unknown';

				if (repo.pushed_at) {
					date = new Date(repo.pushed_at);
					pushed_at = (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear();
				}

				$widget.find('.watchers').text(repo.watchers);
				$widget.find('.forks').text(repo.forks);
				$widget.find('.description span').text(repo.description);
				$widget.find('.link').append($('').attr('href', repo.homepage).text(repo.homepage));
				$widget.find('.updated').html('Latest commit to the master branch on ' + pushed_at);
			}
		});

	});

});
<|endoftext|>


<commit_before>/**
 * Flotr Adapter
 */
(function () {

var
  V = envision,
  A = envision.adapters,
  E = Flotr.EventAdapter,
  DEFAULTS = A.defaultOptions;

function Child (options) {
  this.options = options || {};
  this.flotr = null;
  this._flotrDefaultOptions();
}

Child.prototype = {

  destroy : function () {
    this.flotr.destroy();
  },

  draw : function (data, flotr, node, skipPreprocess, processData) {

    var
      o           = this.options,
      flotrData   = [];

    data = data || o.data;

    if (flotr) {
      flotr = Flotr.clone(flotr);
      flotr = Flotr.merge(o, flotr);
    } else {
      flotr = o;
    }

    o.data = data;
    min = flotr.xaxis.min;
    max = flotr.xaxis.max;

    data = this._getDataArray(data);
    if (skipPreprocess) {
      flotrData = data;
    } else {
      _.each(data, function (d, index) {

        var
          isObject = !_.isArray(d),
          unprocessed = isObject ? d.data : d,
          processed = this._processData(unprocessed, flotr, node, processData),
          x = processed[0],
          y = processed[1],
          data = [],
          o, i;

        // Transform for Flotr
        for (i = 0; i < x.length; i++) {
          data.push([x[i], y[i]]);
        }

        if (isObject) {
          o = _.extend({}, d);
          o.data = data;
          flotrData.push(o);
        } else {
          flotrData.push(data);
        }

      }, this);
    }

    if (!flotr) throw 'No graph submitted.';

    this.flotr = Flotr.draw(node, flotrData, flotr);
  },

  _processData : function (data, flotr, node, processData) {

    var
      options     = this.options,
      resolution  = node.clientWidth,
      axis        = flotr.xaxis,
      min         = axis.min,
      max         = axis.max,
      preprocessor;

    if (_.isFunction(data)) {
      return data(min, max, resolution);
    } else if (processData) {
      preprocessor = new V.Preprocessor({data : data});
      processData.apply(this, [{
        preprocessor : preprocessor,
        min : min,
        max : max,
        resolution : resolution
      }]);
    } else {
      preprocessor = new V.Preprocessor({data : data})
        .bound(min, max)
        .subsampleMinMax(resolution);
    }

    return preprocessor.getData();
  },

  _getDataArray : function (data) {

    if (data[0] && (!_.isArray(data[0]) || (data[0][0] && _.isArray(data[0][0]))))
      return data;
    else
      return [data];
  },

  _flotrDefaultOptions : function (options) {

    var o = options || this.options,
      i;

    for (i in DEFAULTS) {
      if (DEFAULTS.hasOwnProperty(i)) {
        if (_.isUndefined(o[i])) {
          o[i] = DEFAULTS[i];
        } else {
          _.defaults(o[i], DEFAULTS[i]);
        }
      }
    }
  },

  attach : function (component, name, callback) {

    var
      event = this.events[name] || {},
      name = event.name || false,
      handler = event.handler || false;

    if (handler) {

      return E.observe(component.node, name, function () {

        var
          args = [component].concat(Array.prototype.slice.call(arguments)),
          result = handler.apply(this, args);

        return callback.apply(null, [component, result]);

      });
    } else {
      return false;
    }
  },

  detach : function (component, name, callback) {
    return E.stopObserve(component.node, name, handler);
  },

  trigger : function (component, name, options) {

    var
      event = this.events[name],
      consumer = event.consumer || false;

    return consumer ? consumer.apply(this, [component, options]) : false;
  },

  events : {

    hit : {
      name : 'flotr:hit',
      handler : function (component, hit) {

        var
          x = hit.x,
          y = hit.y,
          graph = component.api.flotr,
          options;

        // Normalized hit:
        options = {
          data : {
            index : hit.index,
            x : x,
            y : y
          },
          x : graph.axes.x.d2p(x),
          y : graph.axes.y.d2p(y)
        };

        return options;
      },
      consumer : function (component, hit) {

        var
          graph = component.api.flotr,
          o;

        // TODO this is a hack;
        // the hit plugin should expose an API to do this easily
        o = {
          x : hit.data.x,
          y : hit.data.y || 1,
          relX : hit.x,
          relY : hit.y || 1
        };

        graph.hit.hit(o);
      }
    },

    select : {
      name : 'flotr:selecting',
      handler : selectHandler,
      consumer : function (component, selection) {

        var
          graph = component.api.flotr,
          axes = graph.axes,
          data = selection.data || {},
          options = {},
          x = selection.x,
          y = selection.y;

        if (!x && data.x) {
          // Translate data to pixels
          x = data.x;
          options.x1 = axes.x.d2p(x.min);
          options.x2 = axes.x.d2p(x.max);
        } else if (x) {
          // Use pixels
          options.x1 = x.min;
          options.x2 = x.max;
        }

        if (!y && data.y) {
          // Translate data to pixels
          y = data.y;
          options.y1 = axes.y.d2p(y.min);
          options.y2 = axes.y.d2p(y.max);
        } else if (y) {
          // Use pixels
          options.y1 = y.min;
          options.y2 = y.max;
        }

        graph.selection.setSelection(options);
      }
    },

    zoom : {
      name : 'flotr:select',
      handler : function (component, selection) {
        var options = selectHandler(component, selection);
        component.trigger('zoom', options);
        return options;
      },
      consumer : function (component, selection) {

        var
          x = selection.data.x,
          y = selection.data.y,
          options = {};

        if (x) {
          options.xaxis = {
            min : x.min,
            max : x.max
          };
        }

        if (y) {
          options.yaxis = {
            min : y.min,
            max : y.max
          };
        }

        component.draw(null, options);
      }
    },

    mouseout : {
      name : 'flotr:mouseout',
      handler : function (component) {
      },
      consumer : function (component) {
        component.api.flotr.hit.clearHit();
      }
    },

    reset : {
      name : 'flotr:click',
      handler : function (component) {
        component.draw();
      },
      consumer : function (component) {
        component.draw();
      }
    },

    click : {
      name : 'flotr:click',
      handler : function (component) {

        var
          min = component.api.flotr.axes.x.min,
          max = component.api.flotr.axes.x.max;

        return {
          data : {
            x : {
              min : min,
              max : max
            }
          },
          x : {
            min : component.api.flotr.axes.x.d2p(min),
            max : component.api.flotr.axes.x.d2p(max)
          }
        };
      },
      consumer : function (component, selection) {

        var
          x = selection.data.x,
          y = selection.data.y,
          options = {};

        if (x) {
          options.xaxis = {
            min : x.min,
            max : x.max
          };
        }

        if (y) {
          options.yaxis = {
            min : y.min,
            max : y.max
          };
        }

        component.draw(null, options);
      }
    }
  }
};

function selectHandler (component, selection) {

  var
    mode = component.options.config.selection.mode,
    axes = component.api.flotr.axes,
    datax, datay, x, y, options;

  if (mode.indexOf('x') !== -1) {
    datax = {};
    datax.min = selection.x1;
    datax.max = selection.x2;
    x = {};
    x.min = axes.x.d2p(selection.x1);
    x.max = axes.x.d2p(selection.x2);
  }

  if (mode.indexOf('y') !== -1) {
    datay = {};
    datay.min = selection.y1;
    datay.max = selection.y2;
    y = {};
    y.min = axes.y.d2p(selection.y1);
    y.max = axes.y.d2p(selection.y2);
  }

  // Normalized selection:
  options = {
    data : {
      x : datax,
      y : datay
    },
    x : x,
    y : y
  }

  return options;
}

A.flotr.Child = Child;

})();
<commit_msg>Submitted options should over-ride configured.<commit_after>/**
 * Flotr Adapter
 */
(function () {

var
  V = envision,
  A = envision.adapters,
  E = Flotr.EventAdapter,
  DEFAULTS = A.defaultOptions;

function Child (options) {
  this.options = options || {};
  this.flotr = null;
  this._flotrDefaultOptions();
}

Child.prototype = {

  destroy : function () {
    this.flotr.destroy();
  },

  draw : function (data, flotr, node, skipPreprocess, processData) {

    var
      o           = this.options,
      flotrData   = [];

    data = data || o.data;

    if (flotr) {
      flotr = Flotr.merge(flotr, Flotr.clone(o));
    } else {
      flotr = o;
    }

    o.data = data;
    min = flotr.xaxis.min;
    max = flotr.xaxis.max;

    data = this._getDataArray(data);
    if (skipPreprocess) {
      flotrData = data;
    } else {
      _.each(data, function (d, index) {

        var
          isObject = !_.isArray(d),
          unprocessed = isObject ? d.data : d,
          processed = this._processData(unprocessed, flotr, node, processData),
          x = processed[0],
          y = processed[1],
          data = [],
          o, i;

        // Transform for Flotr
        for (i = 0; i < x.length; i++) {
          data.push([x[i], y[i]]);
        }

        if (isObject) {
          o = _.extend({}, d);
          o.data = data;
          flotrData.push(o);
        } else {
          flotrData.push(data);
        }

      }, this);
    }

    if (!flotr) throw 'No graph submitted.';

    this.flotr = Flotr.draw(node, flotrData, flotr);
  },

  _processData : function (data, flotr, node, processData) {

    var
      options     = this.options,
      resolution  = node.clientWidth,
      axis        = flotr.xaxis,
      min         = axis.min,
      max         = axis.max,
      preprocessor;

    if (_.isFunction(data)) {
      return data(min, max, resolution);
    } else if (processData) {
      preprocessor = new V.Preprocessor({data : data});
      processData.apply(this, [{
        preprocessor : preprocessor,
        min : min,
        max : max,
        resolution : resolution
      }]);
    } else {
      preprocessor = new V.Preprocessor({data : data})
        .bound(min, max)
        .subsampleMinMax(resolution);
    }

    return preprocessor.getData();
  },

  _getDataArray : function (data) {

    if (data[0] && (!_.isArray(data[0]) || (data[0][0] && _.isArray(data[0][0]))))
      return data;
    else
      return [data];
  },

  _flotrDefaultOptions : function (options) {

    var o = options || this.options,
      i;

    for (i in DEFAULTS) {
      if (DEFAULTS.hasOwnProperty(i)) {
        if (_.isUndefined(o[i])) {
          o[i] = DEFAULTS[i];
        } else {
          _.defaults(o[i], DEFAULTS[i]);
        }
      }
    }
  },

  attach : function (component, name, callback) {

    var
      event = this.events[name] || {},
      name = event.name || false,
      handler = event.handler || false;

    if (handler) {

      return E.observe(component.node, name, function () {

        var
          args = [component].concat(Array.prototype.slice.call(arguments)),
          result = handler.apply(this, args);

        return callback.apply(null, [component, result]);

      });
    } else {
      return false;
    }
  },

  detach : function (component, name, callback) {
    return E.stopObserve(component.node, name, handler);
  },

  trigger : function (component, name, options) {

    var
      event = this.events[name],
      consumer = event.consumer || false;

    return consumer ? consumer.apply(this, [component, options]) : false;
  },

  events : {

    hit : {
      name : 'flotr:hit',
      handler : function (component, hit) {

        var
          x = hit.x,
          y = hit.y,
          graph = component.api.flotr,
          options;

        // Normalized hit:
        options = {
          data : {
            index : hit.index,
            x : x,
            y : y
          },
          x : graph.axes.x.d2p(x),
          y : graph.axes.y.d2p(y)
        };

        return options;
      },
      consumer : function (component, hit) {

        var
          graph = component.api.flotr,
          o;

        // TODO this is a hack;
        // the hit plugin should expose an API to do this easily
        o = {
          x : hit.data.x,
          y : hit.data.y || 1,
          relX : hit.x,
          relY : hit.y || 1
        };

        graph.hit.hit(o);
      }
    },

    select : {
      name : 'flotr:selecting',
      handler : selectHandler,
      consumer : function (component, selection) {

        var
          graph = component.api.flotr,
          axes = graph.axes,
          data = selection.data || {},
          options = {},
          x = selection.x,
          y = selection.y;

        if (!x && data.x) {
          // Translate data to pixels
          x = data.x;
          options.x1 = axes.x.d2p(x.min);
          options.x2 = axes.x.d2p(x.max);
        } else if (x) {
          // Use pixels
          options.x1 = x.min;
          options.x2 = x.max;
        }

        if (!y && data.y) {
          // Translate data to pixels
          y = data.y;
          options.y1 = axes.y.d2p(y.min);
          options.y2 = axes.y.d2p(y.max);
        } else if (y) {
          // Use pixels
          options.y1 = y.min;
          options.y2 = y.max;
        }

        graph.selection.setSelection(options);
      }
    },

    zoom : {
      name : 'flotr:select',
      handler : function (component, selection) {
        var options = selectHandler(component, selection);
        component.trigger('zoom', options);
        return options;
      },
      consumer : function (component, selection) {

        var
          x = selection.data.x,
          y = selection.data.y,
          options = {};

        if (x) {
          options.xaxis = {
            min : x.min,
            max : x.max
          };
        }

        if (y) {
          options.yaxis = {
            min : y.min,
            max : y.max
          };
        }

        component.draw(null, options);
      }
    },

    mouseout : {
      name : 'flotr:mouseout',
      handler : function (component) {
      },
      consumer : function (component) {
        component.api.flotr.hit.clearHit();
      }
    },

    reset : {
      name : 'flotr:click',
      handler : function (component) {
        component.draw();
      },
      consumer : function (component) {
        component.draw();
      }
    },

    click : {
      name : 'flotr:click',
      handler : function (component) {

        var
          min = component.api.flotr.axes.x.min,
          max = component.api.flotr.axes.x.max;

        return {
          data : {
            x : {
              min : min,
              max : max
            }
          },
          x : {
            min : component.api.flotr.axes.x.d2p(min),
            max : component.api.flotr.axes.x.d2p(max)
          }
        };
      },
      consumer : function (component, selection) {

        var
          x = selection.data.x,
          y = selection.data.y,
          options = {};

        if (x) {
          options.xaxis = {
            min : x.min,
            max : x.max
          };
        }

        if (y) {
          options.yaxis = {
            min : y.min,
            max : y.max
          };
        }

        component.draw(null, options);
      }
    }
  }
};

function selectHandler (component, selection) {

  var
    mode = component.options.config.selection.mode,
    axes = component.api.flotr.axes,
    datax, datay, x, y, options;

  if (mode.indexOf('x') !== -1) {
    datax = {};
    datax.min = selection.x1;
    datax.max = selection.x2;
    x = {};
    x.min = axes.x.d2p(selection.x1);
    x.max = axes.x.d2p(selection.x2);
  }

  if (mode.indexOf('y') !== -1) {
    datay = {};
    datay.min = selection.y1;
    datay.max = selection.y2;
    y = {};
    y.min = axes.y.d2p(selection.y1);
    y.max = axes.y.d2p(selection.y2);
  }

  // Normalized selection:
  options = {
    data : {
      x : datax,
      y : datay
    },
    x : x,
    y : y
  }

  return options;
}

A.flotr.Child = Child;

})();
<|endoftext|>


<commit_before>var Backbone   = require('backbone'),
    $          = require('jquery'),
    _          = require('underscore');

function navigate(categories, keyWords) {
  var route  = 'query?categories=' + categories.join(',') + '&search=' + encodeURIComponent(keyWords),
      router = require('routers/router').instance;

  router.navigate(route, { trigger: true });
}

var IndexView = Backbone.View.extend({
  template: require('templates/index'),

  events: {
    'click .search-button': 'submit',
    'click ul.categories button': 'toggleCheckbox'
  },

  render: function() {
    this.$el.html(this.template());
    return this;
  },

  toggleCheckbox: function(event) {
    $(event.target).find('.icon-ok').toggle();
  },

  submit: function(event) {
    var category,
        categories   = [],
        keyWords     = this.$('#search_name').val(),
        visibleIcons = this.$('.category .icon-ok:visible');

    _.each(visibleIcons, function(icon) {
      category = $(icon).closest('button').data('category');
      categories.push(category);
    });

    navigate(categories, keyWords);
  }
});

module.exports = IndexView;
<commit_msg>Index: don't allow empty search<commit_after>var Backbone   = require('backbone'),
    $          = require('jquery'),
    _          = require('underscore');

function navigate(categories, keyWords) {
  var route  = 'query?categories=' + categories.join(',') + '&search=' + encodeURIComponent(keyWords),
      router = require('routers/router').instance;

  router.navigate(route, { trigger: true });
}

var IndexView = Backbone.View.extend({
  template: require('templates/index'),

  events: {
    'click .search-button': 'submit',
    'click ul.categories button': 'toggleCheckbox'
  },

  render: function() {
    this.$el.html(this.template());
    return this;
  },

  toggleCheckbox: function(event) {
    $(event.target).find('.icon-ok').toggle();
  },

  submit: function(event) {
    var category,
        categories   = [],
        keyWords     = this.$('#search_name').val(),
        visibleIcons = this.$('.category .icon-ok:visible');

    _.each(visibleIcons, function(icon) {
      category = $(icon).closest('button').data('category');
      categories.push(category);
    });

    if (categories.length === 0 && keyWords === '') { return; }
    navigate(categories, keyWords);
  }
});

module.exports = IndexView;
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    }
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();
    displayProjectStructure();
}

function displayProjectStructure() {

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            //var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);
            console.log(item.id, item.code);

            /*$.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
                });
            });*/
        })
    });
}
<commit_msg>assess score<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.indicators = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    }
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();
    fetchProjectStructure();
}

function fetchProjectStructure() {

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            $.each(item.subcompetences, function(i, subcomp){
                $.each(subcomp.indicators, function(i, indic){
                    var indicator = new Indicator(indic.id, subcomp.id, item.id, indic.name, indic.description);
                    viewModel.indicators.push(indicator);
                });
            });
        })
    });

    console.log(viewModel.indicators);
}

/* Indicators */
function Indicator(id, subcompetenceId, competenceId, name, description) {
    return {
        id: ko.observable(id),
        subcompetenceId: ko.observable(subcompetenceId),
        competenceId: ko.observable(competenceId),
        name: ko.observable(name),
        description : ko.observable(description)
       }
}<|endoftext|>


<commit_before>import app from '../app';
import { integerToDecimal } from '../utils/currency';
import { Collection } from 'backbone';
import ListingShort from '../models/listing/ListingShort';

export default class extends Collection {
  constructor(models = [], options = {}) {
    if (!options.guid) {
      throw new Error('Please provide a guid.');
    }

    super(models, options);
    this.guid = options.guid;
  }

  model(attrs, options) {
    return new ListingShort(attrs, options);
  }

  url() {
    let url;

    if (this.guid === app.profile.id) {
      url = app.getServerUrl('ob/listings');
    } else {
      url = app.getServerUrl(`ipns/${this.guid}/listings/index.json`);
    }

    return url;
  }

  /**
   * Returns a list of the aggregate categories from all
   * the listing in the collection.
   */
  get categories() {
    const cats = [];

    this.models.forEach(listing => {
      listing.get('categories')
        .forEach(cat => {
          if (cats.indexOf(cat) === -1) cats.push(cat);
        });
    });

    // todo: For now sort will only be accurate for standard ascii
    // characters. In order to properly sort categories with
    // foreign characters, we will need to know what language
    // the listing is in and pass that into localeCompare().
    // https://github.com/OpenBazaar/openbazaar-go/issues/143
    return cats.sort();
  }

  parse(response) {
    const parsedResponse = [];

    response.forEach(listing => {
      const updatedListing = listing;
      const priceObj = updatedListing.price;

      updatedListing.price.amount =
        integerToDecimal(priceObj.amount, priceObj.currencyCode === 'BTC');

      parsedResponse.push(updatedListing);
    });

    return parsedResponse;
  }
}
<commit_msg>Handle Listing Category of Null Fixes an issue where categories is returned as null, which causes the forEach on the returned categories value to fail.<commit_after>import app from '../app';
import { integerToDecimal } from '../utils/currency';
import { Collection } from 'backbone';
import ListingShort from '../models/listing/ListingShort';

export default class extends Collection {
  constructor(models = [], options = {}) {
    if (!options.guid) {
      throw new Error('Please provide a guid.');
    }

    super(models, options);
    this.guid = options.guid;
  }

  model(attrs, options) {
    return new ListingShort(attrs, options);
  }

  url() {
    let url;

    if (this.guid === app.profile.id) {
      url = app.getServerUrl('ob/listings');
    } else {
      url = app.getServerUrl(`ipns/${this.guid}/listings/index.json`);
    }

    return url;
  }

  /**
   * Returns a list of the aggregate categories from all
   * the listing in the collection.
   */
  get categories() {
    const cats = [];

    this.models.forEach(listing => {
      const categories = listing.get('categories') || []; // this may be returned as null
      categories.forEach(cat => {
          if (cats.indexOf(cat) === -1) cats.push(cat);
        });
    });

    // todo: For now sort will only be accurate for standard ascii
    // characters. In order to properly sort categories with
    // foreign characters, we will need to know what language
    // the listing is in and pass that into localeCompare().
    // https://github.com/OpenBazaar/openbazaar-go/issues/143
    return cats.sort();
  }

  parse(response) {
    const parsedResponse = [];

    response.forEach(listing => {
      const updatedListing = listing;
      const priceObj = updatedListing.price;

      updatedListing.price.amount =
        integerToDecimal(priceObj.amount, priceObj.currencyCode === 'BTC');

      parsedResponse.push(updatedListing);
    });

    return parsedResponse;
  }
}
<|endoftext|>


<commit_before>/* globals document, ajaxurl, tinymce */
define([
    'jquery',
    'modal',
    'jquery-ui.sortable'
], function ($, modal) {
    return function(areas, callback) {
        var $areas = $(areas).filter(':not(.initialized)');

        $areas.addClass('initialized');

        var updateData = function() {
            if(typeof tinymce !== 'undefined' && tinymce.get('content')) {
                //use WordPress native beforeunload warning if content is modified
                tinymce.get('content').isNotDirty = false;
            }
            var data = {};
            $areas.each(function () {
                var col = [];
                $(this).find('> ul, > div > ul').find('> li[data-widget]:not(.removed)').each(function () {
                    col.push({
                        "widgetId": $(this).data('widget'),
                        "instance": $(this).data('instance')
                    });
                });
                data[$(this).data('id')] = col;
            });

            callback(data);
        };

        $areas.find('> ul, > div > ul').sortable({
            connectWith: $areas.find('> ul, > div > ul'),
            placeholder: "neochic-woodlets-placeholder",
            delay: 250,
            update: updateData,
            receive: function (e, ui) {
                var $area = $(this).closest('.woodlets-content-area');
                var widgetId = ui.item.data('widget');
                var allowed = $area.data('allowed');
                if ($.inArray(widgetId, allowed) < 0) {
                    ui.sender.sortable("cancel");
                }
            }
        });

        $areas.on('click', '.add-element', function (e) {
            var $button = $(this);
            if ($button.hasClass('blocked')) {
                return;
            }
            $button.addClass('blocked');

            e.preventDefault();
            var $area = $(this).closest('.woodlets-content-area');
            $.ajax({
                method: "post",
                url: ajaxurl,
                data: {
                    action: "neochic_woodlets_get_widget_list",
                    allowed: $area.data('allowed')
                }
            }).done(function (data) {
                var $content = $(data);
                var selectWidget = function($widget, preventClose) {
                    var widget = $widget.closest('.widget').data('widget');
                    $button.removeClass('blocked');

                    $.ajax({
                        method: "post",
                        url: ajaxurl,
                        data: {
                            "action": "neochic_woodlets_get_widget_preview",
                            "widget": widget,
                            "instance": null
                        }
                    }).done(function (result) {
                        var item = $(result);
                        $area.find('> ul, > div > ul').append(item);
                        updateData();
                        if (!preventClose) {
                            modal.close();
                        }
                        item.trigger('click');
                    });
                };

                var $widgets = $content.find('.widget-top');
                if ($widgets.length === 1) {
                    selectWidget($widgets, true);
                    return;
                }

                $content.on('click', '.widget-top', function () {
                    selectWidget($(this));
                });

                $content.on('click', '.cancel', function() {
                    modal.close();
                });

                modal.open($content, 'Add item');
            });
        });

        $areas.on('click', '.delete', function () {
            var removed = $(this).closest('.neochic-woodlets-widget');
            removed.addClass('removed');
            updateData();
        });

        $areas.on('click', '.revert-removal a', function() {
            var reverted = $(this).closest('.neochic-woodlets-widget');
            //we wan't the click event to bubble first
            window.setTimeout(function() {
                reverted.removeClass('removed');
                updateData();
            }, 4);
        });

        $areas.on('click', '> ul > li.neochic-woodlets-widget, > div > ul > li.neochic-woodlets-widget', function (e) {
            var el = $(this);
            if (el.hasClass('blocked') || el.hasClass('removed')) {
                return;
            }

            el.addClass('blocked');

            /*
             * stop propagation to prevent widget getting collapsed by WordPress
             */
            e.stopPropagation();

            /*
             * do not open widget form if an action (like "delete") is clicked
             */
            if (!$(e.target).is('.edit') && $(e.target).closest('.row-actions').length > 0) {
                return;
            }

            var widget = $(this).data('widget');

            //this should be done more elegant!
            var name = $(this).find(".widget-title h4").text();

            var data = {
                action: "neochic_woodlets_get_widget_form",
                widget: widget,
                instance: JSON.stringify(el.data('instance'))
            };

            $.ajax({
                method: "post",
                url: ajaxurl,
                data: data
            }).done(function (data) {
                var form = $('<form>' + data + 'Cancel <button type="submit" class="button button-primary">Save</button></form>');
                form.on('submit', function (e) {
                    $(document).trigger('neochic-woodlets-form-end', form);
                    $.ajax({
                        method: "post",
                        url: ajaxurl,
                        data: $(this).serialize() + '&widget=' + widget + '&action=neochic_woodlets_get_widget_update'
                    }).done(function (result) {
                        var instance = $.parseJSON(result);

                        el.data('instance', instance);

                        $.ajax({
                            method: "post",
                            url: ajaxurl,
                            data: {
                                "action": "neochic_woodlets_get_widget_preview",
                                "widget": widget,
                                "instance": JSON.stringify(instance)
                            }
                        }).done(function (result) {
                            el.replaceWith($(result));
                        });
                        modal.close();
                        updateData();
                    });

                    e.preventDefault();
                });

                form.on('click', '.cancel', function() {
                    modal.close();
                });

                modal.open(form, name);
                $(document).trigger('neochic-woodlets-form-init', form);
                el.removeClass('blocked');
            });
        });
    };
});
<commit_msg>* fixed js hint error<commit_after>/* globals document, ajaxurl, tinymce, window */
define([
    'jquery',
    'modal',
    'jquery-ui.sortable'
], function ($, modal) {
    return function(areas, callback) {
        var $areas = $(areas).filter(':not(.initialized)');

        $areas.addClass('initialized');

        var updateData = function() {
            if(typeof tinymce !== 'undefined' && tinymce.get('content')) {
                //use WordPress native beforeunload warning if content is modified
                tinymce.get('content').isNotDirty = false;
            }
            var data = {};
            $areas.each(function () {
                var col = [];
                $(this).find('> ul, > div > ul').find('> li[data-widget]:not(.removed)').each(function () {
                    col.push({
                        "widgetId": $(this).data('widget'),
                        "instance": $(this).data('instance')
                    });
                });
                data[$(this).data('id')] = col;
            });

            callback(data);
        };

        $areas.find('> ul, > div > ul').sortable({
            connectWith: $areas.find('> ul, > div > ul'),
            placeholder: "neochic-woodlets-placeholder",
            delay: 250,
            update: updateData,
            receive: function (e, ui) {
                var $area = $(this).closest('.woodlets-content-area');
                var widgetId = ui.item.data('widget');
                var allowed = $area.data('allowed');
                if ($.inArray(widgetId, allowed) < 0) {
                    ui.sender.sortable("cancel");
                }
            }
        });

        $areas.on('click', '.add-element', function (e) {
            var $button = $(this);
            if ($button.hasClass('blocked')) {
                return;
            }
            $button.addClass('blocked');

            e.preventDefault();
            var $area = $(this).closest('.woodlets-content-area');
            $.ajax({
                method: "post",
                url: ajaxurl,
                data: {
                    action: "neochic_woodlets_get_widget_list",
                    allowed: $area.data('allowed')
                }
            }).done(function (data) {
                var $content = $(data);
                var selectWidget = function($widget, preventClose) {
                    var widget = $widget.closest('.widget').data('widget');
                    $button.removeClass('blocked');

                    $.ajax({
                        method: "post",
                        url: ajaxurl,
                        data: {
                            "action": "neochic_woodlets_get_widget_preview",
                            "widget": widget,
                            "instance": null
                        }
                    }).done(function (result) {
                        var item = $(result);
                        $area.find('> ul, > div > ul').append(item);
                        updateData();
                        if (!preventClose) {
                            modal.close();
                        }
                        item.trigger('click');
                    });
                };

                var $widgets = $content.find('.widget-top');
                if ($widgets.length === 1) {
                    selectWidget($widgets, true);
                    return;
                }

                $content.on('click', '.widget-top', function () {
                    selectWidget($(this));
                });

                $content.on('click', '.cancel', function() {
                    modal.close();
                });

                modal.open($content, 'Add item');
            });
        });

        $areas.on('click', '.delete', function () {
            var removed = $(this).closest('.neochic-woodlets-widget');
            removed.addClass('removed');
            updateData();
        });

        $areas.on('click', '.revert-removal a', function() {
            var reverted = $(this).closest('.neochic-woodlets-widget');
            //we wan't the click event to bubble first
            window.setTimeout(function() {
                reverted.removeClass('removed');
                updateData();
            }, 4);
        });

        $areas.on('click', '> ul > li.neochic-woodlets-widget, > div > ul > li.neochic-woodlets-widget', function (e) {
            var el = $(this);
            if (el.hasClass('blocked') || el.hasClass('removed')) {
                return;
            }

            el.addClass('blocked');

            /*
             * stop propagation to prevent widget getting collapsed by WordPress
             */
            e.stopPropagation();

            /*
             * do not open widget form if an action (like "delete") is clicked
             */
            if (!$(e.target).is('.edit') && $(e.target).closest('.row-actions').length > 0) {
                return;
            }

            var widget = $(this).data('widget');

            //this should be done more elegant!
            var name = $(this).find(".widget-title h4").text();

            var data = {
                action: "neochic_woodlets_get_widget_form",
                widget: widget,
                instance: JSON.stringify(el.data('instance'))
            };

            $.ajax({
                method: "post",
                url: ajaxurl,
                data: data
            }).done(function (data) {
                var form = $('<form>' + data + 'Cancel <button type="submit" class="button button-primary">Save</button></form>');
                form.on('submit', function (e) {
                    $(document).trigger('neochic-woodlets-form-end', form);
                    $.ajax({
                        method: "post",
                        url: ajaxurl,
                        data: $(this).serialize() + '&widget=' + widget + '&action=neochic_woodlets_get_widget_update'
                    }).done(function (result) {
                        var instance = $.parseJSON(result);

                        el.data('instance', instance);

                        $.ajax({
                            method: "post",
                            url: ajaxurl,
                            data: {
                                "action": "neochic_woodlets_get_widget_preview",
                                "widget": widget,
                                "instance": JSON.stringify(instance)
                            }
                        }).done(function (result) {
                            el.replaceWith($(result));
                        });
                        modal.close();
                        updateData();
                    });

                    e.preventDefault();
                });

                form.on('click', '.cancel', function() {
                    modal.close();
                });

                modal.open(form, name);
                $(document).trigger('neochic-woodlets-form-init', form);
                el.removeClass('blocked');
            });
        });
    };
});
<|endoftext|>


<commit_before>/**
 *
 */
App.ProductsController = Ember.ArrayController.extend(
{
  needs: ['user', 'application', 'product', 'products', 'products.show', 'action', 'program'],

  page: 1,
  perPage: 24,
  lastPage: false,
  loadingMore: false,
  currentCategory: null,
  currentProduct: null,
  category: '',
  categories: [],
  categoryMap: [],

  actions:
  {
    show: function(product)
    {
      this.transitionToRoute('products.show', product);
    },
    clickCategory: function(cat)
    {
      this.set('page', 1);
      this.set('lastPage', false);
      Ember.$('div.product-grid').scrollTop(0);
      console.log('clicked on cat: ' + cat.get('id'));
      this.get('controllers.user').send('healthCheck');
      this.transitionToRoute('products', cat.get('urlName'));
    },
    getMore: function()
    {
      if (this.get('loadingMore') || this.get('lastPage'))
      {
        return;
      }

      var controller = this.get('controllers.products');
      var nextPage = controller.get('page') + 1;
      var perPage = controller.get('perPage');

      if (! controller.get('lastPage'))
      {
        controller.send('fetchPage', nextPage, perPage);
      }
      return;
    },
    fetchPage: function(page, perPage)
    {
      this.get('controllers.products').set('loadingMore', true);

      var catId = this.get('controllers.products').get('categoryMap')[this.get('controllers.products').get('category')].id;

      console.log('fetch more: ' + catId + ', page: ' + page);
      var more = this.store.find('product', { catid: catId, page: page });

      self = this;
      more.then(function(data)
      {
        var lastPage = false;
        self.set('loadingMore', false);
        if (data.content.length)
        {
          if (data.content.length < self.get('controllers.products').get('perPage'))
          {
            lastPage = true;
          }
          self.get('controllers.products').set('page', page);
          self.get('controllers.products').get('model').addObjects(more);
        }
        else
        {
          lastPage = true
        }

        if (lastPage)
        {
          self.get('controllers.products').set('lastPage', true);
        }
      });
      return;
    }
  }
});

App.ProductsIndexController = Ember.ObjectController.extend(
{
  needs: ['user', 'application', 'products'],
});

App.ProductsShowController = Ember.ObjectController.extend(
{
  needs: ['user', 'application', 'products'],
});
<commit_msg>use the enumerable array properly<commit_after>/**
 *
 */
App.ProductsController = Ember.ArrayController.extend(
{
  needs: ['user', 'application', 'product', 'products', 'products.show', 'action', 'program'],

  page: 1,
  perPage: 24,
  lastPage: false,
  loadingMore: false,
  currentCategory: null,
  currentProduct: null,
  category: '',
  categories: [],
  categoryMap: [],

  actions:
  {
    show: function(product)
    {
      this.transitionToRoute('products.show', product);
    },
    clickCategory: function(cat)
    {
      this.set('page', 1);
      this.set('lastPage', false);
      Ember.$('div.product-grid').scrollTop(0);
      this.get('controllers.user').send('healthCheck');
      this.transitionToRoute('products', cat.get('urlName'));
    },
    getMore: function()
    {
      if (this.get('loadingMore') || this.get('lastPage'))
      {
        return;
      }

      var controller = this.get('controllers.products');
      var nextPage = controller.get('page') + 1;
      var perPage = controller.get('perPage');

      if (! controller.get('lastPage'))
      {
        controller.send('fetchPage', nextPage, perPage);
      }
      return;
    },
    fetchPage: function(page, perPage)
    {
      this.get('controllers.products').set('loadingMore', true);

      var catId = this.get('controllers.products').get('categoryMap').findBy('urlName', this.get('controllers.products').get('category')).get('id');

      console.log('fetch more: ' + catId + ', page: ' + page);
      var more = this.store.find('product', { catid: catId, page: page });

      self = this;
      more.then(function(data)
      {
        var lastPage = false;
        self.set('loadingMore', false);
        if (data.content.length)
        {
          if (data.content.length < self.get('controllers.products').get('perPage'))
          {
            lastPage = true;
          }
          self.get('controllers.products').set('page', page);
          self.get('controllers.products').get('model').addObjects(more);
        }
        else
        {
          lastPage = true
        }

        if (lastPage)
        {
          self.get('controllers.products').set('lastPage', true);
        }
      });
      return;
    }
  }
});

App.ProductsIndexController = Ember.ObjectController.extend(
{
  needs: ['user', 'application', 'products'],
});

App.ProductsShowController = Ember.ObjectController.extend(
{
  needs: ['user', 'application', 'products'],
});
<|endoftext|>