<commit_before>/*
 * A mixin for views that provides key binding functionality.
 *
 * Views using this mixin can provide a keyBindings map that maps a set of
 * key characters to a function.
 */
RB.KeyBindingsMixin = {
    /*
     * Enables key bindings for the view.
     *
     * Begins listening for any key bindings registered in the view's
     * keyBindings map, and calls the appropriate function.
     *
     * By default, this is called automatically when setting up the view,
     * by way of delegateEvents.
     */
    delegateKeyBindings: function() {
        this.$el.on('keypress.keybindings' + this.cid, _.bind(function(evt) {
            var keyChar,
                keys,
                func,
                i;

            if (evt.altKey || evt.ctrlKey || evt.metaKey) {
                return;
            }

            keyChar = String.fromCharCode(evt.which);

            for (keys in this.keyBindings) {
                if (_.has(this.keyBindings, keys)
                    && keys.indexOf(keyChar) !== -1) {

                    evt.stopPropagation();
                    evt.preventDefault();

                    func = this.keyBindings[keys];

                    if (!_.isFunction(func)) {
                        func = this[func];
                    }

                    func.call(this, evt);
                    return;
                }
            }
        }, this));
    },

    /*
     * Disables key bindings for the view.
     *
     * By default, this is called automatically when calling undelegateEvents.
     */
    undelegateKeyBindings: function() {
        this.$el.off('keypress.keybindings' + this.cid);
    },

    /*
     * Delegates both DOM events and key binding events.
     *
     * This overrides the default Backbone.View.delegateEvents to automatically
     * call delegateKeyBindings.
     */
    delegateEvents: function(events) {
        this.delegateKeyBindings();

        return Backbone.View.prototype.delegateEvents.call(this, events);
    },

    /*
     * Undelegates both DOM events and key binding events.
     *
     * This overrides the default Backbone.View.undelegateEvents to
     * automatically call undelegateKeyBindings.
     */
    undelegateEvents: function() {
        this.undelegateKeyBindings();

        return Backbone.View.prototype.undelegateEvents.call(this);
    }
};
<commit_msg>Fix key bindings for the diff viewer.<commit_after>/*
 * A mixin for views that provides key binding functionality.
 *
 * Views using this mixin can provide a keyBindings map that maps a set of
 * key characters to a function.
 */
