<commit_before>const async = require('async'),
  http = require('http'),
  https = require('https'),
  log = require('../../helpers/logger'),
  Game = require('../../models/game'),
  User = require('../../models/user');

/**
 * Abstraction to handle the page errors
 * @param  {String|Array} errors Single or collection of errors
 */
function handleError(req, res, errors)
{
	log.error(errors);
	if (Array.isArray(errors))
	{
		req.flash('errors', errors);
	}
	else
	{
		req.flash('error', 'Unable to update the game: ' + errors);
	}
	res.redirect(req.originalUrl);
}

function validateRequest(req){
  req.checkBody('title', 'Title is required').notEmpty();
	req.checkBody('bundleId', 'Bundle ID is required').isBundleId();
	req.checkBody('slug', 'Slug is required').isSlug();
	req.checkBody('repository', 'Repository needs to be a URL').isURL();
	req.checkBody('location', 'Location needs to be a URL').isURL();
	req.checkBody('description').optional();
  req.checkBody('thumbnail').optional();
  var errors = req.validationErrors();
	return errors ? errors : false;
}

/**
 * Convert bytes into a human readable format
 * source: https://stackoverflow.com/a/20732091/10236401
 * thanks andrew!
 *
 * @param  {integer} size file size that we want to convert
 * @return {string}       file size in human readable format
 */
function humanFileSize(size) {
	const i = Math.floor( Math.log(size) / Math.log(1024) );

	return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
}

/**
 * Read the "content-length" header of the game resource to determine
 * the byte size
 *
 * @param  {string} host the host where the resource is stored (s3)
 * @param  {string} commitId commit id of the game release we want to check
 * @return {string}      human readable game file size
 */
