<commit_before>exports.CloudFilesEndpoint = function(storageUrl, mgmtUrl, token) {
	var https = require('https');
	var url = require('url');
	var rackapi = require('../lib/api.js');

	this.token = token;
	this.storageUrl = url.parse(storageUrl);
	debugger;
	this.mgmtUrl = (mgmtUrl === null ? null : url.parse(mgmtUrl));

	this.reqOpts = {
		port : 443,
		headers : {
			"X-Auth-Token" : this.token
		}
	};

	this.accountDetails = function(callback) {
		var o = rackapi.clone(this.reqOpts);
		o.method = "HEAD";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.containers = function(params, callback) {
		// Force JSON where possible
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "GET";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.containerDetails = function(name, callback) {
		var o = rackapi.clone(this.reqOpts);
		o.method = "HEAD"; o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.createContainer = function(name, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "PUT";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.deleteContainer = function(name, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "DELETE";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.setContainerMetadata = function(name, data, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "POST";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		for (var key in data) {
			o.headers['X-Container-Meta-' + key] = data[key];
		}

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.containerList = function(name, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "GET";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.get = function(container, object, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "GET";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + container + "/" + object + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.put = function(container, object, data, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "PUT";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + container + "/" + object + params;

		rackapi.callApi(o, data, function(res) {
			callback(res);
		});
	};

	this.copy = function(container, from, to, params, callback) {

	};

};
<commit_msg>Cloud Files storage services complete.<commit_after>exports.CloudFilesEndpoint = function(storageUrl, mgmtUrl, token) {
	var https = require('https');
	var url = require('url');
	var rackapi = require('../lib/api.js');

	this.token = token;
	this.storageUrl = url.parse(storageUrl);
	debugger;
	this.mgmtUrl = (mgmtUrl === null ? null : url.parse(mgmtUrl));

	this.reqOpts = {
		port : 443,
		headers : {
			"X-Auth-Token" : this.token
		}
	};

	this.accountDetails = function(callback) {
		var o = rackapi.clone(this.reqOpts);
		o.method = "HEAD";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.containers = function(params, callback) {
		// Force JSON where possible
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "GET";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.containerDetails = function(name, callback) {
		var o = rackapi.clone(this.reqOpts);
		o.method = "HEAD"; o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.createContainer = function(name, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "PUT";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.deleteContainer = function(name, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "DELETE";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.setContainerMetadata = function(name, data, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "POST";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		for (var key in data) {
			o.headers['X-Container-Meta-' + key] = data[key];
		}

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.containerList = function(name, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "GET";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + name + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.get = function(container, object, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "GET";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + container + "/" + object + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.put = function(container, object, data, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "PUT";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + container + "/" + object + params;

		rackapi.callApi(o, data, function(res) {
			callback(res);
		});
	};

	this.copy = function(from, to, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "PUT";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + to + params;
		o.headers['X-Copy-From'] = "/" + from;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.delete = function(container, object, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "DELETE";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + container + "/" + object + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.objectDetails = function(container, object, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "HEAD";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + container + "/" + object + params;

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

	this.setObjectMetadata = function(container, object, data, params, callback) {
		params = (params ? params : {format:'json'});
		if (params.format != 'xml') {
			params.format = 'json';
		}
		params = (typeof params === "object" ? rackapi.serializeQueryString(params) : "");

		var o = rackapi.clone(this.reqOpts);
		o.method = "POST";
		o.hostname = this.storageUrl.hostname;
		o.path = this.storageUrl.path + "/" + container + "/" + object + params;

		for (var key in data) {
			o.headers['X-Object-Meta-' + key] = data[key];
		}

		rackapi.callApi(o, null, function(res) {
			callback(res);
		});
	};

};
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var should = require('should');
var fs = require('fs');
var app = require('../');
var Person, person1, urls;
var profiles = [];

mongoose.connect('localhost', 'mongoose_fulltongo');

describe('plugin', function() {

  before(function(done) {
    mongoose.connection.on('open', function() {
      for (var i in mongoose.connection.collections) {
        mongoose.connection.collections[i].remove(function() {});
      }
      return done();
    });
  });

  describe('indexing tests', function() {
    var schema, Profile
    before(function(done) {
      schema = new Schema({
        name: { first: String, last: String},
        email: [String]
      });

      Profile = mongoose.model('Profile', schema);

      data = fs.readFileSync(__dirname + '/data', 'utf8').split('\n')
      var stopAt = data.length-1;
      data.forEach(function(dp) {
        var dataFields = dp.split(' ');
        if(dataFields.length === 3) {
          var p = new Profile({name: {last: dataFields[1], first: dataFields[0]}, email: dataFields[2]});
          p.save(function(err, p) {
            should.not.exist(err);
            profiles.push(p);
            if(--stopAt === 0) {
              /*
              var opts = {};
              opts.fields = ['name.first', 'name.last', 'email'];

              schema.plugin(app, opts);
              */

              return done();
            }
          })
        }
      });
    })

    it('should index all', function(done) {
      delete mongoose.connection.models['Profile'];
      schema = new Schema({
        name: { first: String, last: String},
        email: [String]
      });

      var opts = {};
      opts.fields = ['name.first', 'name.last', 'email'];
      schema.plugin(app, opts);
      Profile = mongoose.model('Profile', schema);

      Profile.indexAll(function(err, result) {
        Profile.find({}, function(err, items) {
          items.forEach(function(p) {
            p._keywords.length.should.eql(5);
          })
          done();
        })
      })
    })
  })

  describe('general tests', function() {
    before(function (done) {
      var schema = new Schema({
        name: { first: String, last: String},
        email: [String]
      });

      var opts = {};
      opts.fields = ['name.first', 'name.last', 'email'];

      schema.plugin(app, opts);

      Person = mongoose.model('Person', schema);
      for (var i in mongoose.connection.collections) {
        mongoose.connection.collections[i].remove(function() {});
      }
      done();
    });

    it('should create a _keywords property', function(done) {
      should.exist(Person.schema.paths._keywords);
      done();
    })

    it('should have an indexAll static method', function(done) {
      should.exist(Person.schema.statics.indexAll);
      done();
    });

    it('should have an search static method', function(done) {
      should.exist(Person.schema.statics.search);
      done();
    });

    it('should populate the keywords for name', function(done) {
      var p = new Person({name: {last: 'foo', first: 'bar'}, email: 'foo@example.com'});
      p.updateIndex();
      p._keywords.length.should.eql(4);
      p.save(function(err, p) {
        should.not.exist(err);
        person1 = p;
        done();
      })
    })

    it('should search for foo', function(done) {
      Person.search('foo hound', function(err, items) {
        should.not.exist(err);
        items.length.should.eql(1);
        done();
      });
    })

  })

  after(function(){
    mongoose.connection.close()
  })
})<commit_msg>cruft<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var should = require('should');
var fs = require('fs');
var app = require('../');
var Person, person1, urls;
var profiles = [];

mongoose.connect('localhost', 'mongoose_fulltongo');

describe('plugin', function() {

  before(function(done) {
    mongoose.connection.on('open', function() {
      for (var i in mongoose.connection.collections) {
        mongoose.connection.collections[i].remove(function() {});
      }
      return done();
    });
  });

  describe('indexing tests', function() {
    var schema, Profile
    before(function(done) {
      schema = new Schema({
        name: { first: String, last: String},
        email: [String]
      });

      Profile = mongoose.model('Profile', schema);

      data = fs.readFileSync(__dirname + '/data', 'utf8').split('\n')
      var stopAt = data.length-1;
      data.forEach(function(dp) {
        var dataFields = dp.split(' ');
        if(dataFields.length === 3) {
          var p = new Profile({name: {last: dataFields[1], first: dataFields[0]}, email: dataFields[2]});
          p.save(function(err, p) {
            should.not.exist(err);
            profiles.push(p);
            if(--stopAt === 0) {
              return done();
            }
          })
        }
      });
    })

    it('should index all', function(done) {
      delete mongoose.connection.models['Profile'];
      schema = new Schema({
        name: { first: String, last: String},
        email: [String]
      });

      var opts = {};
      opts.fields = ['name.first', 'name.last', 'email'];
      schema.plugin(app, opts);
      Profile = mongoose.model('Profile', schema);

      Profile.indexAll(function(err, result) {
        Profile.find({}, function(err, items) {
          items.forEach(function(p) {
            p._keywords.length.should.eql(5);
          })
          done();
        })
      })
    })
  })

  describe('general tests', function() {
    before(function (done) {
      var schema = new Schema({
        name: { first: String, last: String},
        email: [String]
      });

      var opts = {};
      opts.fields = ['name.first', 'name.last', 'email'];

      schema.plugin(app, opts);

      Person = mongoose.model('Person', schema);
      for (var i in mongoose.connection.collections) {
        mongoose.connection.collections[i].remove(function() {});
      }
      done();
    });

    it('should create a _keywords property', function(done) {
      should.exist(Person.schema.paths._keywords);
      done();
    })

    it('should have an indexAll static method', function(done) {
      should.exist(Person.schema.statics.indexAll);
      done();
    });

    it('should have an search static method', function(done) {
      should.exist(Person.schema.statics.search);
      done();
    });

    it('should populate the keywords for name', function(done) {
      var p = new Person({name: {last: 'foo', first: 'bar'}, email: 'foo@example.com'});
      p.updateIndex();
      p._keywords.length.should.eql(4);
      p.save(function(err, p) {
        should.not.exist(err);
        person1 = p;
        done();
      })
    })

    it('should search for foo', function(done) {
      Person.search('foo hound', function(err, items) {
        should.not.exist(err);
        items.length.should.eql(1);
        done();
      });
    })

  })

  after(function(){
    mongoose.connection.close()
  })
})<|endoftext|>


<commit_before>'use strict';

angular
		.module('ActivityLogger')
		.controller(
				'SummaryCtrl',
				function($scope, $window, Activity, SummaryService) {

					$scope.period_slider = 42;
					this.period_slider = 42;

					$scope.bestPerfs = SummaryService.getBestPerformances(-1);

					$scope.overallPerfs = SummaryService
							.getOverallPerformances(-1);

					$scope.avgPerfs = SummaryService.getAveragePerformances(-1);

					/**
					 *
					 */
					$scope.update = function() {
						var p = getPeriod(this.period_slider);
						$scope.bestPerfs = SummaryService
								.getBestPerformances(p);
						$scope.overallPerfs = SummaryService
								.getOverallPerformances(p);
						$scope.avgPerfs = SummaryService
								.getAveragePerformances(p);
						$scope.showDisciplineDistributionChart(p);
					}
					/**
					 *
					 */
					$scope.showWeekCharts = function() {
						var weekdays = [ "MO", "DI", "MI", "DO", "FR", "SA",
								"SO" ];
						// rotate weekdays
						var day = new Date().getDay();
						weekdays = weekdays.slice(day).concat(
								weekdays.slice(0, day))

						// draw times chart
						var data_time = SummaryService.getDurations(7);
						drawLineChart(weekdays, data_time, "chart_times_week");

						// draw distance chart
						var data_dist = SummaryService.getDistances(7);
						drawLineChart(weekdays, data_dist, "chart_dist_week");

						// draw calories chart
						var data_kcal = SummaryService.getCalories(7);
						drawLineChart(weekdays, data_kcal, "chart_kcal_week");
					};

					/**
					 *
					 */
					$scope.showMonthCharts = function() {
						var days = [ "1", "2", "3", "4", "5", "6", "7", "8",
								"9", "10", "11", "12", "13", "14", "15", "16",
								"17", "18", "19", "20", "21", "22", "23", "24",
								"25", "26", "27", "28", "29", "30" ];

						// draw times chart
						var data_time = SummaryService.getDurations(30);
						drawLineChart(days, data_time, "chart_times_month");

						// draw distance chart
						var data_dist = SummaryService.getDistances(30);
						drawLineChart(days, data_dist, "chart_dist_month");

						// draw calories chart
						var data_kcal = SummaryService.getCalories(30);
						drawLineChart(days, data_kcal, "chart_kcal_month");

					};

					/**
					 *
					 */
					$scope.showYearCharts = function() {
						var days = [ "", "", "", "", "", "", "", "", "", "10",
								"", "", "", "", "", "", "", "", "", "20", "",
								"", "", "", "", "", "", "", "", "30", "", "",
								"", "", "", "", "", "", "", "40", "", "", "",
								"", "", "", "", "", "", "50", "", "" ];

						// draw times chart
						var data_time = SummaryService.getDurations(364);
						drawLineChart(days, summarize(data_time, 7),
								"chart_times_year");

						// draw distance chart
						var data_dist = SummaryService.getDistances(364);
						drawLineChart(days, summarize(data_dist, 7),
								"chart_dist_year");

						// draw calories chart
						var data_kcal = SummaryService.getCalories(364);
						drawLineChart(days, summarize(data_kcal, 7),
								"chart_kcal_year");
					};

					/**
					 *
					 */
					$scope.showDisciplineDistributionChart = function(period) {
						var durations = SummaryService
								.getDurationOfAllDisciplines(period);
						var labels = [];
						var values = [];

						var i;
						for (i in durations) {
							labels.push(durations[i].discipline);
							values.push(Math.floor(durations[i].duration / 60 / 60));
						}
						return drawPieChart(labels, values,
								"chart_discipline_distribution");
					}

					/**
					 *
					 */
					var getPeriod = function(slider_value) {
						if (slider_value < 30) {
							return slider_value * 60 * 60 * 24;
						}
						if (slider_value < 42) {
							return (slider_value - 29) * 60 * 60 * 24 * 7 * 30;
						}
						return -1;
					}

					$scope.getPeriodText = function(slider_value) {
						var period = getPeriod(slider_value);
						if (period == -1) {
							return "Gesamter Zeitraum";
						}
						if (period % (60 * 60 * 24 * 7 * 30) == 0) {
							return "letzte " + period / (60 * 60 * 24 * 7 * 30)
									+ " Monate";
						}
						if (period % (60 * 60 * 24 * 7) == 0) {
							return "letzte " + period / (60 * 60 * 24 * 7)
									+ " Wochen";
						}
						if (period % (60 * 60 * 24) == 0) {
							return "letzte " + period / (60 * 60 * 24)
									+ " Tage";
						}
					}

					/**
					 *
					 */
					var drawLineChart = function(labels, data, canvas_id) {
						var chart = {
							labels : labels,
							datasets : [ {
								label : "",
								fillColor : "rgba(220,220,220,0.2)",
								strokeColor : "rgba(220,220,220,1)",
								pointColor : "rgba(220,220,220,1)",
								pointStrokeColor : "#fff",
								pointHighlightFill : "#fff",
								pointHighlightStroke : "rgba(220,220,220,1)",
								data : data
							} ]
						};
						var ctx = document.getElementById(canvas_id)
								.getContext("2d");
						$window.chart = new Chart(ctx).Line(chart, {
							showTooltips : false,
							dataSetStroke : false,
							pointDot : false,
							responsive : true
						});
					};

					/**
					 *
					 */
					var drawPieChart = function(labels, data, canvas_id) {
						var colors = [ "#F44336", "#2196F3", "#FFEB3B",
								"#795548", "#009688", "#9C27B0", "#4CAF50" ];
						var chart = [];
						var i;
						for (i = 0; i < data.length; i++) {
							chart.push({
								value : data[i],
								color : colors[i],
								highlight : colors[i],
								label : labels[i]
							});
						}

						var ctx = document.getElementById(canvas_id)
								.getContext("2d");
						$window.chart = new Chart(ctx).Doughnut(chart, {
							responsive : true
						});
						return chart;
					};

					/**
					 *
					 */
					var summarize = function(data, step) {
						var summarized_data = [];
						var i;
						var j;
						for (i = 0; i < data.length; i += step) {
							var val = 0;
							for (j = 0; j < step; j++) {
								val += data[i + j];
							}
							summarized_data.push(val);
						}
						return summarized_data;
					};

					$scope.disciplineDistributionLegend = $scope
							.showDisciplineDistributionChart(-1);

				});
<commit_msg>fixed bug.<commit_after>'use strict';

angular
		.module('ActivityLogger')
		.controller(
				'SummaryCtrl',
				function($scope, $window, Activity, SummaryService) {

					$scope.period_slider = 42;
					this.period_slider = 42;

					$scope.bestPerfs = SummaryService.getBestPerformances(-1);

					$scope.overallPerfs = SummaryService
							.getOverallPerformances(-1);

					$scope.avgPerfs = SummaryService.getAveragePerformances(-1);

					/**
					 *
					 */
					$scope.update = function() {
						var p = getPeriod(this.period_slider);
						$scope.bestPerfs = SummaryService
								.getBestPerformances(p);
						$scope.overallPerfs = SummaryService
								.getOverallPerformances(p);
						$scope.avgPerfs = SummaryService
								.getAveragePerformances(p);
						$scope.disciplineDistributionLegend = $scope
								.showDisciplineDistributionChart(p);
					}
					/**
					 *
					 */
					$scope.showWeekCharts = function() {
						var weekdays = [ "MO", "DI", "MI", "DO", "FR", "SA",
								"SO" ];
						// rotate weekdays
						var day = new Date().getDay();
						weekdays = weekdays.slice(day).concat(
								weekdays.slice(0, day))

						// draw times chart
						var data_time = SummaryService.getDurations(7);
						drawLineChart(weekdays, data_time, "chart_times_week");

						// draw distance chart
						var data_dist = SummaryService.getDistances(7);
						drawLineChart(weekdays, data_dist, "chart_dist_week");

						// draw calories chart
						var data_kcal = SummaryService.getCalories(7);
						drawLineChart(weekdays, data_kcal, "chart_kcal_week");
					};

					/**
					 *
					 */
					$scope.showMonthCharts = function() {
						var days = [ "1", "2", "3", "4", "5", "6", "7", "8",
								"9", "10", "11", "12", "13", "14", "15", "16",
								"17", "18", "19", "20", "21", "22", "23", "24",
								"25", "26", "27", "28", "29", "30" ];

						// draw times chart
						var data_time = SummaryService.getDurations(30);
						drawLineChart(days, data_time, "chart_times_month");

						// draw distance chart
						var data_dist = SummaryService.getDistances(30);
						drawLineChart(days, data_dist, "chart_dist_month");

						// draw calories chart
						var data_kcal = SummaryService.getCalories(30);
						drawLineChart(days, data_kcal, "chart_kcal_month");

					};

					/**
					 *
					 */
					$scope.showYearCharts = function() {
						var days = [ "", "", "", "", "", "", "", "", "", "10",
								"", "", "", "", "", "", "", "", "", "20", "",
								"", "", "", "", "", "", "", "", "30", "", "",
								"", "", "", "", "", "", "", "40", "", "", "",
								"", "", "", "", "", "", "50", "", "" ];

						// draw times chart
						var data_time = SummaryService.getDurations(364);
						drawLineChart(days, summarize(data_time, 7),
								"chart_times_year");

						// draw distance chart
						var data_dist = SummaryService.getDistances(364);
						drawLineChart(days, summarize(data_dist, 7),
								"chart_dist_year");

						// draw calories chart
						var data_kcal = SummaryService.getCalories(364);
						drawLineChart(days, summarize(data_kcal, 7),
								"chart_kcal_year");
					};

					/**
					 *
					 */
					$scope.showDisciplineDistributionChart = function(period) {
						var durations = SummaryService
								.getDurationOfAllDisciplines(period);
						var labels = [];
						var values = [];

						var i;
						for (i in durations) {
							labels.push(durations[i].discipline);
							values.push(Math
									.floor(durations[i].duration / 60 / 60));
						}
						return drawPieChart(labels, values,
								"chart_discipline_distribution");
					}

					/**
					 *
					 */
					var getPeriod = function(slider_value) {
						if (slider_value < 30) {
							return slider_value * 60 * 60 * 24;
						}
						if (slider_value < 42) {
							return (slider_value - 29) * 60 * 60 * 24 * 7 * 30;
						}
						return -1;
					}

					$scope.getPeriodText = function(slider_value) {
						var period = getPeriod(slider_value);
						if (period == -1) {
							return "Gesamter Zeitraum";
						}
						if (period % (60 * 60 * 24 * 7 * 30) == 0) {
							return "letzte " + period / (60 * 60 * 24 * 7 * 30)
									+ " Monate";
						}
						if (period % (60 * 60 * 24 * 7) == 0) {
							return "letzte " + period / (60 * 60 * 24 * 7)
									+ " Wochen";
						}
						if (period % (60 * 60 * 24) == 0) {
							return "letzte " + period / (60 * 60 * 24)
									+ " Tage";
						}
					}

					/**
					 *
					 */
					var drawLineChart = function(labels, data, canvas_id) {
						var chart = {
							labels : labels,
							datasets : [ {
								label : "",
								fillColor : "rgba(220,220,220,0.2)",
								strokeColor : "rgba(220,220,220,1)",
								pointColor : "rgba(220,220,220,1)",
								pointStrokeColor : "#fff",
								pointHighlightFill : "#fff",
								pointHighlightStroke : "rgba(220,220,220,1)",
								data : data
							} ]
						};
						var ctx = document.getElementById(canvas_id)
								.getContext("2d");
						$window.chart = new Chart(ctx).Line(chart, {
							showTooltips : false,
							dataSetStroke : false,
							pointDot : false,
							responsive : true
						});
					};

					/**
					 *
					 */
					var drawPieChart = function(labels, data, canvas_id) {
						var colors = [ "#F44336", "#2196F3", "#FFEB3B",
								"#795548", "#009688", "#9C27B0", "#4CAF50" ];
						var chart = [];
						var i;
						for (i = 0; i < data.length; i++) {
							chart.push({
								value : data[i],
								color : colors[i],
								highlight : colors[i],
								label : labels[i]
							});
						}

						var ctx = document.getElementById(canvas_id)
								.getContext("2d");
						$window.chart = new Chart(ctx).Doughnut(chart, {
							responsive : true
						});
						return chart;
					};

					/**
					 *
					 */
					var summarize = function(data, step) {
						var summarized_data = [];
						var i;
						var j;
						for (i = 0; i < data.length; i += step) {
							var val = 0;
							for (j = 0; j < step; j++) {
								val += data[i + j];
							}
							summarized_data.push(val);
						}
						return summarized_data;
					};

					$scope.disciplineDistributionLegend = $scope
							.showDisciplineDistributionChart(-1);

				});
<|endoftext|>


<commit_before>var __ = require('underscore'),
    Backbone = require('backbone'),
    $ = require('jquery'),
    messageModal = require('../utils/messageModal.js');

module.exports = function(form, modelJSON, endPoint, onSucceed, onFail, addData, skipKeys, onInvalid) {
  // TODO: obtain optional arguments via an options object with it being the last argument. This would
  // prevent the user having to put a bunch of nulls if they only want to pass in one of the last
  // optional args.

  /* form[optional]: the form to pull data from, as a jQuery object
     modelJSON[optional]: model data in JSON format, any data not overwritten by the form will be added to the formData
     endPoint: the API endpoint, in string format, such as "settings"
     onSucceed[optional]: a function to run on success
     onFail[optional]: a function to run on failure
     addData[optional]: insert this data into the formData object, must be an object
     skipKeys[optional]: keys to skip, and not send to the server
   */
  var self = this,
      formData,
      formKeys = [],
      tempDisabledFields = [];

  skipKeys = skipKeys || [];

  if(form){
    form.addClass('formChecked');
    if (!form[0].checkValidity()){
      if(typeof onInvalid === 'function'){
        onInvalid();
      } else {
        messageModal.show(window.polyglot.t('errorMessages.saveError'), window.polyglot.t('errorMessages.missingError'));
      }
      return $.Deferred().reject('failed form validation').promise();
    }

    /*
    //temporarily disable any blank fields so they aren't picked up by the serializeArray
    form.find(":input:not(:disabled)").each(function(){
      if($(this).val() == "") {
        $(this).attr('disabled', true);
        tempDisabledFields.push($(this).attr('name'));
      }
    });
    */

    //temporarily disable any form fields overriden by manual data so they aren't double submitted
    __.each(addData, function(value, key) {
      var disInp = form.find('input[name="'+key+'"]');
      disInp.attr('disabled', true);
      tempDisabledFields.push(disInp.attr('name'));
    });

    __.each(form.serializeArray(), function (value) {
      formKeys.push(value.name);
    });
  }

  //after disabling blank fields, populate the formData
  formData = new FormData((form && form[0]) || "");

  //add manual data not in the form
  __.each(addData, function(value, key){
    formKeys.push(key);
    if(value.constructor === Array){
      __.each(value, function(val){
        formData.append(key, val);
      });
      if(value.length == 0){
        formData.append(key, "");
      }
    }else{
      formData.append(key, value);
    }
  });

  //if key is not in formKeys, get value from the model
  if(modelJSON){
    __.each(modelJSON, function (value, key) {
      if (formKeys.indexOf(key) == -1 && skipKeys.indexOf(key) == -1){
        if(value && value.constructor === Array && key != "shipping_addresses" && key != "moderators"){
          __.each(value, function (val) {
            formData.append(key, val);
          });
          if (value.length == 0){
            formData.append(key, "");
          }
        } else if(key == "shipping_addresses") {
          __.each(value, function(val) {
            formData.append(key, JSON.stringify(val));
          });
          if (value.length == 0) {
            formData.append(key, "");
          }
        } else if(key == "moderators") {
          __.each(value, function(val){
            formData.append(key, val.guid);
          });
          //insert blank if there are no moderators
          if(value.length == 0){
            formData.append(key, "");
          }
        } else{
          formData.append(key, value);
        }
      }
    });
  }

  return $.ajax({
    type: "POST",
    url: endPoint,
    contentType: false,
    processData: false,
    data: formData,
    dataType: "json",
    success: function(data) {
      if (data.success === true){
        typeof onSucceed === 'function' && onSucceed(data);
      }else if (data.success === false){
        if(onFail){
          onFail(data);
        } else{
          messageModal.show(window.polyglot.t('errorMessages.saveError'), "" + data.reason + "");
        }
      } else {
        messageModal.show(window.polyglot.t('errorMessages.saveError'), "" + window.polyglot.t('errorMessages.serverError') + "");
      }
    },
    error: function(jqXHR, status, errorThrown){
      console.log(jqXHR);
      console.log(status);
      console.log(errorThrown);
    },
    complete: function(){
      /*
      //re-enable any disabled fields
      __.each(tempDisabledFields, function(element){
        form.find('input[name="'+element+'"]').attr('disabled', false);
      });
      */
    }
  });
};<commit_msg>de-comment re-enabling of disabled fields<commit_after>var __ = require('underscore'),
    Backbone = require('backbone'),
    $ = require('jquery'),
    messageModal = require('../utils/messageModal.js');

module.exports = function(form, modelJSON, endPoint, onSucceed, onFail, addData, skipKeys, onInvalid) {
  // TODO: obtain optional arguments via an options object with it being the last argument. This would
  // prevent the user having to put a bunch of nulls if they only want to pass in one of the last
  // optional args.

  /* form[optional]: the form to pull data from, as a jQuery object
     modelJSON[optional]: model data in JSON format, any data not overwritten by the form will be added to the formData
     endPoint: the API endpoint, in string format, such as "settings"
     onSucceed[optional]: a function to run on success
     onFail[optional]: a function to run on failure
     addData[optional]: insert this data into the formData object, must be an object
     skipKeys[optional]: keys to skip, and not send to the server
   */
  var self = this,
      formData,
      formKeys = [],
      tempDisabledFields = [];

  skipKeys = skipKeys || [];

  if(form){
    form.addClass('formChecked');
    if (!form[0].checkValidity()){
      if(typeof onInvalid === 'function'){
        onInvalid();
      } else {
        messageModal.show(window.polyglot.t('errorMessages.saveError'), window.polyglot.t('errorMessages.missingError'));
      }
      return $.Deferred().reject('failed form validation').promise();
    }

    /*
    //temporarily disable any blank fields so they aren't picked up by the serializeArray
    form.find(":input:not(:disabled)").each(function(){
      if($(this).val() == "") {
        $(this).attr('disabled', true);
        tempDisabledFields.push($(this).attr('name'));
      }
    });
    */

    //temporarily disable any form fields overriden by manual data so they aren't double submitted
    __.each(addData, function(value, key) {
      var disInp = form.find('input[name="'+key+'"]');
      disInp.attr('disabled', true);
      tempDisabledFields.push(disInp.attr('name'));
    });

    __.each(form.serializeArray(), function (value) {
      formKeys.push(value.name);
    });
  }

  //after disabling blank fields, populate the formData
  formData = new FormData((form && form[0]) || "");

  //add manual data not in the form
  __.each(addData, function(value, key){
    formKeys.push(key);
    if(value.constructor === Array){
      __.each(value, function(val){
        formData.append(key, val);
      });
      if(value.length == 0){
        formData.append(key, "");
      }
    }else{
      formData.append(key, value);
    }
  });

  //if key is not in formKeys, get value from the model
  if(modelJSON){
    __.each(modelJSON, function (value, key) {
      if (formKeys.indexOf(key) == -1 && skipKeys.indexOf(key) == -1){
        if(value && value.constructor === Array && key != "shipping_addresses" && key != "moderators"){
          __.each(value, function (val) {
            formData.append(key, val);
          });
          if (value.length == 0){
            formData.append(key, "");
          }
        } else if(key == "shipping_addresses") {
          __.each(value, function(val) {
            formData.append(key, JSON.stringify(val));
          });
          if (value.length == 0) {
            formData.append(key, "");
          }
        } else if(key == "moderators") {
          __.each(value, function(val){
            formData.append(key, val.guid);
          });
          //insert blank if there are no moderators
          if(value.length == 0){
            formData.append(key, "");
          }
        } else{
          formData.append(key, value);
        }
      }
    });
  }

  return $.ajax({
    type: "POST",
    url: endPoint,
    contentType: false,
    processData: false,
    data: formData,
    dataType: "json",
    success: function(data) {
      if (data.success === true){
        typeof onSucceed === 'function' && onSucceed(data);
      }else if (data.success === false){
        if(onFail){
          onFail(data);
        } else{
          messageModal.show(window.polyglot.t('errorMessages.saveError'), "" + data.reason + "");
        }
      } else {
        messageModal.show(window.polyglot.t('errorMessages.saveError'), "" + window.polyglot.t('errorMessages.serverError') + "");
      }
    },
    error: function(jqXHR, status, errorThrown){
      console.log(jqXHR);
      console.log(status);
      console.log(errorThrown);
    },
    complete: function(){
      //re-enable any disabled fields
      __.each(tempDisabledFields, function(element){
        form.find('input[name="'+element+'"]').attr('disabled', false);
      });
    }
  });
};<|endoftext|>


<commit_before>
var assert = require('assert');
var carto = require('../lib/carto');
describe('RenderingJS', function() {
  var shader;
  var style = [
  '#world {',
    'line-width: 2;',
    'line-color: #f00;',
    '[frame-offset = 1] {',
      'line-width: 3;',
    '}',
    '[frame-offset = 2] {',
      'line-width: 3;',
    '}',
  '}',
  '',
  '#worls[frame-offset = 10] {',
      'line-width: 4;',
  '}'
  ].join('\n');

  beforeEach(function() {
    shader = (new carto.RendererJS({ debug: false })).render(style);
  });

  it ("shold render layers", function() {
    assert(shader.getLayers().length === 2);
  });

  it ("shold report frames used in the layer", function() {
    var layer = shader.getLayers()[0];
    assert( layer.frames()[0] === 0);
    assert( layer.frames()[1] === 1);

    layer = shader.getLayers()[1];
    assert( layer.frames()[0] === 10);
  });

  it ("shold render with frames var", function() {
    var layer = shader.getLayers()[1];
    var props = layer.getStyle({}, { 'zoom': 0, 'frame-offset': 10 });
    assert( props['line-width'] === 4);
  });

  it ("shold render variables", function() {
    var style = '#test { marker-width: [testing]; }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({testing: 2}, { 'zoom': 0, 'frame-offset': 10 });
    assert( props['marker-width'] === 2);
  });

  it ("should allow filter based rendering", function() {
    var style = '#test { marker-width: 10; [zoom = 1] { marker-width: 1; } }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({}, { 'zoom': 0, 'frame-offset': 10 });
    assert( props['marker-width'] ===  10);
    props = layer.getStyle({}, { 'zoom': 1, 'frame-offset': 10 });
    assert( props['marker-width'] ===  1);
  });

  it ("symbolizers should be in rendering order", function() {
    var style = '#test { polygon-fill: red; line-color: red; }';
    style += '#test2 { line-color: red;polygon-fill: red; line-witdh: 10; }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer0 = shader.getLayers()[0];
    assert(layer0.getSymbolizers()[0] === 'polygon');
    assert(layer0.getSymbolizers()[1] === 'line');

    var layer1 = shader.getLayers()[1];
    assert(layer0.getSymbolizers()[0] === 'polygon');
    assert(layer0.getSymbolizers()[1] === 'line');
  });

  it ("colorize should return a list of colours in same order", function() {
    var style = '#test { image-filters: colorize-alpha(blue, cyan, green, yellow, orange, red); }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer0 = shader.getLayers()[0];
    var st = layer0.getStyle({ value: 1 }, {"frame-offset": 0, "zoom": 3});
    var expectedColours = [[0, 0, 255], [0, 255, 255], [0, 128, 0], [255, 255, 0], [255, 165, 0], [255, 0, 0]];
    for (var i = 0; i < st["image-filters"].args; i++){
      assert (st["image-filters"].args[i].rgb === expectedColours[i]);
    }
  });

  it ("should return list of marker-files", function(){
    var css = [
          'Map {',
          '-torque-time-attribute: "date";',
          '-torque-aggregation-function: "count(cartodb_id)";',
          '-torque-frame-count: 760;',
          '-torque-animation-duration: 15;',
          '-torque-resolution: 2',
          '}',
          '#layer {',
          '  marker-width: 3;',
          '  marker-fill-opacity: 0.8;',
          '  marker-fill: #FEE391; ',
          '  marker-file: url(http://localhost:8081/gal.svg); ',
          '  comp-op: "lighten";',
          '  [value > 2] { marker-file: url(http://upload.wikimedia.org/wikipedia/commons/4/43/Flag_of_the_Galactic_Empire.svg); }',
          '  [value > 3] { marker-file: url(http://upload.wikimedia.org/wikipedia/commons/c/c9/Flag_of_Syldavia.svg); }',
          '  [frame-offset = 1] { marker-width: 10; marker-fill-opacity: 0.05;}',
          '  [frame-offset = 2] { marker-width: 15; marker-fill-opacity: 0.02;}',
          '}'
      ].join('\n');
      var shader = (new carto.RendererJS({ debug: true })).render(css);
      var markerURLs = shader.getImageURLs();
      var against = ["http://localhost:8081/gal.svg", "http://upload.wikimedia.org/wikipedia/commons/4/43/Flag_of_the_Galactic_Empire.svg", "http://upload.wikimedia.org/wikipedia/commons/c/c9/Flag_of_Syldavia.svg"];
      for(var i = 0; i<against.length; i++){
        assert(against[i] == markerURLs[i])
      }
  })

  it ("should return variable for styles that change", function() {
    var style = '#test { marker-width: [prop]; }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer0 = shader.getLayers()[0];
    assert(layer0.isVariable());

    style = '#test { marker-width: 1; }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    layer0 = shader.getLayers()[0];
    assert(!layer0.isVariable());

    style = '#test { marker-width: [prop]; marker-fill: red;  }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    layer0 = shader.getLayers()[0];
    assert(layer0.isVariable());
  });

  it("should parse styles with string", function() {
    var style = '#test { [column = "test\'ing"] { marker-width: 10; } }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({column: 'test\'ing'}, {  'zoom': 0, 'frame-offset': 10 });
    assert(props['marker-width'] ===  10);
  });

  it("should parse styles with filters not supported by dot notation", function() {
    var style = '#test["mapnik::geometry_type"=1] { marker-width: 10; }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({"mapnik::geometry_type": 1}, { 'zoom': 0 });
    assert.equal(props['marker-width'], 10);
    var emptyFilterProps = layer.getStyle({"mapnik::geometry_type": 2}, { 'zoom': 0 });
    assert.equal(emptyFilterProps['marker-width'], null);
  });

  it ("should parse turbocarto", function(){
    var css = [
          '#layer {',
          '  marker-width: ramp([cartodb_id], (#fff, #bbb), jenks);',
          '}'
      ].join('\n');
      var shader = (new carto.RendererJS({ debug: true })).render(css);
      var layer = shader.getLayers()[0];
      var st = layer.shader['marker-width'].style({}, {zoom: 1})
      assert.equal(st.name, "ramp")
      assert.equal(st.args.length, 3);
      assert.equal(st.args[1].value[0].rgb[0], 255);
      assert.equal(st.args[1].value[0].rgb[1], 255);
      assert.equal(st.args[1].value[0].rgb[2], 255);
      assert.equal(st.args[2].value, 'jenks');
  })

  it("should parse turbocarto with inner functions", function(){
    var css = [
      '#layer {',
      '  marker-width: ramp([cartodb_id], cartocolor(Bold), category(10));',
      '}'
    ].join('\n');
    var shader = (new carto.RendererJS({ debug: true })).render(css);
    var layer = shader.getLayers()[0];
    var st = layer.shader['marker-width'].style({}, {zoom: 1});
    assert.equal(st.name, "ramp");
    assert.equal(st.args.length, 3);
    assert.equal(st.args[1].name, 'cartocolor');
    assert.equal(st.args[1].args[0].value, 'Bold');
    assert.equal(st.args[2].name, 'category');
    assert.equal(st.args[2].args[0].value, 10);
  });

  it("should not throw `ReferenceError` with `=~` operator", function(){
    var css = [
      '#layer[name=~".*Cairo*"] {',
      '  marker-width: 14;',
      '}'
    ].join('\n');

    assert.doesNotThrow(function () {
      var shader = (new carto.RendererJS({})).render(css);
      var layer = shader.getLayers()[0];
      var value = layer.shader['marker-width'].style({ name: 'wadus' }, { zoom: 1 });
    });
  });

  it("should not throw `TypeError` if left operand is not a `string` with operator `=~`", function(){
    var css = [
      '#layer[name=~1] {',
      '  marker-width: 14;',
      '}'
    ].join('\n');

    assert.doesNotThrow(function () {
      var shader = (new carto.RendererJS({})).render(css);
      var layer = shader.getLayers()[0];
      var value = layer.shader['marker-width'].style({ name: 1 }, { zoom: 1 });
      value = layer.shader['marker-width'].style({ name: null }, { zoom: 1 });
      value = layer.shader['marker-width'].style({ name: undefined }, { zoom: 1 });
      value = layer.shader['marker-width'].style({ name: true }, { zoom: 1 });
    });
  });
});
<commit_msg>Fix typo<commit_after>
var assert = require('assert');
var carto = require('../lib/carto');
describe('RenderingJS', function() {
  var shader;
  var style = [
  '#world {',
    'line-width: 2;',
    'line-color: #f00;',
    '[frame-offset = 1] {',
      'line-width: 3;',
    '}',
    '[frame-offset = 2] {',
      'line-width: 3;',
    '}',
  '}',
  '',
  '#worls[frame-offset = 10] {',
      'line-width: 4;',
  '}'
  ].join('\n');

  beforeEach(function() {
    shader = (new carto.RendererJS({ debug: false })).render(style);
  });

  it ("shold render layers", function() {
    assert(shader.getLayers().length === 2);
  });

  it ("shold report frames used in the layer", function() {
    var layer = shader.getLayers()[0];
    assert( layer.frames()[0] === 0);
    assert( layer.frames()[1] === 1);

    layer = shader.getLayers()[1];
    assert( layer.frames()[0] === 10);
  });

  it ("shold render with frames var", function() {
    var layer = shader.getLayers()[1];
    var props = layer.getStyle({}, { 'zoom': 0, 'frame-offset': 10 });
    assert( props['line-width'] === 4);
  });

  it ("shold render variables", function() {
    var style = '#test { marker-width: [testing]; }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({testing: 2}, { 'zoom': 0, 'frame-offset': 10 });
    assert( props['marker-width'] === 2);
  });

  it ("should allow filter based rendering", function() {
    var style = '#test { marker-width: 10; [zoom = 1] { marker-width: 1; } }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({}, { 'zoom': 0, 'frame-offset': 10 });
    assert( props['marker-width'] ===  10);
    props = layer.getStyle({}, { 'zoom': 1, 'frame-offset': 10 });
    assert( props['marker-width'] ===  1);
  });

  it ("symbolizers should be in rendering order", function() {
    var style = '#test { polygon-fill: red; line-color: red; }';
    style += '#test2 { line-color: red;polygon-fill: red; line-witdh: 10; }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer0 = shader.getLayers()[0];
    assert(layer0.getSymbolizers()[0] === 'polygon');
    assert(layer0.getSymbolizers()[1] === 'line');

    var layer1 = shader.getLayers()[1];
    assert(layer0.getSymbolizers()[0] === 'polygon');
    assert(layer0.getSymbolizers()[1] === 'line');
  });

  it ("colorize should return a list of colours in same order", function() {
    var style = '#test { image-filters: colorize-alpha(blue, cyan, green, yellow, orange, red); }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer0 = shader.getLayers()[0];
    var st = layer0.getStyle({ value: 1 }, {"frame-offset": 0, "zoom": 3});
    var expectedColours = [[0, 0, 255], [0, 255, 255], [0, 128, 0], [255, 255, 0], [255, 165, 0], [255, 0, 0]];
    for (var i = 0; i < st["image-filters"].args; i++){
      assert (st["image-filters"].args[i].rgb === expectedColours[i]);
    }
  });

  it ("should return list of marker-files", function(){
    var css = [
          'Map {',
          '-torque-time-attribute: "date";',
          '-torque-aggregation-function: "count(cartodb_id)";',
          '-torque-frame-count: 760;',
          '-torque-animation-duration: 15;',
          '-torque-resolution: 2',
          '}',
          '#layer {',
          '  marker-width: 3;',
          '  marker-fill-opacity: 0.8;',
          '  marker-fill: #FEE391; ',
          '  marker-file: url(http://localhost:8081/gal.svg); ',
          '  comp-op: "lighten";',
          '  [value > 2] { marker-file: url(http://upload.wikimedia.org/wikipedia/commons/4/43/Flag_of_the_Galactic_Empire.svg); }',
          '  [value > 3] { marker-file: url(http://upload.wikimedia.org/wikipedia/commons/c/c9/Flag_of_Syldavia.svg); }',
          '  [frame-offset = 1] { marker-width: 10; marker-fill-opacity: 0.05;}',
          '  [frame-offset = 2] { marker-width: 15; marker-fill-opacity: 0.02;}',
          '}'
      ].join('\n');
      var shader = (new carto.RendererJS({ debug: true })).render(css);
      var markerURLs = shader.getImageURLs();
      var against = ["http://localhost:8081/gal.svg", "http://upload.wikimedia.org/wikipedia/commons/4/43/Flag_of_the_Galactic_Empire.svg", "http://upload.wikimedia.org/wikipedia/commons/c/c9/Flag_of_Syldavia.svg"];
      for(var i = 0; i<against.length; i++){
        assert(against[i] == markerURLs[i])
      }
  })

  it ("should return variable for styles that change", function() {
    var style = '#test { marker-width: [prop]; }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer0 = shader.getLayers()[0];
    assert(layer0.isVariable());

    style = '#test { marker-width: 1; }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    layer0 = shader.getLayers()[0];
    assert(!layer0.isVariable());

    style = '#test { marker-width: [prop]; marker-fill: red;  }';
    shader = (new carto.RendererJS({ debug: true })).render(style);
    layer0 = shader.getLayers()[0];
    assert(layer0.isVariable());
  });

  it("should parse styles with string", function() {
    var style = '#test { [column = "test\'ing"] { marker-width: 10; } }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({column: 'test\'ing'}, {  'zoom': 0, 'frame-offset': 10 });
    assert(props['marker-width'] ===  10);
  });

  it("should parse styles with filters not supported by dot notation", function() {
    var style = '#test["mapnik::geometry_type"=1] { marker-width: 10; }';
    var shader = (new carto.RendererJS({ debug: true })).render(style);
    var layer = shader.getLayers()[0];
    var props = layer.getStyle({"mapnik::geometry_type": 1}, { 'zoom': 0 });
    assert.equal(props['marker-width'], 10);
    var emptyFilterProps = layer.getStyle({"mapnik::geometry_type": 2}, { 'zoom': 0 });
    assert.equal(emptyFilterProps['marker-width'], null);
  });

  it ("should parse turbocarto", function(){
    var css = [
          '#layer {',
          '  marker-width: ramp([cartodb_id], (#fff, #bbb), jenks);',
          '}'
      ].join('\n');
      var shader = (new carto.RendererJS({ debug: true })).render(css);
      var layer = shader.getLayers()[0];
      var st = layer.shader['marker-width'].style({}, {zoom: 1})
      assert.equal(st.name, "ramp")
      assert.equal(st.args.length, 3);
      assert.equal(st.args[1].value[0].rgb[0], 255);
      assert.equal(st.args[1].value[0].rgb[1], 255);
      assert.equal(st.args[1].value[0].rgb[2], 255);
      assert.equal(st.args[2].value, 'jenks');
  })

  it("should parse turbocarto with inner functions", function(){
    var css = [
      '#layer {',
      '  marker-width: ramp([cartodb_id], cartocolor(Bold), category(10));',
      '}'
    ].join('\n');
    var shader = (new carto.RendererJS({ debug: true })).render(css);
    var layer = shader.getLayers()[0];
    var st = layer.shader['marker-width'].style({}, {zoom: 1});
    assert.equal(st.name, "ramp");
    assert.equal(st.args.length, 3);
    assert.equal(st.args[1].name, 'cartocolor');
    assert.equal(st.args[1].args[0].value, 'Bold');
    assert.equal(st.args[2].name, 'category');
    assert.equal(st.args[2].args[0].value, 10);
  });

  it("should not throw `ReferenceError` with `=~` operator", function(){
    var css = [
      '#layer[name=~".*wadus*"] {',
      '  marker-width: 14;',
      '}'
    ].join('\n');

    assert.doesNotThrow(function () {
      var shader = (new carto.RendererJS({})).render(css);
      var layer = shader.getLayers()[0];
      var value = layer.shader['marker-width'].style({ name: 'wadus' }, { zoom: 1 });
    });
  });

  it("should not throw `TypeError` if left operand is not a `string` with operator `=~`", function(){
    var css = [
      '#layer[name=~".*wadus*"] {',
      '  marker-width: 14;',
      '}'
    ].join('\n');

    assert.doesNotThrow(function () {
      var shader = (new carto.RendererJS({})).render(css);
      var layer = shader.getLayers()[0];
      var value = layer.shader['marker-width'].style({ name: 1 }, { zoom: 1 });
      value = layer.shader['marker-width'].style({ name: null }, { zoom: 1 });
      value = layer.shader['marker-width'].style({ name: undefined }, { zoom: 1 });
      value = layer.shader['marker-width'].style({ name: true }, { zoom: 1 });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule dangerousStyleValue
 */

'use strict';

var CSSProperty = require('CSSProperty');
var warning = require('warning');

var isUnitlessNumber = CSSProperty.isUnitlessNumber;
var styleWarnings = {};

/**
 * Convert a value into the proper css writable value. The style name `name`
 * should be logical (no hyphens), as specified
 * in `CSSProperty.isUnitlessNumber`.
 *
 * @param {string} name CSS property name such as `topMargin`.
 * @param {*} value CSS property value such as `10px`.
 * @param {ReactDOMComponent} component
 * @return {string} Normalized style value with dimensions applied.
 */
function dangerousStyleValue(name, value, component) {
  // Note that we've removed escapeTextForBrowser() calls here since the
  // whole string will be escaped when the attribute is injected into
  // the markup. If you provide unsafe user data here they can inject
  // arbitrary CSS which may be problematic (I couldn't repro this):
  // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
  // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
  // This is not an XSS hole but instead a potential CSS injection issue
  // which has lead to a greater discussion about how we're going to
  // trust URLs moving forward. See #2115901

  var isEmpty = value == null || typeof value === 'boolean' || value === '';
  if (isEmpty) {
    return '';
  }

  var isNonNumeric = isNaN(value);
  if (isNonNumeric || value === 0 || value === '0' ||
      isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
    return '' + value; // cast to string
  }

  if (typeof value === 'string') {
    if (__DEV__) {
      if (component) {
        var owner = component._currentElement._owner;
        var ownerName = owner ? owner.getName() : null;
        if (ownerName && !styleWarnings[ownerName]) {
          styleWarnings[ownerName] = {};
        }
        var warned = false;
        if (ownerName) {
          var warnings = styleWarnings[ownerName];
          warned = warnings[name];
          if (!warned) {
            warnings[name] = true;
          }
        }
        if (!warned) {
          warning(
            false,
            'a `%s` tag (owner: `%s`) was passed a numeric string value ' +
            'for CSS property `%s` (value: `%s`) which will be treated ' +
            'as a unitless number in a future version of React.',
            component._currentElement.type,
            ownerName || 'unknown',
            name,
            value
          );
        }
      }
    }
    value = value.trim();
  }
  return value + 'px';
}

module.exports = dangerousStyleValue;
<commit_msg>Revert "Merge pull request #6458 from mondaychen/master"<commit_after>/**
 * Copyright 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule dangerousStyleValue
 */

'use strict';

var CSSProperty = require('CSSProperty');
var warning = require('warning');

var isUnitlessNumber = CSSProperty.isUnitlessNumber;
var styleWarnings = {};

/**
 * Convert a value into the proper css writable value. The style name `name`
 * should be logical (no hyphens), as specified
 * in `CSSProperty.isUnitlessNumber`.
 *
 * @param {string} name CSS property name such as `topMargin`.
 * @param {*} value CSS property value such as `10px`.
 * @param {ReactDOMComponent} component
 * @return {string} Normalized style value with dimensions applied.
 */
function dangerousStyleValue(name, value, component) {
  // Note that we've removed escapeTextForBrowser() calls here since the
  // whole string will be escaped when the attribute is injected into
  // the markup. If you provide unsafe user data here they can inject
  // arbitrary CSS which may be problematic (I couldn't repro this):
  // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
  // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
  // This is not an XSS hole but instead a potential CSS injection issue
  // which has lead to a greater discussion about how we're going to
  // trust URLs moving forward. See #2115901

  var isEmpty = value == null || typeof value === 'boolean' || value === '';
  if (isEmpty) {
    return '';
  }

  var isNonNumeric = isNaN(value);
  if (isNonNumeric || value === 0 ||
      isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
    return '' + value; // cast to string
  }

  if (typeof value === 'string') {
    if (__DEV__) {
      if (component) {
        var owner = component._currentElement._owner;
        var ownerName = owner ? owner.getName() : null;
        if (ownerName && !styleWarnings[ownerName]) {
          styleWarnings[ownerName] = {};
        }
        var warned = false;
        if (ownerName) {
          var warnings = styleWarnings[ownerName];
          warned = warnings[name];
          if (!warned) {
            warnings[name] = true;
          }
        }
        if (!warned) {
          warning(
            false,
            'a `%s` tag (owner: `%s`) was passed a numeric string value ' +
            'for CSS property `%s` (value: `%s`) which will be treated ' +
            'as a unitless number in a future version of React.',
            component._currentElement.type,
            ownerName || 'unknown',
            name,
            value
          );
        }
      }
    }
    value = value.trim();
  }
  return value + 'px';
}

module.exports = dangerousStyleValue;
<|endoftext|>


<commit_before>'use strict';

var express = require( 'express' ),
    app = express.createServer(),
    async = require( 'async'),
    crypto = require( 'crypto' ),
    fs = require( 'fs' ),
    Git = require( './lib/git'),
    exec = require( 'child_process' ).exec,
    path = require( 'path' ),
    regexp = require( './lib/regexp' ),
	requirejs = require( 'requirejs' ),
    requirejs_traceFiles = require( './lib/r.js' ),
    rimraf = require( 'rimraf' );

var httpPort = process.env.PORT || 8080,
    repoBaseDir = path.normalize( process.env.REPO_BASE_DIR ),
    workBaseDir = path.normalize ( process.env.WORK_BASE_DIR );

app.configure('development', function(){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
    app.use( express.logger( 'tiny' ) );
});

app.configure('production', function(){
});

app.use(express.bodyParser());

app.get( '/', function ( req, res ) {
    res.send( "
ZOMG JQM-BUILDER
" );
});

function fetch( repoDir, callback ) {
    Git( repoDir );
    Git.exec( [ "fetch" ], callback );
}

function checkout( repoName, repoDir, tag, force, callback ){
    if ( typeof force === "function" ) {
        callback = force;
        force = false;
    }
    if (!repoName) throw new Error( "No repo name specified" );
    if (!repoDir) throw new Error( "No repo dir specified" );
    if (!callback) throw new Error( "No callback passed to checkout()" );
    if (!tag) {
        tag = "master";
    }

    // Workspace
    var wsDir  = getWorkspaceDirSync( repoName, tag );

    path.exists( wsDir, function( exists ) {
        if ( exists || force ) {
            fs.mkdir( wsDir, function () {
                Git( repoDir, wsDir );
                Git.exec( [ "checkout", "-f", tag ], callback );
            });
        } else {
            callback( "Worspace for " + repoName + "/" + tag + " has not been created" );
        }
    });
}

function getFirstExistingDir( candidates, callback ) {
    var dir = candidates.shift();
    path.exists( dir , function( exists ) {
        if ( exists ) {
            callback( null, dir );
        } else {
            if ( candidates.length ) {
                getFirstExistingDir( candidates, callback );
            } else {
                callback( "none found" );
            }
        }
    });
}

function getRepoDir( repo, callback ) {
    var repoDir = repoBaseDir + "/" + repo;
    getFirstExistingDir( [ repoDir, repoDir + ".git" ], callback );
}

function getWorkspaceDirSync( repo, tag ) {
    return workBaseDir + "/" + repo + "." + tag;
}

function getCompiledDirSync( repo, tag ) {
    return getWorkspaceDirSync( repo, tag ) + "/__compiled";
}

app.get( '/:repo/fetch', function ( req, res ) {
    var repo = repoBaseDir + "/" + req.params.repo;
    async.waterfall([
        function( callback ) {
            getRepoDir( req.params.repo, callback )
        },
        fetch,
        function ( out ) {
            res.send( out );
        }
    ], function( err ) {
        if ( err ) {
            res.send( err, 500 );
        }
    })
});

app.post( '/post_receive', function ( req, res ) {
    var payload = req.body.payload,
        repoName, repoDir, tag,
        fetchIfExists = function( candidates, callback ) {
            var dir = candidates.shift();
            path.exists( dir , function( exists ) {
                if ( exists ) {
                    fetch( dir,
                        function ( error, stdout, stderr ) {
                            if ( error !== null ) {
                                res.send( error, 500 );
                            } else {
                                callback( dir );
                            }
                        }
                    );
                } else {
                    if ( candidates.length ) {
                        fetchIfExists( candidates );
                    } else {
                        res.send( "Workspace for '" + repoName + "' hasn't been checked out", 404 );
                    }
                }
            });
        };

    if ( payload ) {
        try {
            payload = JSON.parse( payload );
            repoName = payload.repository.name;
            tag = payload.ref.split( "/" ).pop();

            if ( payload.repository && payload.repository.name ) {
                async.waterfall([
                    function( callback ){
                        getRepoDir( repoName, callback );
                    },
                    function( dir, callback ) {
                        repoDir = dir;
                        fetch( dir, callback );
                    },
                    function( out, callback ) {
                        checkout( repoName, repoDir, tag, callback );
                    },
                    function( out, callback ) {
                        var compiled = getCompiledDirSync( repoName, tag );
                        async.series([
                            function( cb ) {
                                rimraf( compiled, cb );
                            },
                            function( cb ) {
                                fs.mkdir( compiled, cb );
                            }
                        ], function( err, results ) {
                            if ( err )  {
                                callback( err );
                            } else {
                                callback( null, out );
                            }
                        });
                    }
                ],
                function ( err, result ) {
                    if ( err ) {
                        res.send( err, 500 );
                    } else {
                        res.send( "OK" );
                    }
                });
            } else {
                res.send( "Payload is missing data", 404 );
            }
        } catch( e ) {
            res.send( e, 500 );
        }
    } else {
        res.send( "No Payload!", 400 );
    }
});

app.get( '/:repo/:tag/checkout', function ( req, res ) {
    var repoName = req.params.repo,
        tag      = req.params.tag;

    async.waterfall([
        function( callback ) {
            getRepoDir( repoName, callback )
        },
        function( repoDir, callback ) {
            checkout( repoName, repoDir, tag, callback );
        }

    ], function( err ) {
        if ( err ) {
            res.send( err, 500 );
        } else {
            res.send( "OK" );
        }
    });
});

app.get( '/:repo/:tag/make', function ( req, res ) {
    var include = req.param( "include", "main" ).split( "," ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        optimize = req.param( "optimize", "none" ),
        baseUrl = req.param( "baseUrl", "." ),
        pragmas = JSON.parse( req.param( "pragmas", "{}" ) ),
        pragmasOnSave = JSON.parse( req.param( "pragmasOnSave", "{}" ) ),
        name = path.basename( req.param( "name", req.params.repo ), ".js" ),
        shasum = crypto.createHash( 'sha1' ),
        wsDir   = getWorkspaceDirSync( req.params.repo, req.params.tag ),
        dstDir, dstFile;

	//Set up the config passed to the optimizer
	var config = {
		baseUrl: wsDir + "/" + baseUrl,
		include: include,
        pragmas: pragmas,
        pragmasOnSave: pragmasOnSave
	};

    shasum.update( JSON.stringify( config ) );

    dstDir = getCompiledDirSync( req.params.repo, req.params.tag ) + shasum.digest( 'hex' );
    dstFile = dstDir + "/" + name + (optimize !== "none" ? ".min" : "") + ".js";

    config.out = dstFile;
    config.optimize = optimize;

    path.exists( dstFile, function ( exists ) {
        if ( exists ) {
            res.download( dstFile, path.basename( dstFile ) );
        } else {
            try {
				requirejs.optimize( config, function ( buildResponse ) {
					//buildResponse is just a text output of the modules
					//included. Load the built file for the contents.
					fs.readFile( config.out, 'utf8', function( err, contents ) {
                        if ( err ) throw err;
						res.send( contents );
					});
				});
			} catch ( e ) {
				res.send( e.toString(), 500 );
			}
        }
    });
});

app.get( '/:repo/:tag/dependencies', function ( req, res ) {
    var wsDir = getWorkspaceDirSync( req.params.repo, req.params.tag ),
        names = req.param( "names", "" ).split( "," ).filter( function(name) {return !!name} ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        baseUrl = path.normalize( wsDir + "/" + req.param( "baseUrl", "." ) ),
        shasum = crypto.createHash( 'sha1' ),
        compileDir = getCompiledDirSync( req.params.repo, req.params.tag ),
        filename = compileDir + "/deps-";

    async.waterfall([
        function( callback ) {
            // If no name is provided, scan the baseUrl for js files and return the dep map for all JS objects in baseUrl
            if ( names.length ) {
                callback( null );
            } else {
                fs.readdir(baseUrl, function( err, files ) {
                    if ( err ) {
                        callback( err );
                    } else {
                        files = files.filter( function( file ) { return path.extname( file ) === ".js" } );
                        names = files.map( function( file ) { return path.basename( file, ".js" ) } );

                        callback( null );
                    }
                });
            }
        },
        function( callback ) {
            // Generate a sha on the sorted names
            shasum.update( names.join( "," ) );
            filename += shasum.digest( 'hex' ) + ".json";

            path.exists( filename, function( exists ) {
                callback( null, exists )
            });
        },
        function( exists, callback ) {
            if ( exists ){
                res.sendfile( filename );
            } else {
                async.series([
                    function( callback ) {
                        fs.mkdir( compileDir, callback );
                    },
                    function( callback ) {
                        requirejs_traceFiles.tools.traceFiles( {
                                baseUrl: baseUrl,
                                modules: names.map( function( name ) { return { name: name } } )
                            },
                            function( deps ) {
                                // Walk through the dep map and remove baseUrl and js extention
                                var module,
                                    baseUrlRE = new RegExp( "^" + regexp.escapeString( baseUrl + "/") ),
                                    jsExtRE = new RegExp( regexp.escapeString( ".js" ) + "$" );
                                for ( module in deps ) {
                                    deps[ module ].files.pop();
                                    deps[ module ].deps = deps[ module ].files.map(
                                        function( file ) {
                                            return file.replace( baseUrlRE, "" ).replace( jsExtRE, "" );
                                        }
                                    );
                                    delete deps[ module ].files;
                                }
                                fs.writeFile( filename, JSON.stringify( deps ),
                                    function (err) {
                                        if (err) throw err;
                                    }
                                );
                                res.json( deps );
                            }
                        );
                    }
                ])
            }
        }
    ],
    function( err ) {
        if ( err ) {
            res.send( err, 500 );
        }
    });
});

console.log( "listening on port:", httpPort );
app.listen( httpPort );<commit_msg>Handled EEXIST for __compiled<commit_after>'use strict';

var express = require( 'express' ),
    app = express.createServer(),
    async = require( 'async'),
    crypto = require( 'crypto' ),
    fs = require( 'fs' ),
    Git = require( './lib/git'),
    exec = require( 'child_process' ).exec,
    path = require( 'path' ),
    regexp = require( './lib/regexp' ),
	requirejs = require( 'requirejs' ),
    requirejs_traceFiles = require( './lib/r.js' ),
    rimraf = require( 'rimraf' );

var httpPort = process.env.PORT || 8080,
    repoBaseDir = path.normalize( process.env.REPO_BASE_DIR ),
    workBaseDir = path.normalize ( process.env.WORK_BASE_DIR );

app.configure('development', function(){
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
    app.use( express.logger( 'tiny' ) );
});

app.configure('production', function(){
});

app.use(express.bodyParser());

app.get( '/', function ( req, res ) {
    res.send( "
ZOMG JQM-BUILDER
" );
});

function fetch( repoDir, callback ) {
    Git( repoDir );
    Git.exec( [ "fetch" ], callback );
}

function checkout( repoName, repoDir, tag, force, callback ){
    if ( typeof force === "function" ) {
        callback = force;
        force = false;
    }
    if (!repoName) throw new Error( "No repo name specified" );
    if (!repoDir) throw new Error( "No repo dir specified" );
    if (!callback) throw new Error( "No callback passed to checkout()" );
    if (!tag) {
        tag = "master";
    }

    // Workspace
    var wsDir  = getWorkspaceDirSync( repoName, tag );

    path.exists( wsDir, function( exists ) {
        if ( exists || force ) {
            fs.mkdir( wsDir, function () {
                Git( repoDir, wsDir );
                Git.exec( [ "checkout", "-f", tag ], callback );
            });
        } else {
            callback( "Worspace for " + repoName + "/" + tag + " has not been created" );
        }
    });
}

function getFirstExistingDir( candidates, callback ) {
    var dir = candidates.shift();
    path.exists( dir , function( exists ) {
        if ( exists ) {
            callback( null, dir );
        } else {
            if ( candidates.length ) {
                getFirstExistingDir( candidates, callback );
            } else {
                callback( "none found" );
            }
        }
    });
}

function getRepoDir( repo, callback ) {
    var repoDir = repoBaseDir + "/" + repo;
    getFirstExistingDir( [ repoDir, repoDir + ".git" ], callback );
}

function getWorkspaceDirSync( repo, tag ) {
    return workBaseDir + "/" + repo + "." + tag;
}

function getCompiledDirSync( repo, tag ) {
    return getWorkspaceDirSync( repo, tag ) + "/__compiled";
}

app.get( '/:repo/fetch', function ( req, res ) {
    var repo = repoBaseDir + "/" + req.params.repo;
    async.waterfall([
        function( callback ) {
            getRepoDir( req.params.repo, callback )
        },
        fetch,
        function ( out ) {
            res.send( out );
        }
    ], function( err ) {
        if ( err ) {
            res.send( err, 500 );
        }
    })
});

app.post( '/post_receive', function ( req, res ) {
    var payload = req.body.payload,
        repoName, repoDir, tag,
        fetchIfExists = function( candidates, callback ) {
            var dir = candidates.shift();
            path.exists( dir , function( exists ) {
                if ( exists ) {
                    fetch( dir,
                        function ( error, stdout, stderr ) {
                            if ( error !== null ) {
                                res.send( error, 500 );
                            } else {
                                callback( dir );
                            }
                        }
                    );
                } else {
                    if ( candidates.length ) {
                        fetchIfExists( candidates );
                    } else {
                        res.send( "Workspace for '" + repoName + "' hasn't been checked out", 404 );
                    }
                }
            });
        };

    if ( payload ) {
        try {
            payload = JSON.parse( payload );
            repoName = payload.repository.name;
            tag = payload.ref.split( "/" ).pop();

            if ( payload.repository && payload.repository.name ) {
                async.waterfall([
                    function( callback ){
                        getRepoDir( repoName, callback );
                    },
                    function( dir, callback ) {
                        repoDir = dir;
                        fetch( dir, callback );
                    },
                    function( out, callback ) {
                        checkout( repoName, repoDir, tag, callback );
                    },
                    function( out, callback ) {
                        var compiled = getCompiledDirSync( repoName, tag );
                        async.series([
                            function( cb ) {
                                rimraf( compiled, cb );
                            },
                            function( cb ) {
                                fs.mkdir( compiled, cb );
                            }
                        ], function( err, results ) {
                            if ( err )  {
                                callback( err );
                            } else {
                                callback( null, out );
                            }
                        });
                    }
                ],
                function ( err, result ) {
                    if ( err ) {
                        res.send( err, 500 );
                    } else {
                        res.send( "OK" );
                    }
                });
            } else {
                res.send( "Payload is missing data", 404 );
            }
        } catch( e ) {
            res.send( e, 500 );
        }
    } else {
        res.send( "No Payload!", 400 );
    }
});

app.get( '/:repo/:tag/checkout', function ( req, res ) {
    var repoName = req.params.repo,
        tag      = req.params.tag;

    async.waterfall([
        function( callback ) {
            getRepoDir( repoName, callback )
        },
        function( repoDir, callback ) {
            checkout( repoName, repoDir, tag, callback );
        }

    ], function( err ) {
        if ( err ) {
            res.send( err, 500 );
        } else {
            res.send( "OK" );
        }
    });
});

app.get( '/:repo/:tag/make', function ( req, res ) {
    var include = req.param( "include", "main" ).split( "," ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        optimize = req.param( "optimize", "none" ),
        baseUrl = req.param( "baseUrl", "." ),
        pragmas = JSON.parse( req.param( "pragmas", "{}" ) ),
        pragmasOnSave = JSON.parse( req.param( "pragmasOnSave", "{}" ) ),
        name = path.basename( req.param( "name", req.params.repo ), ".js" ),
        shasum = crypto.createHash( 'sha1' ),
        wsDir   = getWorkspaceDirSync( req.params.repo, req.params.tag ),
        dstDir, dstFile;

	//Set up the config passed to the optimizer
	var config = {
		baseUrl: wsDir + "/" + baseUrl,
		include: include,
        pragmas: pragmas,
        pragmasOnSave: pragmasOnSave
	};

    shasum.update( JSON.stringify( config ) );

    dstDir = getCompiledDirSync( req.params.repo, req.params.tag ) + shasum.digest( 'hex' );
    dstFile = dstDir + "/" + name + (optimize !== "none" ? ".min" : "") + ".js";

    config.out = dstFile;
    config.optimize = optimize;

    path.exists( dstFile, function ( exists ) {
        if ( exists ) {
            res.download( dstFile, path.basename( dstFile ) );
        } else {
            try {
				requirejs.optimize( config, function ( buildResponse ) {
					//buildResponse is just a text output of the modules
					//included. Load the built file for the contents.
					fs.readFile( config.out, 'utf8', function( err, contents ) {
                        if ( err ) throw err;
						res.send( contents );
					});
				});
			} catch ( e ) {
				res.send( e.toString(), 500 );
			}
        }
    });
});

app.get( '/:repo/:tag/dependencies', function ( req, res ) {
    var wsDir = getWorkspaceDirSync( req.params.repo, req.params.tag ),
        names = req.param( "names", "" ).split( "," ).filter( function(name) {return !!name} ).sort(),
        exclude = req.param( "exclude", "" ).split( "," ).sort(),
        baseUrl = path.normalize( wsDir + "/" + req.param( "baseUrl", "." ) ),
        shasum = crypto.createHash( 'sha1' ),
        compileDir = getCompiledDirSync( req.params.repo, req.params.tag ),
        filename = compileDir + "/deps-";

    async.waterfall([
        function( callback ) {
            // If no name is provided, scan the baseUrl for js files and return the dep map for all JS objects in baseUrl
            if ( names.length ) {
                callback( null );
            } else {
                fs.readdir(baseUrl, function( err, files ) {
                    if ( err ) {
                        callback( err );
                    } else {
                        files = files.filter( function( file ) { return path.extname( file ) === ".js" } );
                        names = files.map( function( file ) { return path.basename( file, ".js" ) } );

                        callback( null );
                    }
                });
            }
        },
        function( callback ) {
            // Generate a sha on the sorted names
            shasum.update( names.join( "," ) );
            filename += shasum.digest( 'hex' ) + ".json";

            path.exists( filename, function( exists ) {
                callback( null, exists )
            });
        },
        function( exists, callback ) {
            if ( exists ){
                res.sendfile( filename );
            } else {
                async.series([
                    function( cb ) {
                        fs.mkdir( compileDir, function( err ) {
                            if ( err && err.code != "EEXIST" ) {
                                cb( err );
                            } else {
                                cb( null );
                            }
                        });
                    },
                    function( cb ) {
                        requirejs_traceFiles.tools.traceFiles( {
                                baseUrl: baseUrl,
                                modules: names.map( function( name ) { return { name: name } } )
                            },
                            function( deps ) {
                                // Walk through the dep map and remove baseUrl and js extention
                                var module,
                                    baseUrlRE = new RegExp( "^" + regexp.escapeString( baseUrl + "/") ),
                                    jsExtRE = new RegExp( regexp.escapeString( ".js" ) + "$" );
                                for ( module in deps ) {
                                    deps[ module ].files.pop();
                                    deps[ module ].deps = deps[ module ].files.map(
                                        function( file ) {
                                            return file.replace( baseUrlRE, "" ).replace( jsExtRE, "" );
                                        }
                                    );
                                    delete deps[ module ].files;
                                }
                                fs.writeFile( filename, JSON.stringify( deps ),
                                    function (err) {
                                        if (err) throw err;
                                    }
                                );
                                res.json( deps );
                            }
                        );
                    }
                ],
                function( err ) {
                    if ( err ) {
                        res.send( err, 500 );
                    } else {
                        callback( null );
                    }
                })
            }
        }
    ],
    function( err ) {
        if ( err ) {
            res.send( err, 500 );
        }
    });
});

console.log( "listening on port:", httpPort );
app.listen( httpPort );<|endoftext|>


<commit_before>/**
 * Node Modules
 */
var Promise = require('promise');
var extend = require('util')._extend;

/**
 * Library modules
 */

/**
 * buildapp
 *
 * @global - qsocks global connection object
 * @data - serialized app json
 */

function buildapp(global, data, opts) {
	if(typeof data === 'undefined') throw new Error('Expects qsocks global and json data.');
	if(typeof data === 'string') data = JSON.parse(data);

	/**
	 * Options
	 */
	var defaults = {
		filename: data.properties.qTitle,
		reload: false
	};

	var config = extend(defaults, opts)

	var context = {
		global: global
	};

	/**
	 * Main promise chain
	 */
	return global.createApp(config.filename + '.qvf')
	.then(function(response) {
		return global.openDoc(response.qAppId);
	})
	.then(function(app) {
		return context.app = app;
	})
	.then(function() {
		return context.app.setAppProperties(data.properties);
	})
	.then(function() {
		return context.app.setScript(data.loadScript);
	})
	.then(function() {
		return Promise.all(data.dimension.map(function(d) {
			return context.app.createDimension(d);
		}));
	})
	.then(function() {
		return Promise.all(data.measure.map(function(d) {
			return context.app.createMeasure(d);
		}));
	})
	.then(function() {
		return Promise.all(data.masterobject.map(function(d) {
			return context.app.createObject(d.qProperty).then(function(obj) {
				return obj.setProperties(d.qProperty);
			});
		}));
	})
	.then(function() {
		return Promise.all(data.sheet.map(function(d) {
			return context.app.createObject(d.qProperty).then(function(handle) {
				return handle.setFullPropertyTree(d);
			});
		}))
	})
	.then(function() {
		return Promise.all(data.snapshot.map(function(d) {
			//Snapshot but using the bookmark class.
			return context.app.createBookmark(d);
		}));
	})
	.then(function() {
		return Promise.all(data.story.map(function(d) {
			return context.app.createObject(d.qProperty).then(function(handle) {
				return handle.setFullPropertyTree(d);
			})
		}))
	})
	.then(function() {
		// Add snapshots to slide items
		return context.app.getAllInfos();
	})
	.then(function(objects) {
		return Promise.all(objects.qInfos.filter(function(d) {
			return d.qType === 'slideitem'
		}).map(function(d) {
			return context.app.getObject(d.qId);
		}));
	})
	.then(function(handles) {
		return Promise.all(handles.map(function(d) {
			return d.getLayout().then(function(layout) {
				if(layout.style.id) {
					return d.embedSnapshotObject(layout.style.id);
				}
			});
		}));
		// End of adding snapshots to slide item
	})
	.then(function() {
		return Promise.all(data.dataconnection.map(function(d) {
			return context.app.createConnection(d.qConnection)
		}));
	})
	.then(function() {
		if ( config.reload ) {
			return context.app.doReload().then(function() { return context.app.doSave(); })
		}
		return context.app.doSave();
	})
	.then(function() { return context.app; });

};
module.exports = buildapp;<commit_msg>plural in property name mapping<commit_after>/**
 * Node Modules
 */
var Promise = require('promise');
var extend = require('util')._extend;

/**
 * Library modules
 */

/**
 * buildapp
 *
 * @global - qsocks global connection object
 * @data - serialized app json
 * @opts - Options
 */

function buildapp(global, data, opts) {
	if(typeof data === 'undefined') throw new Error('Expects qsocks global and json data.');
	if(typeof data === 'string') data = JSON.parse(data);

	/**
	 * Options
	 */
	var defaults = {
		filename: data.properties.qTitle,
		reload: false
	};

	var config = extend(defaults, opts)

	var context = {
		global: global
	};

	/**
	 * Main promise chain
	 */
	return global.createApp(config.filename + '.qvf')
	.then(function(response) {
		return global.openDoc(response.qAppId);
	})
	.then(function(app) {
		return context.app = app;
	})
	.then(function() {
		return context.app.setAppProperties(data.properties);
	})
	.then(function() {
		return context.app.setScript(data.loadScript);
	})
	.then(function() {
		return Promise.all(data.dimensions.map(function(d) {
			return context.app.createDimension(d);
		}));
	})
	.then(function() {
		return Promise.all(data.measures.map(function(d) {
			return context.app.createMeasure(d);
		}));
	})
	.then(function() {
		return Promise.all(data.masterobjects.map(function(d) {
			return context.app.createObject(d.qProperty).then(function(obj) {
				return obj.setProperties(d.qProperty);
			});
		}));
	})
	.then(function() {
		return Promise.all(data.sheets.map(function(d) {
			return context.app.createObject(d.qProperty).then(function(handle) {
				return handle.setFullPropertyTree(d);
			});
		}))
	})
	.then(function() {
		return Promise.all(data.snapshots.map(function(d) {
			//Snapshot but using the bookmark class.
			return context.app.createBookmark(d);
		}));
	})
	.then(function() {
		return Promise.all(data.stories.map(function(d) {
			return context.app.createObject(d.qProperty).then(function(handle) {
				return handle.setFullPropertyTree(d);
			})
		}))
	})
	.then(function() {
		// Add snapshots to slide items
		return context.app.getAllInfos();
	})
	.then(function(objects) {
		return Promise.all(objects.qInfos.filter(function(d) {
			return d.qType === 'slideitem'
		}).map(function(d) {
			return context.app.getObject(d.qId);
		}));
	})
	.then(function(handles) {
		return Promise.all(handles.map(function(d) {
			return d.getLayout().then(function(layout) {
				if(layout.style.id) {
					return d.embedSnapshotObject(layout.style.id);
				}
			});
		}));
		// End of adding snapshots to slide item
	})
	.then(function() {
		return Promise.all(data.dataconnections.map(function(d) {
			return context.app.createConnection(d.qConnection)
		}));
	})
	.then(function() {
		if ( config.reload ) {
			return context.app.doReload().then(function() { return context.app.doSave(); })
		}
		return context.app.doSave();
	})
	.then(function() { return context.app; });

};
module.exports = buildapp;<|endoftext|>


<commit_before>import { init } from '../htmlnano';
import safePreset from '../../lib/presets/safe';

describe('minifyCss', function () {
    this.timeout(3000);

    const options = {
        minifyCss: safePreset.minifyCss,
    };
    const html = `<div></div>`;

    it('should minify CSS inside
',
            options
        );
    });

    it('should minify CSS inside style attribute', () => {
        return init(
            '

',
            '

',
            options
        );
    });

    it('should do nothing if style attribute is empty', () => {
        return init(
            '

',
            '

',
            options
        );
    });

    it('should pass options to cssnano', () => {
        return init(
            html,
            '

',
            {
                minifyCss: {
                    preset: ['default', {
                        colormin: false,
                    }],
                }
            }
        );
    });

    it('should not minify CSS inside HTML comments', () => {
        return init(
            '

',
            '

',
            options
        );
    });

    it('should ignore AMP boilerplate', () => {
        const amphtml = '';
        return init(
            amphtml,
            amphtml,
            options
        );
    });
});
<commit_msg>Adjust minifyCss tests to new version of cssnano<commit_after>import { init } from '../htmlnano';
import safePreset from '../../lib/presets/safe';

describe('minifyCss', function () {
    this.timeout(3000);

    const options = {
        minifyCss: safePreset.minifyCss,
    };
    const html = `<div></div>`;

    it('should minify CSS inside
',
            options
        );
    });

    it('should minify CSS inside style attribute', () => {
        return init(
            '

',
            '

',
            options
        );
    });

    it('should do nothing if style attribute is empty', () => {
        return init(
            '

',
            '

',
            options
        );
    });

    it('should pass options to cssnano', () => {
        return init(
            html,
            '

',
            {
                minifyCss: {
                    preset: ['default', {
                        colormin: false,
                    }],
                }
            }
        );
    });

    it('should not minify CSS inside HTML comments', () => {
        return init(
            '

',
            '

',
            options
        );
    });

    it('should ignore AMP boilerplate', () => {
        const amphtml = '';
        return init(
            amphtml,
            amphtml,
            options
        );
    });
});
<|endoftext|>


<commit_before>// Copyright 2015

/**
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var RectangularMomentaryButton = require( 'SUN/buttons/RectangularMomentaryButton' );
  var ArrowNode = require( 'SCENERY_PHET/ArrowNode' );
  var Property = require( 'AXON/Property' );
  var Vector2 = require( 'DOT/Vector2' );

  function ButtonControls( cupcakeSnakeScreenView, leftButtonProperty, rightButtonProperty ) {
    Node.call( this );

    var s = 1.5;
    var buttonScaleVector = new Vector2( 1.4 * s, 2 * s );
    var leftButton = new RectangularMomentaryButton( false, true, leftButtonProperty, {
      content: new ArrowNode( 0, 0, -20, -0, {
        scale: buttonScaleVector
      } )
    } );
    var dilationTouchAreaDelta = 250;
    leftButton.touchArea = leftButton.localBounds.dilatedXY( dilationTouchAreaDelta, dilationTouchAreaDelta );

    var rightButton = new RectangularMomentaryButton( false, true, rightButtonProperty, {
      content: new ArrowNode( 0, 0, 20, -0, {
        scale: buttonScaleVector
      } )
    } );
    rightButton.touchArea = rightButton.localBounds.dilatedXY( dilationTouchAreaDelta, dilationTouchAreaDelta );

    this.addChild( leftButton );
    this.addChild( rightButton );
    cupcakeSnakeScreenView.events.on( 'layoutFinished', function( dx, dy, width, height ) {
        leftButton.left = -dx + 10;
        leftButton.bottom = -dy - 10 + height;

        rightButton.right = -dx - 10 + width;
        rightButton.bottom = -dy - 10 + height;
      }
    );
  }

  return inherit( Node, ButtonControls, {} );
} );<commit_msg>Made button controls bigger<commit_after>// Copyright 2015

/**
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var RectangularMomentaryButton = require( 'SUN/buttons/RectangularMomentaryButton' );
  var ArrowNode = require( 'SCENERY_PHET/ArrowNode' );
  var Property = require( 'AXON/Property' );
  var Vector2 = require( 'DOT/Vector2' );

  function ButtonControls( cupcakeSnakeScreenView, leftButtonProperty, rightButtonProperty ) {
    Node.call( this );

    var s = 1.5;
    var buttonScaleVector = new Vector2( 1.4 * s, 2 * s );
    var leftButton = new RectangularMomentaryButton( false, true, leftButtonProperty, {
      content: new ArrowNode( 0, 0, -20, -0, {
        scale: buttonScaleVector
      } ),
      scale: 1.7
    } );
    var dilationTouchAreaDelta = 210;
    leftButton.touchArea = leftButton.localBounds.dilatedXY( dilationTouchAreaDelta, dilationTouchAreaDelta );

    var rightButton = new RectangularMomentaryButton( false, true, rightButtonProperty, {
      content: new ArrowNode( 0, 0, 20, -0, {
        scale: buttonScaleVector
      } ),
      scale: 1.7
    } );
    rightButton.touchArea = rightButton.localBounds.dilatedXY( dilationTouchAreaDelta, dilationTouchAreaDelta );

    this.addChild( leftButton );
    this.addChild( rightButton );
    cupcakeSnakeScreenView.events.on( 'layoutFinished', function( dx, dy, width, height ) {
        leftButton.left = -dx + 20;
        leftButton.bottom = -dy - 20 + height;

        rightButton.right = -dx - 20 + width;
        rightButton.bottom = -dy - 20 + height;
      }
    );
  }

  return inherit( Node, ButtonControls, {} );
} );<|endoftext|>