RB.KeyBindingsMixin = {
    /*
     * Enables key bindings for the view.
     *
     * Begins listening for any key bindings registered in the view's
     * keyBindings map, and calls the appropriate function.
     *
     * By default, this is called automatically when setting up the view,
     * by way of delegateEvents.
     */
    delegateKeyBindings: function() {
        $(document).on('keypress.keybindings' + this.cid, _.bind(function(evt) {
            var keyChar,
                keys,
                func,
                i;

            if (evt.altKey || evt.ctrlKey || evt.metaKey ||
                evt.target.tagName === 'INPUT' ||
                evt.target.tagName === 'TEXTAREA') {
                /* These are all unsupported, and things we want to ignore. */
                return;
            }

            keyChar = String.fromCharCode(evt.which);

            for (keys in this.keyBindings) {
                if (_.has(this.keyBindings, keys)
                    && keys.indexOf(keyChar) !== -1) {

                    evt.stopPropagation();
                    evt.preventDefault();

                    func = this.keyBindings[keys];

                    if (!_.isFunction(func)) {
                        func = this[func];
                    }

                    func.call(this, evt);
                    return;
                }
            }
        }, this));
    },

    /*
     * Disables key bindings for the view.
     *
     * By default, this is called automatically when calling undelegateEvents.
     */
    undelegateKeyBindings: function() {
        $(document).off('keypress.keybindings' + this.cid);
    },

    /*
     * Delegates both DOM events and key binding events.
     *
     * This overrides the default Backbone.View.delegateEvents to automatically
     * call delegateKeyBindings.
     */
    delegateEvents: function(events) {
        this.delegateKeyBindings();

        return Backbone.View.prototype.delegateEvents.call(this, events);
    },

    /*
     * Undelegates both DOM events and key binding events.
     *
     * This overrides the default Backbone.View.undelegateEvents to
     * automatically call undelegateKeyBindings.
     */
    undelegateEvents: function() {
        this.undelegateKeyBindings();

        return Backbone.View.prototype.undelegateEvents.call(this);
    }
};
<|endoftext|>


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

	angular.module('xpsui:services')
	.factory('xpsui:GeneratorsGenerator', [ '$http', 'xpsui:safeUrlEncoder',
		'xpsui:SchemaUtil','$q','xpsui:ObjectTools',
		function($http, urlEncoder,schemaUtilFactory,$q,objectTools) {
		var service = {};

		/** Counts porter(-berger) table
		 * @teams - array of objects that will be used to define match
		 * @terms - array of object that will be used to define round, its size limits result
		 * @returns - object in form
				[{ round:<index>,term:<round_term>,matches:[{home:teams[x1],visitors:teams[y1],board:<board_index>},...] },...]
		 */
		function bergerTable(teams,terms) {

			var floatTable = [];
			var n, i, increment=1, atype=1, minmove=0, flipcolors=0;

			if (teams.length%2===1) {
				teams.push({complement:true});
			}

			n = teams.length;

			var nr = n-1; // Number of rounds

			var n2 = n / 2;
			var x, j, temp, colorFlag, incr;

			var max_round = terms.length;

			var test_r = 0;
			var outRounds=[];

			var textPrefix = 'A-';
			var match_id = 0;

			for (var r=1; r<= max_round; r++) {	// r is the round number.

				var outRound={round:r,term:terms[r-1],matches:[]};
				outRounds.push(outRound);

				if(r == nr+1) {
					match_id=0;
					textPrefix = 'B-';
				}

				if(r == 1) {		 // Round 1 initially seat the players
					incr=n-3; j = 0;

					for (i = 1; i < n; i++) {
						floatTable[j]=i;
						j += incr;
						j = j % (n-1);
					}
					floatTable[nr]=n;	// Identifies the "ghost" player, will not move
				}else {			// Other rounds, rotate the players "clockwise"
					temp = floatTable[n-2];
					for (i=n-2;	i > 0 ; i--) {
						floatTable[i] = floatTable[i-1];
					}
					floatTable[0] = temp;
				}
				if (r == n) {
					flipcolors ^= 1; // Swap colors for 2nd half
					test_r = 1;
				}

				i=0; // i is the board number about to be displayed, changed at bottom of loop
				if (atype == '1')
					increment=2;

				while (1) {	 //Must get out of this loop with break

					match_id++;

					var matchPrefix=textPrefix+match_id;

					if (i === 0)	 //At ghost board, color determined by round number
						colorFlag = ((r-test_r)%2) ? 1 : 0;
					else			//On other boards, board number determines it
						colorFlag = (i % 2) ? 0 : 1;

					colorFlag ^= flipcolors; //Will reverse color assignment if checked

					var match={home:teams[floatTable[colorFlag?nr-i:i]-1].team ,visitors:teams[floatTable[colorFlag?i:nr-i]-1].team ,boar:i ,matchNumber:matchPrefix, homeClub:teams[floatTable[colorFlag?nr-i:i]-1].club ,visitorClub:teams[floatTable[colorFlag?i:nr-i]-1].club};

					if (i===0) {
						match={home:match.visitors,visitors:match.home,board:i, matchNumber:matchPrefix, homeClub:match.visitorClub, visitorClub:match.homeClub};
					}

					if (match.home.complement) {
						outRound.notPlaying=match.visitors;
					} else if (match.visitors.complement) {
						outRound.notPlaying=match.home;
					} else {
						outRound.matches.push(match);
					}

					if (minmove && (i===0) && (r % 2)===0)
						i = 1;
					else
						i+= increment;
					if (i >= n2)
						if (increment == 1)	//Board number option
							break;
						else	{	//Come back to display the boards we missed
							increment = -2;
							i = ((i > n2) ? i - 3 : --i) ;
						}
					if ((i < 1) && (increment == -2)) //Finished with NOT board number option, exit loop
						break;
				}
			}

			// console.log(outRounds);
			// console.log(JSON.stringify(outRounds));
			return outRounds;
		}

		function saveBerger(entity,callback) {

			var saveSchema= schemaUtilFactory.encodeUri('uri://registries/refereeReports#views/refereeReports/new');
			var saved=0;
			var all=[];

			entity.saving=true;

			entity.generated.map(function(round) {
				round.matches.map(function(match) {
					var toSave={};
					toSave.baseData={};
					toSave.baseData.competition={schema:'uri://registries/competitions#views/competitions/view',oid:entity.baseData.competition.oid};
					toSave.baseData.season={schema:'uri://registries/seasons#views/seasons/view',oid:entity.competitionData.baseData.season.oid};
					toSave.baseData.competitionPart={schema:'uri://registries/competitionPart#views/competitionPart/view',oid:entity.id};
					toSave.baseData.ageCategory={schema:'uri://registries/ageCategory#views/ageCategory/view',oid:entity.competitionData.baseData.ageCategory.oid};
					toSave.baseData.homeClubSec={schema:'uri://registries/organizations#views/club/view',oid:match.homeClub.oid};
					toSave.baseData.awayClubSec={schema:'uri://registries/organizations#views/club/view',oid:match.visitorClub.oid};
					toSave.baseData.homeClub={schema:'uri://registries/rosters#views/rosters/view',oid:match.home.oid};
					toSave.baseData.awayClub={schema:'uri://registries/rosters#views/rosters/view',oid:match.visitors.oid};
					toSave.baseData.matchRound={schema:'uri://registries/schedule#views/schedule/view',oid:round.term.id};
					toSave.baseData.matchDate=round.term.baseData.date;
					toSave.baseData.state='Otvorený';

					if (entity.baseData.prefix) {
						toSave.baseData.matchNumber=entity.baseData.prefix+match.matchNumber;
					};

					toSave.baseData.printTemplate=entity.baseData.printTemplate;

					all.push( $http({url: '/udao/saveBySchema/'+saveSchema, method: 'PUT',data: toSave}));
				});
			});
			$q.all(all).then(function() {
				callback(null);
			});
		}

		function generateBerger(entity,callback) {
			var searchSchema='uri://registries/schedule#views/schedule/search';
			$http({
				method : 'POST',
				url : '/search/' + schemaUtilFactory.encodeUri(searchSchema),
				data : {
					crits :[{
						f : 'baseData.competitionPart.oid',
						v : entity.id,
						op : 'eq'
					}],
					sorts: [ { f:'baseData.date', o: 'asc'}]
				}
			}).success(function(terms) {
				var teams=entity.listOfTeam.team;

				var n = teams.length;

				//get competition object
				var getSchemaCompetition = 'uri://registries/competitions#views/competitions/';
				$http({
					method : 'GET',
					url: '/udao/getBySchema/'+schemaUtilFactory.encodeUri(schemaUtilFactory.concatUri(getSchemaCompetition, 'view'))+'/'+ entity.baseData.competition.oid
				})
				.success(function(dataCom) {
					console.log(JSON.stringify(dataCom, null, 4));
					entity.competitionData = dataCom;

					//get roster object
					var getSchemaRoster = 'uri://registries/rosters#views/rosters/';
					var httpArray = [];

					for (var i = 0; i < n; i++) {
						httpArray.push(
							$http({
								method : 'GET',
								url: '/udao/getBySchema/'+schemaUtilFactory.encodeUri(schemaUtilFactory.concatUri(getSchemaRoster, 'view'))+'/'+ entity.listOfTeam.team[i].team.oid
							})
						);
					};

					$q.all(httpArray).then(function(listOfRoster) {
						if(!entity.rosters) {
							entity.rosters = {};
						}
						entity.rosters = listOfRoster;
						var rosters = entity.rosters;

						for (var i = 0; i < n; i++) {
							teams[i].club = rosters[i].data.baseData.club;
						}

						entity.generated=bergerTable(teams,terms);

						callback();
					});

				}).error(function(err) {
					callback(err);
				});

			}).error(function(err) {
				callback(err);
			});
		}

		function generateUserAccounting(entity,callback) {

			$http({
				method : 'GET',
				url : '/info/accounting/user/' + entity.id,

			}).success(function(info) {
				entity.accounting=info;
				callback();
			}).error(function(err) {
				callback(err);
			});
		}

		function generateClubAccounting(entity,callback) {

			$http({
				method : 'get',
				url : '/info/accounting/club/' + entity.id,

			}).success(function(info) {
				entity.accounting=info;
				callback();
			}).error(function(err) {
				callback(err);
			});
		}

		service.exportCsv = function() {
			var c = convertCriteria($scope.searchCrit);
			// add forced criteria
			for (var idx = 0; idx < $scope.forcedCriterias.length; idx++) {
				c.push($scope.forcedCriterias[idx]);
			}
			genericSearchFactory.getSearch($scope.entityUri, $scope.lastCriteria,convertSortBy( $scope.sortBy),0,1000).success(function(data) {

				data=toHtml($scope.schema,data);

				var blob = new Blob([data], {type: 'application/vnd.ms-excel;charset=utf-8'});
				var url  =  window.webkitURL||window.URL;
				var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
				link.href = url.createObjectURL(blob);
				link.download = 'search-export.xls'; // whatever file name you want :)

				var event = document.createEvent('MouseEvents');
				event.initEvent('click', true, false);
				link.dispatchEvent(event);

			}).error(function(err) {
				notificationFactory.error(err);
			});
		};

		service.generate=function(entity,type,callback) {
			switch (type) {
				case 'BERGER':
					generateBerger(entity,callback);
					break;
				case 'USER-ACCOUNTING':
					generateUserAccounting(entity,callback);
					break;
				case 'CLUB-ACCOUNTING':
					generateClubAccounting(entity,callback);
					break;
			}
		};
		service.save=function(entity,type,callback) {
			switch (type) {
				case 'BERGER':
					saveBerger(entity,callback);
					break;
			}
		};

		return service;
	}]);

}(window.angular));
<commit_msg>Fixed problem with notPlaying team.<commit_after>(function(angular) {
	'use strict';

	angular.module('xpsui:services')
	.factory('xpsui:GeneratorsGenerator', [ '$http', 'xpsui:safeUrlEncoder',
		'xpsui:SchemaUtil','$q','xpsui:ObjectTools',
		function($http, urlEncoder,schemaUtilFactory,$q,objectTools) {
		var service = {};

		/** Counts porter(-berger) table
		 * @teams - array of objects that will be used to define match
		 * @terms - array of object that will be used to define round, its size limits result
		 * @returns - object in form
				[{ round:<index>,term:<round_term>,matches:[{home:teams[x1],visitors:teams[y1],board:<board_index>},...] },...]
		 */
		function bergerTable(teams,terms) {

			var floatTable = [];
			var n, i, increment=1, atype=1, minmove=0, flipcolors=0;

			if (teams.length%2===1) {
				teams.push({complement:true});
			}

			n = teams.length;

			var nr = n-1; // Number of rounds

			var n2 = n / 2;
			var x, j, temp, colorFlag, incr;

			var max_round = terms.length;

			var test_r = 0;
			var outRounds=[];

			var textPrefix = 'A-';
			var match_id = 0;

			for (var r=1; r<= max_round; r++) {	// r is the round number.

				var outRound={round:r,term:terms[r-1],matches:[]};
				outRounds.push(outRound);

				if(r == nr+1) {
					match_id=0;
					textPrefix = 'B-';
				}

				if(r == 1) {		 // Round 1 initially seat the players
					incr=n-3; j = 0;

					for (i = 1; i < n; i++) {
						floatTable[j]=i;
						j += incr;
						j = j % (n-1);
					}
					floatTable[nr]=n;	// Identifies the "ghost" player, will not move
				}else {			// Other rounds, rotate the players "clockwise"
					temp = floatTable[n-2];
					for (i=n-2;	i > 0 ; i--) {
						floatTable[i] = floatTable[i-1];
					}
					floatTable[0] = temp;
				}
				if (r == n) {
					flipcolors ^= 1; // Swap colors for 2nd half
					test_r = 1;
				}

				i=0; // i is the board number about to be displayed, changed at bottom of loop
				if (atype == '1')
					increment=2;

				while (1) {	 //Must get out of this loop with break

					match_id++;

					var matchPrefix=textPrefix+match_id;

					if (i === 0)	 //At ghost board, color determined by round number
						colorFlag = ((r-test_r)%2) ? 1 : 0;
					else			//On other boards, board number determines it
						colorFlag = (i % 2) ? 0 : 1;

					colorFlag ^= flipcolors; //Will reverse color assignment if checked

					var pHome = teams[floatTable[colorFlag?nr-i:i]-1];
					var pVisitors = teams[floatTable[colorFlag?i:nr-i]-1];

					var match={home:pHome.team ,visitors:pVisitors.team ,boar:i ,matchNumber:matchPrefix, homeClub:teams[floatTable[colorFlag?nr-i:i]-1].club ,visitorClub:teams[floatTable[colorFlag?i:nr-i]-1].club};

					if (i===0) {
						match={home:match.visitors,visitors:match.home,board:i, matchNumber:matchPrefix, homeClub:match.visitorClub, visitorClub:match.homeClub};
					}

					if (pHome.complement) {
						outRound.notPlaying=pVisitors;
					} else if (pVisitors.complement) {
						outRound.notPlaying=pHome;
					} else {
						outRound.matches.push(match);
					}

					if (minmove && (i===0) && (r % 2)===0)
						i = 1;
					else
						i+= increment;
					if (i >= n2)
						if (increment == 1)	//Board number option
							break;
						else	{	//Come back to display the boards we missed
							increment = -2;
							i = ((i > n2) ? i - 3 : --i) ;
						}
					if ((i < 1) && (increment == -2)) //Finished with NOT board number option, exit loop
						break;
				}
			}

			// console.log(outRounds);
			// console.log(JSON.stringify(outRounds));
			return outRounds;
		}

		function saveBerger(entity,callback) {

			var saveSchema= schemaUtilFactory.encodeUri('uri://registries/refereeReports#views/refereeReports/new');
			var saved=0;
			var all=[];

			entity.saving=true;

			entity.generated.map(function(round) {
				round.matches.map(function(match) {
					var toSave={};
					toSave.baseData={};
					toSave.baseData.competition={schema:'uri://registries/competitions#views/competitions/view',oid:entity.baseData.competition.oid};
					toSave.baseData.season={schema:'uri://registries/seasons#views/seasons/view',oid:entity.competitionData.baseData.season.oid};
					toSave.baseData.competitionPart={schema:'uri://registries/competitionPart#views/competitionPart/view',oid:entity.id};
					toSave.baseData.ageCategory={schema:'uri://registries/ageCategory#views/ageCategory/view',oid:entity.competitionData.baseData.ageCategory.oid};
					toSave.baseData.homeClubSec={schema:'uri://registries/organizations#views/club/view',oid:match.homeClub.oid};
					toSave.baseData.awayClubSec={schema:'uri://registries/organizations#views/club/view',oid:match.visitorClub.oid};
					toSave.baseData.homeClub={schema:'uri://registries/rosters#views/rosters/view',oid:match.home.oid};
					toSave.baseData.awayClub={schema:'uri://registries/rosters#views/rosters/view',oid:match.visitors.oid};
					toSave.baseData.matchRound={schema:'uri://registries/schedule#views/schedule/view',oid:round.term.id};
					toSave.baseData.matchDate=round.term.baseData.date;
					toSave.baseData.state='Otvorený';

					if (entity.baseData.prefix) {
						toSave.baseData.matchNumber=entity.baseData.prefix+match.matchNumber;
					};

					toSave.baseData.printTemplate=entity.baseData.printTemplate;

					all.push( $http({url: '/udao/saveBySchema/'+saveSchema, method: 'PUT',data: toSave}));
				});
			});
			$q.all(all).then(function() {
				callback(null);
			});
		}

		function generateBerger(entity,callback) {
			var searchSchema='uri://registries/schedule#views/schedule/search';
			$http({
				method : 'POST',
				url : '/search/' + schemaUtilFactory.encodeUri(searchSchema),
				data : {
					crits :[{
						f : 'baseData.competitionPart.oid',
						v : entity.id,
						op : 'eq'
					}],
					sorts: [ { f:'baseData.date', o: 'asc'}]
				}
			}).success(function(terms) {
				var teams=entity.listOfTeam.team;

				var n = teams.length;

				//get competition object
				var getSchemaCompetition = 'uri://registries/competitions#views/competitions/';
				$http({
					method : 'GET',
					url: '/udao/getBySchema/'+schemaUtilFactory.encodeUri(schemaUtilFactory.concatUri(getSchemaCompetition, 'view'))+'/'+ entity.baseData.competition.oid
				})
				.success(function(dataCom) {
					console.log(JSON.stringify(dataCom, null, 4));
					entity.competitionData = dataCom;

					//get roster object
					var getSchemaRoster = 'uri://registries/rosters#views/rosters/';
					var httpArray = [];

					for (var i = 0; i < n; i++) {
						httpArray.push(
							$http({
								method : 'GET',
								url: '/udao/getBySchema/'+schemaUtilFactory.encodeUri(schemaUtilFactory.concatUri(getSchemaRoster, 'view'))+'/'+ entity.listOfTeam.team[i].team.oid
							})
						);
					};

					$q.all(httpArray).then(function(listOfRoster) {
						if(!entity.rosters) {
							entity.rosters = {};
						}
						entity.rosters = listOfRoster;
						var rosters = entity.rosters;

						for (var i = 0; i < n; i++) {
							teams[i].club = rosters[i].data.baseData.club;
						}

						entity.generated=bergerTable(teams,terms);

						callback();
					});

				}).error(function(err) {
					callback(err);
				});

			}).error(function(err) {
				callback(err);
			});
		}

		function generateUserAccounting(entity,callback) {

			$http({
				method : 'GET',
				url : '/info/accounting/user/' + entity.id,

			}).success(function(info) {
				entity.accounting=info;
				callback();
			}).error(function(err) {
				callback(err);
			});
		}

		function generateClubAccounting(entity,callback) {

			$http({
				method : 'get',
				url : '/info/accounting/club/' + entity.id,

			}).success(function(info) {
				entity.accounting=info;
				callback();
			}).error(function(err) {
				callback(err);
			});
		}

		service.exportCsv = function() {
			var c = convertCriteria($scope.searchCrit);
			// add forced criteria
			for (var idx = 0; idx < $scope.forcedCriterias.length; idx++) {
				c.push($scope.forcedCriterias[idx]);
			}
			genericSearchFactory.getSearch($scope.entityUri, $scope.lastCriteria,convertSortBy( $scope.sortBy),0,1000).success(function(data) {

				data=toHtml($scope.schema,data);

				var blob = new Blob([data], {type: 'application/vnd.ms-excel;charset=utf-8'});
				var url  =  window.webkitURL||window.URL;
				var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
				link.href = url.createObjectURL(blob);
				link.download = 'search-export.xls'; // whatever file name you want :)

				var event = document.createEvent('MouseEvents');
				event.initEvent('click', true, false);
				link.dispatchEvent(event);

			}).error(function(err) {
				notificationFactory.error(err);
			});
		};

		service.generate=function(entity,type,callback) {
			switch (type) {
				case 'BERGER':
					generateBerger(entity,callback);
					break;
				case 'USER-ACCOUNTING':
					generateUserAccounting(entity,callback);
					break;
				case 'CLUB-ACCOUNTING':
					generateClubAccounting(entity,callback);
					break;
			}
		};
		service.save=function(entity,type,callback) {
			switch (type) {
				case 'BERGER':
					saveBerger(entity,callback);
					break;
			}
		};

		return service;
	}]);

}(window.angular));
<|endoftext|>