function gameSize(host, gameSlug, commitId) {
  return new Promise(function (resolve, reject) {
    // set defaults
    let port = 80;
    let client = http;
    // check for https
    if (host.indexOf("https") === -1) {
      // update settings
      port = 443;
      client = https;
    }

    // remove prefix from host
    host = host.replace(/https:\/\/|http:\/\//, "");
    // remove game slug
    host = host.replace(`/${gameSlug}`, "");
    const options = {
      method: "HEAD",
      host,
      port,
      path: `/${gameSlug}/${commitId}/release.zip`,
    };

    const req = client.request(options, function (res, err) {
    	if (err) return reject(err);

    	resolve(humanFileSize(res.headers["content-length"]));
    });
    // make request
    req.end();
  });
}

/**
 * Abstraction to render a page, takes care of all
 * of the access control and populate the page with
 * standard parameters
 * @param  {Object} req The express request object
 * @param {Object} res The express response object
 * @param {string} template The template to use
 * @param {String} [populate='groups.group'] The game fields to populate
 * @param {function} [success] Callback when completed
 */
function renderPage(req, res, template, populate=null)
{
	async.waterfall(
		[
			function(done)
			{
        var game = Game.getBySlug(req.params.slug, done);
        if (populate){
          game.populate({
						path: populate,
						options: { sort: { 'updated': -1 } }
					});
				};
      },
			function(game, done)
			{
				if (!game){
					return res.status(404).render('404');
				}

				game.getAccess(req.user, done);
			}
		],
		function(err, game, access)
		{
			if (err)
			{
				return res.status(401).render('401');
			}

			// Gets the page index if the page supports query string pages
			const pages = Math.ceil(game.releases.length / 10);

			const pageIndex =
				// Verify that the page is passed a number
				req.query &&
				req.query.page &&
				Number.isInteger(Number(req.query.page)) &&
				// Check to make sure it's greater than zero
				0 < req.query.page
					// Check to make sure that it's not greater than the maximum
					? req.query.page > pages
						? pages
						: Number(req.query.page)
					: 1;

			res.render(template, {
			game: game,
			page: pageIndex,
			totalPages: pages,
			capabilities: game.capabilities,
			host: req.headers.host,
			isEditor: access.permission > 0,
			isAdmin: access.permission > 1,
			token: access.token,
			errors: req.flash('errors'),
			success: req.flash('success'),
			error: req.flash('error')
			});
		}
	);
}

/**
 * Abstraction to post a page, takes care of all
 * of the access control and populate the page with
 * standard parameters.
 * @param  {Object} req The express request object
 * @param {Object} res The express response object
 * @param {string} minPrivilege The minimum privilege needed to run all form
 * @param {Object} actions Run custom page actions
 */
function postPage(req, res, minPrivilege, actions)
{
	async.waterfall(
		[
			function(done)
			{
				Game.getBySlug(req.params.slug, done).populate('groups.group');
			},
			function(game, done)
			{
				if (!game) {
					return res.status(404).render('404');
				}

				game.getAccess(req.user, done);
			},
			function(game, access, done)
			{
				var response = function(err)
				{
					if (err) {
						return done(err);
					}
					done(null, game);
					return;
				};

				if (access.permission < minPrivilege)
				{
					return done('Invalid form permissions');
				}

				if (!req.body.action || !actions[req.body.action])
				{
					done('Invalid form action');
				}
				actions[req.body.action](response, game, access);
			}
		],
		function(err, game)
		{
			if (err) {
				return handleError(req, res, err);
			}

			req.flash('success', game.title + " updated successfully");
			res.redirect(req.body.slug ? req.baseUrl + `/${req.body.slug}` : req.originalUrl);
		}
	);
}

function defaultCapabilities(capabilities)
{
	capabilities.ui = Object.assign({
		mouse: false,
		touch: false
	}, capabilities.ui);

	capabilities.sizes = Object.assign({
			xsmall: false,
			small: false,
			medium: false,
			large: false,
			xlarge: false
		}, capabilities.sizes);
}

module.exports = {renderPage, postPage, defaultCapabilities, validateRequest, handleError};<commit_msg>add release human file size to release object<commit_after>const async = require('async'),
  http = require('http'),
  https = require('https'),
  log = require('../../helpers/logger'),
  Game = require('../../models/game'),
  User = require('../../models/user');

/**
 * Abstraction to handle the page errors
 * @param  {String|Array} errors Single or collection of errors
 */
function handleError(req, res, errors)
{
	log.error(errors);
	if (Array.isArray(errors))
	{
		req.flash('errors', errors);
	}
	else
	{
		req.flash('error', 'Unable to update the game: ' + errors);
	}
	res.redirect(req.originalUrl);
}

function validateRequest(req){
  req.checkBody('title', 'Title is required').notEmpty();
	req.checkBody('bundleId', 'Bundle ID is required').isBundleId();
	req.checkBody('slug', 'Slug is required').isSlug();
	req.checkBody('repository', 'Repository needs to be a URL').isURL();
	req.checkBody('location', 'Location needs to be a URL').isURL();
	req.checkBody('description').optional();
  req.checkBody('thumbnail').optional();
  var errors = req.validationErrors();
	return errors ? errors : false;
}

/**
 * Convert bytes into a human readable format
 * source: https://stackoverflow.com/a/20732091/10236401
 * thanks andrew!
 *
 * @param  {integer} size file size that we want to convert
 * @return {string}       file size in human readable format
 */
function humanFileSize(size) {
	const i = Math.floor( Math.log(size) / Math.log(1024) );

	return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
}

/**
 * Read the "content-length" header of the game resource to determine
 * the byte size
 *
 * @param  {string} host the host where the resource is stored (s3)
 * @param  {string} commitId commit id of the game release we want to check
 * @return {string}      human readable game file size
 */
function releaseSize(host, gameSlug, commitId) {
  return new Promise(function (resolve, reject) {
    // set defaults
    let port = 80;
    let client = http;
    // check for https
    if (host.indexOf("https") === -1) {
      // update settings
      port = 443;
      client = https;
    }

    // remove prefix from host
    host = host.replace(/https:\/\/|http:\/\//, "");
    // remove game slug
    host = host.replace(`/${gameSlug}`, "");
    const options = {
      method: "HEAD",
      host,
      port,
      path: `/${gameSlug}/${commitId}/release.zip`,
    };

    const req = client.request(options, function (res, err) {
    	if (err) return reject(err);

    	resolve(humanFileSize(res.headers["content-length"]));
    });
    // make request
    req.end();
  });
}

/**
 * Abstraction to render a page, takes care of all
 * of the access control and populate the page with
 * standard parameters
 * @param  {Object} req The express request object
 * @param {Object} res The express response object
 * @param {string} template The template to use
 * @param {String} [populate='groups.group'] The game fields to populate
 * @param {function} [success] Callback when completed
 */
function renderPage(req, res, template, populate=null)
{
	async.waterfall(
		[
			function(done)
			{
        var game = Game.getBySlug(req.params.slug, done);
        if (populate){
          game.populate({
						path: populate,
						options: { sort: { 'updated': -1 } }
					});
				};
      },
			function(game, done)
			{
				if (!game){
					return res.status(404).render('404');
				}

				game.getAccess(req.user, done);
			}
		],
		async function(err, game, access)
		{
			if (err)
			{
				return res.status(401).render('401');
			}

			// Gets the page index if the page supports query string pages
			const pages = Math.ceil(game.releases.length / 10);

			const pageIndex =
				// Verify that the page is passed a number
				req.query &&
				req.query.page &&
				Number.isInteger(Number(req.query.page)) &&
				// Check to make sure it's greater than zero
				0 < req.query.page
					// Check to make sure that it's not greater than the maximum
					? req.query.page > pages
						? pages
						: Number(req.query.page)
					: 1;

			// iterate game releases to add file sizes
			for (let k = 0; k < game.releases.length; k++) {
				const commitId = game.releases[k].commitId;
				const humanFileSize = await releaseSize(game.location, game.slug, commitId)
			  game.releases[k].fileSize = humanFileSize;
			}

			res.render(template, {
			game: game,
			page: pageIndex,
			totalPages: pages,
			capabilities: game.capabilities,
			host: req.headers.host,
			isEditor: access.permission > 0,
			isAdmin: access.permission > 1,
			token: access.token,
			errors: req.flash('errors'),
			success: req.flash('success'),
			error: req.flash('error')
			});
		}
	);
}

/**
 * Abstraction to post a page, takes care of all
 * of the access control and populate the page with
 * standard parameters.
 * @param  {Object} req The express request object
 * @param {Object} res The express response object
 * @param {string} minPrivilege The minimum privilege needed to run all form
 * @param {Object} actions Run custom page actions
 */
function postPage(req, res, minPrivilege, actions)
{
	async.waterfall(
		[
			function(done)
			{
				Game.getBySlug(req.params.slug, done).populate('groups.group');
			},
			function(game, done)
			{
				if (!game) {
					return res.status(404).render('404');
				}

				game.getAccess(req.user, done);
			},
			function(game, access, done)
			{
				var response = function(err)
				{
					if (err) {
						return done(err);
					}
					done(null, game);
					return;
				};

				if (access.permission < minPrivilege)
				{
					return done('Invalid form permissions');
				}

				if (!req.body.action || !actions[req.body.action])
				{
					done('Invalid form action');
				}
				actions[req.body.action](response, game, access);
			}
		],
		function(err, game)
		{
			if (err) {
				return handleError(req, res, err);
			}

			req.flash('success', game.title + " updated successfully");
			res.redirect(req.body.slug ? req.baseUrl + `/${req.body.slug}` : req.originalUrl);
		}
	);
}

function defaultCapabilities(capabilities)
{
	capabilities.ui = Object.assign({
		mouse: false,
		touch: false
	}, capabilities.ui);

	capabilities.sizes = Object.assign({
			xsmall: false,
			small: false,
			medium: false,
			large: false,
			xlarge: false
		}, capabilities.sizes);
}

module.exports = {renderPage, postPage, defaultCapabilities, validateRequest, handleError};<|endoftext|>


<commit_before>var fs = require('fs'),
    page = new WebPage(),
    file = fs.absolute('test/index.html');

page.onConsoleMessage = function(msg) {
    console.log(msg);
    if (/^Tests completed in/.test(msg)) {
        phantom.exit(page.evaluate(function () {
            if (window.QUnit && QUnit.config && QUnit.config.stats) {
                return QUnit.config.stats.bad || 0;
            }
            return 1;
        }));
    }
};

page.open('file://' + file, function (status) {
    if (status !== 'success') {
        console.log('FAIL to load the address');
        phantom.exit(1);
    }
});<commit_msg>Fixed path in the phantom runner<commit_after>var fs = require('fs'),
    page = new WebPage(),
    file = fs.absolute('/test/index.html');

page.onConsoleMessage = function(msg) {
    console.log(msg);
    if (/^Tests completed in/.test(msg)) {
        phantom.exit(page.evaluate(function () {
            if (window.QUnit && QUnit.config && QUnit.config.stats) {
                return QUnit.config.stats.bad || 0;
            }
            return 1;
        }));
    }
};

page.open('file://' + file, function (status) {
    console.log(status);
    if (status !== 'success') {
        console.log('FAIL to load the address');
        phantom.exit(1);
    }
});<|endoftext|>


<commit_before>angular.module("ui.timepicker", ["angularMoment"])
    .directive("uiTimepicker", ["moment", function (moment) {
        return {
            restrict: "EA",

            require: 'ngModel',

            scope: {
                datetime: '=ngModel'
            },

            replace: true,

            template: '

',

            link: function (scope, element, attrs) {
                var _selection = d3.select(element[0]);

                var _arc = d3.svg.arc().startAngle(0 * (Math.PI / 180)).endAngle(360 * (Math.PI / 180));

                var _w = 200;
                var _h = _w;
                var _diameter = _w;
                var _margin = { top:10, right:10, bottom:10, left:10 };
                var _fontSize = 10;

                var _width;
                var _height;
                var _x0;
                var _y0;

                var _minValue = 1;
                var _maxValue = 720;
                var _value = 1;

                var _setAsAM = false;

                _selection.each(function (data) {
                    measure();

                    var svg = d3.select(this).selectAll("svg").data([data]);

                    var enter = svg.enter().append("svg")
                        .attr("class", "x1-timepicker-svg").append("g")
                        .attr("transform", "translate(" + _margin.left + "," + _margin.top + ")");

                    svg.attr("width", _w).attr("height", _h);

                    var background = enter.append("g")
                        .attr("class", "x1-timepicker-component");

                    var body = background.append("circle")
                        .attr("class", "x1-timepicker-inner")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("cx", 0)
                        .attr("cy", 0)
                        .attr("r", _width / 2);

                    var slider = background.append("path")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("d", _arc);

                    var arcContainer = enter.append("g")
                        .attr("class", "x1-timepicker-arcs");

                    var selectedArc = arcContainer.append("path")
                        .attr("class", "arc")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("d", _arc);

                    // ---------- labels for the picker ------------------------------------------
                    var labels = enter.append("g")
                        .attr("class", "x1-timepicker-labels");

                    var labelSendAt = labels.append("text")
                        .attr("class", "title")
                        .attr("x", _x0)
                        .attr("y", _width / 4.2 + _fontSize / 3)
                        .attr("width", _width)
                        .text("Time")
                        .style("font-size", (_fontSize * 0.4) + "px");

                    var labelTime = labels.append("text")
                        .attr("class", "time")
                        .attr("x", _x0)
                        .attr("y", _y0 + _fontSize / 3)
                        .attr("width", _width)
                        .style("font-size", (_fontSize * 1.4) + "px");

                    var labelAMPM = labels.append("text")
                        .attr("class", "ampm")
                        .attr("cursor", "pointer")
                        .attr("x", _x0)
                        .attr("y", _width / 1.4 + _fontSize / 3)
                        .attr("width", _width)
                        .style("font-size", (_fontSize * 0.6) + "px")
                        .on("click", function () {
                            var blnAM = isAM(scope.datetime);
                            var offset = blnAM ? 12 : -12;
                            _setAsAM = !blnAM;
                            scope.datetime = moment(scope.datetime).add(offset, 'hour').toDate();
                            d3.select(this).text(moment(scope.datetime).format("A"));
                            scope.$apply();
                        });

                    // ---------- slider handler ------------------------------------------
                    var drag = d3.behavior.drag().on("drag", function () {
                        var eventX = d3.event.x;
                        var eventY = d3.event.y;

                        // --------------------------
                        var _C = Math.PI * _width;

                        var ox = 0;
                        var oy = 0;

                        var ax = 0;
                        var ay = _height / 2;

                        var bx = eventX - _width / 2;
                        var by = _height / 2 - eventY;

                        var k = (by - oy)/(bx - ox);

                        var angel = Math.abs(Math.atan(k) / (Math.PI / 180));
                        var targetAngel = 0;

                        if (bx > 0 && by >= 0) {
                            targetAngel = 90 - angel;
                        } else if (bx >= 0 && by < 0) {
                            targetAngel = 90 + angel;
                        } else if (bx < 0 && by <= 0) {
                            targetAngel = 270 - angel;
                        } else if (bx <= 0 && by > 0) {
                            targetAngel = 270 + angel;
                        }

                        _value = _maxValue * (targetAngel / 360);

                        // update scope.datetime
                        var hours = Math.floor(_value / 60);
                        hours = _setAsAM ? hours : (hours + 12);

                        scope.datetime = moment(scope.datetime)
                            .set('hour', hours)
                            .set('minute', _value % 60)
                            .set('second', 0)
                            .toDate();

                        scope.$apply(function(){
                            setCurrent(selectedArc, handler, labelTime, labelAMPM);
                        });
                    });

                    var handler = enter.append("g").append("circle")
                        .attr("class", "x1-timepicker-handler")
                        .attr("cursor", "pointer")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("cx", 0)
                        .attr("cy", 0)
                        .attr("r", 10)
                        .attr("fill", "#FFFFFF")
                        .call(drag);

                    // ---------- set the init value from ng-model ----------------------------------------------
                    var updateValue = function (v) {
                        var hours = moment(v).hours();
                        var hours12 = hours >= 12 ? hours - 12 : hours;
                        var minutes = moment(v).minutes();
                        _value = (hours12 * 60 + minutes);
                        setCurrent(selectedArc, handler, labelTime, labelAMPM);
                    };

                    updateValue(scope.datetime);

                    _setAsAM = isAM(scope.datetime);

                    scope.$watch("datetime", function (newVal, oldVal) {
                        updateValue(newVal);
                    });
                });

                function isAM (date) {
                    return moment(date).format("A") === "AM";
                }

                function measure () {
                    _width = _height = _diameter - _margin.right - _margin.left - _margin.top - _margin.bottom;
                    _x0 = _y0 = _width / 2;
                    _fontSize = _width * .2;
                    _arc.outerRadius(_width / 2);
                    _arc.innerRadius(_width / 2 * .85);
                }

                function setCurrent (selectedArc, handler, labelTime, labelAMPM) {
                    // set the selected arc
                    var ratio = Math.min((_value - _minValue) / (_maxValue - _minValue), 1);
                    var endAng = Math.min(360 * ratio, 360) * Math.PI / 180;
                    _arc.endAngle(endAng);
                    selectedArc.attr("d", _arc);

                    // set the handler position
                    var oAngel = 360 * _value / _maxValue;
                    var r = _width / 2 - 5;
                    var x = r * Math.cos((oAngel - 90) * Math.PI / 180);
                    var y = r * Math.sin((oAngel - 90) * Math.PI / 180);
                    handler.attr('cx', x).attr('cy', y);

                    // update time label
                    var hours = moment(scope.datetime).hours();
                    var hours12 = hours >= 12 ? hours - 12 : hours;
                    var minutes = moment(scope.datetime).minutes();

                    var lbTime = "" + hours12 + ":";
                    if (minutes < 10) {
                        lbTime += "0";
                    }
                    lbTime += minutes;

                    labelTime.text(lbTime);
                    labelAMPM.text(moment(scope.datetime).format("A"));
                }

            }
        };
    }]);
<commit_msg>added basic functionality for increments<commit_after>angular.module("ui.timepicker", ["angularMoment"])
    .directive("uiTimepicker", ["moment", function (moment) {
        return {
            restrict: "EA",

            require: 'ngModel',

            scope: {
                datetime: '=ngModel',
                increments: '='
            },

            replace: true,

            template: '

',

            link: function (scope, element, attrs) {
                var _selection = d3.select(element[0]);

                var _arc = d3.svg.arc().startAngle(0 * (Math.PI / 180)).endAngle(360 * (Math.PI / 180));

                var _w = 200;
                var _h = _w;
                var _diameter = _w;
                var _margin = { top:10, right:10, bottom:10, left:10 };
                var _fontSize = 10;

                var _width;
                var _height;
                var _x0;
                var _y0;

                var _minValue = 1;
                var _maxValue = 720;
                var _value = 1;

                var _increments = 15;

                var _setAsAM = false;

                _selection.each(function (data) {
                    measure();

                    var svg = d3.select(this).selectAll("svg").data([data]);

                    var enter = svg.enter().append("svg")
                        .attr("class", "x1-timepicker-svg").append("g")
                        .attr("transform", "translate(" + _margin.left + "," + _margin.top + ")");

                    svg.attr("width", _w).attr("height", _h);

                    var background = enter.append("g")
                        .attr("class", "x1-timepicker-component");

                    var body = background.append("circle")
                        .attr("class", "x1-timepicker-inner")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("cx", 0)
                        .attr("cy", 0)
                        .attr("r", _width / 2);

                    var slider = background.append("path")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("d", _arc);

                    var arcContainer = enter.append("g")
                        .attr("class", "x1-timepicker-arcs");

                    var selectedArc = arcContainer.append("path")
                        .attr("class", "arc")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("d", _arc);

                    // ---------- labels for the picker ------------------------------------------
                    var labels = enter.append("g")
                        .attr("class", "x1-timepicker-labels");

                    var labelSendAt = labels.append("text")
                        .attr("class", "title")
                        .attr("x", _x0)
                        .attr("y", _width / 4.2 + _fontSize / 3)
                        .attr("width", _width)
                        .text("Time")
                        .style("font-size", (_fontSize * 0.4) + "px");

                    var labelTime = labels.append("text")
                        .attr("class", "time")
                        .attr("x", _x0)
                        .attr("y", _y0 + _fontSize / 3)
                        .attr("width", _width)
                        .style("font-size", (_fontSize * 1.4) + "px");

                    var labelAMPM = labels.append("text")
                        .attr("class", "ampm")
                        .attr("cursor", "pointer")
                        .attr("x", _x0)
                        .attr("y", _width / 1.4 + _fontSize / 3)
                        .attr("width", _width)
                        .style("font-size", (_fontSize * 0.6) + "px")
                        .on("click", function () {
                            var blnAM = isAM(scope.datetime);
                            var offset = blnAM ? 12 : -12;
                            _setAsAM = !blnAM;
                            scope.datetime = moment(scope.datetime).add(offset, 'hour').toDate();
                            d3.select(this).text(moment(scope.datetime).format("A"));
                            scope.$apply();
                        });

                    // ---------- slider handler ------------------------------------------
                    var drag = d3.behavior.drag().on("drag", function () {
                        var eventX = d3.event.x;
                        var eventY = d3.event.y;

                        // --------------------------
                        var _C = Math.PI * _width;

                        var ox = 0;
                        var oy = 0;

                        var ax = 0;
                        var ay = _height / 2;

                        var bx = eventX - _width / 2;
                        var by = _height / 2 - eventY;

                        var k = (by - oy)/(bx - ox);

                        var angle = Math.abs(Math.atan(k) / (Math.PI / 180));
                        var targetAngle = 0;

                        if (bx > 0 && by >= 0) {
                            targetAngle = 90 - angle;
                        } else if (bx >= 0 && by < 0) {
                            targetAngle = 90 + angle;
                        } else if (bx < 0 && by <= 0) {
                            targetAngle = 270 - angle;
                        } else if (bx <= 0 && by > 0) {
                            targetAngle = 270 + angle;
                        }

                        _value = _maxValue * (targetAngle / 360);

                        // update scope.datetime
                        var hours = Math.floor(_value / 60);
                        hours = _setAsAM ? hours : (hours + 12);

                        var minutes = _value % 60;
                        console.log('orig',minutes);

                        minutes = Math.floor(minutes / _increments);
                        minutes = minutes * _increments;
                        console.log('next',minutes);

                        scope.datetime = moment(scope.datetime)
                            .set('hour', hours)
                            .set('minute', minutes)
                            .set('second', 0)
                            .toDate();

                        scope.$apply(function(){
                            setCurrent(selectedArc, handler, labelTime, labelAMPM);
                        });
                    });

                    var handler = enter.append("g").append("circle")
                        .attr("class", "x1-timepicker-handler")
                        .attr("cursor", "pointer")
                        .attr("transform", "translate(" + _x0 + "," + _y0 + ")")
                        .attr("cx", 0)
                        .attr("cy", 0)
                        .attr("r", 10)
                        .attr("fill", "#FFFFFF")
                        .call(drag);

                    // ---------- set the init value from ng-model ----------------------------------------------
                    var updateValue = function (v) {
                        var hours = moment(v).hours();
                        var hours12 = hours >= 12 ? hours - 12 : hours;
                        var minutes = moment(v).minutes();
                        _value = (hours12 * 60 + minutes);
                        setCurrent(selectedArc, handler, labelTime, labelAMPM);
                    };

                    updateValue(scope.datetime);

                    _setAsAM = isAM(scope.datetime);

                    scope.$watch("datetime", function (newVal, oldVal) {
                        updateValue(newVal);
                    });
                });

                function isAM (date) {
                    return moment(date).format("A") === "AM";
                }

                function measure () {
                    _width = _height = _diameter - _margin.right - _margin.left - _margin.top - _margin.bottom;
                    _x0 = _y0 = _width / 2;
                    _fontSize = _width * .2;
                    _arc.outerRadius(_width / 2);
                    _arc.innerRadius(_width / 2 * .85);
                }

                function setCurrent (selectedArc, handler, labelTime, labelAMPM) {
                    // set the selected arc
                    var ratio = Math.min((_value - _minValue) / (_maxValue - _minValue), 1);
                    var endAng = Math.min(360 * ratio, 360) * Math.PI / 180;
                    _arc.endAngle(endAng);
                    selectedArc.attr("d", _arc);

                    // set the handler position
                    var oAngle = 360 * _value / _maxValue;
                    var r = _width / 2 - 5;
                    var x = r * Math.cos((oAngle - 90) * Math.PI / 180);
                    var y = r * Math.sin((oAngle - 90) * Math.PI / 180);
                    handler.attr('cx', x).attr('cy', y);

                    // update time label
                    var hours = moment(scope.datetime).hours();
                    var hours12 = hours >= 12 ? hours - 12 : hours;
                    var minutes = moment(scope.datetime).minutes();

                    var lbTime = "" + hours12 + ":";
                    if (minutes < 10) {
                        lbTime += "0";
                    }
                    lbTime += minutes;

                    labelTime.text(lbTime);
                    labelAMPM.text(moment(scope.datetime).format("A"));
                }

            }
        };
    }]);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Peter Michaux, http://peter.michaux.ca/
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/**

@property evento.addEventListener

@parameter element {EventTarget} The object you'd like to observe.

@parameter type {string} The name of the event.

@parameter listener {object|function} The listener object or callback function.

@parameter auxArg {string|object} Optional. See description.

@description

If the listener is an object then when a matching event type is dispatched on
the event target, the listener object's handleEvent method will be called.
By supplying a string value for auxArg you can specify the name of
the method to be called. You can also supply a function object for auxArg for
early binding.

If the listener is a function then when a matching event type is dispatched on
the event target, the listener function is called with event target object set as
the "this" object. Using the auxArg you can specifiy a different object to be
the "this" object.

One listener (or type/listener/auxArg pair to be more precise) can be added
only once.

evento.addEventListener(document.body, 'click', {handleEvent:function(){}});
evento.addEventListener(document.body, 'click', {handleClick:function(){}}, 'handleClick');
evento.addEventListener(document.body, 'click', {}, function(){});
evento.addEventListener(document.body, 'click', function(){});
evento.addEventListener(document.body, 'click', this.handleClick, this);

*/

/**

@property evento.removeEventListener

@parameter element {EventTarget} The object you'd like to stop observing.

@parameter type {string} The name of the event.

@parameter listener {object|function} The listener object or callback function.

@parameter auxArg {string|object} Optional.

@description

Removes added listener matching the element/type/listener/auxArg combination exactly.
If this combination is not found there are no errors.

var o = {handleEvent:function(){}, handleClick:function(){}};
evento.removeEventListener(document.body, 'click', o);
evento.removeEventListener(document.body, 'click', o, 'handleClick');
evento.removeEventListener(document.body, 'click', o, fn);
evento.removeEventListener(document.body, 'click', fn);
evento.removeEventListener(document.body, 'click', this.handleClick, this);

*/

/**

@property evento.purgeEventListener

@parameter listener {EventListener} The listener object that should stop listening.

@description

Removes all registrations of the listener added through evento.addEventListener.
This purging should be done before your application code looses its last reference
to listener. (This can also be done with more work using evento.removeEventListener for
each registeration.) If the listeners are not removed or purged, the listener
will continue to observe the EventTarget and cannot be garbage collected. In an
MVC application this can lead to "zombie views" if the model data cannot be
garbage collected. Event listeners need to be removed from event targets in browsers
with circular reference memory leak problems (i.e. old versions of Internet Explorer.)

The primary motivation for this purge function is to easy cleanup in MVC View destroy
methods. For example,

var APP_BoxView = function(model, controller) {
    this.model = model || new APP_BoxModel();
    this.controller = controller || new APP_BoxController();
    this.rootEl = document.createElement('div');

    // subscribe to DOM node(s) and model object(s) or anything else
    // implementing the EventTarget interface using listener objects
    // and specifying method name using the same subscription interface.
    //
    evento.addEventListener(this.rootEl, 'click', this, 'handleClick');
    evento.addEventListener(this.model, 'change', this, 'handleModelChange');
};

APP_BoxView.prototype.handleClick = function() {
    // might subscribe/unsubscribe to more DOM nodes or models here
};

APP_BoxView.prototype.handleModelChange = function() {
    // might subscribe/unsubscribe to more DOM nodes or models here
};

APP_BoxView.prototype.destroy = function() {

    // Programmer doesn't need to remember anything. Purge all subscriptions
    // to DOM nodes, model objects, or anything else implementing
    // the EventTarget interface in one fell swoop.
    //
    evento.purgeEventListener(this);
};

*/

(function() {

    function createListener(element, type, listener, /*optional*/ auxArg) {
        var o = {
            element: element,
            type: type,
            listener: listener
        };
        if (arguments.length > 3) {
            o.auxArg = auxArg;
        }
        if (typeof listener === 'function') {
            var thisObj = arguments.length > 3 ? auxArg : element;
            o.wrappedHandler = function(evt) {
                listener.call(thisObj, evt);
            };
        }
        else if (typeof auxArg === 'function') {
            o.wrappedHandler = function(evt) {
                auxArg.call(listener, evt);
            };
        }
        else {
            var methodName = arguments.length > 3 ? auxArg : 'handleEvent';
            o.wrappedHandler = function(evt) {
                listener[methodName](evt);
            };
        }
        return o;
    }

    function listenersAreEqual(a, b) {
        return (a.element === b.element) &&
               (a.type === b.type) &&
               (a.listener === b.listener) &&
               ((!a.hasOwnProperty('auxArg') &&
                 !b.hasOwnProperty('auxArg')) ||
                (a.hasOwnProperty('auxArg') &&
                 b.hasOwnProperty('auxArg') &&
                 (a.auxArg === b.auxArg)));
    }

    function indexOfListener(listeners, o) {
        for (var i = 0, ilen = listeners.length; i < ilen; i++) {
            if (listenersAreEqual(listeners[i], o)) {
                return i;
            }
        }
        return -1;
    }

    evento.addEventListener = function(element, type, listener, /*optional*/ auxArg) {
        // Want to call createListener with the same number of arguments
        // that were passed to this function. Using apply preserves
        // the number of arguments.
        var o = createListener.apply(null, arguments);
        if (listener._evento_listeners) {
            if (indexOfListener(listener._evento_listeners, o) >= 0) {
                // do not add the same listener twice
                return;
            }
        }
        else {
            listener._evento_listeners = [];
        }
        if (typeof element.addEventListener === 'function') {
            o.element.addEventListener(o.type, o.wrappedHandler, false);
        }
        else if ((typeof element.attachEvent === 'object') &&
                 (element.attachEvent !== null)) {
            o.element.attachEvent('on'+o.type, o.wrappedHandler);
        }
        else {
            throw new Error('evento.addEventListener: Supported EventTarget interface not found.');
        }
        listener._evento_listeners.push(o);
    };

    var remove = evento.removeEventListener = function(element, type, listener, /*optional*/ auxArg) {
        if (listener._evento_listeners) {
            var i = indexOfListener(listener._evento_listeners, createListener.apply(null, arguments));
            if (i >= 0) {
                var o = listener._evento_listeners[i];
                if (typeof o.element.removeEventListener === 'function') {
                    o.element.removeEventListener(o.type, o.wrappedHandler, false);
                }
                else if ((typeof element.detachEvent === 'object') &&
                         (element.detachEvent !== null)) {
                    o.element.detachEvent('on'+o.type, o.wrappedHandler);
                }
                else {
                    throw new Error('evento.removeEventListener: Supported EventTarget interface not found.');
                }
                listener._evento_listeners.splice(i, 1);
            }
        }
    };

    evento.purgeEventListener = function(lstnr) {
        if (lstnr._evento_listeners) {
            var listeners = lstnr._evento_listeners.slice(0);
            for (var i = 0, ilen = listeners.length; i < ilen; i++) {
                var listener = listeners[i];
                if (listener.hasOwnProperty('auxArg')) {
                    remove(listener.element, listener.type, listener.listener, listener.auxArg);
                }
                else {
                    remove(listener.element, listener.type, listener.listener);
                }
            }
        }
    };

}());
<commit_msg>Rename variables because listener.listener was confusing to read. Now it is bundle.listener which is at least a bit better.<commit_after>/*
 * Copyright (c) 2012, Peter Michaux, http://peter.michaux.ca/
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/**

@property evento.addEventListener

@parameter element {EventTarget} The object you'd like to observe.

@parameter type {string} The name of the event.

@parameter listener {object|function} The listener object or callback function.

@parameter auxArg {string|object} Optional. See description.

@description

If the listener is an object then when a matching event type is dispatched on
the event target, the listener object's handleEvent method will be called.
By supplying a string value for auxArg you can specify the name of
the method to be called. You can also supply a function object for auxArg for
early binding.

If the listener is a function then when a matching event type is dispatched on
the event target, the listener function is called with event target object set as
the "this" object. Using the auxArg you can specifiy a different object to be
the "this" object.

One listener (or type/listener/auxArg pair to be more precise) can be added
only once.

evento.addEventListener(document.body, 'click', {handleEvent:function(){}});
evento.addEventListener(document.body, 'click', {handleClick:function(){}}, 'handleClick');
evento.addEventListener(document.body, 'click', {}, function(){});
evento.addEventListener(document.body, 'click', function(){});
evento.addEventListener(document.body, 'click', this.handleClick, this);

*/

/**

@property evento.removeEventListener

@parameter element {EventTarget} The object you'd like to stop observing.

@parameter type {string} The name of the event.

@parameter listener {object|function} The listener object or callback function.

@parameter auxArg {string|object} Optional.

@description

Removes added listener matching the element/type/listener/auxArg combination exactly.
If this combination is not found there are no errors.

var o = {handleEvent:function(){}, handleClick:function(){}};
evento.removeEventListener(document.body, 'click', o);
evento.removeEventListener(document.body, 'click', o, 'handleClick');
evento.removeEventListener(document.body, 'click', o, fn);
evento.removeEventListener(document.body, 'click', fn);
evento.removeEventListener(document.body, 'click', this.handleClick, this);

*/

/**

@property evento.purgeEventListener

@parameter listener {EventListener} The listener object that should stop listening.

@description

Removes all registrations of the listener added through evento.addEventListener.
This purging should be done before your application code looses its last reference
to listener. (This can also be done with more work using evento.removeEventListener for
each registeration.) If the listeners are not removed or purged, the listener
will continue to observe the EventTarget and cannot be garbage collected. In an
MVC application this can lead to "zombie views" if the model data cannot be
garbage collected. Event listeners need to be removed from event targets in browsers
with circular reference memory leak problems (i.e. old versions of Internet Explorer.)

The primary motivation for this purge function is to easy cleanup in MVC View destroy
methods. For example,

var APP_BoxView = function(model, controller) {
    this.model = model || new APP_BoxModel();
    this.controller = controller || new APP_BoxController();
    this.rootEl = document.createElement('div');

    // subscribe to DOM node(s) and model object(s) or anything else
    // implementing the EventTarget interface using listener objects
    // and specifying method name using the same subscription interface.
    //
    evento.addEventListener(this.rootEl, 'click', this, 'handleClick');
    evento.addEventListener(this.model, 'change', this, 'handleModelChange');
};

APP_BoxView.prototype.handleClick = function() {
    // might subscribe/unsubscribe to more DOM nodes or models here
};

APP_BoxView.prototype.handleModelChange = function() {
    // might subscribe/unsubscribe to more DOM nodes or models here
};

APP_BoxView.prototype.destroy = function() {

    // Programmer doesn't need to remember anything. Purge all subscriptions
    // to DOM nodes, model objects, or anything else implementing
    // the EventTarget interface in one fell swoop.
    //
    evento.purgeEventListener(this);
};

*/

(function() {

    function createBundle(element, type, listener, /*optional*/ auxArg) {
        var bundle = {
            element: element,
            type: type,
            listener: listener
        };
        if (arguments.length > 3) {
            bundle.auxArg = auxArg;
        }
        if (typeof listener === 'function') {
            var thisObj = arguments.length > 3 ? auxArg : element;
            bundle.wrappedHandler = function(evt) {
                listener.call(thisObj, evt);
            };
        }
        else if (typeof auxArg === 'function') {
            bundle.wrappedHandler = function(evt) {
                auxArg.call(listener, evt);
            };
        }
        else {
            var methodName = arguments.length > 3 ? auxArg : 'handleEvent';
            bundle.wrappedHandler = function(evt) {
                listener[methodName](evt);
            };
        }
        return bundle;
    }

    function bundlesAreEqual(a, b) {
        return (a.element === b.element) &&
               (a.type === b.type) &&
               (a.listener === b.listener) &&
               ((!a.hasOwnProperty('auxArg') &&
                 !b.hasOwnProperty('auxArg')) ||
                (a.hasOwnProperty('auxArg') &&
                 b.hasOwnProperty('auxArg') &&
                 (a.auxArg === b.auxArg)));
    }

    function indexOfBundle(bundles, bundle) {
        for (var i = 0, ilen = bundles.length; i < ilen; i++) {
            if (bundlesAreEqual(bundles[i], bundle)) {
                return i;
            }
        }
        return -1;
    }

    evento.addEventListener = function(element, type, listener, /*optional*/ auxArg) {
        // Want to call createBundle with the same number of arguments
        // that were passed to this function. Using apply preserves
        // the number of arguments.
        var bundle = createBundle.apply(null, arguments);
        if (listener._evento_bundles) {
            if (indexOfBundle(listener._evento_bundles, bundle) >= 0) {
                // do not add the same listener twice
                return;
            }
        }
        else {
            listener._evento_bundles = [];
        }
        if (typeof bundle.element.addEventListener === 'function') {
            bundle.element.addEventListener(bundle.type, bundle.wrappedHandler, false);
        }
        else if ((typeof bundle.element.attachEvent === 'object') &&
                 (bundle.element.attachEvent !== null)) {
            bundle.element.attachEvent('on'+bundle.type, bundle.wrappedHandler);
        }
        else {
            throw new Error('evento.addEventListener: Supported EventTarget interface not found.');
        }
        listener._evento_bundles.push(bundle);
    };

    var remove = evento.removeEventListener = function(element, type, listener, /*optional*/ auxArg) {
        if (listener._evento_bundles) {
            var i = indexOfBundle(listener._evento_bundles, createBundle.apply(null, arguments));
            if (i >= 0) {
                var bundle = listener._evento_bundles[i];
                if (typeof bundle.element.removeEventListener === 'function') {
                    bundle.element.removeEventListener(bundle.type, bundle.wrappedHandler, false);
                }
                else if ((typeof bundle.element.detachEvent === 'object') &&
                         (bundle.element.detachEvent !== null)) {
                    bundle.element.detachEvent('on'+bundle.type, bundle.wrappedHandler);
                }
                else {
                    throw new Error('evento.removeEventListener: Supported EventTarget interface not found.');
                }
                listener._evento_bundles.splice(i, 1);
            }
        }
    };

    evento.purgeEventListener = function(listener) {
        if (listener._evento_bundles) {
            var bundles = listener._evento_bundles.slice(0);
            for (var i = 0, ilen = bundles.length; i < ilen; i++) {
                var bundle = bundles[i];
                if (bundle.hasOwnProperty('auxArg')) {
                    remove(bundle.element, bundle.type, bundle.listener, bundle.auxArg);
                }
                else {
                    remove(bundle.element, bundle.type, bundle.listener);
                }
            }
        }
    };

}());
<|endoftext|>


<commit_before>function flacso_adv_search_click()
{
	jQuery('.icon-spin6.animate-spin.icon--large').removeClass('hidden');
	var checkValues = jQuery("input[name*='adv-search-box-']:checked").map(function()
    {
        return {name: jQuery(this).attr("name").replace("adv-search-box-","").replace("[]", ""), value:jQuery(this).val()};
    }).get();

	var texts = jQuery("input[name*='adv-search-box-input-']").map(function()
    {
		return { name:jQuery(this).attr("name").replace("adv-search-box-input-",""), value:jQuery(this).val()};
    }).get();

	jQuery.ajax({
		type   : 'post',
		url    : 'http://' + window.location.host + '/wp-admin/admin-ajax.php',
		data   : {
			action: 'flacso_adv_search',
			checked: checkValues,
			fields: texts,
			paged: jQuery('input[name="adv-search-paged"]').val()
		},
		success: function(response) {
			jQuery("html, body").animate({ scrollTop: jQuery('#main').first().offset().top }, "slow");
			jQuery('.general-list').replaceWith(response);
			flacso_adv_search_result();
			jQuery('.icon-spin6.animate-spin.icon--large').addClass('hidden')
		}
	});

}

function flacso_adv_search_result()
{
	var checkValues = jQuery("input[name*='adv-search-box-']:checked").map(function()
    {
        return {
        	name:  jQuery(this).attr("name").replace("adv-search-box-","").replace("[]", ""),
        	value: jQuery(this).val(),
        	title: jQuery(this).parent().text().trim(),
        	tax_label: jQuery(this).parent().parent().parent().parent().parent().parent().find('.dropdown-checkbox-header-label').text()
        };
    }).get();

	var texts = jQuery("input[name*='adv-search-box-input-']").map(function()
	{
		if(jQuery(this).val().length > 0)
		{
			return {
				name:jQuery(this).attr("name").replace("adv-search-box-input-",""),
				value:jQuery(this).val(),
				label: jQuery(this).parent().find('label').text()
			};
		}
	}).get();

	/*

Biblioteca
					*/

	var html = '
Busca por:
';

	for (i = 0; i < checkValues.length; i++)
	{
		html+="
" + checkValues[i].tax_label + ": "+ checkValues[i].title + "
";
	}
	for (i = 0; i < texts.length; i++)
	{
		html+="
" + texts[i].label + ": "+ texts[i].value + "
";
	}
	html+="";

	jQuery('main article header').first().replaceWith(html);
	jQuery('main article .entry-content').hide();

}

jQuery(document).ready(function () {
	var w = jQuery('.clickable').width();
	jQuery('.mutliSelect ul').width(w);

	jQuery('.adv-search-box-button').click(function(){
		flacso_adv_search_click();
	});
	jQuery('.adv-search-box-custom-field input').bind("enterKey",function(e){
		flacso_adv_search_click();
	});
	jQuery('.adv-search-box-custom-field input').keyup(function(e){
	    if(e.keyCode == 13)
	    {
	        jQuery(this).trigger("enterKey");
	    }
	});
});

function flacso_tax_click(name, id)
{
	var checkValues = [{name:name, value:id}];

	jQuery("input[name='adv-search-box-"+name+"[]'][value="+id+"]").attr("checked", "checked");
	dropdownCheckboxMark();

	if(adv_search_box.gea != '')
	{
		checkValues[1] = {name:'gea', value:adv_search_box.gea}
	}

	if(adv_search_box.library != 1)
	{
		window.location.href = adv_search_box.library_url + "&"+name+"="+id;
		return false;
	}

	var texts = [];

	jQuery.ajax({
		type   : 'post',
		url    : 'http://' + window.location.host + '/wp-admin/admin-ajax.php',
		data   : {
			action: 'flacso_adv_search',
			checked: checkValues,
			fields: texts
		},
		success: function(response) {
			jQuery("html, body").animate({ scrollTop: 0 }, "slow");
			jQuery('.general-list').replaceWith(response);
			flacso_adv_search_result();
		}
	});
}

function flacso_adv_searchget_pagenum(num)
{
	jQuery('input[name="adv-search-paged"]').val(num);
	flacso_adv_search_click();
}<commit_msg>show loading icon before ajax, for #119<commit_after>function flacso_adv_search_click()
{
	jQuery('.icon-spin6.animate-spin.icon--large').removeClass('hidden');
	jQuery("html, body").animate({ scrollTop: jQuery('#main').first().offset().top }, "slow");
	var checkValues = jQuery("input[name*='adv-search-box-']:checked").map(function()
    {
        return {name: jQuery(this).attr("name").replace("adv-search-box-","").replace("[]", ""), value:jQuery(this).val()};
    }).get();

	var texts = jQuery("input[name*='adv-search-box-input-']").map(function()
    {
		return { name:jQuery(this).attr("name").replace("adv-search-box-input-",""), value:jQuery(this).val()};
    }).get();

	jQuery.ajax({
		type   : 'post',
		url    : 'http://' + window.location.host + '/wp-admin/admin-ajax.php',
		data   : {
			action: 'flacso_adv_search',
			checked: checkValues,
			fields: texts,
			paged: jQuery('input[name="adv-search-paged"]').val()
		},
		success: function(response) {
			jQuery('.general-list').replaceWith(response);
			flacso_adv_search_result();
		}
	});

}

function flacso_adv_search_result()
{
	var checkValues = jQuery("input[name*='adv-search-box-']:checked").map(function()
    {
        return {
        	name:  jQuery(this).attr("name").replace("adv-search-box-","").replace("[]", ""),
        	value: jQuery(this).val(),
        	title: jQuery(this).parent().text().trim(),
        	tax_label: jQuery(this).parent().parent().parent().parent().parent().parent().find('.dropdown-checkbox-header-label').text()
        };
    }).get();

	var texts = jQuery("input[name*='adv-search-box-input-']").map(function()
	{
		if(jQuery(this).val().length > 0)
		{
			return {
				name:jQuery(this).attr("name").replace("adv-search-box-input-",""),
				value:jQuery(this).val(),
				label: jQuery(this).parent().find('label').text()
			};
		}
	}).get();

	/*

Biblioteca
					*/

	var html = '
Busca por:
';

	for (i = 0; i < checkValues.length; i++)
	{
		html+="
" + checkValues[i].tax_label + ": "+ checkValues[i].title + "
";
	}
	for (i = 0; i < texts.length; i++)
	{
		html+="
" + texts[i].label + ": "+ texts[i].value + "
";
	}
	html+="";

	jQuery('main article header').first().replaceWith(html);
	jQuery('main article .entry-content').hide();
	jQuery('.icon-spin6.animate-spin.icon--large').addClass('hidden')

}

jQuery(document).ready(function () {
	var w = jQuery('.clickable').width();
	jQuery('.mutliSelect ul').width(w);

	jQuery('.adv-search-box-button').click(function(){
		flacso_adv_search_click();
	});
	jQuery('.adv-search-box-custom-field input').bind("enterKey",function(e){
		flacso_adv_search_click();
	});
	jQuery('.adv-search-box-custom-field input').keyup(function(e){
	    if(e.keyCode == 13)
	    {
	        jQuery(this).trigger("enterKey");
	    }
	});
});

function flacso_tax_click(name, id)
{
	jQuery('.icon-spin6.animate-spin.icon--large').removeClass('hidden');
	jQuery("html, body").animate({ scrollTop: jQuery('#main').first().offset().top }, "slow");

	var checkValues = [{name:name, value:id}];

	jQuery("input[name='adv-search-box-"+name+"[]'][value="+id+"]").attr("checked", "checked");
	dropdownCheckboxMark();

	if(adv_search_box.gea != '')
	{
		checkValues[1] = {name:'gea', value:adv_search_box.gea}
	}

	if(adv_search_box.library != 1)
	{
		window.location.href = adv_search_box.library_url + "&"+name+"="+id;
		return false;
	}

	var texts = [];

	jQuery.ajax({
		type   : 'post',
		url    : 'http://' + window.location.host + '/wp-admin/admin-ajax.php',
		data   : {
			action: 'flacso_adv_search',
			checked: checkValues,
			fields: texts
		},
		success: function(response) {
			jQuery("html, body").animate({ scrollTop: 0 }, "slow");
			jQuery('.general-list').replaceWith(response);
			flacso_adv_search_result();
		}
	});
}

function flacso_adv_searchget_pagenum(num)
{
	jQuery('input[name="adv-search-paged"]').val(num);
	flacso_adv_search_click();
}<|endoftext|>


<commit_before><commit_msg>refactor: global mocks warning<commit_after><|endoftext|>


<commit_before>function mockApiAccountCall() {
    inject(function($httpBackend) {
        $httpBackend.whenGET(/api\/account.*/).respond({});
    });
}

function mockI18nCalls() {
    inject(function($httpBackend) {
        $httpBackend.whenGET(/i18n\/en\/.+\.json/).respond({});
    });
}
<commit_msg>#74 set german as default language<commit_after>function mockApiAccountCall() {
    inject(function($httpBackend) {
        $httpBackend.whenGET(/api\/account.*/).respond({});
    });
}

function mockI18nCalls() {
    inject(function($httpBackend) {
        $httpBackend.whenGET(/i18n\/de\/.+\.json/).respond({});
    });
}
<|endoftext|>


<commit_before>var usage = function () {
  return 'usage: bolt build [-c|--config CONFIG_JS] [-o|--output OUTPUT_DIR] [-s|--src-dir SRC_DIR]\n' +
         '                  [-i|--inline] [-n|--invoke-main MAIN_MODULE] [-r|--register]\n' +
         '                  [-m|--modules] [-e|--entry-points FILE ...] [-g|--entry-group NAME FILE ...]\n' +
         '\n' +
         'options:\n' +
         '  -c|--config CONFIG_JS         override bolt configuration file\n' +
         '                                   default: config/bolt/prod.js\n' +
         '  -o|--output OUTPUT_DIR         override output directory, note this is different\n' +
         '                                 to the jsc compile directory, the compiled output,\n' +
         '                                 will be located at $OUTPUT_DIR/compile\n' +
         '                                   default: scratch/main/js\n' +
         '  -s|--src-dir SRC_DIR           override source directory\n' +
         '                                   default: src/main/js\n' +
         '  -i|--inline                    enable generation of inline scripts (only produces output\n' +
         '                                 in conjunction with -e or -g).\n' +
         '  -n|--invoke-main MAIN_MODULE   specify main module of inline scripts.\n' +
         '  -r|--register                  register modules in global namespace for inline scripts,\n' +
         '                                 this will default to true unless -n is specified.\n' +
         '  -m|--modules                   enable generation of flat module files.\n' +
         '  -e|--entry-points FILE ...     specify a set of entry points, a compiled output\n' +
         '                                 will be generated for each entry point. Multiple\n' +
         '                                 -e flags may be specified.\n' +
         '  -g|--entry-group NAME FILE ... specify an entry group, a single compiled output\n' +
         '                                 will be generated with NAME for each entry-group.\n' +
         '                                 Multiple -g flags may be specified.\n' +
         '\n' +
         'example:\n' +
         '  Produce a bolt build for a top level application. A compiled file will be\n' +
         '  generated for each Main module in this example.\n' +
         '\n' +
         '    bolt build -e src/main/js/**/*Main.js\n' +
         '\n' +
         '\n' +
         '  Produce a bolt build for a top level library. A self contained script registering\n' +
         '  all modules in their namespace will be produced.\n' +
         '\n' +
         '    bolt build -i -g example src/main/js/**/api/*.js\n' +
         '\n' +
         '\n' +
         '  Produce a bolt build for a general purpose library, in this build we only want\n' +
         '  modules to be produced, no compiled output.\n' +
         '\n' +
         '    bolt build -m src/main/js\n' +
         '\n' +
         '\n' +
         'note:\n' +
         '  Examples assume use of a shell with "**" glob support. This means either zsh or\n' +
         '  bash 4.x with `shopt -s globstar` set. If you are an insolent mac user with a\n' +
         '  default bash 3.x, this tool strongly recommends you upgrade (although defenestration\n' +
         '  of said mac is also a valid option).\n' +
         '\n' +
         '  If you become desperate something like $(find src/test/js/atomic -name \*.js) could be\n' +
         '  used as a substitute.\n';
}

var fail_usage = function (code, message) {
  console.error(message);
  console.error('');
  console.error(usage());
  process.exit(code);
};

var fail = function (code, message) {
  console.error(message);
  process.exit(code);
};

module.exports = function (help_mode) {
  if (help_mode) {
    console.log(usage());
    process.exit();
  }

  var config_js = 'config/bolt/prod.js';
  var output_dir = 'scratch/main/js';
  var src_dir = 'src/main/js';
  var generate_inline = false;
  var generate_modules = false;
  var register_modules = false;
  var main = undefined;
  var entry_points = [];
  var entry_groups = {};

  var path = require('path');
  var fs = require('fs');

  while (process.argv.length > 0 && process.argv[0][0] === '-') {
    var flag = process.argv[0];
    process.argv.shift();

    switch (flag) {
      case '-c':
      case '--config':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
        config_js = process.argv[0];
        process.argv.shift();
        break;
      case '-o':
      case '--output':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
        output_dir = process.argv[0];
        process.argv.shift();
        break;
      case '-s':
      case '--src-dir':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
        src_dir = process.argv[0];
        process.argv.shift();
        break;
      case '-n':
      case '--invoke-main':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
      main = process.argv[0];
      process.argv.shift();
        break;
      case '-r':
      case '--register':
        register_modules = true;
        break;
      case '-i':
      case '--inline':
        generate_inline = true;
        break;
      case '-m':
      case '--modules':
        generate_modules = true;
        break;
      case '-e':
      case '--entry-points':
        while (process.argv.length > 0 && process.argv[0][0] !== '-') {
          var entry = process.argv[0];
          process.argv.shift();
          if (!fs.existsSync(entry) || !fs.statSync(entry).isFile())
            fail(1, 'specified file for entry point not found [' + entry + ']');
          entry_points.push(entry);
        }
        break;
      case '-g':
      case '--entry-group':
        if (process.argv.length < 2)
          fail_usage(1, flag + ' requires two arguments to be specified');
        var name = process.argv[0];
        process.argv.shift();
        if (name.indexOf('/') !== -1)
          fail(1, 'entry group name must not contain special characters');
        entry_groups[name] = [];

        while (process.argv.length > 0 && process.argv[0][0] !== '-') {
          var file = process.argv[0];
          process.argv.shift();
          if (!fs.existsSync(file) || !fs.statSync(file).isFile())
            fail(1, 'specified file for entry group not found [' + file + ']');
          entry_groups[name].push(file);
        }
        break;
      case '--':
        break;
      default:
        fail_usage(1, 'invalid flag [' + flag +']');
    }
  }

  // nodejs doesn't have an mkdir -p equivalent
  var mkdirp = function (dir) {
    dir = path.resolve(dir);
    if (!fs.existsSync(dir)) {
      mkdirp(path.dirname(dir));
      fs.mkdirSync(dir);
    }
  };

  // walk a directory tree
  var walk = function (root, processor) {
    var files = fs.readdirSync(root);
    files.forEach(function (file) {
      var filepath = path.join(root, file);
      fs.statSync(filepath).isDirectory() ?
        walk(filepath, processor) : processor(filepath);
    });
  };

  require('./kernel');
  require('./loader');
  require('./module');
  require('./compiler');

  var targets = [];

  var bolt_build_inline = function (file, name) {
    mkdirp(path.join(output_dir, 'inline'));
    var target = path.join(output_dir, 'inline', name + '.js');
    ephox.bolt.compiler.mode.inline.run(config_js, [ file ], target, register_modules, main);
  };

  var bolt_build_entry_point = function (done) {
    mkdirp(path.join(output_dir, 'compile'));

    var process = function (file) {
      var id = ephox.bolt.compiler.mode.identify.run(file);
      var target = path.join(output_dir, 'compile', id + '.js');
      targets.push(target);  // So that things can be linked together later

      ephox.bolt.compiler.mode.compile.run(config_js, [ file ], target, function () {
        if (generate_inline)
          bolt_build_inline(target, id);
        next();
      });
    };

    var next = function () {
      entry_points.length > 0 ? process(entry_points.shift()) : done();
    };

    next();
  };

  var bolt_build_entry_group = function (done) {
    mkdirp(path.join(output_dir, 'compile'));

    var groups = Object.keys(entry_groups);

    var process = function (group) {
      var target = path.join(output_dir, 'compile', group + '.js');
      targets.push(target);  // So that things can be linked together later

      ephox.bolt.compiler.mode.compile.run(config_js, entry_groups[group], target, function () {
        if (generate_inline)
          bolt_build_inline(target, group);
        next();
      });
    };

    var next = function () {
      groups.length > 0 ? process(groups.shift()) : done();
    };

    next();
  };

  var bolt_link = function () {
    var link_output = path.join(output_dir, 'compile/bootstrap.js');
    ephox.bolt.compiler.mode.link.run(config_js, targets, link_output);
  };

  var bolt_modules = function () {
    if (!fs.existsSync(src_dir) || !fs.statSync(src_dir).isDirectory())
      fail(1, config_js + ' does not exist or is not a directory');

    if (generate_modules) {
      var module_dir = path.join(output_dir, 'module');
      mkdirp(module_dir);
      walk(src_dir, function (file) {
        var name = ephox.bolt.compiler.mode.identify.run(file);
        fs.writeFileSync(path.join(module_dir, name + '.js'), fs.readFileSync(file));
      });
    }
  };

  if (!fs.existsSync(config_js) || !fs.statSync(config_js).isFile())
    fail(1, config_js + ' does not exist or is not a file');

  bolt_build_entry_point(function () {
    bolt_build_entry_group(function () {
      if (targets.length > 0)
        bolt_link();

      if (generate_modules)
        bolt_modules();
    });
  });
};
<commit_msg>Fix -o|--output flag help text so that it makes sense.<commit_after>var usage = function () {
  return 'usage: bolt build [-c|--config CONFIG_JS] [-o|--output OUTPUT_DIR] [-s|--src-dir SRC_DIR]\n' +
         '                  [-i|--inline] [-n|--invoke-main MAIN_MODULE] [-r|--register]\n' +
         '                  [-m|--modules] [-e|--entry-points FILE ...] [-g|--entry-group NAME FILE ...]\n' +
         '\n' +
         'options:\n' +
         '  -c|--config CONFIG_JS          override bolt configuration file\n' +
         '                                   default: config/bolt/prod.js\n' +
         '  -o|--output OUTPUT_DIR         override output directory, compiled output will be\n' +
         '                                 located at $OUTPUT_DIR/compile, inline output at\n' +
         '                                 $OUTPUT_DIR/inline, modules at $OUTPUT_DIR/module'
         '                                   default: scratch/main/js\n' +
         '  -s|--src-dir SRC_DIR           override source directory\n' +
         '                                   default: src/main/js\n' +
         '  -i|--inline                    enable generation of inline scripts (only produces output\n' +
         '                                 in conjunction with -e or -g).\n' +
         '  -n|--invoke-main MAIN_MODULE   specify main module of inline scripts.\n' +
         '  -r|--register                  register modules in global namespace for inline scripts,\n' +
         '                                 this will default to true unless -n is specified.\n' +
         '  -m|--modules                   enable generation of flat module files.\n' +
         '  -e|--entry-points FILE ...     specify a set of entry points, a compiled output\n' +
         '                                 will be generated for each entry point. Multiple\n' +
         '                                 -e flags may be specified.\n' +
         '  -g|--entry-group NAME FILE ... specify an entry group, a single compiled output\n' +
         '                                 will be generated with NAME for each entry-group.\n' +
         '                                 Multiple -g flags may be specified.\n' +
         '\n' +
         'example:\n' +
         '  Produce a bolt build for a top level application. A compiled file will be\n' +
         '  generated for each Main module in this example.\n' +
         '\n' +
         '    bolt build -e src/main/js/**/*Main.js\n' +
         '\n' +
         '\n' +
         '  Produce a bolt build for a top level library. A self contained script registering\n' +
         '  all modules in their namespace will be produced.\n' +
         '\n' +
         '    bolt build -i -g example src/main/js/**/api/*.js\n' +
         '\n' +
         '\n' +
         '  Produce a bolt build for a general purpose library, in this build we only want\n' +
         '  modules to be produced, no compiled output.\n' +
         '\n' +
         '    bolt build -m src/main/js\n' +
         '\n' +
         '\n' +
         'note:\n' +
         '  Examples assume use of a shell with "**" glob support. This means either zsh or\n' +
         '  bash 4.x with `shopt -s globstar` set. If you are an insolent mac user with a\n' +
         '  default bash 3.x, this tool strongly recommends you upgrade (although defenestration\n' +
         '  of said mac is also a valid option).\n' +
         '\n' +
         '  If you become desperate something like $(find src/test/js/atomic -name \*.js) could be\n' +
         '  used as a substitute.\n';
}

var fail_usage = function (code, message) {
  console.error(message);
  console.error('');
  console.error(usage());
  process.exit(code);
};

var fail = function (code, message) {
  console.error(message);
  process.exit(code);
};

module.exports = function (help_mode) {
  if (help_mode) {
    console.log(usage());
    process.exit();
  }

  var config_js = 'config/bolt/prod.js';
  var output_dir = 'scratch/main/js';
  var src_dir = 'src/main/js';
  var generate_inline = false;
  var generate_modules = false;
  var register_modules = false;
  var main = undefined;
  var entry_points = [];
  var entry_groups = {};

  var path = require('path');
  var fs = require('fs');

  while (process.argv.length > 0 && process.argv[0][0] === '-') {
    var flag = process.argv[0];
    process.argv.shift();

    switch (flag) {
      case '-c':
      case '--config':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
        config_js = process.argv[0];
        process.argv.shift();
        break;
      case '-o':
      case '--output':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
        output_dir = process.argv[0];
        process.argv.shift();
        break;
      case '-s':
      case '--src-dir':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
        src_dir = process.argv[0];
        process.argv.shift();
        break;
      case '-n':
      case '--invoke-main':
        if (process.argv.length < 1)
          fail_usage(1, flag + ' requires an argument to be specified');
      main = process.argv[0];
      process.argv.shift();
        break;
      case '-r':
      case '--register':
        register_modules = true;
        break;
      case '-i':
      case '--inline':
        generate_inline = true;
        break;
      case '-m':
      case '--modules':
        generate_modules = true;
        break;
      case '-e':
      case '--entry-points':
        while (process.argv.length > 0 && process.argv[0][0] !== '-') {
          var entry = process.argv[0];
          process.argv.shift();
          if (!fs.existsSync(entry) || !fs.statSync(entry).isFile())
            fail(1, 'specified file for entry point not found [' + entry + ']');
          entry_points.push(entry);
        }
        break;
      case '-g':
      case '--entry-group':
        if (process.argv.length < 2)
          fail_usage(1, flag + ' requires two arguments to be specified');
        var name = process.argv[0];
        process.argv.shift();
        if (name.indexOf('/') !== -1)
          fail(1, 'entry group name must not contain special characters');
        entry_groups[name] = [];

        while (process.argv.length > 0 && process.argv[0][0] !== '-') {
          var file = process.argv[0];
          process.argv.shift();
          if (!fs.existsSync(file) || !fs.statSync(file).isFile())
            fail(1, 'specified file for entry group not found [' + file + ']');
          entry_groups[name].push(file);
        }
        break;
      case '--':
        break;
      default:
        fail_usage(1, 'invalid flag [' + flag +']');
    }
  }

  // nodejs doesn't have an mkdir -p equivalent
  var mkdirp = function (dir) {
    dir = path.resolve(dir);
    if (!fs.existsSync(dir)) {
      mkdirp(path.dirname(dir));
      fs.mkdirSync(dir);
    }
  };

  // walk a directory tree
  var walk = function (root, processor) {
    var files = fs.readdirSync(root);
    files.forEach(function (file) {
      var filepath = path.join(root, file);
      fs.statSync(filepath).isDirectory() ?
        walk(filepath, processor) : processor(filepath);
    });
  };

  require('./kernel');
  require('./loader');
  require('./module');
  require('./compiler');

  var targets = [];

  var bolt_build_inline = function (file, name) {
    mkdirp(path.join(output_dir, 'inline'));
    var target = path.join(output_dir, 'inline', name + '.js');
    ephox.bolt.compiler.mode.inline.run(config_js, [ file ], target, register_modules, main);
  };

  var bolt_build_entry_point = function (done) {
    mkdirp(path.join(output_dir, 'compile'));

    var process = function (file) {
      var id = ephox.bolt.compiler.mode.identify.run(file);
      var target = path.join(output_dir, 'compile', id + '.js');
      targets.push(target);  // So that things can be linked together later

      ephox.bolt.compiler.mode.compile.run(config_js, [ file ], target, function () {
        if (generate_inline)
          bolt_build_inline(target, id);
        next();
      });
    };

    var next = function () {
      entry_points.length > 0 ? process(entry_points.shift()) : done();
    };

    next();
  };

  var bolt_build_entry_group = function (done) {
    mkdirp(path.join(output_dir, 'compile'));

    var groups = Object.keys(entry_groups);

    var process = function (group) {
      var target = path.join(output_dir, 'compile', group + '.js');
      targets.push(target);  // So that things can be linked together later

      ephox.bolt.compiler.mode.compile.run(config_js, entry_groups[group], target, function () {
        if (generate_inline)
          bolt_build_inline(target, group);
        next();
      });
    };

    var next = function () {
      groups.length > 0 ? process(groups.shift()) : done();
    };

    next();
  };

  var bolt_link = function () {
    var link_output = path.join(output_dir, 'compile/bootstrap.js');
    ephox.bolt.compiler.mode.link.run(config_js, targets, link_output);
  };

  var bolt_modules = function () {
    if (!fs.existsSync(src_dir) || !fs.statSync(src_dir).isDirectory())
      fail(1, config_js + ' does not exist or is not a directory');

    if (generate_modules) {
      var module_dir = path.join(output_dir, 'module');
      mkdirp(module_dir);
      walk(src_dir, function (file) {
        var name = ephox.bolt.compiler.mode.identify.run(file);
        fs.writeFileSync(path.join(module_dir, name + '.js'), fs.readFileSync(file));
      });
    }
  };

  if (!fs.existsSync(config_js) || !fs.statSync(config_js).isFile())
    fail(1, config_js + ' does not exist or is not a file');

  bolt_build_entry_point(function () {
    bolt_build_entry_group(function () {
      if (targets.length > 0)
        bolt_link();

      if (generate_modules)
        bolt_modules();
    });
  });
};
<|endoftext|>


<commit_before>'use strict'

const co = require('co')
const cli = require('heroku-cli-util')
const {flags} = require('cli-engine-heroku')
const {SpaceCompletion} = require('cli-engine-heroku/lib/completions')

function * run (context, heroku) {
  const sortBy = require('lodash.sortby')
  const partition = require('lodash.partition')

  let team = context.org || context.team || context.flags.team
  let org = (!context.flags.personal && team) ? team : null
  let space = context.flags.space
  if (space) org = (yield heroku.get(`/spaces/${space}`)).organization.name

  function regionizeAppName (app) {
    let name = app.locked ? `${app.name} [locked]` : app.name
    if (app.region && app.region.name !== 'us') {
      return `${name} (${cli.color.green(app.region.name)})`
    } else {
      return name
    }
  }

  function listApps (apps) {
    apps.forEach((app) => cli.log(regionizeAppName(app)))
    cli.log()
  }

  function print (apps, user) {
    if (apps.length === 0) {
      if (space) cli.log(`There are no apps in space ${cli.color.green(space)}.`)
      else if (org) cli.log(`There are no apps in team ${cli.color.magenta(org)}.`)
      else cli.log('You have no apps.')
    } else if (space) {
      cli.styledHeader(`Apps in space ${cli.color.green(space)}`)
      listApps(apps)
    } else if (org) {
      cli.styledHeader(`Apps in team ${cli.color.magenta(org)}`)
      listApps(apps)
    } else {
      apps = partition(apps, (app) => app.owner.email === user.email)
      if (apps[0].length > 0) {
        cli.styledHeader(`${cli.color.cyan(user.email)} Apps`)
        listApps(apps[0])
      }

      if (apps[1].length > 0) {
        cli.styledHeader('Collaborated Apps')
        cli.table(apps[1], {
          printHeader: false,
          columns: [
            {key: 'name', get: regionizeAppName},
            {key: 'owner.email'}
          ]
        })
      }
    }
  }

  let path = '/users/~/apps'
  if (org) path = `/organizations/${org}/apps`
  else if (context.flags.all) path = '/apps'
  let [apps, user] = yield [
    heroku.get(path),
    heroku.get('/account')
  ]
  apps = sortBy(apps, 'name')
  if (space) {
    apps = apps.filter(a => a.space && (a.space.name === space || a.space.id === space))
  }

  if (context.flags.json) {
    cli.styledJSON(apps)
  } else {
    print(apps, user)
  }
}

let cmd = {
  description: 'list your apps',
  help: `
Example:

    $ heroku apps
    === My Apps
    example
    example2

    === Collaborated Apps
    theirapp   other@owner.name`,
  needsAuth: true,
  wantsOrg: true,
  flags: [
    {name: 'all', char: 'A', description: 'include apps in all teams'},
    {name: 'json', description: 'output in json format'},
    {name: 'space', char: 's', hasValue: true, description: 'filter by space', completion: SpaceCompletion},
    {name: 'personal', char: 'p', description: 'list apps in personal account when a default team is set'},
    // flags.org({name: 'org', hasValue: true}),
    flags.team({name: 'team', hasValue: true})
  ],
  run: cli.command(co.wrap(run))
}

module.exports = [
  Object.assign({topic: 'apps'}, cmd),
  Object.assign({topic: 'list', hidden: true}, cmd),
  Object.assign({topic: 'apps', command: 'list', hidden: true}, cmd)
]
<commit_msg>fix: fixed example syntax<commit_after>'use strict'

const co = require('co')
const cli = require('heroku-cli-util')
const {flags} = require('cli-engine-heroku')
const {SpaceCompletion} = require('cli-engine-heroku/lib/completions')

function * run (context, heroku) {
  const sortBy = require('lodash.sortby')
  const partition = require('lodash.partition')

  let team = context.org || context.team || context.flags.team
  let org = (!context.flags.personal && team) ? team : null
  let space = context.flags.space
  if (space) org = (yield heroku.get(`/spaces/${space}`)).organization.name

  function regionizeAppName (app) {
    let name = app.locked ? `${app.name} [locked]` : app.name
    if (app.region && app.region.name !== 'us') {
      return `${name} (${cli.color.green(app.region.name)})`
    } else {
      return name
    }
  }

  function listApps (apps) {
    apps.forEach((app) => cli.log(regionizeAppName(app)))
    cli.log()
  }

  function print (apps, user) {
    if (apps.length === 0) {
      if (space) cli.log(`There are no apps in space ${cli.color.green(space)}.`)
      else if (org) cli.log(`There are no apps in team ${cli.color.magenta(org)}.`)
      else cli.log('You have no apps.')
    } else if (space) {
      cli.styledHeader(`Apps in space ${cli.color.green(space)}`)
      listApps(apps)
    } else if (org) {
      cli.styledHeader(`Apps in team ${cli.color.magenta(org)}`)
      listApps(apps)
    } else {
      apps = partition(apps, (app) => app.owner.email === user.email)
      if (apps[0].length > 0) {
        cli.styledHeader(`${cli.color.cyan(user.email)} Apps`)
        listApps(apps[0])
      }

      if (apps[1].length > 0) {
        cli.styledHeader('Collaborated Apps')
        cli.table(apps[1], {
          printHeader: false,
          columns: [
            {key: 'name', get: regionizeAppName},
            {key: 'owner.email'}
          ]
        })
      }
    }
  }

  let path = '/users/~/apps'
  if (org) path = `/organizations/${org}/apps`
  else if (context.flags.all) path = '/apps'
  let [apps, user] = yield [
    heroku.get(path),
    heroku.get('/account')
  ]
  apps = sortBy(apps, 'name')
  if (space) {
    apps = apps.filter(a => a.space && (a.space.name === space || a.space.id === space))
  }

  if (context.flags.json) {
    cli.styledJSON(apps)
  } else {
    print(apps, user)
  }
}

let cmd = {
  description: 'list your apps',
  examples: `$ heroku apps
=== My Apps
example
example2

=== Collaborated Apps
theirapp   other@owner.name`,
  needsAuth: true,
  wantsOrg: true,
  flags: [
    {name: 'all', char: 'A', description: 'include apps in all teams'},
    {name: 'json', description: 'output in json format'},
    {name: 'space', char: 's', hasValue: true, description: 'filter by space', completion: SpaceCompletion},
    {name: 'personal', char: 'p', description: 'list apps in personal account when a default team is set'},
    // flags.org({name: 'org', hasValue: true}),
    flags.team({name: 'team', hasValue: true})
  ],
  run: cli.command(co.wrap(run))
}

module.exports = [
  Object.assign({topic: 'apps'}, cmd),
  Object.assign({topic: 'list', hidden: true}, cmd),
  Object.assign({topic: 'apps', command: 'list', hidden: true}, cmd)
]
<|endoftext|>