<commit_before>import "./style.css";

setTimeout(() => {
  console.log(
    getComputedStyle(document.body).background.match(/rgb\(255, 0, 0\)/)
      ? "ok"
      : "error"
  );
}, 0);
<commit_msg>Fix tests<commit_after>import "./style.css";

window.addEventListener("DOMContentLoaded", () => {
  console.log(
    getComputedStyle(document.body).background.match(/rgb\(255, 0, 0\)/)
      ? "ok"
      : "error"
  );
});
<|endoftext|>


<commit_before>var sidebar = null;
var viewer = null;
var libselect = null;
var icl = null;

var curmod = null;
var refresh_on_hash = true;
var line = null;

function loadModule(elem) {
	if (typeof elem != 'undefined') {
		line = null;
		curmod = elem.dataset.module;
	}

	updateHash();
	updateLibraryPanel();

	viewer.innerHTML = '
Loading...
';

	var url = 'src.php';
	url += '?lib=' + libselect.value;
	url += '&mod=' + curmod;
	if (icl.checked)
		url += '&icl';
	var hashelems = decodeURIComponent(window.location.hash.substring(1)).split(';');
	for (var i in hashelems)
		if (hashelems[i].substring(0,5) == 'line=')
			url += '&line=' + hashelems[i].substring(5);

	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			viewer.innerHTML = xmlHttp.response;
			if (line != null)
				document.getElementById('line-' + line).scrollIntoView(true);
		}
	}
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function updateLibraryPanel() {
	var mods = document.getElementsByClassName('module');
	for (var i = 0; i < mods.length; i++)
		mods[i].style.fontStyle = '';

	var e = document.getElementById('sidebar');
	var modpath = curmod.split('.');
	for (var m = 0; m < modpath.length - 1; m++) {
		var dirs = e.getElementsByClassName('directory');
		for (var d = 0; d < dirs.length; d++) {
			var t = dirs[d].getElementsByClassName('title')[0];
			if (t.innerHTML == modpath[m]) {
				e = dirs[d];
				toggle(e.getElementsByClassName('toggler')[0], true);
			}
		}
	}

	var modules = e.getElementsByClassName('module');
	for (var m = 0; m < modules.length; m++)
		if (modules[m].innerHTML == modpath[modpath.length-1])
			modules[m].style.fontStyle = 'italic';
}

function updateHash() {
	var newhash = curmod;
	if (icl.checked)
		newhash += ';icl';
	if (line != null)
		newhash += ';line=' + line;

	if (window.location.hash.substring(1) != encodeURIComponent(newhash)) {
		refresh_on_hash = false;
		window.location.hash = '#' + newhash;
	}
}

window.onhashchange = function() {
	if (!refresh_on_hash) {
		refresh_on_hash = true;
	} else {
		var elems = decodeURIComponent(window.location.hash.substring(1)).split(';');
		curmod = elems[0];
		icl.checked = elems.indexOf('icl') != -1;
		for (var i in elems)
			if (elems[i].substring(0,5) == 'line=')
				line = elems[i].substring(5);
		loadModule();
	}
}

window.onload = function () {
	sidebar = document.getElementById('sidebar');
	viewer = document.getElementById('viewer');
	libselect = document.getElementById('select-lib');
	icl = document.getElementById('icl');

	if (window.innerWidth > 800) {
		var height = window.innerHeight;
		sidebar.style.height = (height - 20) + 'px';
		viewer.style.height = height + 'px';
	}

	libselect.onchange = function() {
		window.location.href = 'view.php?lib=' + this.value;
	}

	icl.onchange = function() {
		line = null;
		loadModule();
	}

	window.onhashchange();
}
<commit_msg>Don't request source when no module is selected<commit_after>var sidebar = null;
var viewer = null;
var libselect = null;
var icl = null;

var curmod = null;
var refresh_on_hash = true;
var line = null;

function loadModule(elem) {
	if (typeof elem != 'undefined') {
		line = null;
		curmod = elem.dataset.module;
	}

	updateHash();
	updateLibraryPanel();

	viewer.innerHTML = '
Loading...
';

	var url = 'src.php';
	url += '?lib=' + libselect.value;
	if (curmod != '')
		url += '&mod=' + curmod;
	if (icl.checked)
		url += '&icl';
	var hashelems = decodeURIComponent(window.location.hash.substring(1)).split(';');
	for (var i in hashelems)
		if (hashelems[i].substring(0,5) == 'line=')
			url += '&line=' + hashelems[i].substring(5);

	var xmlHttp = new XMLHttpRequest();
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			viewer.innerHTML = xmlHttp.response;
			if (line != null)
				document.getElementById('line-' + line).scrollIntoView(true);
		}
	}
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function updateLibraryPanel() {
	var mods = document.getElementsByClassName('module');
	for (var i = 0; i < mods.length; i++)
		mods[i].style.fontStyle = '';

	var e = document.getElementById('sidebar');
	var modpath = curmod.split('.');
	for (var m = 0; m < modpath.length - 1; m++) {
		var dirs = e.getElementsByClassName('directory');
		for (var d = 0; d < dirs.length; d++) {
			var t = dirs[d].getElementsByClassName('title')[0];
			if (t.innerHTML == modpath[m]) {
				e = dirs[d];
				toggle(e.getElementsByClassName('toggler')[0], true);
			}
		}
	}

	var modules = e.getElementsByClassName('module');
	for (var m = 0; m < modules.length; m++)
		if (modules[m].innerHTML == modpath[modpath.length-1])
			modules[m].style.fontStyle = 'italic';
}

function updateHash() {
	var newhash = curmod;
	if (icl.checked)
		newhash += ';icl';
	if (line != null)
		newhash += ';line=' + line;

	if (window.location.hash.substring(1) != encodeURIComponent(newhash)) {
		refresh_on_hash = false;
		window.location.hash = '#' + newhash;
	}
}

window.onhashchange = function() {
	if (!refresh_on_hash) {
		refresh_on_hash = true;
	} else {
		var elems = decodeURIComponent(window.location.hash.substring(1)).split(';');
		curmod = elems[0];
		icl.checked = elems.indexOf('icl') != -1;
		for (var i in elems)
			if (elems[i].substring(0,5) == 'line=')
				line = elems[i].substring(5);
		loadModule();
	}
}

window.onload = function () {
	sidebar = document.getElementById('sidebar');
	viewer = document.getElementById('viewer');
	libselect = document.getElementById('select-lib');
	icl = document.getElementById('icl');

	if (window.innerWidth > 800) {
		var height = window.innerHeight;
		sidebar.style.height = (height - 20) + 'px';
		viewer.style.height = height + 'px';
	}

	libselect.onchange = function() {
		window.location.href = 'view.php?lib=' + this.value;
	}

	icl.onchange = function() {
		line = null;
		loadModule();
	}

	window.onhashchange();
}
<|endoftext|>


<commit_before>// Generated on 2013-07-24 using generator-angular 0.3.0
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
    /*jslint es5: true */  // allow use of reserved word statuc
    return connect.static(require('path').resolve(dir));
};

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
    // load all grunt tasks
    require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

    // configurable paths
    var yeomanConfig = {
        app: 'app',
        dist: 'dist'
    };

    try {
        yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app;
    } catch (e) {}

    grunt.initConfig({
        yeoman: yeomanConfig,
        watch: {
            compass: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
                tasks: ['compass:server']
            },
            livereload: {
                options: {
                    livereload: LIVERELOAD_PORT
                },
                files: [
                    '<%= yeoman.app %>/{,*/}*.html',
                    '{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',
                    '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },
        connect: {
            options: {
                port: 9000,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: '0.0.0.0'
            },
            livereload: {
                options: {
                    middleware: function (connect) {
                        return [
                            lrSnippet,
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, yeomanConfig.app)
                        ];
                    }
                }
            },
            test: {
                options: {
                    port: 9001,
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, 'test')
                        ];
                    }
                }
            },
            dist: {
                options: {
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, yeomanConfig.dist)
                        ];
                    }
                }
            }
        },
        open: {
            server: {
                url: 'http://localhost:<%= connect.options.port %>'
            }
        },
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
                        '.tmp',
                        '<%= yeoman.dist %>/*',
                        '!<%= yeoman.dist %>/.git*'
                    ]
                }]
            },
            server: '.tmp'
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [
                'Gruntfile.js',
                '<%= yeoman.app %>/scripts/{,*/}*.js'
            ]
        },
        compass: {
            options: {
                sassDir: '<%= yeoman.app %>/styles',
                cssDir: '.tmp/styles',
                generatedImagesDir: '.tmp/images/generated',
                imagesDir: '<%= yeoman.app %>/images',
                javascriptsDir: '<%= yeoman.app %>/scripts',
                fontsDir: '<%= yeoman.app %>/styles/fonts',
                importPath: '<%= yeoman.app %>/components',
                httpImagesPath: '/images',
                httpGeneratedImagesPath: '/images/generated',
                httpFontsPath: '/styles/fonts',
                relativeAssets: false
            },
            dist: {},
            server: {
                options: {
                    debugInfo: true
                }
            }
        },
        // not used since Uglify task does concat,
        // but still available if needed
        /*concat: {
          dist: {}
          },*/
        rev: {
            dist: {
                files: {
                    src: [
                        '<%= yeoman.dist %>/scripts/{,*/}*.js',
                        '<%= yeoman.dist %>/styles/{,*/}*.css',
                        '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
                        '<%= yeoman.dist %>/styles/fonts/*'
                    ]
                }
            }
        },
        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>'
            }
        },
        usemin: {
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
            options: {
                dirs: ['<%= yeoman.dist %>']
            }
        },
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.{png,jpg,jpeg}',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },
        cssmin: {
            // By default, your `index.html` <!-- Usemin Block --> will take care of
            // minification. This option is pre-configured if you do not wish to use
            // Usemin blocks.
            // dist: {
            //   files: {
            //     '<%= yeoman.dist %>/styles/main.css': [
            //       '.tmp/styles/{,*/}*.css',
            //       '<%= yeoman.app %>/styles/{,*/}*.css'
            //     ]
            //   }
            // }
        },
        htmlmin: {
            dist: {
                options: {
                    /*removeCommentsFromCDATA: true,
                    // https://github.com/yeoman/grunt-usemin/issues/44
                    //collapseWhitespace: true,
                    collapseBooleanAttributes: true,
                    removeAttributeQuotes: true,
                    removeRedundantAttributes: true,
                    useShortDoctype: true,
                    removeEmptyAttributes: true,
                    removeOptionalTags: true*/
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>',
                    src: ['*.html', 'views/*.html'],
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },
        // Put files not handled in other tasks here
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,png,txt}',
                        '.htaccess',
                        //'components/**/*',
                        'images/{,*/}*.{gif,webp,svg}',
                        'styles/fonts/*'
                    ]
                }, {
                    expand: true,
                    cwd: '.tmp/images',
                    dest: '<%= yeoman.dist %>/images',
                    src: [
                        'generated/*'
                    ]
                }]
            }
        },
        concurrent: {
            server: [
                'compass:server'
            ],
            test: [
                'compass'
            ],
            dist: [
                'compass:dist',
                'imagemin',
                'htmlmin'
            ]
        },
        karma: {
            unit: {
                configFile: 'test/karma.conf.js',
                singleRun: true
            },
            e2e: {
                configFile: 'test/karma-e2e.conf.js',
                singleRun: true
            }
        },
        cdnify: {
            dist: {
                html: ['<%= yeoman.dist %>/*.html']
            }
        },
        ngmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.dist %>/scripts',
                    src: '*.js',
                    dest: '<%= yeoman.dist %>/scripts'
                }]
            }
        },
        uglify: {
            dist: {
                files: {
                    '<%= yeoman.dist %>/scripts/scripts.js': [
                        '<%= yeoman.dist %>/scripts/scripts.js'
                    ]
                }
            }
        }
    });

    grunt.registerTask('server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'concurrent:server',
            'connect:livereload',
            'open',
            'watch'
        ]);
    });

    grunt.registerTask('test', [
        'clean:server',
        'concurrent:test',
        'connect:test',
        'karma'
    ]);

    grunt.registerTask('build', [
        'clean:dist',
        'useminPrepare',
        'concurrent:dist',
        'concat',
        'copy',
        'cdnify',
        'ngmin',
        //'cssmin',
        'uglify',
        'rev',
        'usemin'
    ]);

    grunt.registerTask('default', [
        'jshint',
        'test',
        'build'
    ]);
};
<commit_msg>disable e2e tests<commit_after>// Generated on 2013-07-24 using generator-angular 0.3.0
'use strict';
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({ port: LIVERELOAD_PORT });
var mountFolder = function (connect, dir) {
    return connect.static(require('path').resolve(dir));
};

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {
    // load all grunt tasks
    require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

    // configurable paths
    var yeomanConfig = {
        app: 'app',
        dist: 'dist'
    };

    try {
        yeomanConfig.app = require('./bower.json').appPath || yeomanConfig.app;
    } catch (e) {}

    grunt.initConfig({
        yeoman: yeomanConfig,
        watch: {
            compass: {
                files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
                tasks: ['compass:server']
            },
            livereload: {
                options: {
                    livereload: LIVERELOAD_PORT
                },
                files: [
                    '<%= yeoman.app %>/{,*/}*.html',
                    '{.tmp,<%= yeoman.app %>}/styles/{,*/}*.css',
                    '{.tmp,<%= yeoman.app %>}/scripts/{,*/}*.js',
                    '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },
        connect: {
            options: {
                port: 9000,
                // Change this to '0.0.0.0' to access the server from outside.
                hostname: '0.0.0.0'
            },
            livereload: {
                options: {
                    middleware: function (connect) {
                        return [
                            lrSnippet,
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, yeomanConfig.app)
                        ];
                    }
                }
            },
            test: {
                options: {
                    port: 9001,
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, 'test')
                        ];
                    }
                }
            },
            dist: {
                options: {
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, yeomanConfig.dist)
                        ];
                    }
                }
            }
        },
        open: {
            server: {
                url: 'http://localhost:<%= connect.options.port %>'
            }
        },
        clean: {
            dist: {
                files: [{
                    dot: true,
                    src: [
                        '.tmp',
                        '<%= yeoman.dist %>/*',
                        '!<%= yeoman.dist %>/.git*'
                    ]
                }]
            },
            server: '.tmp'
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            all: [
                'Gruntfile.js',
                '<%= yeoman.app %>/scripts/{,*/}*.js'
            ]
        },
        compass: {
            options: {
                sassDir: '<%= yeoman.app %>/styles',
                cssDir: '.tmp/styles',
                generatedImagesDir: '.tmp/images/generated',
                imagesDir: '<%= yeoman.app %>/images',
                javascriptsDir: '<%= yeoman.app %>/scripts',
                fontsDir: '<%= yeoman.app %>/styles/fonts',
                importPath: '<%= yeoman.app %>/components',
                httpImagesPath: '/images',
                httpGeneratedImagesPath: '/images/generated',
                httpFontsPath: '/styles/fonts',
                relativeAssets: false
            },
            dist: {},
            server: {
                options: {
                    debugInfo: true
                }
            }
        },
        // not used since Uglify task does concat,
        // but still available if needed
        /*concat: {
          dist: {}
          },*/
        rev: {
            dist: {
                files: {
                    src: [
                        '<%= yeoman.dist %>/scripts/{,*/}*.js',
                        '<%= yeoman.dist %>/styles/{,*/}*.css',
                        '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
                        '<%= yeoman.dist %>/styles/fonts/*'
                    ]
                }
            }
        },
        useminPrepare: {
            html: '<%= yeoman.app %>/index.html',
            options: {
                dest: '<%= yeoman.dist %>'
            }
        },
        usemin: {
            html: ['<%= yeoman.dist %>/{,*/}*.html'],
            css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
            options: {
                dirs: ['<%= yeoman.dist %>']
            }
        },
        imagemin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>/images',
                    src: '{,*/}*.{png,jpg,jpeg}',
                    dest: '<%= yeoman.dist %>/images'
                }]
            }
        },
        cssmin: {
            // By default, your `index.html` <!-- Usemin Block --> will take care of
            // minification. This option is pre-configured if you do not wish to use
            // Usemin blocks.
            // dist: {
            //   files: {
            //     '<%= yeoman.dist %>/styles/main.css': [
            //       '.tmp/styles/{,*/}*.css',
            //       '<%= yeoman.app %>/styles/{,*/}*.css'
            //     ]
            //   }
            // }
        },
        htmlmin: {
            dist: {
                options: {
                    /*removeCommentsFromCDATA: true,
                    // https://github.com/yeoman/grunt-usemin/issues/44
                    //collapseWhitespace: true,
                    collapseBooleanAttributes: true,
                    removeAttributeQuotes: true,
                    removeRedundantAttributes: true,
                    useShortDoctype: true,
                    removeEmptyAttributes: true,
                    removeOptionalTags: true*/
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.app %>',
                    src: ['*.html', 'views/*.html'],
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },
        // Put files not handled in other tasks here
        copy: {
            dist: {
                files: [{
                    expand: true,
                    dot: true,
                    cwd: '<%= yeoman.app %>',
                    dest: '<%= yeoman.dist %>',
                    src: [
                        '*.{ico,png,txt}',
                        '.htaccess',
                        //'components/**/*',
                        'images/{,*/}*.{gif,webp,svg}',
                        'styles/fonts/*'
                    ]
                }, {
                    expand: true,
                    cwd: '.tmp/images',
                    dest: '<%= yeoman.dist %>/images',
                    src: [
                        'generated/*'
                    ]
                }]
            }
        },
        concurrent: {
            server: [
                'compass:server'
            ],
            test: [
                'compass'
            ],
            dist: [
                'compass:dist',
                'imagemin',
                'htmlmin'
            ]
        },
        karma: {
            unit: {
                configFile: 'test/karma.conf.js',
                singleRun: true
            },
            // e2e: {
            //     configFile: 'test/karma-e2e.conf.js',
            //     singleRun: true
            // }
        },
        cdnify: {
            dist: {
                html: ['<%= yeoman.dist %>/*.html']
            }
        },
        ngmin: {
            dist: {
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.dist %>/scripts',
                    src: '*.js',
                    dest: '<%= yeoman.dist %>/scripts'
                }]
            }
        },
        uglify: {
            dist: {
                files: {
                    '<%= yeoman.dist %>/scripts/scripts.js': [
                        '<%= yeoman.dist %>/scripts/scripts.js'
                    ]
                }
            }
        }
    });

    grunt.registerTask('server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['build', 'open', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'concurrent:server',
            'connect:livereload',
            'open',
            'watch'
        ]);
    });

    grunt.registerTask('test', [
        'clean:server',
        'concurrent:test',
        'connect:test',
        'karma'
    ]);

    grunt.registerTask('build', [
        'clean:dist',
        'useminPrepare',
        'concurrent:dist',
        'concat',
        'copy',
        'cdnify',
        'ngmin',
        //'cssmin',
        'uglify',
        'rev',
        'usemin'
    ]);

    grunt.registerTask('default', [
        'jshint',
        'test',
        'build'
    ]);
};
<|endoftext|>


<commit_before>// ==========================================================================
// Grunt Build
// ==========================================================================

module.exports = function(grunt) {
  'use strict';

  grunt.initConfig({

    sass: {
      dev: {
        options: {
          style: 'expanded',
          compass: true
        },
        files: {
          'public/css/core.css': 'public/css/core.scss'
        }
      },
      dist: {
        options: {
          style: 'compressed',
          compass: true,
          sourcemap: 'none'
        },
        files: {
          'public/css/core.css': 'public/css/core.scss'
        }
      },
      prototype: {
        options: {
          style: 'expanded',
          compass: true,
          require: ['breakpoint']
        },
        files: {
          'prototype/core.css': 'prototype/core.scss'
        }
      }
    },

    jshint: {
      options: {
        '-W058': true,
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: false,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        unused: false,
        boss: true,
        eqnull: false,
        browser: true,
        esnext: true,
        debug: true,
        globalstrict: true,
        globals: {
          '$': false,
          'module': true,
          'require': false,
          'console': false,
          'window': true,
          'debug': true,
          'log': true,
          'io': true,
          'process': false,
          '__dirname': false,
          'ZeroClipboard': false,
          'chrome': true
        }
      },
      files: ['Gruntfile.js', 'app.js', 'models/*.js', 'public/js/*.js', 'chrome/ext/*.js', 'prototype/core.js']
    },

    jasmine: {
      pivotal: {
        src: 'public/js/core.js',
        options: {
          vendor: ['public/js/vendor/socket.io.js', 'public/js/vendor/clipboard.min.js', 'public/js/vendor/jquery.min.js'],
          helpers: ['spec/helpers/jasmine-jquery.js'],
          specs: 'spec/*Spec.js',
          keepRunner: true
        }
      }
    },

    preprocess: {
      html : {
        src : 'tmpl/index.html',
        dest : 'public/index.html'
      }
    },

    watch: {
      sass: {
        files: ['public/css/**/*.scss'],
        tasks: ['sass:dist']
      },
      js: {
        files: ['<%= jshint.files %>'],
        tasks: ['jshint']
      },
      test: {
        files: ['spec/**/*.js', 'tmpl/inc/*.html', 'public/js/*.js'],
        tasks: ['test']
      },
      html: {
        files: ['tmpl/**/*.html'],
        tasks: ['preprocess']
      },
      options: {
        livereload: true
      },
      prototype: {
        files: ['prototype/core.scss'],
        tasks: ['sass:prototype']
      }
    }

  });

  // Load Modules
  // ----------------------------------------------------------
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-preprocess');

  // Register Tasks
  // ----------------------------------------------------------
  grunt.registerTask('default', ['sass:dev', 'jshint', 'preprocess', 'jasmine']);
  grunt.registerTask('dev', ['sass:dev', 'jshint', 'preprocess', 'jasmine', 'watch']);
  grunt.registerTask('dist', ['sass:dist', 'jshint', 'jasmine', 'preprocess']);
  grunt.registerTask('proto', ['sass:prototype', 'jshint', 'watch']);
  grunt.registerTask('test', ['jasmine']);
  grunt.registerTask('heroku', ['sass:dist']);

  // Show Timer
  // ----------------------------------------------------------
  require('time-grunt')(grunt);

};
<commit_msg>disable heroku post-hook sass<commit_after>// ==========================================================================
// Grunt Build
// ==========================================================================

module.exports = function(grunt) {
  'use strict';

  grunt.initConfig({

    sass: {
      dev: {
        options: {
          style: 'expanded',
          compass: true
        },
        files: {
          'public/css/core.css': 'public/css/core.scss'
        }
      },
      dist: {
        options: {
          style: 'compressed',
          compass: true,
          sourcemap: 'none'
        },
        files: {
          'public/css/core.css': 'public/css/core.scss'
        }
      },
      prototype: {
        options: {
          style: 'expanded',
          compass: true,
          require: ['breakpoint']
        },
        files: {
          'prototype/core.css': 'prototype/core.scss'
        }
      }
    },

    jshint: {
      options: {
        '-W058': true,
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: false,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        unused: false,
        boss: true,
        eqnull: false,
        browser: true,
        esnext: true,
        debug: true,
        globalstrict: true,
        globals: {
          '$': false,
          'module': true,
          'require': false,
          'console': false,
          'window': true,
          'debug': true,
          'log': true,
          'io': true,
          'process': false,
          '__dirname': false,
          'ZeroClipboard': false,
          'chrome': true
        }
      },
      files: ['Gruntfile.js', 'app.js', 'models/*.js', 'public/js/*.js', 'chrome/ext/*.js', 'prototype/core.js']
    },

    jasmine: {
      pivotal: {
        src: 'public/js/core.js',
        options: {
          vendor: ['public/js/vendor/socket.io.js', 'public/js/vendor/clipboard.min.js', 'public/js/vendor/jquery.min.js'],
          helpers: ['spec/helpers/jasmine-jquery.js'],
          specs: 'spec/*Spec.js',
          keepRunner: true
        }
      }
    },

    preprocess: {
      html : {
        src : 'tmpl/index.html',
        dest : 'public/index.html'
      }
    },

    watch: {
      sass: {
        files: ['public/css/**/*.scss'],
        tasks: ['sass:dist']
      },
      js: {
        files: ['<%= jshint.files %>'],
        tasks: ['jshint']
      },
      test: {
        files: ['spec/**/*.js', 'tmpl/inc/*.html', 'public/js/*.js'],
        tasks: ['test']
      },
      html: {
        files: ['tmpl/**/*.html'],
        tasks: ['preprocess']
      },
      options: {
        livereload: true
      },
      prototype: {
        files: ['prototype/core.scss'],
        tasks: ['sass:prototype']
      }
    }

  });

  // Load Modules
  // ----------------------------------------------------------
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-jasmine');
  grunt.loadNpmTasks('grunt-preprocess');

  // Register Tasks
  // ----------------------------------------------------------
  grunt.registerTask('default', ['sass:dev', 'jshint', 'preprocess', 'jasmine']);
  grunt.registerTask('dev', ['sass:dev', 'jshint', 'preprocess', 'jasmine', 'watch']);
  grunt.registerTask('dist', ['sass:dist', 'jshint', 'jasmine', 'preprocess']);
  grunt.registerTask('proto', ['sass:prototype', 'jshint', 'watch']);
  grunt.registerTask('test', ['jasmine']);
  // grunt.registerTask('heroku', ['sass:dist']);
  grunt.registerTask('heroku', ['']);

  // Show Timer
  // ----------------------------------------------------------
  require('time-grunt')(grunt);

};
<|endoftext|>


<commit_before>/*
 * grunt-grunticon-pigment
 * https://github.com/springload/grunticon-pigment
 *
 * Copyright (c) 2014 Thomas Winter
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({
        paths: {
            grunticons: 'examples/',
            css: 'result/',
        },

        watch: {
            files: '<config:lint.files>',
            tasks: 'default'
        },

        grunticon_pigment: {
            foo: {
                files: [{
                    cwd: '<%= paths.grunticons %>',
                    dest: '<%= paths.css %>'
                }],
                options: {

                    // CSS filenames
                    datasvgcss: "icons-data-svg.css",
                    datapngcss: "icons-data-png.css",
                    urlpngcss: "icons-fallback.css",

                    // preview HTML filename
                    previewhtml: "icons-preview.html",

                    // grunticon loader code snippet filename
                    loadersnippet: "grunticon-loader.js",

                    // folder name (within cwd) for svg files
                    svgFolder: "source",
                    svgColorFolder: "source-colourise",

                    // folder name (within dest) for png output
                    pngfolder: "png",

                    // prefix for CSS classnames
                    cssprefix: ".i-",

                    defaultWidth: "32px",
                    defaultHeight: "32px",

                    // colours for svg colourising
                    svgColors: ["#ffffff", "#A6CC85"],

                    // css file path prefix - this defaults to "/" and will be placed before the "dest" path when stylesheets are loaded.
                    // This allows root-relative referencing of the CSS. If you don't want a prefix path, set to to ""
                    cssbasepath: "",
                    customselectors: {
                        "twitter": [".alternative-selector"]
                    },

                    // templates for css output and preview page
                    template: "<%= paths.grunticons %>default-css.hbs",
                    previewTemplate:  "<%= paths.grunticons %>preview.hbs"

                }
            }
        },
        jshint: {
            all: [
                'Gruntfile.js',
                'tasks/*.js',
                'lib/*.js'
            ],
            options: {
                jshintrc: '.jshintrc'
            }
        },

        // Before generating any new files, remove any previously-created files.
        clean: {
            tests: ['tmp']
        }
    });

    // Load local tasks.
    grunt.loadTasks('tasks');

    grunt.loadNpmTasks( 'grunt-contrib-jshint' );

    // Default task.
    grunt.registerTask('skip-tests', ['jshint', 'grunticon_pigment:foo']);
    grunt.registerTask('travis', ['jshint', 'svgmin', 'grunticon_pigment:foo']);
    grunt.registerTask('default', ['travis']);

};
<commit_msg>Add another color to the example config<commit_after>/*
 * grunt-grunticon-pigment
 * https://github.com/springload/grunticon-pigment
 *
 * Copyright (c) 2014 Thomas Winter
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

    // Project configuration.
    grunt.initConfig({
        paths: {
            grunticons: 'examples/',
            css: 'result/',
        },

        watch: {
            files: '<config:lint.files>',
            tasks: 'default'
        },

        grunticon_pigment: {
            foo: {
                files: [{
                    cwd: '<%= paths.grunticons %>',
                    dest: '<%= paths.css %>'
                }],
                options: {

                    // CSS filenames
                    datasvgcss: "icons-data-svg.css",
                    datapngcss: "icons-data-png.css",
                    urlpngcss: "icons-fallback.css",

                    // preview HTML filename
                    previewhtml: "icons-preview.html",

                    // grunticon loader code snippet filename
                    loadersnippet: "grunticon-loader.js",

                    // folder name (within cwd) for svg files
                    svgFolder: "source",
                    svgColorFolder: "source-colourise",

                    // folder name (within dest) for png output
                    pngfolder: "png",

                    // prefix for CSS classnames
                    cssprefix: ".i-",

                    defaultWidth: "32px",
                    defaultHeight: "32px",

                    // colours for svg colourising
                    svgColors: ["#ffffff", "#f24785", "#7dc265"],

                    // css file path prefix - this defaults to "/" and will be placed before the "dest" path when stylesheets are loaded.
                    // This allows root-relative referencing of the CSS. If you don't want a prefix path, set to to ""
                    cssbasepath: "",
                    customselectors: {
                        "twitter": [".alternative-selector"]
                    },

                    // templates for css output and preview page
                    template: "<%= paths.grunticons %>default-css.hbs",
                    previewTemplate:  "<%= paths.grunticons %>preview.hbs"

                }
            }
        },
        jshint: {
            all: [
                'Gruntfile.js',
                'tasks/*.js',
                'lib/*.js'
            ],
            options: {
                jshintrc: '.jshintrc'
            }
        },

        // Before generating any new files, remove any previously-created files.
        clean: {
            tests: ['tmp']
        }
    });

    // Load local tasks.
    grunt.loadTasks('tasks');

    grunt.loadNpmTasks( 'grunt-contrib-jshint' );

    // Default task.
    grunt.registerTask('skip-tests', ['jshint', 'grunticon_pigment:foo']);
    grunt.registerTask('travis', ['jshint', 'svgmin', 'grunticon_pigment:foo']);
    grunt.registerTask('default', ['travis']);

};
<|endoftext|>


<commit_before>define(["js/core/TextElement", 'md/lib/marked'], function (TextElement, marked) {

        var rDos = /\r\n/g,
            rMac = /\r/g,
            rUnix = /\n/,
            hasContent = /\S/,
            rIndent = /\s*/;

        return TextElement.inherit("md.MarkdownTextElement", {

            render: function () {
                if (!this.$initialized) {
                    this._initialize(this.$creationPolicy);
                }

                this.$el = this.$systemManager.$document.createElement(this.$tagName);
                if (!_.isUndefined(this.$.textContent)) {
                    this._renderTextContent(this.$.textContent);
                }

                return this.$el;
            },

            normalizeIndent: function(text) {

                var lines = text.split(rUnix),
                    indentSize = null,
                    i,
                    line;

                for (i = 0; i < lines.length; i++) {
                    line = lines[i];

                    if (hasContent.test(line)) {
                        var param = rIndent.exec(line);
                        if (!param) {
                            // indent not found
                            return text;
                        }

                        if (indentSize === null) {
                            indentSize = param[0].length;
                        } else {
                            indentSize = Math.min(indentSize, param[0].length);
                        }

                        if (indentSize === 0) {
                            return text;
                        }
                    }
                }

                var removeIndent = new RegExp("^\\s{" + indentSize + "}");
                for (i = 0; i < lines.length; i++) {
                    // remove indent from lines
                    lines[i] = lines[i].replace(removeIndent, '');
                }

                return lines.join('\n');
            },

            _renderTextContent: function (textContent) {

                // Standardize line endings

                textContent = textContent.replace(rDos, "\n"); // DOS to Unix
                textContent = textContent.replace(rMac, "\n"); // Mac to Unix

                if (this.$.normalizeIndent === true) {
                    textContent = this.normalizeIndent(textContent);
                }

                // Indent code between ``` ``` blocks

//                this.$el.innerHTML = this.$converter.makeHtml(textContent.trim());
                this.$el.innerHTML = marked(textContent.trim());
            }
        });
    }
);<commit_msg>added missing reference to underscore<commit_after>define(["js/core/TextElement", 'md/lib/marked', 'underscore'], function (TextElement, marked, _) {

        var rDos = /\r\n/g,
            rMac = /\r/g,
            rUnix = /\n/,
            hasContent = /\S/,
            rIndent = /\s*/;

        return TextElement.inherit("md.MarkdownTextElement", {

            render: function () {
                if (!this.$initialized) {
                    this._initialize(this.$creationPolicy);
                }

                this.$el = this.$systemManager.$document.createElement('span');
                if (!_.isUndefined(this.$.textContent)) {
                    this._renderTextContent(this.$.textContent);
                }

                return this.$el;
            },

            normalizeIndent: function(text) {

                var lines = text.split(rUnix),
                    indentSize = null,
                    i,
                    line;

                for (i = 0; i < lines.length; i++) {
                    line = lines[i];

                    if (hasContent.test(line)) {
                        var param = rIndent.exec(line);
                        if (!param) {
                            // indent not found
                            return text;
                        }

                        if (indentSize === null) {
                            indentSize = param[0].length;
                        } else {
                            indentSize = Math.min(indentSize, param[0].length);
                        }

                        if (indentSize === 0) {
                            return text;
                        }
                    }
                }

                var removeIndent = new RegExp("^\\s{" + indentSize + "}");
                for (i = 0; i < lines.length; i++) {
                    // remove indent from lines
                    lines[i] = lines[i].replace(removeIndent, '');
                }

                return lines.join('\n');
            },

            _renderTextContent: function (textContent) {

                // Standardize line endings

                textContent = textContent.replace(rDos, "\n"); // DOS to Unix
                textContent = textContent.replace(rMac, "\n"); // Mac to Unix

                if (this.$.normalizeIndent === true) {
                    textContent = this.normalizeIndent(textContent);
                }

                // Indent code between ``` ``` blocks

//                this.$el.innerHTML = this.$converter.makeHtml(textContent.trim());
                this.$el.innerHTML = marked(textContent.trim());
            }
        });
    }
);<|endoftext|>


<commit_before>// LICENSE : MIT
"use strict";
import * as assert from "assert";
import * as glob from "glob";
import * as fs from "fs";
import * as path from "path";
import { Config } from "../../src/config/config";
/* load config from "./config/" and match expected result */
describe("config-as-example", function() {
    const configList = glob.sync(path.join(__dirname, "/config-fixtures/**/.textlintrc"));
    configList.forEach(textlintrcPath => {
        const projectDir = path.dirname(textlintrcPath);
        const dirName = projectDir.split("/").pop();
        it(`test config: ${dirName}`, function() {
            let config;
            try {
                config = Config.initWithAutoLoading({
                    textlintrc: true,
                    configFile: textlintrcPath, // == node_modules/
                    rulesBaseDirectory: path.join(__dirname, "config-fixtures", dirName, "modules")
                });
            } catch (error) {
                // eslint-disable-next-line no-console
                console.error(`Fail: ${dirName}`);
                throw error;
            }
            const expectedPath = fs.existsSync(path.join(projectDir, "expect.json"))
                ? path.join(projectDir, "expect.json")
                : path.join(projectDir, "expect.js");
            const expect = require(expectedPath);
            const actual = config.toJSON();
            Object.keys(expect).forEach(key => {
                try {
                    assert.deepStrictEqual(actual[key], expect[key]);
                } catch (error) {
                    console.error(`Fail: does not match expected config.
    at ${textlintrcPath}:1:1
    at ${expectedPath}:1:1`);
                    throw error;
                }
            });
        });
    });
});
<commit_msg>chore(textlint): disable eslint at line<commit_after>// LICENSE : MIT
"use strict";
import * as assert from "assert";
import * as glob from "glob";
import * as fs from "fs";
import * as path from "path";
import { Config } from "../../src/config/config";
/* load config from "./config/" and match expected result */
describe("config-as-example", function() {
    const configList = glob.sync(path.join(__dirname, "/config-fixtures/**/.textlintrc"));
    configList.forEach(textlintrcPath => {
        const projectDir = path.dirname(textlintrcPath);
        const dirName = projectDir.split("/").pop();
        it(`test config: ${dirName}`, function() {
            let config;
            try {
                config = Config.initWithAutoLoading({
                    textlintrc: true,
                    configFile: textlintrcPath, // == node_modules/
                    rulesBaseDirectory: path.join(__dirname, "config-fixtures", dirName, "modules")
                });
            } catch (error) {
                // eslint-disable-next-line no-console
                console.error(`Fail: ${dirName}`);
                throw error;
            }
            const expectedPath = fs.existsSync(path.join(projectDir, "expect.json"))
                ? path.join(projectDir, "expect.json")
                : path.join(projectDir, "expect.js");
            const expect = require(expectedPath);
            const actual = config.toJSON();
            Object.keys(expect).forEach(key => {
                try {
                    assert.deepStrictEqual(actual[key], expect[key]);
                } catch (error) {
                    // eslint-disable-next-line no-console
                    console.error(`Fail: does not match expected config.
    at ${textlintrcPath}:1:1
    at ${expectedPath}:1:1`);
                    throw error;
                }
            });
        });
    });
});
<|endoftext|>


<commit_before>import Request from 'immutable-request'
import Url from 'url'

export default {
  get(url) {
//    if (global.fs && fs.existsSync(`cache/${ encodeURI(url) }.json`)) {
//    }
    const {protocol, host, pathname} = Url.parse(url)
    return requestFrom(`${protocol}//${host}`).GET(pathname)
//   .then((rv)=>{
//        if (global.fs) {
//            fs.writeFileSync(`cache/${ encodeURI(url) }.json`)...)
//        }
//        return rv
//    });
  }
}

const domainToRequest = {}

function requestFrom(domain) {
  domainToRequest[domain] = domainToRequest[domain] || new Request.Requester(domain, {
    max: 100, // cache no more than 100 HTTP requests
    maxAge: 60000, // cache expires after 60s
    timeout: 10000, // request timeout after 10000
  })
  return domainToRequest[domain]
}
<commit_msg>* Use localStorage for cache<commit_after>import Request from 'immutable-request'
import Url from 'url'
import Promise from 'bluebird'

export default {
  get(url) {
    return new Promise((resolve)=> {
      if (window.localStorage && window.localStorage.getItem(encodeURI(url))) {
        return resolve(JSON.parse(window.localStorage.getItem(encodeURI(url))))
      }
      const {protocol, host, pathname} = Url.parse(url)
      return requestFrom(`${protocol}//${host}`).GET(pathname)
        .then((rv)=>{
          if (window.localStorage) {
            window.localStorage.setItem(encodeURI(url), JSON.stringify(rv))
          }
          return resolve(rv)
        })
    })
  }
}

const domainToRequest = {}

function requestFrom(domain) {
  domainToRequest[domain] = domainToRequest[domain] || new Request.Requester(domain, {
    max: 100, // cache no more than 100 HTTP requests
    maxAge: 60000, // cache expires after 60s
    timeout: 10000, // request timeout after 10000
  })
  return domainToRequest[domain]
}
<|endoftext|>


<commit_before>// Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
// Find all unique triplets in the array which gives the sum of zero.

// Note:
// Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
// The solution set must not contain duplicate triplets.
//     For example, given array S = {-1 0 1 2 -1 -4},

//     A solution set is:
//     (-1, 0, 1)
//     (-1, -1, 2)

var threeSum = function(nums) {
    nums = nums.sort(function(a, b) { return a - b; });

    var results = [];
    var i, j, k, n = nums.length;

    for (i = 0; i < n; ++i) {
        if (i > 0 && nums[i] === nums[i-1]) continue;

        for (j = i + 1; j < n; ++j) {
            if (j > i + 1 && nums[j] === nums[j-1]) continue;

            for (k = j + 1; k < n; ++k) {
                if (k > j + 1 && nums[k] === nums[k-1]) continue;

                if (nums[i] + nums[j] + nums[k] === 0) results.push([nums[i], nums[j], nums[k]]);
            }
        }
    }
    return results;
};
<commit_msg>add notes<commit_after>// Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
// Find all unique triplets in the array which gives the sum of zero.

// Note:
// Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
// The solution set must not contain duplicate triplets.
//     For example, given array S = {-1 0 1 2 -1 -4},

//     A solution set is:
//     (-1, 0, 1)
//     (-1, -1, 2)

// BREAKDOWN PROBLEM

var threeSum = function(nums) {
    var rtn = [];
    if (nums.length < 3) {
        return rtn;
    }
    nums = nums.sort(function(a, b) {
        return a - b;
    });
    for (var i = 0; i < nums.length - 2; i++) {
        if (nums[i] > 0) {
            return rtn;
        }
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        for (var j = i + 1, k = nums.length - 1; j < k;) {
            if (nums[i] + nums[j] + nums[k] === 0) {
                rtn.push([nums[i], nums[j], nums[k]]);
                j++;
                k--;
                while (j < k && nums[j] == nums[j - 1]) {
                    j++;
                }
                while (j < k && nums[k] == nums[k + 1]) {
                    k--;
                }
            } else if (nums[i] + nums[j] + nums[k] > 0) {
                k--;
            } else {
                j++;
            }
        }
    }
    return rtn;
};

// BREAKDOWN PROBLEM

var threeSum = function(nums) {
    nums = nums.sort(function(a, b) { return a - b; });

    var results = [];
    var i, j, k, n = nums.length;

    for (i = 0; i < n; ++i) {
        if (i > 0 && nums[i] === nums[i-1]) continue;

        for (j = i + 1; j < n; ++j) {
            if (j > i + 1 && nums[j] === nums[j-1]) continue;

            for (k = j + 1; k < n; ++k) {
                if (k > j + 1 && nums[k] === nums[k-1]) continue;

                if (nums[i] + nums[j] + nums[k] === 0) results.push([nums[i], nums[j], nums[k]]);
            }
        }
    }
    return results;
};
<|endoftext|>


<commit_before>define(
    [
        'graphicore',
        'graphicore/errors',
        'graphicore/tools/misc/transform',
        'graphicore/tools/pens/BasePen',
        'graphicore/tools/pens/testPens'
    ],
    function(graphicore, errors, transform, BasePen, testPens)
{
    /*shortcuts*/
    var TestPen = testPens.BaseTestPen,
    /**
     * a little helper to round the results of the testpen. This is good
     * to overcome floating point rounding errors
     */
        roundRecursive = function(item, factor) {
        //currying the factor away
        var round = graphicore.round,
            roundRecursive = function(item) {
            if(item instanceof Array)
                return item.map(roundRecursive);
            if(typeof item === 'number')
                return round(item, factor);
            return item;
        }
        return roundRecursive(item);
    };

    doh.register("graphicore.pens.BasePen", [
    function Test_BasePen_Errors() {
        var pen = new BasePen();

        doh.assertError(
            errors.NotImplemented,
            pen, 'moveTo',
            [[1, 1]],
            '_moveTo is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'lineTo',
            [[1, 1]],
            '_lineTo is not implemented'
        );

        doh.assertError(
            errors.Assertion,
            pen, 'curveTo'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1,1]],
            '_lineto is not implemented'
        );

        doh.assertError(
            TypeError,
            pen, 'curveTo',
            [[1, 1], [1, 1]],
            '_qCurveToOne is called and wants to access __curentPoint as a List'
        );

        doh.assertError(
            TypeError,
            pen, 'qCurveTo',
            [[1, 1], [1, 1]],
            '_qCurveToOne is called and wants to access __curentPoint as a List'
        );

        //faking this in
        pen.__currentPoint = [1, 1];

        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );
        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1, 1], [1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1, 1], [1, 1], [1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );

        doh.assertError(
            errors.Assertion,
            pen, 'qCurveTo'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'qCurveTo',
            [[1, 1]],
            '_lineTo is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'qCurveTo',
            [[1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'qCurveTo',
            [[1, 1], null],
            '_moveTo is not implemented'
        );

        doh.assertError(
            TypeError,
            pen, 'addComponent'
            ['test'],
            'there is no glyphset'
        );
    },
    function Test_BasePen_closePath() {
        var pen = new TestPen();

        var expected = ['_closePath'];
        pen.closePath();
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_endPath() {
        var pen = new TestPen([]);

        var expected = ['_endPath'];
        pen.endPath();
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_lineTo() {
        var pen = new TestPen();

        var expected = [ ['_lineTo', [1, 2] ] ];
        pen.lineTo( [1, 2] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_moveTo() {
        var pen = new TestPen();

        var expected = [ ['_moveTo', [1, 2] ] ];
        pen.moveTo( [1, 2] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_curveTo() {
        var pen = new TestPen();

        var expected = [ ['_curveToOne', [1, 1], [1, 1], [1, 1] ] ];
        pen.curveTo( [1, 1], [1, 1], [1, 1] );
        doh.assertEqual(expected, pen.flush());

        var expected = [ ['_curveToOne', [1, 2], [3, 4], [5, 6] ] ];
        pen.curveTo( [1, 2], [3, 4], [5, 6] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            [
                '_curveToOne',
                [1, 2],
                [2, 3],
                [3, 4]
            ],
            [
                '_curveToOne',
                [4, 5],
                [5, 6],
                [7, 8]
            ]
        ];
        pen.curveTo( [1, 2], [3, 4], [5, 6], [7, 8] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_lineTo', [0, 0] ],
            ['_curveToOne', [2, 2], [2, 2], [0, 0] ]
        ];
        pen.lineTo([0, 0]);
        pen.curveTo( [3, 3], [0, 0] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_curveToOne', [2, 2], [5, 5], [9, 9] ]
        ];
        pen.curveTo( [3, 3], [9, 9] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_lineTo', [123, 123] ]
        ];
        pen.curveTo( [123, 123] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_qCurveTo() {
        var pen = new TestPen();

        var expected = [
            ['_moveTo', [1, 1] ],
            ['_curveToOne', [1, 1], [1, 1], [1, 1]]
        ];
        pen.qCurveTo( [1, 1], null );
        doh.assertEqual(expected, pen.flush());

        // >>> tp = fontTools.pens.basePen._TestPen([])
        // >>> tp.qCurveTo( [35, 35], [70, 70], None )
        // 52.5 52.5 moveto
        // 40.8333333333 40.8333333333 40.8333333333 40.8333333333 52.5 52.5 curveto
        // 64.1666666667 64.1666666667 64.1666666667 64.1666666667 52.5 52.5 curveto
        var expected = [
            ['_moveTo', [52.5, 52.5] ],
            ['_curveToOne', [40.8333333,40.8333333], [40.8333333, 40.8333333], [52.5, 52.5]],
            ['_curveToOne', [64.1666667, 64.1666667], [64.1666667, 64.1666667], [52.5, 52.5]]
        ];

        pen.qCurveTo( [35, 35], [70, 70], null );
        var result = roundRecursive(pen.flush(), 10000000);
        doh.assertEqual(expected, result);

        var expected = [
            [ '_moveTo', [0, 0] ],
            ['_curveToOne', [23.3333333,23.3333333], [46.6666667, 46.6666667], [70, 70] ]
        ];
        pen.moveTo( [0, 0] );
        pen.qCurveTo( [35, 35], [70, 70] );
        var result = roundRecursive(pen.flush(), 10000000);
        doh.assertEqual(expected, result);

        var expected = [
            ['_lineTo', [1, 1] ]
        ];
        pen.qCurveTo( [1, 1] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_addComponent() {
        // There's currently no glyphset object and no glyph  objekt with
        // a draw method so here are some fakes for that stuff
        var testGlyph = {
            draw: function(pen)
            {
                pen.moveTo([1, 1]);
                pen.lineTo([2, 2]);
                pen.curveTo([3, 3], [4, 4], [5, 5]);
                pen.closePath();
            }
        },
        pen = new TestPen({'testglyph': testGlyph});

        doh.assertError(
            TypeError,
            pen, 'addComponent',
            ['testglyph'],
            'transformation is undefined'
        );

        var expected = [
            ['_moveTo', [1, 1] ],
            ['_lineTo', [2, 2] ],
            ['_curveToOne', [3, 3], [4, 4], [5, 5] ],
            ['_closePath']
        ];
        pen.addComponent('testglyph', transform.Identity);
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_moveTo', [-1, 1] ],
            ['_lineTo', [-2, 2] ],
            ['_curveToOne', [-3, 3], [-4, 4], [-5, 5] ],
            ['_closePath']
        ];
        pen.addComponent('testglyph', transform.Identity.rotate(Math.PI / 2));
        doh.assertEqual(expected, pen.flush());

        var expected = [];
        pen.addComponent('not_existing');
        doh.assertEqual(expected, pen.flush());

        var expected = [];
        pen.addComponent('not_existing', transform.Identity);
        doh.assertEqual(expected, pen.flush());
    }
    ]);
});
<commit_msg>Test for the inherited instance(s) of BasePen<commit_after>define(
    [
        'graphicore',
        'graphicore/errors',
        'graphicore/tools/misc/transform',
        'graphicore/tools/pens/AbstractPen',
        'graphicore/tools/pens/BasePen',
        'graphicore/tools/pens/testPens'
    ],
    function(graphicore, errors, transform, AbstractPen, BasePen, testPens)
{
    /*shortcuts*/
    var TestPen = testPens.BaseTestPen,
    /**
     * a little helper to round the results of the testpen. This is good
     * to overcome floating point rounding errors
     */
        roundRecursive = function(item, factor) {
        //currying the factor away
        var round = graphicore.round,
            roundRecursive = function(item) {
            if(item instanceof Array)
                return item.map(roundRecursive);
            if(typeof item === 'number')
                return round(item, factor);
            return item;
        }
        return roundRecursive(item);
    };

    doh.register("graphicore.pens.BasePen", [
    function Test_BasePen_inheritance() {
        var pen = new BasePen();
        doh.assertTrue(pen instanceof AbstractPen);
    },
    function Test_BasePen_Errors() {
        var pen = new BasePen();

        doh.assertError(
            errors.NotImplemented,
            pen, 'moveTo',
            [[1, 1]],
            '_moveTo is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'lineTo',
            [[1, 1]],
            '_lineTo is not implemented'
        );

        doh.assertError(
            errors.Assertion,
            pen, 'curveTo'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1,1]],
            '_lineto is not implemented'
        );

        doh.assertError(
            TypeError,
            pen, 'curveTo',
            [[1, 1], [1, 1]],
            '_qCurveToOne is called and wants to access __curentPoint as a List'
        );

        doh.assertError(
            TypeError,
            pen, 'qCurveTo',
            [[1, 1], [1, 1]],
            '_qCurveToOne is called and wants to access __curentPoint as a List'
        );

        //faking this in
        pen.__currentPoint = [1, 1];

        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );
        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1, 1], [1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'curveTo',
            [[1, 1], [1, 1], [1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );

        doh.assertError(
            errors.Assertion,
            pen, 'qCurveTo'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'qCurveTo',
            [[1, 1]],
            '_lineTo is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'qCurveTo',
            [[1, 1], [1, 1]],
            '_curveToOne is not implemented'
        );

        doh.assertError(
            errors.NotImplemented,
            pen, 'qCurveTo',
            [[1, 1], null],
            '_moveTo is not implemented'
        );

        doh.assertError(
            TypeError,
            pen, 'addComponent'
            ['test'],
            'there is no glyphset'
        );
    },
    function Test_BasePen_closePath() {
        var pen = new TestPen();

        var expected = ['_closePath'];
        pen.closePath();
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_endPath() {
        var pen = new TestPen([]);

        var expected = ['_endPath'];
        pen.endPath();
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_lineTo() {
        var pen = new TestPen();

        var expected = [ ['_lineTo', [1, 2] ] ];
        pen.lineTo( [1, 2] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_moveTo() {
        var pen = new TestPen();

        var expected = [ ['_moveTo', [1, 2] ] ];
        pen.moveTo( [1, 2] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_curveTo() {
        var pen = new TestPen();

        var expected = [ ['_curveToOne', [1, 1], [1, 1], [1, 1] ] ];
        pen.curveTo( [1, 1], [1, 1], [1, 1] );
        doh.assertEqual(expected, pen.flush());

        var expected = [ ['_curveToOne', [1, 2], [3, 4], [5, 6] ] ];
        pen.curveTo( [1, 2], [3, 4], [5, 6] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            [
                '_curveToOne',
                [1, 2],
                [2, 3],
                [3, 4]
            ],
            [
                '_curveToOne',
                [4, 5],
                [5, 6],
                [7, 8]
            ]
        ];
        pen.curveTo( [1, 2], [3, 4], [5, 6], [7, 8] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_lineTo', [0, 0] ],
            ['_curveToOne', [2, 2], [2, 2], [0, 0] ]
        ];
        pen.lineTo([0, 0]);
        pen.curveTo( [3, 3], [0, 0] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_curveToOne', [2, 2], [5, 5], [9, 9] ]
        ];
        pen.curveTo( [3, 3], [9, 9] );
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_lineTo', [123, 123] ]
        ];
        pen.curveTo( [123, 123] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_qCurveTo() {
        var pen = new TestPen();

        var expected = [
            ['_moveTo', [1, 1] ],
            ['_curveToOne', [1, 1], [1, 1], [1, 1]]
        ];
        pen.qCurveTo( [1, 1], null );
        doh.assertEqual(expected, pen.flush());

        // >>> tp = fontTools.pens.basePen._TestPen([])
        // >>> tp.qCurveTo( [35, 35], [70, 70], None )
        // 52.5 52.5 moveto
        // 40.8333333333 40.8333333333 40.8333333333 40.8333333333 52.5 52.5 curveto
        // 64.1666666667 64.1666666667 64.1666666667 64.1666666667 52.5 52.5 curveto
        var expected = [
            ['_moveTo', [52.5, 52.5] ],
            ['_curveToOne', [40.8333333,40.8333333], [40.8333333, 40.8333333], [52.5, 52.5]],
            ['_curveToOne', [64.1666667, 64.1666667], [64.1666667, 64.1666667], [52.5, 52.5]]
        ];

        pen.qCurveTo( [35, 35], [70, 70], null );
        var result = roundRecursive(pen.flush(), 10000000);
        doh.assertEqual(expected, result);

        var expected = [
            [ '_moveTo', [0, 0] ],
            ['_curveToOne', [23.3333333,23.3333333], [46.6666667, 46.6666667], [70, 70] ]
        ];
        pen.moveTo( [0, 0] );
        pen.qCurveTo( [35, 35], [70, 70] );
        var result = roundRecursive(pen.flush(), 10000000);
        doh.assertEqual(expected, result);

        var expected = [
            ['_lineTo', [1, 1] ]
        ];
        pen.qCurveTo( [1, 1] );
        doh.assertEqual(expected, pen.flush());
    },
    function Test_BasePen_addComponent() {
        // There's currently no glyphset object and no glyph  objekt with
        // a draw method so here are some fakes for that stuff
        var testGlyph = {
            draw: function(pen)
            {
                pen.moveTo([1, 1]);
                pen.lineTo([2, 2]);
                pen.curveTo([3, 3], [4, 4], [5, 5]);
                pen.closePath();
            }
        },
        pen = new TestPen({'testglyph': testGlyph});

        doh.assertError(
            TypeError,
            pen, 'addComponent',
            ['testglyph'],
            'transformation is undefined'
        );

        var expected = [
            ['_moveTo', [1, 1] ],
            ['_lineTo', [2, 2] ],
            ['_curveToOne', [3, 3], [4, 4], [5, 5] ],
            ['_closePath']
        ];
        pen.addComponent('testglyph', transform.Identity);
        doh.assertEqual(expected, pen.flush());

        var expected = [
            ['_moveTo', [-1, 1] ],
            ['_lineTo', [-2, 2] ],
            ['_curveToOne', [-3, 3], [-4, 4], [-5, 5] ],
            ['_closePath']
        ];
        pen.addComponent('testglyph', transform.Identity.rotate(Math.PI / 2));
        doh.assertEqual(expected, pen.flush());

        var expected = [];
        pen.addComponent('not_existing');
        doh.assertEqual(expected, pen.flush());

        var expected = [];
        pen.addComponent('not_existing', transform.Identity);
        doh.assertEqual(expected, pen.flush());
    }
    ]);
});
<|endoftext|>