<commit_before>function BeamModelDemo(id, map, sensorRadius, sensorNoise, miniId)
{
	//Visualization stuff
	const nLasers = 19;
	this.scale = 50;

	//the canvas element
	this.view = new View(document.getElementById(id), this.scale);

	this.miniView = new View(document.getElementById(miniId), this.scale);
	this.miniView.previewMap(map);

	this.robotSize = 0.2;
	this.map = map;
	this.z = new Array(nLasers);
	this.tracker = new ParticleTracker();
	this.resolution = 10;
	this.shouldColor = false;
	this.isCalculating = false;

	//Math model used for likelihood calculation
	this.sensorModel = new BeamModel(sensorNoise, sensorRadius, map);

	//Initial robot pose
	this.x = random() * this.sensorModel.width;
	this.y = random() * this.sensorModel.height;
	this.dir = random() * TWO_PI;
	this.view.recenter(this.x, this.y);

	//cursor position in world
	this.curX = this.x;
	this.curY = this.y;

	//Event listeners
	const self = this;
	this.view.canvas.onmousedown = (event) => {return this.largeViewMouseDown(event)};

	this.miniView.canvas.onmousedown = (event) => {return this.miniViewMouseDown(event)};

	this.miniView.canvas.onmousemove = (event) => {return this.miniViewMouseMove(event)};

	this.miniView.canvas.onmouseout = (event) => {return this.miniViewMouseOut(event)};

	this.manager = new ColorizeManager(this.view, (p) =>
	{
		const ctx = this.view.ctx;
		const barHeight = 20;
		const width = this.view.canvas.width;
		const height = this.view.canvas.height;
		this.isCalculating = true;

		ctx.save();
		ctx.setTransform(1, 0, 0, 1, 0, 0);
		ctx.strokeStyle = 'rgba(0,0,255,0.5)';
		ctx.strokeRect(0, height - barHeight, width, barHeight);
		ctx.fillRect(0, height - barHeight, width * p, barHeight);
		ctx.restore();
	}, (probs, resolution) =>
	{
		this.isCalculating = false;
		this.draw();
		this.drawLaserLines();
		this.view.drawProbabilityGrid(probs, resolution);
	});

	this.miniView.ctx.drawMap(self.map);
	this.updateRender();
	this.drawSmall();
}

Object.defineProperties(BeamModelDemo.prototype, {
	"sensorRadius":{
		get: function(){return this.sensorModel.sensorRadius},
		set: function(r){
			if (r === this.sensorRadius)
				return;
			this.sensorModel.sensorRadius = r;
			this.updateRender();
		}
	},
	"sensorNoise":{
		get: function () {return this.sensorModel.a1},
		set: function(p) {
			if (this.sensorModel.a1 === p)
				return;
			this.sensorModel.a1 = p;
			this.updateRender();
		}
	}
});

BeamModelDemo.prototype.miniViewMouseOut = function (event)
{
	this.drawSmall();
};

BeamModelDemo.prototype.miniViewMouseMove = function (event)
{
	const w = this.view.width;
	const h = this.view.height;
	const view = this.miniView;
	let coor = getClickLoc(event);

	const x = view.toWorldX(coor.x);
	const y = view.toWorldY(coor.y);

	this.drawSmall();
	view.ctx.drawRect(x - w/2, y - h/2, x + w/2, y + h/2);
};

BeamModelDemo.prototype.miniViewMouseDown = function (event)
{
	const view = this.miniView;
	let coor = getClickLoc(event);

	this.curX = view.toWorldX(coor.x);
	this.curY = view.toWorldY(coor.y);

	this.view.recenter(this.curX, this.curY);
	this.drawSmall();
	this.draw();
	this.drawLaserLines();
	this.colorMapIfShould();
};

BeamModelDemo.prototype.largeViewMouseDown = function (event)
{
	if (this.isCalculating)
		return;
	//Shorthand for this.view and this.ctx
	const view = this.view;
	let coor = getClickLoc(event);

	const x = view.toWorldX(coor.x);
	const y = view.toWorldY(coor.y);

	if (event.altKey)
	{
		if (this.shouldColor)
			return;
		const resolution = this.resolution / this.view.scale;
		const w = this.sensorModel.probability(this.z,
			new RobotState(x - resolution / 2, y - resolution / 2, this.dir));
		this.tracker.addParticle(new Particle(x, y, this.dir, w));
		this.draw();
		this.drawLaserLines();
		this.view.ctx.fillTextWithColorFont('probability: ' + w, 'black', '20px Menlo Regular', 10, 20);
		return;
	}

	cancelAnimationFrame(this.frameId);

	//update robot's location
	this.x = x;
	this.y = y;

	this.view.canvas.onmousemove = (event) => {return this.largeViewMouseMove(event)};
	this.view.canvas.onmouseup = (event) => {return this.largeViewMouseUp(event)};
	this.view.canvas.onmouseout = this.view.canvas.onmouseup;

	this.draw();
};

BeamModelDemo.prototype.largeViewMouseMove = function (event)
{
	if (this.isCalculating)
		return;
	const view = this.view;
	const coor = getClickLoc(event);
	const x = view.toWorldX(coor.x);
	const y = view.toWorldY(coor.y);

	this.dir = atan2(y - this.y, x - this.x);
	this.draw();
};

BeamModelDemo.prototype.largeViewMouseUp = function (event)
{
	if (this.isCalculating)
		return;
	this.view.canvas.onmousemove = undefined;
	this.view.canvas.onmouseup = undefined;
	this.view.canvas.onmouseout = undefined;
	this.tracker.clear();
	this.updateRender();
	this.colorMapIfShould();
	this.drawSmall();
};

BeamModelDemo.prototype.draw = function ()
{
	this.drawLarge();
};

BeamModelDemo.prototype.drawSmall = function ()
{
	clearCanvas(this.miniView.canvas);
	const ctx = this.miniView.ctx;

	ctx.drawMap(this.map);
	const w = this.view.width;
	const h = this.view.height;

	ctx.fillStyle = 'rgba(180,180,180,0.5)';
	ctx.fillRect(this.curX - w / 2, this.curY - h / 2, w, h);
	ctx.drawRobot(this.x, this.y, this.dir, this.robotSize*10);
};

BeamModelDemo.prototype.drawLarge = function ()
{
	clearCanvas(this.view.canvas);
	const ctx = this.view.ctx;
	ctx.drawMap(this.map);
	ctx.drawRobot(this.x, this.y, this.dir, this.robotSize);
	//Only draw particles if color map is not enabled
	if (!this.shouldColor)
	{
		const resolution = this.resolution / this.view.scale;
		this.tracker.forEach((x, y, dir, w) =>
		{
			ctx.fillStyle = 'rgba(' + round(w * 255) + ', 0, ' + (255 - round(w * 255)) + ', 0.5)';
			ctx.fillRect(x - resolution / 2, y - resolution / 2, resolution, resolution);
		});
	}
};

BeamModelDemo.prototype.update = function ()
{
	//Only scan if location changed
	scan(this.x, this.y, this.dir, this.sensorModel.sensorRadius, this.map, this.z);
	for (let i = 0; i < this.z.length; i++)
	{
		if (this.z[i] < this.sensorModel.sensorRadius)
		{
			this.z[i] = gaussian(this.z[i], this.sensorModel.a1);
			if (this.z[i] < 0) this.z[i] = 0;
		}
	}
};

BeamModelDemo.prototype.setNLasers = function (n)
{
	if (this.z.length === n + 1)
		return;
	this.z = new Array(n + 1);
	this.updateRender();
};

BeamModelDemo.prototype.updateRender = function()
{
	this.update();
	this.draw();
	this.drawLaserLines();
};

BeamModelDemo.prototype.drawLaserLines = function ()
{
	this.view.ctx.drawLaserLines(this.z, this.x, this.y, this.dir, this.sensorModel.sensorRadius, true);
};

BeamModelDemo.prototype.setColoring = function (shouldColor)
{
	this.shouldColor = shouldColor;
	this.draw();
	this.drawLaserLines();
	this.colorMapIfShould();
};

BeamModelDemo.prototype.setColoringResolution = function (resolution)
{
	this.resolution = resolution;
};

BeamModelDemo.prototype.colorMapIfShould = function ()
{
	if (this.shouldColor && !this.isCalculating)
		this.manager.start(this.resolution, this.sensorModel, this.z, this.dir);
};

function ParticleTracker()
{
	this.clear();
}

ParticleTracker.prototype.clear = function ()
{
	this.maxW = Number.NEGATIVE_INFINITY;
	this.minW = Number.POSITIVE_INFINITY;
	this.particles = [];
};

ParticleTracker.prototype.addParticle = function (particle)
{
	this.particles.push(particle);
	this.maxW = max(particle.w, this.maxW);
	this.minW = min(particle.w, this.minW);
};

ParticleTracker.prototype.forEach = function (callback)
{
	const minW = this.minW;
	const maxW = this.maxW;
	if (this.particles.length === 1)
	{
		const p = this.particles[0];
		callback(p.x, p.y, p.dir, p.w);
	} else if (this.particles.length)
	{
		//pass in the particle's location and normalized weight
		this.particles.forEach((p) =>
			callback(p.x, p.y, p.dir, (p.w - minW) / (maxW - minW))
		);
	}
};
<commit_msg>add touch screen support<commit_after>function BeamModelDemo(id, map, sensorRadius, sensorNoise, miniId)
{
	//Visualization stuff
	const nLasers = 19;
	this.scale = 50;

	//the canvas element
	this.view = new View(document.getElementById(id), this.scale);

	this.miniView = new View(document.getElementById(miniId), this.scale);
	this.miniView.previewMap(map);

	this.robotSize = 0.2;
	this.map = map;
	this.z = new Array(nLasers);
	this.tracker = new ParticleTracker();
	this.resolution = 10;
	this.shouldColor = false;
	this.isCalculating = false;

	//Math model used for likelihood calculation
	this.sensorModel = new BeamModel(sensorNoise, sensorRadius, map);

	//Initial robot pose
	this.x = random() * this.sensorModel.width;
	this.y = random() * this.sensorModel.height;
	this.dir = random() * TWO_PI;
	this.view.recenter(this.x, this.y);

	//cursor position in world
	this.curX = this.x;
	this.curY = this.y;

	//Event listeners
	const self = this;
	this.view.canvas.onmousedown = (event) => {return this.largeViewMouseDown(event)};
	this.view.canvas.addEventListener("touchstart", this.view.canvas.onmousedown);

	this.miniView.canvas.onmousedown = (event) => {return this.miniViewMouseDown(event)};
	this.miniView.canvas.addEventListener("touchstart", this.miniView.canvas.onmousedown);

	this.miniView.canvas.onmousemove = (event) => {return this.miniViewMouseMove(event)};
	this.miniView.canvas.addEventListener("touchmove", this.miniView.canvas.onmousemove);

	this.miniView.canvas.onmouseout = (event) => {return this.miniViewMouseOut(event)};
	this.miniView.canvas.addEventListener("touchend", this.miniView.canvas.onmouseout);
	this.miniView.canvas.addEventListener("touchcancel", this.miniView.canvas.onmouseout);

	this.manager = new ColorizeManager(this.view, (p) =>
	{
		const ctx = this.view.ctx;
		const barHeight = 20;
		const width = this.view.canvas.width;
		const height = this.view.canvas.height;
		this.isCalculating = true;

		ctx.save();
		ctx.setTransform(1, 0, 0, 1, 0, 0);
		ctx.strokeStyle = 'rgba(0,0,255,0.5)';
		ctx.strokeRect(0, height - barHeight, width, barHeight);
		ctx.fillRect(0, height - barHeight, width * p, barHeight);
		ctx.restore();
	}, (probs, resolution) =>
	{
		this.isCalculating = false;
		this.draw();
		this.drawLaserLines();
		this.view.drawProbabilityGrid(probs, resolution);
	});

	this.miniView.ctx.drawMap(self.map);
	this.updateRender();
	this.drawSmall();
}

Object.defineProperties(BeamModelDemo.prototype, {
	"sensorRadius":{
		get: function(){return this.sensorModel.sensorRadius},
		set: function(r){
			if (r === this.sensorRadius)
				return;
			this.sensorModel.sensorRadius = r;
			this.updateRender();
		}
	},
	"sensorNoise":{
		get: function () {return this.sensorModel.a1},
		set: function(p) {
			if (this.sensorModel.a1 === p)
				return;
			this.sensorModel.a1 = p;
			this.updateRender();
		}
	}
});

BeamModelDemo.prototype.miniViewMouseOut = function (event)
{
	this.drawSmall();
};

BeamModelDemo.prototype.miniViewMouseMove = function (event)
{
	const w = this.view.width;
	const h = this.view.height;
	const view = this.miniView;
	let coor = getClickLoc(event);

	const x = view.toWorldX(coor.x);
	const y = view.toWorldY(coor.y);

	this.drawSmall();
	view.ctx.drawRect(x - w/2, y - h/2, x + w/2, y + h/2);
};

BeamModelDemo.prototype.miniViewMouseDown = function (event)
{
	const view = this.miniView;
	let coor = getClickLoc(event);

	this.curX = view.toWorldX(coor.x);
	this.curY = view.toWorldY(coor.y);

	this.view.recenter(this.curX, this.curY);
	this.drawSmall();
	this.draw();
	this.drawLaserLines();
	this.colorMapIfShould();
};

BeamModelDemo.prototype.largeViewMouseDown = function (event)
{
	if (this.isCalculating)
		return;
	//Shorthand for this.view and this.ctx
	const view = this.view;
	let coor = getClickLoc(event);

	const x = view.toWorldX(coor.x);
	const y = view.toWorldY(coor.y);

	if (event.altKey)
	{
		if (this.shouldColor)
			return;
		const resolution = this.resolution / this.view.scale;
		const w = this.sensorModel.probability(this.z,
			new RobotState(x - resolution / 2, y - resolution / 2, this.dir));
		this.tracker.addParticle(new Particle(x, y, this.dir, w));
		this.draw();
		this.drawLaserLines();
		this.view.ctx.fillTextWithColorFont('probability: ' + w, 'black', '20px Menlo Regular', 10, 20);
		return;
	}

	cancelAnimationFrame(this.frameId);

	//update robot's location
	this.x = x;
	this.y = y;

	this.view.canvas.onmousemove = (event) => {return this.largeViewMouseMove(event)};
	this.view.canvas.onmouseup = (event) => {return this.largeViewMouseUp(event)};
	this.view.canvas.onmouseout = this.view.canvas.onmouseup;

	this.draw();
};

BeamModelDemo.prototype.largeViewMouseMove = function (event)
{
	if (this.isCalculating)
		return;
	const view = this.view;
	const coor = getClickLoc(event);
	const x = view.toWorldX(coor.x);
	const y = view.toWorldY(coor.y);

	this.dir = atan2(y - this.y, x - this.x);
	this.draw();
};

BeamModelDemo.prototype.largeViewMouseUp = function (event)
{
	if (this.isCalculating)
		return;
	this.view.canvas.onmousemove = undefined;
	this.view.canvas.onmouseup = undefined;
	this.view.canvas.onmouseout = undefined;
	this.tracker.clear();
	this.updateRender();
	this.colorMapIfShould();
	this.drawSmall();
};

BeamModelDemo.prototype.draw = function ()
{
	this.drawLarge();
};

BeamModelDemo.prototype.drawSmall = function ()
{
	clearCanvas(this.miniView.canvas);
	const ctx = this.miniView.ctx;

	ctx.drawMap(this.map);
	const w = this.view.width;
	const h = this.view.height;

	ctx.fillStyle = 'rgba(180,180,180,0.5)';
	ctx.fillRect(this.curX - w / 2, this.curY - h / 2, w, h);
	ctx.drawRobot(this.x, this.y, this.dir, this.robotSize*10);
};

BeamModelDemo.prototype.drawLarge = function ()
{
	clearCanvas(this.view.canvas);
	const ctx = this.view.ctx;
	ctx.drawMap(this.map);
	ctx.drawRobot(this.x, this.y, this.dir, this.robotSize);
	//Only draw particles if color map is not enabled
	if (!this.shouldColor)
	{
		const resolution = this.resolution / this.view.scale;
		this.tracker.forEach((x, y, dir, w) =>
		{
			ctx.fillStyle = 'rgba(' + round(w * 255) + ', 0, ' + (255 - round(w * 255)) + ', 0.5)';
			ctx.fillRect(x - resolution / 2, y - resolution / 2, resolution, resolution);
		});
	}
};

BeamModelDemo.prototype.update = function ()
{
	//Only scan if location changed
	scan(this.x, this.y, this.dir, this.sensorModel.sensorRadius, this.map, this.z);
	for (let i = 0; i < this.z.length; i++)
	{
		if (this.z[i] < this.sensorModel.sensorRadius)
		{
			this.z[i] = gaussian(this.z[i], this.sensorModel.a1);
			if (this.z[i] < 0) this.z[i] = 0;
		}
	}
};

BeamModelDemo.prototype.setNLasers = function (n)
{
	if (this.z.length === n + 1)
		return;
	this.z = new Array(n + 1);
	this.updateRender();
};

BeamModelDemo.prototype.updateRender = function()
{
	this.update();
	this.draw();
	this.drawLaserLines();
};

BeamModelDemo.prototype.drawLaserLines = function ()
{
	this.view.ctx.drawLaserLines(this.z, this.x, this.y, this.dir, this.sensorModel.sensorRadius, true);
};

BeamModelDemo.prototype.setColoring = function (shouldColor)
{
	this.shouldColor = shouldColor;
	this.draw();
	this.drawLaserLines();
	this.colorMapIfShould();
};

BeamModelDemo.prototype.setColoringResolution = function (resolution)
{
	this.resolution = resolution;
};

BeamModelDemo.prototype.colorMapIfShould = function ()
{
	if (this.shouldColor && !this.isCalculating)
		this.manager.start(this.resolution, this.sensorModel, this.z, this.dir);
};

function ParticleTracker()
{
	this.clear();
}

ParticleTracker.prototype.clear = function ()
{
	this.maxW = Number.NEGATIVE_INFINITY;
	this.minW = Number.POSITIVE_INFINITY;
	this.particles = [];
};

ParticleTracker.prototype.addParticle = function (particle)
{
	this.particles.push(particle);
	this.maxW = max(particle.w, this.maxW);
	this.minW = min(particle.w, this.minW);
};

ParticleTracker.prototype.forEach = function (callback)
{
	const minW = this.minW;
	const maxW = this.maxW;
	if (this.particles.length === 1)
	{
		const p = this.particles[0];
		callback(p.x, p.y, p.dir, p.w);
	} else if (this.particles.length)
	{
		//pass in the particle's location and normalized weight
		this.particles.forEach((p) =>
			callback(p.x, p.y, p.dir, (p.w - minW) / (maxW - minW))
		);
	}
};
<|endoftext|>


<commit_before>var log4js = require('log4js');
var PlurkClient = require('plurk').PlurkClient;
var nconf = require('nconf');
nconf.file('config', __dirname + '/config/config.json')
	.file('keywords', __dirname + '/config/keywords.json');

var filter = require(nconf.get('filter_lib').lib_path).function;
var respond = require(nconf.get('response_lib').lib_path).function;

var logging = nconf.get('log').logging;
var log_path = nconf.get('log').log_path;

if (logging) {
	log4js.clearAppenders();
	log4js.loadAppender('file');
	log4js.addAppender(log4js.appenders.file(log_path), 'BOT_LOG');
}

var logger = log4js.getLogger('BOT_LOG');

var consumerKey = nconf.get('token').consume_key;
var consumerSecret = nconf.get('token').consume_secret;
var accessToken = nconf.get('token').access_token;
var accessTokenSecret = nconf.get('token').access_token_secret;

var summon_keywords = nconf.get('summon_keywords');
var keywords = nconf.get('keywords');

var client = new PlurkClient(true, consumerKey, consumerSecret, accessToken, accessTokenSecret);

startComet();

function startComet() {

	client.startComet(function(err, data, cometUrl) {

		if (err) {
			logger.error(err);
			setTimeout(startComet, 5000);
			return;
		}

		logger.info('Comet channel started.');

		checkTL(cometUrl);

	});
}

function checkTL(reqUrl) {

	client.rq('Alerts/addAllAsFriends');

	client.comet(reqUrl, function(err, cometData, newUrl) {
		if (err) {
			logger.error('There are some error ! ', err);
			setTimeout(startComet, 5000);
			return;
		}

		var msgs = cometData.data;

		if (msgs && Array.isArray(msgs)) {

			msgs.filter(function(data) {
				return (data && (data.type === 'new_plurk'));
			}).forEach(function(data) {

				var content = data.content_raw;

				var plurkId = data.plurk_id;

				var response = filter(keywords, content);

				if (response) {

					respond(client, plurkId, response);
				}
			});
		}
		checkTL(newUrl);
	});
}
<commit_msg>Fix the bug of cannot get function<commit_after>var log4js = require('log4js');
var PlurkClient = require('plurk').PlurkClient;
var nconf = require('nconf');
nconf.file('config', __dirname + '/config/config.json')
	.file('keywords', __dirname + '/config/keywords.json');

var filterLib = require(nconf.get('filter_lib').lib_path);
var respondLib = require(nconf.get('response_lib').lib_path);

var filter = filterLib[nconf.get('filter_lib').function];
var respond = respondLib[nconf.get('response_lib').function];

var logging = nconf.get('log').logging;
var log_path = nconf.get('log').log_path;

if (logging) {
	log4js.clearAppenders();
	log4js.loadAppender('file');
	log4js.addAppender(log4js.appenders.file(log_path), 'BOT_LOG');
}

var logger = log4js.getLogger('BOT_LOG');

var consumerKey = nconf.get('token').consume_key;
var consumerSecret = nconf.get('token').consume_secret;
var accessToken = nconf.get('token').access_token;
var accessTokenSecret = nconf.get('token').access_token_secret;

var summon_keywords = nconf.get('summon_keywords');
var keywords = nconf.get('keywords');

var client = new PlurkClient(true, consumerKey, consumerSecret, accessToken, accessTokenSecret);

startComet();

function startComet() {

	client.startComet(function(err, data, cometUrl) {

		if (err) {
			logger.error(err);
			setTimeout(startComet, 5000);
			return;
		}

		logger.info('Comet channel started.');

		checkTL(cometUrl);

	});
}

function checkTL(reqUrl) {

	client.rq('Alerts/addAllAsFriends');

	client.comet(reqUrl, function(err, cometData, newUrl) {
		if (err) {
			logger.error('There are some error ! ', err);
			setTimeout(startComet, 5000);
			return;
		}

		var msgs = cometData.data;

		if (msgs && Array.isArray(msgs)) {

			msgs.filter(function(data) {
				return (data && (data.type === 'new_plurk'));
			}).forEach(function(data) {

				var content = data.content_raw;

				var plurkId = data.plurk_id;

				var response = filter(keywords, content);

				if (response) {

					respond(client, plurkId, response);
				}
			});
		}
		checkTL(newUrl);
	});
}
<|endoftext|>


<commit_before>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210', 'snap.svg_030'],
    function (ext, $, Raphael, Snap) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide = {};
            cur_slide["in"] = data[0];
            this_e.addAnimationSlide(cur_slide);
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'clock_angle';

            var checkioInput = data.in || "14:30";
            var checkioInputStr = fname + '(' + JSON.stringify(checkioInput) + ')';

            var failError = function (dError) {
                $content.find('.call').html(checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            $content.find('.call').html(checkioInputStr);
            $content.find('.output').html('Working...');

            var svg = new SVG($content.find(".explanation")[0]);
            svg.draw(checkioInput);

            if (data.ext) {
                var rightResult = data.ext["answer"];
                var userResult = data.out;
                var result = data.ext["result"];
                var result_addon = data.ext["result_addon"];

                //if you need additional info from tests (if exists)
                var explanation = data.ext["explanation"];
                $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));
                if (!result) {
                    $content.find('.answer').html('Right result: ' + JSON.stringify(rightResult));
                    $content.find('.answer').addClass('error');
                    $content.find('.output').addClass('error');
                    $content.find('.call').addClass('error');
                }
                else {
                    $content.find('.answer').remove();
                }
            }
            else {
                $content.find('.answer').remove();
            }

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        function SVG(dom) {

            var colorOrange4 = "#F0801A";
            var colorOrange3 = "#FA8F00";
            var colorOrange2 = "#FAA600";
            var colorOrange1 = "#FABA00";

            var colorBlue4 = "#294270";
            var colorBlue3 = "#006CA9";
            var colorBlue2 = "#65A1CF";
            var colorBlue1 = "#8FC7ED";

            var colorGrey4 = "#737370";
            var colorGrey3 = "#9D9E9E";
            var colorGrey2 = "#C5C6C6";
            var colorGrey1 = "#EBEDED";

            var colorWhite = "#FFFFFF";

            var pad = 10;
            var paper;

            var R = 150;
            var inR = 135;

            var aText = {"font-family": "Roboto, Arial, sans", "stroke": colorBlue4, "font-size": 30};
            var aHour = {"stroke": colorBlue3, "stroke-width": 6};
            var aMinute = {"stroke": colorBlue3, "stroke-width": 4};
            var aClock = {"stroke": colorBlue4, "fill": colorBlue1, "stroke-width": 3};

            this.draw = function(data) {
                paper = Raphael(dom, (R + pad) * 2, (R + pad) * 2);
                paper.circle(R +pad,  R + pad, R).attr(aClock);
                paper.circle(R +pad,  R + pad, 1).attr(aClock);

                for (var i = 1; i <= 12; i++) {
                    var angle = (90 - 30 * i) * (Math.PI / 180);
                    var x = Math.cos(angle) * inR + R + pad;
                    var y = -1 * Math.sin(angle) * inR + R + pad;
                    paper.text(x, y, i).attr(aText);
                }
            }

        }

        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<commit_msg>arrows<commit_after>//Dont change it
requirejs(['ext_editor_1', 'jquery_190', 'raphael_210', 'snap.svg_030'],
    function (ext, $, Raphael, Snap) {

        var cur_slide = {};

        ext.set_start_game(function (this_e) {
        });

        ext.set_process_in(function (this_e, data) {
            cur_slide = {};
            cur_slide["in"] = data[0];
            this_e.addAnimationSlide(cur_slide);
        });

        ext.set_process_out(function (this_e, data) {
            cur_slide["out"] = data[0];
        });

        ext.set_process_ext(function (this_e, data) {
            cur_slide.ext = data;
        });

        ext.set_process_err(function (this_e, data) {
            cur_slide['error'] = data[0];
            this_e.addAnimationSlide(cur_slide);
            cur_slide = {};
        });

        ext.set_animate_success_slide(function (this_e, options) {
            var $h = $(this_e.setHtmlSlide('

'));
            this_e.setAnimationHeight(115);
        });

        ext.set_animate_slide(function (this_e, data, options) {
            var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content');
            if (!data) {
                console.log("data is undefined");
                return false;
            }

            //YOUR FUNCTION NAME
            var fname = 'clock_angle';

            var checkioInput = data.in || "14:30";
            var checkioInputStr = fname + '(' + JSON.stringify(checkioInput) + ')';

            var failError = function (dError) {
                $content.find('.call').html(checkioInputStr);
                $content.find('.output').html(dError.replace(/\n/g, ","));

                $content.find('.output').addClass('error');
                $content.find('.call').addClass('error');
                $content.find('.answer').remove();
                $content.find('.explanation').remove();
                this_e.setAnimationHeight($content.height() + 60);
            };

            if (data.error) {
                failError(data.error);
                return false;
            }

            if (data.ext && data.ext.inspector_fail) {
                failError(data.ext.inspector_result_addon);
                return false;
            }

            $content.find('.call').html(checkioInputStr);
            $content.find('.output').html('Working...');

            var svg = new SVG($content.find(".explanation")[0]);
            svg.draw(checkioInput);

            if (data.ext) {
                var rightResult = data.ext["answer"];
                var userResult = data.out;
                var result = data.ext["result"];
                var result_addon = data.ext["result_addon"];

                //if you need additional info from tests (if exists)
                var explanation = data.ext["explanation"];
                $content.find('.output').html(' Your result: ' + JSON.stringify(userResult));
                if (!result) {
                    $content.find('.answer').html('Right result: ' + JSON.stringify(rightResult));
                    $content.find('.answer').addClass('error');
                    $content.find('.output').addClass('error');
                    $content.find('.call').addClass('error');
                }
                else {
                    $content.find('.answer').remove();
                }
            }
            else {
                $content.find('.answer').remove();
            }

            //Your code here about test explanation animation
            //$content.find(".explanation").html("Something text for example");
            //
            //
            //
            //
            //

            this_e.setAnimationHeight($content.height() + 60);

        });

        //This is for Tryit (but not necessary)
//        var $tryit;
//        ext.set_console_process_ret(function (this_e, ret) {
//            $tryit.find(".checkio-result").html("Result
" + ret);
//        });
//
//        ext.set_generate_animation_panel(function (this_e) {
//            $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content');
//            $tryit.find('.bn-check').click(function (e) {
//                e.preventDefault();
//                this_e.sendToConsoleCheckiO("something");
//            });
//        });

        function SVG(dom) {

            var colorOrange4 = "#F0801A";
            var colorOrange3 = "#FA8F00";
            var colorOrange2 = "#FAA600";
            var colorOrange1 = "#FABA00";

            var colorBlue4 = "#294270";
            var colorBlue3 = "#006CA9";
            var colorBlue2 = "#65A1CF";
            var colorBlue1 = "#8FC7ED";

            var colorGrey4 = "#737370";
            var colorGrey3 = "#9D9E9E";
            var colorGrey2 = "#C5C6C6";
            var colorGrey1 = "#EBEDED";

            var colorWhite = "#FFFFFF";

            var pad = 10;
            var paper;

            var R = 150;
            var inR = 130;

            var hLen = 70;
            var mLen = 100;

            var aText = {"font-family": "Roboto, Arial, sans", "stroke": colorBlue4, "font-size": 30};
            var aHour = {"stroke": colorBlue3, "stroke-width": 6};
            var aMinute = {"stroke": colorBlue3, "stroke-width": 4};
            var aClock = {"stroke": colorBlue4, "fill": colorBlue1, "stroke-width": 3};

            this.draw = function(data) {
                paper = Raphael(dom, (R + pad) * 2, (R + pad) * 2);

                var center = R + pad;

                paper.circle(center,  center, R).attr(aClock);
                paper.circle(center,  center, 1).attr(aClock);

                for (var i = 1; i <= 12; i++) {
                    var angle = (90 - 30 * i) * (Math.PI / 180);
                    var x = Math.cos(angle) * inR + center;
                    var y = -1 * Math.sin(angle) * inR + center;
                    paper.text(x, y, i).attr(aText);
                }

                var time = data.split(":");
                var hour = Number(time[0]);
                var minute = Number(time[1]);

                var hourHand = paper.path(["M", center, center], ["V", center - hLen]).attr(aHour);

                var minHand = paper.path(["M", center, center], ["V", center - mLen]).attr(aMinute);
                minHand.transform(["R", minute * 6, center, center]);
                hourHand.transform(["R", hour * 30 + minute / 2, center, center]);
            }

        }

        //Your Additional functions or objects inside scope
        //
        //
        //

    }
);
<|endoftext|>


<commit_before>/*globals svgEditor */
svgEditor.readLang({
	lang: "sq",
	dir : "ltr",
	common: {
		"ok": "Ruaj",
		"cancel": "Anulo",
		"key_backspace": "backspace",
		"key_del": "delete",
		"key_down": "down",
		"key_up": "up",
		"more_opts": "More Options",
		"url": "URL",
		"width": "Width",
		"height": "Height"
	},
	misc: {
		"powered_by": "Powered by"
	},
	ui: {
		"toggle_stroke_tools": "Show/hide more stroke tools",
		"palette_info": "Klikoni për të ndryshuar mbushur me ngjyra, shift-klikoni për të ndryshuar ngjyrën pash",
		"zoom_level": "Ndryshimi zoom nivel",
		"panel_drag": "Drag left/right to resize side panel"
	},
	properties: {
		"id": "Identify the element",
		"fill_color": "Ndryshimi mbush color",
		"stroke_color": "Change color pash",
		"stroke_style": "Ndryshimi dash goditje stil",
		"stroke_width": "Ndryshimi goditje width",
		"pos_x": "Change X coordinate",
		"pos_y": "Change Y coordinate",
		"linecap_butt": "Linecap: Butt",
		"linecap_round": "Linecap: Round",
		"linecap_square": "Linecap: Square",
		"linejoin_bevel": "Linejoin: Bevel",
		"linejoin_miter": "Linejoin: Miter",
		"linejoin_round": "Linejoin: Round",
		"angle": "Kënd Ndryshimi rrotullim",
		"blur": "Change gaussian blur value",
		"opacity": "Ndryshimi zgjedhur errësirë item",
		"circle_cx": "Cx rrethi Ndryshimi i bashkërenduar",
		"circle_cy": "Ndryshimi i rrethit cy koordinuar",
		"circle_r": "Rreze rreth Ndryshimi i",
		"ellipse_cx": "Ndryshimi elips e cx koordinuar",
		"ellipse_cy": "Elips cy Ndryshimi i bashkërenduar",
		"ellipse_rx": "Rreze x elips Ndryshimi i",
		"ellipse_ry": "Radiusi y elips ndërroj",
		"line_x1": "Shkarko Ndryshimi që fillon x koordinuar",
		"line_x2": "Linjë Ndryshimi i fund x koordinuar",
		"line_y1": "Shkarko Ndryshimi që fillon y koordinuar",
		"line_y2": "Shkarko Ndryshimi i dhënë fund y koordinuar",
		"rect_height": "Height Ndryshimi drejtkëndësh",
		"rect_width": "Width Ndryshimi drejtkëndësh",
		"corner_radius": "Ndryshimi Rectangle Corner Radius",
		"image_width": "Ndryshimi image width",
		"image_height": "Height të ndryshuar imazhin",
		"image_url": "Ndrysho URL",
		"node_x": "Change node's x coordinate",
		"node_y": "Change node's y coordinate",
		"seg_type": "Change Segment type",
		"straight_segments": "Straight",
		"curve_segments": "Curve",
		"text_contents": "Text contents Ndryshimi",
		"font_family": "Ndryshimi Font Family",
		"font_size": "Ndryshimi Font Size",
		"bold": "Bold Text",
		"italic": "Italic Text"
	},
	tools: {
		"main_menu": "Main Menu",
		"bkgnd_color_opac": "Change color background / patejdukshmëri",
		"connector_no_arrow": "No arrow",
		"fitToContent": "Fit to Content",
		"fit_to_all": "Fit për të gjithë përmbajtjen",
		"fit_to_canvas": "Fit në kanavacë",
		"fit_to_layer_content": "Shtresë Fit to content",
		"fit_to_sel": "Fit to Selection",
		"align_relative_to": "Vendose në lidhje me ...",
		"relativeTo": "lidhje me:",
		"faqe": "faqe",
		"largest_object": "madh objekt",
		"selected_objects": "objektet e zgjedhur",
		"smallest_object": "objektit më të vogël",
		"new_doc": "New Image",
		"open_doc": "Image Hapur",
		"export_img": "Export",
		"save_doc": "Image Ruaj",
		"import_doc": "Import Image",
		"align_to_page": "Align Element to Page",
		"align_bottom": "Align Bottom",
		"align_center": "Align Center",
		"align_left": "Align Left",
		"align_middle": "Align Mesme",
		"align_right": "Align Right",
		"align_top": "Align Top",
		"mode_select": "Zgjidhni Tool",
		"mode_fhpath": "Pencil Tool",
		"mode_line": "Line Tool",
		"mode_connect": "Connect two objects",
		"mode_rect": "Rectangle Tool",
		"mode_square": "Square Tool",
		"mode_fhrect": "Lëndë Hand Rectangle",
		"mode_ellipse": "Elips",
		"mode_circle": "Rrethi",
		"mode_fhellipse": "Free-Hand Ellipse",
		"mode_path": "Path Tool",
		"mode_shapelib": "Shape library",
		"mode_text": "Text Tool",
		"mode_image": "Image Tool",
		"mode_zoom": "Zoom Tool",
		"mode_eyedropper": "Eye Dropper Tool",
		"no_embed": "NOTE: This image cannot be embedded. It will depend on this path to be displayed",
		"undo": "Undo",
		"redo": "Redo",
		"tool_source": "Burimi Edit",
		"wireframe_mode": "Wireframe Mode",
		"toggle_grid": "Show/Hide Grid",
		"clone": "Clone Element(s)",
		"del": "Delete Element(s)",
		"group_elements": "Elementet e Grupit",
		"make_link": "Make (hyper)link",
		"set_link_url": "Set link URL (leave empty to remove)",
		"to_path": "Convert to Path",
		"reorient_path": "Reorient path",
		"ungroup": "Elemente Ungroup",
		"docprops": "Dokumenti Prona",
		"imagelib": "Image Library",
		"move_bottom": "Move to Bottom",
		"move_top": "Move to Top",
		"node_clone": "Clone Node",
		"node_delete": "Delete Node",
		"node_link": "Link Control Points",
		"add_subpath": "Add sub-path",
		"openclose_path": "Open/close sub-path",
		"source_save": "Ruaj",
		"cut": "Cut",
		"copy": "Copy",
		"paste": "Paste",
		"paste_in_place": "Paste in Place",
		"delete": "Delete",
		"group": "Group",
		"move_front": "Bring to Front",
		"move_up": "Bring Forward",
		"move_down": "Send Backward",
		"move_back": "Send to Back"
	},
	layers: {
		"layer":"Layer",
		"layers": "Layers",
		"del": "Delete Layer",
		"move_down": "Move Down Layer",
		"new": "Re Shtresa",
		"rename": "Rename Layer",
		"move_up": "Move Up Layer",
		"dupe": "Duplicate Layer",
		"merge_down": "Merge Down",
		"merge_all": "Merge All",
		"move_elems_to": "Move elements to:",
		"move_selected": "Move selected elements to a different layer"
	},
	config: {
		"image_props": "Image Properties",
		"doc_title": "Title",
		"doc_dims": "Canvas Dimensions",
		"included_images": "Included Images",
		"image_opt_embed": "Embed data (local files)",
		"image_opt_ref": "Use file reference",
		"editor_prefs": "Editor Preferences",
		"icon_size": "Icon size",
		"language": "Language",
		"background": "Editor Background",
		"editor_img_url": "Image URL",
		"editor_bg_note": "Note: Background will not be saved with image.",
		"icon_large": "Large",
		"icon_medium": "Medium",
		"icon_small": "Small",
		"icon_xlarge": "Extra Large",
		"select_predefined": "Zgjidhni paracaktuara:",
		"units_and_rulers": "Units & Rulers",
		"show_rulers": "Show rulers",
		"base_unit": "Base Unit:",
		"grid": "Grid",
		"snapping_onoff": "Snapping on/off",
		"snapping_stepsize": "Snapping Step-Size:",
		"grid_color": "Grid color"
	},
	shape_cats: {
		"basic": "Basic",
		"object": "Objects",
		"symbol": "Symbols",
		"arrow": "Arrows",
		"flowchart": "Flowchart",
		"animal": "Animals",
		"game": "Cards & Chess",
		"dialog_balloon": "Dialog balloons",
		"electronics": "Electronics",
		"math": "Mathematical",
		"music": "Music",
		"misc": "Miscellaneous",
		"raphael_1": "raphaeljs.com set 1",
		"raphael_2": "raphaeljs.com set 2"
	},
	imagelib: {
		"select_lib": "Select an image library",
		"show_list": "Show library list",
		"import_single": "Import single",
		"import_multi": "Import multiple",
		"open": "Open as new document"
	},
	notification: {
		"invalidAttrValGiven":"Invalid value given",
		"noContentToFitTo":"No content to fit to",
		"dupeLayerName":"There is already a layer named that!",
		"enterUniqueLayerName":"Please enter a unique layer name",
		"enterNewLayerName":"Please enter the new layer name",
		"layerHasThatName":"Layer already has that name",
		"QmoveElemsToLayer":"Move selected elements to layer '%s'?",
		"QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!",
		"QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!",
		"QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?",
		"QignoreSourceChanges":"Ignore changes made to SVG source?",
		"featNotSupported":"Feature not supported",
		"enterNewImgURL":"Enter the new image URL",
		"defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
		"loadingImage":"Loading image, please wait...",
		"saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.",
		"noteTheseIssues": "Also note the following issues: ",
		"unsavedChanges": "There are unsaved changes.",
		"enterNewLinkURL": "Enter the new hyperlink URL",
		"errorLoadingSVG": "Error: Unable to load SVG data",
		"URLloadFail": "Unable to load from URL",
		"retrieving": "Retrieving \"%s\"..."
	},
	confirmSetStorage: {
		message: "By default and where supported, SVG-Edit can store your editor "+
		"preferences and SVG content locally on your machine so you do not "+
		"need to add these back each time you load SVG-Edit. If, for privacy "+
		"reasons, you do not wish to store this information on your machine, "+
		"you can change away from the default option below.",
		storagePrefsAndContent: "Store preferences and SVG content locally",
		storagePrefsOnly: "Only store preferences locally",
		storagePrefs: "Store preferences locally",
		storageNoPrefsOrContent: "Do not store my preferences or SVG content locally",
		storageNoPrefs: "Do not store my preferences locally",
		rememberLabel: "Remember this choice?",
		rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again."
	}
});<commit_msg>Update lang.sq.js<commit_after>/*globals svgEditor */
svgEditor.readLang({
	lang: "sq",
	dir : "ltr",
	common: {
		"ok": "Ruaj",
		"cancel": "Anulo",
		"key_backspace": "backspace",
		"key_del": "delete",
		"key_down": "down",
		"key_up": "up",
		"more_opts": "More Options",
		"url": "URL",
		"width": "Width",
		"height": "Height"
	},
	misc: {
		"powered_by": "Powered by"
	},
	ui: {
		"toggle_stroke_tools": "Show/hide more stroke tools",
		"palette_info": "Klikoni për të ndryshuar mbushur me ngjyra, shift-klikoni për të ndryshuar ngjyrën pash",
		"zoom_level": "Ndryshimi zoom nivel",
		"panel_drag": "Drag left/right to resize side panel"
	},
	properties: {
		"id": "Identify the element",
		"fill_color": "Ndryshimi mbush color",
		"stroke_color": "Change color pash",
		"stroke_style": "Ndryshimi dash goditje stil",
		"stroke_width": "Ndryshimi goditje width",
		"pos_x": "Change X coordinate",
		"pos_y": "Change Y coordinate",
		"linecap_butt": "Linecap: Butt",
		"linecap_round": "Linecap: Round",
		"linecap_square": "Linecap: Square",
		"linejoin_bevel": "Linejoin: Bevel",
		"linejoin_miter": "Linejoin: Miter",
		"linejoin_round": "Linejoin: Round",
		"angle": "Kënd Ndryshimi rrotullim",
		"blur": "Change gaussian blur value",
		"opacity": "Ndryshimi zgjedhur errësirë item",
		"circle_cx": "Cx rrethi Ndryshimi i bashkërenduar",
		"circle_cy": "Ndryshimi i rrethit cy koordinuar",
		"circle_r": "Rreze rreth Ndryshimi i",
		"ellipse_cx": "Ndryshimi elips e cx koordinuar",
		"ellipse_cy": "Elips cy Ndryshimi i bashkërenduar",
		"ellipse_rx": "Rreze x elips Ndryshimi i",
		"ellipse_ry": "Radiusi y elips ndërroj",
		"line_x1": "Shkarko Ndryshimi që fillon x koordinuar",
		"line_x2": "Linjë Ndryshimi i fund x koordinuar",
		"line_y1": "Shkarko Ndryshimi që fillon y koordinuar",
		"line_y2": "Shkarko Ndryshimi i dhënë fund y koordinuar",
		"rect_height": "Height Ndryshimi drejtkëndësh",
		"rect_width": "Width Ndryshimi drejtkëndësh",
		"corner_radius": "Ndryshimi Rectangle Corner Radius",
		"image_width": "Ndryshimi image width",
		"image_height": "Height të ndryshuar imazhin",
		"image_url": "Ndrysho URL",
		"node_x": "Change node's x coordinate",
		"node_y": "Change node's y coordinate",
		"seg_type": "Change Segment type",
		"straight_segments": "Straight",
		"curve_segments": "Curve",
		"text_contents": "Text contents Ndryshimi",
		"font_family": "Ndryshimi Font Family",
		"font_size": "Ndryshimi Font Size",
		"bold": "Bold Text",
		"italic": "Italic Text"
	},
	tools: {
		"main_menu": "Main Menu",
		"bkgnd_color_opac": "Change color background / patejdukshmëri",
		"connector_no_arrow": "No arrow",
		"fitToContent": "Fit to Content",
		"fit_to_all": "Fit për të gjithë përmbajtjen",
		"fit_to_canvas": "Fit në kanavacë",
		"fit_to_layer_content": "Shtresë Fit to content",
		"fit_to_sel": "Fit to Selection",
		"align_relative_to": "Vendose në lidhje me ...",
		"relativeTo": "lidhje me:",
		"page": "faqe",
		"largest_object": "madh objekt",
		"selected_objects": "objektet e zgjedhur",
		"smallest_object": "objektit më të vogël",
		"new_doc": "New Image",
		"open_doc": "Image Hapur",
		"export_img": "Export",
		"save_doc": "Image Ruaj",
		"import_doc": "Import Image",
		"align_to_page": "Align Element to Page",
		"align_bottom": "Align Bottom",
		"align_center": "Align Center",
		"align_left": "Align Left",
		"align_middle": "Align Mesme",
		"align_right": "Align Right",
		"align_top": "Align Top",
		"mode_select": "Zgjidhni Tool",
		"mode_fhpath": "Pencil Tool",
		"mode_line": "Line Tool",
		"mode_connect": "Connect two objects",
		"mode_rect": "Rectangle Tool",
		"mode_square": "Square Tool",
		"mode_fhrect": "Lëndë Hand Rectangle",
		"mode_ellipse": "Elips",
		"mode_circle": "Rrethi",
		"mode_fhellipse": "Free-Hand Ellipse",
		"mode_path": "Path Tool",
		"mode_shapelib": "Shape library",
		"mode_text": "Text Tool",
		"mode_image": "Image Tool",
		"mode_zoom": "Zoom Tool",
		"mode_eyedropper": "Eye Dropper Tool",
		"no_embed": "NOTE: This image cannot be embedded. It will depend on this path to be displayed",
		"undo": "Undo",
		"redo": "Redo",
		"tool_source": "Burimi Edit",
		"wireframe_mode": "Wireframe Mode",
		"toggle_grid": "Show/Hide Grid",
		"clone": "Clone Element(s)",
		"del": "Delete Element(s)",
		"group_elements": "Elementet e Grupit",
		"make_link": "Make (hyper)link",
		"set_link_url": "Set link URL (leave empty to remove)",
		"to_path": "Convert to Path",
		"reorient_path": "Reorient path",
		"ungroup": "Elemente Ungroup",
		"docprops": "Dokumenti Prona",
		"imagelib": "Image Library",
		"move_bottom": "Move to Bottom",
		"move_top": "Move to Top",
		"node_clone": "Clone Node",
		"node_delete": "Delete Node",
		"node_link": "Link Control Points",
		"add_subpath": "Add sub-path",
		"openclose_path": "Open/close sub-path",
		"source_save": "Ruaj",
		"cut": "Cut",
		"copy": "Copy",
		"paste": "Paste",
		"paste_in_place": "Paste in Place",
		"delete": "Delete",
		"group": "Group",
		"move_front": "Bring to Front",
		"move_up": "Bring Forward",
		"move_down": "Send Backward",
		"move_back": "Send to Back"
	},
	layers: {
		"layer":"Layer",
		"layers": "Layers",
		"del": "Delete Layer",
		"move_down": "Move Down Layer",
		"new": "Re Shtresa",
		"rename": "Rename Layer",
		"move_up": "Move Up Layer",
		"dupe": "Duplicate Layer",
		"merge_down": "Merge Down",
		"merge_all": "Merge All",
		"move_elems_to": "Move elements to:",
		"move_selected": "Move selected elements to a different layer"
	},
	config: {
		"image_props": "Image Properties",
		"doc_title": "Title",
		"doc_dims": "Canvas Dimensions",
		"included_images": "Included Images",
		"image_opt_embed": "Embed data (local files)",
		"image_opt_ref": "Use file reference",
		"editor_prefs": "Editor Preferences",
		"icon_size": "Icon size",
		"language": "Language",
		"background": "Editor Background",
		"editor_img_url": "Image URL",
		"editor_bg_note": "Note: Background will not be saved with image.",
		"icon_large": "Large",
		"icon_medium": "Medium",
		"icon_small": "Small",
		"icon_xlarge": "Extra Large",
		"select_predefined": "Zgjidhni paracaktuara:",
		"units_and_rulers": "Units & Rulers",
		"show_rulers": "Show rulers",
		"base_unit": "Base Unit:",
		"grid": "Grid",
		"snapping_onoff": "Snapping on/off",
		"snapping_stepsize": "Snapping Step-Size:",
		"grid_color": "Grid color"
	},
	shape_cats: {
		"basic": "Basic",
		"object": "Objects",
		"symbol": "Symbols",
		"arrow": "Arrows",
		"flowchart": "Flowchart",
		"animal": "Animals",
		"game": "Cards & Chess",
		"dialog_balloon": "Dialog balloons",
		"electronics": "Electronics",
		"math": "Mathematical",
		"music": "Music",
		"misc": "Miscellaneous",
		"raphael_1": "raphaeljs.com set 1",
		"raphael_2": "raphaeljs.com set 2"
	},
	imagelib: {
		"select_lib": "Select an image library",
		"show_list": "Show library list",
		"import_single": "Import single",
		"import_multi": "Import multiple",
		"open": "Open as new document"
	},
	notification: {
		"invalidAttrValGiven":"Invalid value given",
		"noContentToFitTo":"No content to fit to",
		"dupeLayerName":"There is already a layer named that!",
		"enterUniqueLayerName":"Please enter a unique layer name",
		"enterNewLayerName":"Please enter the new layer name",
		"layerHasThatName":"Layer already has that name",
		"QmoveElemsToLayer":"Move selected elements to layer '%s'?",
		"QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!",
		"QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!",
		"QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?",
		"QignoreSourceChanges":"Ignore changes made to SVG source?",
		"featNotSupported":"Feature not supported",
		"enterNewImgURL":"Enter the new image URL",
		"defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
		"loadingImage":"Loading image, please wait...",
		"saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.",
		"noteTheseIssues": "Also note the following issues: ",
		"unsavedChanges": "There are unsaved changes.",
		"enterNewLinkURL": "Enter the new hyperlink URL",
		"errorLoadingSVG": "Error: Unable to load SVG data",
		"URLloadFail": "Unable to load from URL",
		"retrieving": "Retrieving \"%s\"..."
	},
	confirmSetStorage: {
		message: "By default and where supported, SVG-Edit can store your editor "+
		"preferences and SVG content locally on your machine so you do not "+
		"need to add these back each time you load SVG-Edit. If, for privacy "+
		"reasons, you do not wish to store this information on your machine, "+
		"you can change away from the default option below.",
		storagePrefsAndContent: "Store preferences and SVG content locally",
		storagePrefsOnly: "Only store preferences locally",
		storagePrefs: "Store preferences locally",
		storageNoPrefsOrContent: "Do not store my preferences or SVG content locally",
		storageNoPrefs: "Do not store my preferences locally",
		rememberLabel: "Remember this choice?",
		rememberTooltip: "If you choose to opt out of storage while remembering this choice, the URL will change so as to avoid asking again."
	}
});
<|endoftext|>


<commit_before>/**
 * Created by luke on 2015/1/25.
 */

/*
 内部排序

 在信息处理过程中，最基本的操作是查找。从查找来说，效率最高的是折半查找，折半查找的前提是所有的数据元素(记录)是按关键字有序的。需要将一个无序的数据文件转变为一个有序的数据文件。
 将任一文件中的记录通过某种方法整理成为按(记录)关键字有序排列的处理过程称为排序。
 排序是数据处理中一种最常用的操作。

 排序的基本概念

 ⑴  排序(Sorting)
 排序是将一批(组)任意次序的记录重新排列成按关键字有序的记录序列的过程，其定义为：
 给定一组记录序列：{R1 , R2 ,…, Rn}，其相应的关键字序列是{K1 , K2 ,…, Kn} 。确定1, 2, … n的一个排列p1 , p2 ,…, pn，使其相应的关键字满足如下非递减(或非递增)关系： Kp1<=Kp2 <=…<=Kpn的序列{Kp1 ,Kp2 , …,Kpn} ，这种操作称为排序。
 关键字Ki可以是记录Ri的主关键字，也可以是次关键字或若干数据项的组合。
 ◆  Ki是主关键字：排序后得到的结果是唯一的；
 ◆  Ki是次关键字：排序后得到的结果是不唯一的。

 ⑵  排序的稳定性
 若记录序列中有两个或两个以上关键字相等的记录： Ki =Kj(i≠j，i, j=1, 2, … n)，且在排序前Ri先于Rj(i<j)，排序后的记录序列仍然是Ri先于Rj，称排序方法是稳定的，否则是不稳定的。

 排序算法有许多，但就全面性能而言，还没有一种公认为最好的。每种算法都有其优点和缺点，分别适合不同的数据量和硬件配置。
 评价排序算法的标准有：执行时间和所需的辅助空间，其次是算法的稳定性。
 若排序算法所需的辅助空间不依赖问题的规模n，即空间复杂度是O(1) ，则称排序方法是就地排序，否则是非就地排序。

 ⑶ 排序的分类
 待排序的记录数量不同，排序过程中涉及的存储器的不同，有不同的排序分类。
 ①  待排序的记录数不太多：所有的记录都能存放在内存中进行排序，称为内部排序；
 ②  待排序的记录数太多：所有的记录不可能存放在内存中， 排序过程中必须在内、外存之间进行数据交换，这样的排序称为外部排序。

 ⑷ 内部排序的基本操作
 对内部排序地而言，其基本操作有两种：
 ◆  比较两个关键字的大小；
 ◆ 存储位置的移动：从一个位置移到另一个位置。

 第一种操作是必不可少的；而第二种操作却不是必须的，取决于记录的存储方式，具体情况是：
 ① 记录存储在一组连续地址的存储空间：记录之间的逻辑顺序关系是通过其物理存储位置的相邻来体现，记录的移动是必不可少的；
 ②  记录采用链式存储方式：记录之间的逻辑顺序关系是通过结点中的指针来体现，排序过程仅需修改结点的指针，而不需要移动记录；
 ③  记录存储在一组连续地址的存储空间：构造另一个辅助表来保存各个记录的存放地址(指针) ：排序过程不需要移动记录，而仅需修改辅助表中的指针，排序后视具体情况决定是否调整记录的存储位置。

 ①比较适合记录数较少的情况；而②、③则适合记录数较多的情况。
 为讨论方便，假设待排序的记录是以①的情况存储，且设排序是按升序排列的；关键字是一些可直接用比较运算符进行比较的类型。
 */

// It's just a comparison version, will be removed soon.
Array.prototype.swap = function(i, j)
{
    var temp = this[i];
    this[i] = this[j];
    this[j] = temp;
}
Array.prototype.bubbleSort = function()
{
    for (var i = this.length - 1; i > 0; --i)
    {
        for (var j = 0; j < i; ++j)
        {
            if (this[j] > this[j + 1]) this.swap(j, j + 1);
        }
    }
}
Array.prototype.selectionSort = function()
{
    for (var i = 0; i < this.length; ++i)
    {
        var index = i;
        for (var j = i + 1; j < this.length; ++j)
        {
            if (this[j] < this[index]) index = j;
        }
        this.swap(i, index);
    }
}
Array.prototype.insertionSort = function()
{
    for (var i = 1; i < this.length; ++i)
    {
        var j = i, value = this[i];
        while (j > 0 && this[j - 1] > value)
        {
            this[j] = this[j - 1];
            --j;
        }
        this[j] = value;
    }
}
Array.prototype.shellSort = function()
{
    for (var step = this.length >> 1; step > 0; step >>= 1)
    {
        for (var i = 0; i < step; ++i)
        {
            for (var j = i + step; j < this.length; j += step)
            {
                var k = j, value = this[j];
                while (k >= step && this[k - step] > value)
                {
                    this[k] = this[k - step];
                    k -= step;
                }
                this[k] = value;
            }
        }
    }
}
Array.prototype.quickSort = function(s, e)
{
    if (s == null) s = 0;
    if (e == null) e = this.length - 1;
    if (s >= e) return;
    this.swap((s + e) >> 1, e);
    var index = s - 1;
    for (var i = s; i <= e; ++i)
    {
        if (this[i] <= this[e]) this.swap(i, ++index);
    }
    this.quickSort(s, index - 1);
    this.quickSort(index + 1, e);
}
Array.prototype.stackQuickSort = function()
{
    var stack = [0, this.length - 1];
    while (stack.length > 0)
    {
        var e = stack.pop(), s = stack.pop();
        if (s >= e) continue;
        this.swap((s + e) >> 1, e);
        var index = s - 1;
        for (var i = s; i <= e; ++i)
        {
            if (this[i] <= this[e]) this.swap(i, ++index);
        }
        stack.push(s, index - 1, index + 1, e);
    }
}
Array.prototype.mergeSort = function(s, e, b)
{
    if (s == null) s = 0;
    if (e == null) e = this.length - 1;
    if (b == null) b = new Array(this.length);
    if (s >= e) return;
    var m = (s + e) >> 1;
    this.mergeSort(s, m, b);
    this.mergeSort(m + 1, e, b);
    for (var i = s, j = s, k = m + 1; i <= e; ++i)
    {
        b[i] = this[(k > e || j <= m && this[j] < this[k]) ? j++ : k++];
    }
    for (var i = s; i <= e; ++i) this[i] = b[i];
}
Array.prototype.heapSort = function()
{
    for (var i = 1; i < this.length; ++i)
    {
        for (var j = i, k = (j - 1) >> 1; k >= 0; j = k, k = (k - 1) >> 1)
        {
            if (this[k] >= this[j]) break;
            this.swap(j, k);
        }
    }
    for (var i = this.length - 1; i > 0; --i)
    {
        this.swap(0, i);
        for (var j = 0, k = (j + 1) << 1; k <= i; j = k, k = (k + 1) << 1)
        {
            if (k == i || this[k] < this[k - 1]) --k;
            if (this[k] <= this[j]) break;
            this.swap(j, k);
        }
    }
}
<commit_msg>modified<commit_after>/**
 * Created by luke on 2015/1/25.
 */

/*
 内部排序

 在信息处理过程中，最基本的操作是查找。从查找来说，效率最高的是折半查找，折半查找的前提是所有的数据元素(记录)是按关键字有序的。需要将一个无序的数据文件转变为一个有序的数据文件。
 将任一文件中的记录通过某种方法整理成为按(记录)关键字有序排列的处理过程称为排序。
 排序是数据处理中一种最常用的操作。

 排序的基本概念

 ⑴  排序(Sorting)
 排序是将一批(组)任意次序的记录重新排列成按关键字有序的记录序列的过程，其定义为：
 给定一组记录序列：{R1 , R2 ,…, Rn}，其相应的关键字序列是{K1 , K2 ,…, Kn} 。确定1, 2, … n的一个排列p1 , p2 ,…, pn，使其相应的关键字满足如下非递减(或非递增)关系： Kp1<=Kp2 <=…<=Kpn的序列{Kp1 ,Kp2 , …,Kpn} ，这种操作称为排序。
 关键字Ki可以是记录Ri的主关键字，也可以是次关键字或若干数据项的组合。
 ◆  Ki是主关键字：排序后得到的结果是唯一的；
 ◆  Ki是次关键字：排序后得到的结果是不唯一的。

 ⑵  排序的稳定性
 若记录序列中有两个或两个以上关键字相等的记录： Ki =Kj(i≠j，i, j=1, 2, … n)，且在排序前Ri先于Rj(i<j)，排序后的记录序列仍然是Ri先于Rj，称排序方法是稳定的，否则是不稳定的。

 排序算法有许多，但就全面性能而言，还没有一种公认为最好的。每种算法都有其优点和缺点，分别适合不同的数据量和硬件配置。
 评价排序算法的标准有：执行时间和所需的辅助空间，其次是算法的稳定性。
 若排序算法所需的辅助空间不依赖问题的规模n，即空间复杂度是O(1) ，则称排序方法是就地排序，否则是非就地排序。

 ⑶ 排序的分类
 待排序的记录数量不同，排序过程中涉及的存储器的不同，有不同的排序分类。
 ①  待排序的记录数不太多：所有的记录都能存放在内存中进行排序，称为内部排序；
 ②  待排序的记录数太多：所有的记录不可能存放在内存中， 排序过程中必须在内、外存之间进行数据交换，这样的排序称为外部排序。

 ⑷ 内部排序的基本操作
 对内部排序地而言，其基本操作有两种：
 ◆  比较两个关键字的大小；
 ◆ 存储位置的移动：从一个位置移到另一个位置。

 第一种操作是必不可少的；而第二种操作却不是必须的，取决于记录的存储方式，具体情况是：
 ① 记录存储在一组连续地址的存储空间：记录之间的逻辑顺序关系是通过其物理存储位置的相邻来体现，记录的移动是必不可少的；
 ②  记录采用链式存储方式：记录之间的逻辑顺序关系是通过结点中的指针来体现，排序过程仅需修改结点的指针，而不需要移动记录；
 ③  记录存储在一组连续地址的存储空间：构造另一个辅助表来保存各个记录的存放地址(指针) ：排序过程不需要移动记录，而仅需修改辅助表中的指针，排序后视具体情况决定是否调整记录的存储位置。

 ①比较适合记录数较少的情况；而②、③则适合记录数较多的情况。
 为讨论方便，假设待排序的记录是以①的情况存储，且设排序是按升序排列的；关键字是一些可直接用比较运算符进行比较的类型。
 */

// It's just a comparison version, will be removed soon.
Array.prototype.swap = function(i, j)
{
    var temp = this[i];
    this[i] = this[j];
    this[j] = temp;
}
Array.prototype.shellSort = function()
{
    for (var step = this.length >> 1; step > 0; step >>= 1)
    {
        for (var i = 0; i < step; ++i)
        {
            for (var j = i + step; j < this.length; j += step)
            {
                var k = j, value = this[j];
                while (k >= step && this[k - step] > value)
                {
                    this[k] = this[k - step];
                    k -= step;
                }
                this[k] = value;
            }
        }
    }
}
Array.prototype.quickSort = function(s, e)
{
    if (s == null) s = 0;
    if (e == null) e = this.length - 1;
    if (s >= e) return;
    this.swap((s + e) >> 1, e);
    var index = s - 1;
    for (var i = s; i <= e; ++i)
    {
        if (this[i] <= this[e]) this.swap(i, ++index);
    }
    this.quickSort(s, index - 1);
    this.quickSort(index + 1, e);
}
Array.prototype.stackQuickSort = function()
{
    var stack = [0, this.length - 1];
    while (stack.length > 0)
    {
        var e = stack.pop(), s = stack.pop();
        if (s >= e) continue;
        this.swap((s + e) >> 1, e);
        var index = s - 1;
        for (var i = s; i <= e; ++i)
        {
            if (this[i] <= this[e]) this.swap(i, ++index);
        }
        stack.push(s, index - 1, index + 1, e);
    }
}
Array.prototype.mergeSort = function(s, e, b)
{
    if (s == null) s = 0;
    if (e == null) e = this.length - 1;
    if (b == null) b = new Array(this.length);
    if (s >= e) return;
    var m = (s + e) >> 1;
    this.mergeSort(s, m, b);
    this.mergeSort(m + 1, e, b);
    for (var i = s, j = s, k = m + 1; i <= e; ++i)
    {
        b[i] = this[(k > e || j <= m && this[j] < this[k]) ? j++ : k++];
    }
    for (var i = s; i <= e; ++i) this[i] = b[i];
}
Array.prototype.heapSort = function()
{
    for (var i = 1; i < this.length; ++i)
    {
        for (var j = i, k = (j - 1) >> 1; k >= 0; j = k, k = (k - 1) >> 1)
        {
            if (this[k] >= this[j]) break;
            this.swap(j, k);
        }
    }
    for (var i = this.length - 1; i > 0; --i)
    {
        this.swap(0, i);
        for (var j = 0, k = (j + 1) << 1; k <= i; j = k, k = (k + 1) << 1)
        {
            if (k == i || this[k] < this[k - 1]) --k;
            if (this[k] <= this[j]) break;
            this.swap(j, k);
        }
    }
}
<|endoftext|>


<commit_before>var locastyle = locastyle || {};

locastyle.templates = (function() {
  'use strict';

  var templatesPath = 'locastyle/templates/_';

  function init() {
  }

  function popover(elementData) {
    return JST[templatesPath + 'popover'](elementData)
  }

  function modal(elementData) {
    return JST[templatesPath + 'modal'](elementData)
  }

  function dropdown(elements) {
    return JST[templatesPath + 'dropdown']({elements: elements})
  }

  return {
    init: init,
    popover: popover,
    modal: modal,
    dropdown: dropdown
  }

}());
<commit_msg>lint templates<commit_after>var locastyle = locastyle || {};

locastyle.templates = (function() {
  'use strict';

  var templatesPath = 'locastyle/templates/_';

  function init() {}

  function popover(elementData) {
    return JST[templatesPath + 'popover'](elementData);
  }

  function modal(elementData) {
    return JST[templatesPath + 'modal'](elementData);
  }

  function dropdown(elements) {
    return JST[templatesPath + 'dropdown']({elements: elements});
  }

  return {
    init: init,
    popover: popover,
    modal: modal,
    dropdown: dropdown
  };

}());
<|endoftext|>


<commit_before>module.exports = function( grunt ) {
    "use strict";
    var fs = require( "fs" );
    var requirejs = require( "requirejs" );
    var rdefineEnd = /\}\);[^}\w]*$/;

    var config = {
        baseUrl: "./",
        name: "js/main",
        dir: "dist/",
        optimize: "none",
        optimizeCss: "standard",
        mainConfigFile: "js/main.js",
        exclude: ["js/text.js"], // We're handling text plugins separately
        // Include dependencies loaded with require
        findNestedDependencies: true,
        // Avoid breaking semicolons inserted by r.js
        skipSemiColonInsertion: true,
        wrap: {
            startFile: "js/header.part",
            endFile: "js/footer.part"
        },
        fileExclusionRegExp:/^\.|factor-trinomials|node_modules\/*\/*.js|node_modules\/*|build|Gruntfile.js|package.json/,
        preserveLicenseComments: false,
        onBuildWrite: convert
    };

    /**
     * Strip all definitions generated by requirejs
     * Convert "var" modules to var declarations
     * "var module" means the module only contains a return statement that should be converted to a var declaration
     * This is indicated by including the file in any "var" folder
     * @param {String} name
     * @param {String} path
     * @param {String} contents The contents to be written (including their AMD wrappers)
     */
    function convert( name, path, contents ) {
        var amdName;
        // Convert var modules
        if ( /.\/var\//.test( path ) ) {
            contents = contents
                .replace( /define\([\w\W]*?return\s/, "var " + (/var\/([\w-]+)/.exec(name)[1]) + " = " )
                .replace( rdefineEnd, "" );
        }
        else {
            // ignore main module
            switch (name) {
                case "js/main":
                    break;
                case "js/templates":
                    console.log("Building Template module");
                    contents = buildTemplateModule(contents);
                    console.log("Done Building Template module");
                    break;
                default:
                contents = contents
                    .replace( /\s*return\s+[^\}]+(\}\);[^\w\}]*)$/, "$1" )
                    // Multiple exports
                    .replace( /\s*exports\.\w+\s*=\s*\w+;/g, "" );
            }

            // Remove define wrappers, closure ends, and empty declarations
            contents = contents
                .replace( /define\([^{]*?{/, "" )
                .replace( rdefineEnd, "" );

            // Remove empty definitions
            contents = contents
                .replace( /define\(\[[^\]]+\]\)[\W\n]+$/, "" );
        }
        return contents;
    }

    /**
     * Our build process doesn't handle the require text plugin.
     * Since we are using simple html templates, we will just append each template file's contents
     * to a key of the templates object
     */
    function buildTemplateModule(contents) {
        var header = "var templates = {\n"
        var body   = "";
        var footer = "};";
        var rPath  = /(text!(.*))/;         // get requirejs text! paths.
        var rVars  = /function.*?\((.*)\)/; // get first function declaration with template var names.
        var paths  = [];
        var vars   = null; // will be array
        var result = null;

        do {
            result = rPath.exec(contents);
            if (result !== null && result[2] !== undefined) {
                paths.push(result[2].replace(/"|,/g, ""));
                console.log("Recognized template path: "+paths[paths.length-1]);
                contents = contents.replace(result[1], ""); // remove string.
            }
        } while (result !== null);

        result = null; // clear it
        result = rVars.exec(contents);
        vars = result[1].split(",");
        for (var i = 0; i< vars.length; i++) console.log(vars[i]);

        paths.forEach(function(path, index, array) {
            // TODO: Hmmmm... replacing ../ with ./ should be rethought, but it works fine for this project.
            body += vars[index] + ":" + "'" + fs.readFileSync(path.replace("../", "./"), {encoding:"utf8", flag:"r"})
                .replace(/\n/g, "") // remove line breaks
                .replace(/([^\\])'/g, "$1\\'") + "'"; // escape single quotes

            //TODO: can't have "\'" combinations in the file content from the line above

            if (index !== array.length - 1) {
                body += ",";
            }
            body += "\n";
        });

        return (header + body + footer);
    }

    grunt.registerTask(
        "build",
        "run a build",
    function() {
        var done = this.async();
        // Trace dependencies and concatenate files
        requirejs.optimize(config, function( response ) {
            console.log(response);
            done();
        }, function( err ) {
            done( err );
        });
    });
};

<commit_msg>fixing issue in build when path has whitespace<commit_after>module.exports = function( grunt ) {
    "use strict";
    var fs = require( "fs" );
    var requirejs = require( "requirejs" );
    var rdefineEnd = /\}\);[^}\w]*$/;

    var config = {
        baseUrl: "./",
        name: "js/main",
        dir: "dist/",
        optimize: "none",
        optimizeCss: "standard",
        mainConfigFile: "js/main.js",
        exclude: ["js/text.js"], // We're handling text plugins separately
        // Include dependencies loaded with require
        findNestedDependencies: true,
        // Avoid breaking semicolons inserted by r.js
        skipSemiColonInsertion: true,
        wrap: {
            startFile: "js/header.part",
            endFile: "js/footer.part"
        },
        fileExclusionRegExp:/^\.|factor-trinomials|node_modules\/*\/*.js|node_modules\/*|build|Gruntfile.js|package.json/,
        preserveLicenseComments: false,
        onBuildWrite: convert
    };

    /**
     * Strip all definitions generated by requirejs
     * Convert "var" modules to var declarations
     * "var module" means the module only contains a return statement that should be converted to a var declaration
     * This is indicated by including the file in any "var" folder
     * @param {String} name
     * @param {String} path
     * @param {String} contents The contents to be written (including their AMD wrappers)
     */
    function convert( name, path, contents ) {
        var amdName;
        // Convert var modules
        if ( /.\/var\//.test( path ) ) {
            contents = contents
                .replace( /define\([\w\W]*?return\s/, "var " + (/var\/([\w-]+)/.exec(name)[1]) + " = " )
                .replace( rdefineEnd, "" );
        }
        else {
            // ignore main module
            switch (name) {
                case "js/main":
                    break;
                case "js/templates":
                    console.log("Building Template module");
                    contents = buildTemplateModule(contents);
                    console.log("Done Building Template module");
                    break;
                default:
                contents = contents
                    .replace( /\s*return\s+[^\}]+(\}\);[^\w\}]*)$/, "$1" )
                    // Multiple exports
                    .replace( /\s*exports\.\w+\s*=\s*\w+;/g, "" );
            }

            // Remove define wrappers, closure ends, and empty declarations
            contents = contents
                .replace( /define\([^{]*?{/, "" )
                .replace( rdefineEnd, "" );

            // Remove empty definitions
            contents = contents
                .replace( /define\(\[[^\]]+\]\)[\W\n]+$/, "" );
        }
        return contents;
    }

    /**
     * Our build process doesn't handle the require text plugin.
     * Since we are using simple html templates, we will just append each template file's contents
     * to a key of the templates object
     */
    function buildTemplateModule(contents) {
        var header = "var templates = {\n"
        var body   = "";
        var footer = "};";
        var rPath  = /(text!(.*))/;         // get requirejs text! paths.
        var rVars  = /function.*?\((.*)\)/; // get first function declaration with template var names.
        var paths  = [];
        var vars   = null; // will be array
        var result = null;

        do {
            result = rPath.exec(contents);
            if (result !== null && result[2] !== undefined) {
                paths.push(result[2].replace(/"|,/g, ""));
                console.log("Recognized template path: "+paths[paths.length-1]);
                contents = contents.replace(result[1], ""); // remove string.
            }
        } while (result !== null);

        result = null; // clear it
        result = rVars.exec(contents);
        vars = result[1].split(",");
        for (var i = 0; i< vars.length; i++) { console.log(vars[i]); }

        paths.forEach(function(path, index, array) {
            // TODO: Hmmmm... replacing ../ with ./ should be rethought, but it works fine for this project.
            path = path.trim();
            body += vars[index] + ":" + "'" + fs.readFileSync(path.replace("../", "./"), {encoding:"utf8", flag:"r"})
                .replace(/\n/g, "") // remove line breaks
                .replace(/([^\\])'/g, "$1\\'") + "'"; // escape single quotes

            //TODO: can't have "\'" combinations in the file content from the line above

            if (index !== array.length - 1) {
                body += ",";
            }
            body += "\n";
        });

        return (header + body + footer);
    }

    grunt.registerTask(
        "build",
        "run a build",
    function() {
        var done = this.async();
        // Trace dependencies and concatenate files
        requirejs.optimize(config, function( response ) {
            console.log(response);
            done();
        }, function( err ) {
            done( err );
        });
    });
};

<|endoftext|>


<commit_before>$(document).on('ready', function() {
  var $table = $('table[data-table-eventhandler="tableRowToggle"]');
  var $selectedRows;
  $table.on('click', 'tbody>tr', function() {
    $(this).toggleClass('selected');
    if ($(this).hasClass('selected')) {
      $(this).find('td:last-child span').hide();
      $(this).find('td:last-child span.undo-action').show();
    } else {
      $(this).find('td:last-child span').hide();
      $(this).find('td:last-child span.remove-action').show();
    }
    if ($table.find('tr.selected').length > 0) {
      $('.segment-done').show();
    } else {
      $('.segment-done').hide();
    }
  });
  $('.add-remove-all').on('click', function() {
    if ($table.find('tbody>tr.selected').length === $table.find('tbody>tr').length) {
      $table.find('tbody>tr').removeClass('selected');
      $table.find('td:last-child span').hide();
      $table.find('td:last-child span.remove-action').show();
      $('.segment-done').hide();
    } else {
      $table.find('tbody>tr').addClass('selected');
      $table.find('td:last-child span').hide();
      $table.find('td:last-child span.undo-action').show();
      $('.segment-done').show();
    }
  });
  $('#confirm-deletion').on('click', function() {
    if ($table.find('tbody>tr.selected').length === $table.find('tbody>tr').length) {
      // redirect to receipt
    } else {
      $selectedRows = $table.find('tbody>tr.selected');
      $selectedRows.removeClass('selected');
      $selectedRows.find('td:last-child span').hide();
      $selectedRows.find('td:last-child span.deleted-action').show();
    }
  });
});
<commit_msg>Added JS functionality to client delegation table and done segment<commit_after>$(document).on('ready', function() {
  var $table = $('table[data-table-eventhandler="tableRowToggle"]');
  var $segmentDone = $('.segment-done');
  var $selectedRows;
  $table.on('click', 'tbody>tr', function() {
    $(this).toggleClass('selected');
    if ($(this).hasClass('selected')) {
      $(this).find('td:last-child span').hide();
      $(this).find('td:last-child span.undo-action').show();
    } else {
      $(this).find('td:last-child span').hide();
      $(this).find('td:last-child span.remove-action').show();
    }
    if ($table.find('tr.selected').length > 0) {
      $segmentDone.show();
    } else {
      $segmentDone.hide();
    }
  });
  $('.add-remove-all').on('click', function() {
    if ($table.find('tbody>tr.selected').length === $table.find('tbody>tr').length) {
      $table.find('tbody>tr').removeClass('selected');
      $table.find('td:last-child span').hide();
      $table.find('td:last-child span.remove-action').show();
      $segmentDone.hide();
    } else {
      $table.find('tbody>tr').addClass('selected');
      $table.find('td:last-child span').hide();
      $table.find('td:last-child span.undo-action').show();
      $segmentDone.show();
    }
  });
  $('#confirm-deletion').on('click', function() {
    if ($table.find('tbody>tr.selected').length === $table.find('tbody>tr').length) {
      // redirect to receipt
    } else {
      $selectedRows = $table.find('tbody>tr.selected');
      $selectedRows.removeClass('selected').addClass('deleted');
      $selectedRows.find('td:last-child span').hide();
      $selectedRows.find('td:last-child span.deleted-action').show();
      $segmentDone.hide();
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

module.exports =

/*@ngInject*/
function ProofreadingPlayCtrl(
  $scope, $state, ProofreadingService, RuleService, _
) {
  $scope.id = $state.params.id;

  function error(e) {
    console.error(e);
    $state.go('index');
  }

  function prepareProofreading(pf) {
    $scope.passageQuestions = {};
    pf.replace(/{\+([^-]+)-([^|]+)\|([^}]+)}/g, function(key, plus, minus, ruleNumber) {
      $scope.passageQuestions[key] = {
        plus: plus,
        minus: minus,
        ruleNumber: ruleNumber
      };
      pf = pf.replace(key, minus.split(/\s/).join('|'));
    });
    var prepared = _.chain(pf.split(/\s/))
      .filter(function removeNullWords(n) {
        return n !== '';
      })
      .map(function parseHangingPfQuestionsWithNoSpace(w) {
        _.each($scope.passageQuestions, function(v, key) {
          if (w !== key && w.indexOf(key) !== -1) {
            w = w.split(key).join(' ' + key).split(/\s/);
          }
        });
        return w;
      })
      .flatten()
      .map(function(w) {
        w = w.replace(/\|/g, ' ');
        var passageQuestion = _.findWhere($scope.passageQuestions, {minus: w});
        if (passageQuestion) {
          var c = _.clone(passageQuestion);
          c.text = c.minus;
          c.responseText = c.text;
          console.log(c);
          return c;
        } else {
          return {
            text: w,
            responseText: w
          };
        }
      })
      .map(function trim(w) {
        w.text = w.text.trim();
        w.responseText = w.responseText.trim();
        return w;
      })
      .value();

    prepared = _.chain(prepared)
      .zip(_.map(_.range(prepared.length), function() {
        return {
          text: ' ',
          responseText: ' '
        };
      }))
      .flatten()
      .value();
    return prepared;

  }

  $scope.obscure = function(key) {
    return btoa(key);
  };

  $scope.ubObscure = function(o) {
    return atob(o);
  };

  ProofreadingService.getProofreading($scope.id).then(function(pf) {
    pf.passage = prepareProofreading(pf.passage);
    console.log(pf.passage);
    $scope.pf = pf;
  }, error);

  $scope.submitPassage = function(passage) {
    function isValid(passageEntry) {
      if (_.has(passageEntry, 'minus')) {
        //A grammar entry
        return passageEntry.responseText === passageEntry.plus;
      } else {
        //A regular word
        return passageEntry.text === passageEntry.responseText;
      }
    }
    var errors = [];
    _.each(passage, function(p) {
      if (!isValid(p)) {
        errors.push(p);
      }
    });
    if (errors.length > 1) {
      showErrors(errors);
    } else {
      showNext();
    }
  };

  $scope.isBr = function(text) {
    return text.toLowerCase().indexOf('<br/>') !== -1;
  };

  function showErrors(errors) {
    $scope.errors = errors;
  }

  function showNext() {

  }
};
<commit_msg>Correctly sanitize embedded br tags<commit_after>'use strict';

module.exports =

/*@ngInject*/
function ProofreadingPlayCtrl(
  $scope, $state, ProofreadingService, RuleService, _
) {
  $scope.id = $state.params.id;

  function error(e) {
    $state.go('index');
  }

  /* Returns null or an array of matches */
  //TODO Only looking for line break tags right now
  function htmlMatches(text) {
    if (!text) {
      return null;
    }
    return text.match(/<\s*br\s*?\/>/g);
  }

  function prepareProofreading(pf) {
    $scope.passageQuestions = {};
    pf.replace(/{\+([^-]+)-([^|]+)\|([^}]+)}/g, function(key, plus, minus, ruleNumber) {
      $scope.passageQuestions[key] = {
        plus: plus,
        minus: minus,
        ruleNumber: ruleNumber
      };
      pf = pf.replace(key, minus.split(/\s/).join('|'));
    });
    var prepared = _.chain(pf.split(/\s/))
      .filter(function removeNullWords(n) {
        return n !== '';
      })
      .map(function parseHtmlTokens(w) {
        var matches = htmlMatches(w);
        if (matches) {
          _.each(matches, function(match) {
            if (w !== match) {
              w = w.replace(match, ' ' + match + ' ');
            }
          });
          w = w.trim();
          return w.split(/\s/);
        }
        return w;
      })
      .flatten()
      .map(function parseHangingPfQuestionsWithNoSpace(w) {
        _.each($scope.passageQuestions, function(v, key) {
          if (w !== key && w.indexOf(key) !== -1) {
            w = w.split(key).join(' ' + key).split(/\s/);
          }
        });
        return w;
      })
      .flatten()
      .map(function(w) {
        w = w.replace(/\|/g, ' ');
        var passageQuestion = _.findWhere($scope.passageQuestions, {minus: w});
        if (passageQuestion) {
          var c = _.clone(passageQuestion);
          c.text = c.minus;
          c.responseText = c.text;
          return c;
        } else {
          return {
            text: w,
            responseText: w
          };
        }
      })
      .map(function trim(w) {
        w.text = w.text.trim();
        w.responseText = w.responseText.trim();
        return w;
      })
      .value();

    prepared = _.chain(prepared)
      .zip(_.map(_.range(prepared.length), function() {
        return {
          text: ' ',
          responseText: ' '
        };
      }))
      .flatten()
      .value();
    return prepared;

  }

  $scope.obscure = function(key) {
    return btoa(key);
  };

  $scope.ubObscure = function(o) {
    return atob(o);
  };

  ProofreadingService.getProofreading($scope.id).then(function(pf) {
    pf.passage = prepareProofreading(pf.passage);
    $scope.pf = pf;
  }, error);

  $scope.submitPassage = function(passage) {
    function isValid(passageEntry) {
      if (_.has(passageEntry, 'minus')) {
        //A grammar entry
        return passageEntry.responseText === passageEntry.plus;
      } else {
        //A regular word
        return passageEntry.text === passageEntry.responseText;
      }
    }
    var errors = [];
    _.each(passage, function(p) {
      if (!isValid(p)) {
        errors.push(p);
      }
    });
    if (errors.length > 1) {
      showErrors(errors);
    } else {
      showNext();
    }
  };

  $scope.isBr = function(text) {
    return htmlMatches(text) !== null;
  };

  function showErrors(errors) {
    $scope.errors = errors;
  }

  function showNext() {

  }
};
<|endoftext|>


<commit_before>sn.replaceAll = function(whatToReplace) {
  return {
    with: function(replaceWith) {
      return typeof sn.__EC__ === 'string'
        ? sn.__EC__.replace(new RegExp(whatToReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replaceWith)
        : sn.__EC__;
    }
  }
};

sn.capitalize = function(str) {
  return typeof str === 'string' ? str[(0)].toUpperCase() + str.slice(1) : str;
};

/***********************************************
 * Below methods has been taken from
 * https://github.com/epeli/underscore.string
************************************************/

/*
 * test if string contains substring
 * @ignore case - case is ignored on comparation
 * @example capitalize('foo Bar', 'oo'); => 'Foo Bar'; capitalize('FOO Bar', true); => 'Foo bar'
 * https://github.com/epeli/underscore.string
*/
sn.contains = function(str1, str2, ignoreCase) {
  if (ignoreCase === true) {
    str1 = str1.toLowerCase();
    str2 = str2.toLowerCase();
  }
  return str1.indexOf(str2) !== -1;
};

/*
 * Break string in array of substring
 * @example: chop("whitespace", 3); => ['whi', 'tes', 'pac', 'e']
*/
sn.chop = function(str, step) {
  if (!str) { return []; }
  str = String(str);
  step = ~~step;
  return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
};

/*
* Trim and replace multiple spaces with a single space.
* @example clean(' foo    bar   '); => 'foo bar'
*/
sn.clean = function(str) {
  return str.trim().replace(/\s\s+/g, ' ');
};

/**
* Truncate string if it exceed max number of characters,
* apply provided truncate string at the end of truncated string (default: '...')
*/
sn.truncate = function(str, length, truncateStr) {
  truncateStr = truncateStr || '...';
  length = ~~length;
  return str.length > length ? str.slice(0, length) + truncateStr : str;
};
<commit_msg>add between method to sn.string<commit_after>sn.replaceAll = function (whatToReplace) {
  return {
    with: function (replaceWith) {
      return typeof sn.__EC__ === 'string'
        ? sn.__EC__.replace(new RegExp(whatToReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replaceWith)
        : sn.__EC__;
    }
  };
};

sn.capitalize = function (str) {
  return typeof str === 'string' ? str[(0)].toUpperCase() + str.slice(1) : str;
};

/***********************************************
 * Below methods has been taken from
 * https://github.com/epeli/underscore.string
************************************************/

/*
 * test if string contains substring
 * @ignore case - case is ignored on comparation
 * @example capitalize('foo Bar', 'oo'); => 'Foo Bar'; capitalize('FOO Bar', true); => 'Foo bar'
 * https://github.com/epeli/underscore.string
*/
sn.contains = function (str1, str2, ignoreCase) {
  if (ignoreCase === true) {
    str1 = str1.toLowerCase();
    str2 = str2.toLowerCase();
  }
  return str1.indexOf(str2) !== -1;
};

/*
 * Break string in array of substring
 * @example: chop("whitespace", 3); => ['whi', 'tes', 'pac', 'e']
*/
sn.chop = function (str, step) {
  if (!str) { return []; }
  str = String(str);
  step = ~~step;
  return step > 0 ? str.match(new RegExp('.{1,' + step + '}', 'g')) : [str];
};

/*
* Trim and replace multiple spaces with a single space.
* @example clean(' foo    bar   '); => 'foo bar'
*/
sn.clean = function (str) {
  return str.trim().replace(/\s\s+/g, ' ');
};

/**
* Truncate string if it exceed max number of characters,
* apply provided truncate string at the end of truncated string (default: '...')
*/
sn.truncate = function (str, length, truncateStr) {
  truncateStr = truncateStr || '...';
  length = ~~length;
  return str.length > length ? str.slice(0, length) + truncateStr : str;
};

/**********************************************
* Get the substring of the string between 2 substrings,
TODO: not documented or tested
***************************************************/
sn.between = function (startStr, endStr) {
  var startIndex = sn.__EC__.indexOf(startStr);
  var endIndex = sn.__EC__.indexOf(endStr);

  if (startIndex === -1 || startIndex === -1) {
    return undefined;
  }

  startIndex += startStr.length;
  return sn.__EC__.substr(startIndex, endIndex - startIndex);
};
<|endoftext|>


<commit_before>/*global requestAnimationFrame */

var Three = require('../lib/three.min');

var Wall = require('./wall');
var Lights = require('./lights');
var Controls = require('./controls');

var create = function(sceneWidth, sceneHeight) {

    'use strict';

    var scene = new Three.Scene();
    var camera = new Three.PerspectiveCamera(
        75,
        sceneWidth / sceneHeight,
        0.1,
        1000
    );
    var cameraDist = 200;
    camera.position.set(0, 0, cameraDist);
    var vFOV = camera.fov * Math.PI / 180;
    var height = 2 * Math.tan( vFOV / 2 ) * cameraDist; // visible height

    var aspect = sceneWidth / sceneHeight;
    var width = height * aspect;
    console.log(height, width);

    var tilesize = 5;
    var wallWidth = Math.ceil(width / tilesize) + 4;
    var wallHeight = Math.ceil(height / tilesize) + 4;
    var wall = Wall.createWall(wallWidth, wallHeight, tilesize);
    scene.add(wall.mesh);

    var renderer = new Three.WebGLRenderer();
    renderer.setSize( sceneWidth, sceneHeight );

    scene.add(Lights.createDirectional(0xffaaff,1));

    scene.add(Lights.createAmbient(0x001100));

    var speed = 0.1;

    var render = function (t) {
        requestAnimationFrame(function () {
            render(t + speed);
        });
        renderer.render(scene, camera);
        wall.animate(t);
    };

    var raycaster = new Three.Raycaster();
    var mouse = new Three.Vector2();
    var click = function (xVal, yVal) {
        var xPos, yPos, p;
        mouse.x = (xVal * 2) - 1;
        mouse.y = -(yVal * 2) + 1;
        console.log(mouse);
        raycaster.setFromCamera( mouse, camera );
        var intersects = raycaster.intersectObjects( [wall.mesh] );
        console.log(intersects);
        if (intersects.length > 0) {
            p = intersects[0].face.a;
            xPos = Math.floor(p / wall.points.yPoints);
            yPos = p % wall.points.yPoints;
            wall.createRipple(xPos, yPos);
            console.log(xPos, yPos);
        }
    };

    return {
        click: click,
        renderer: renderer,
        scene: scene,
        camera: camera,
        render: render
    };

};

module.exports = {
    create: create
};

<commit_msg>Removing debug statements<commit_after>/*global requestAnimationFrame */

var Three = require('../lib/three.min');

var Wall = require('./wall');
var Lights = require('./lights');
var Controls = require('./controls');

var create = function(sceneWidth, sceneHeight) {

    'use strict';

    var scene = new Three.Scene();
    var camera = new Three.PerspectiveCamera(
        75,
        sceneWidth / sceneHeight,
        0.1,
        1000
    );
    var cameraDist = 200;
    camera.position.set(0, 0, cameraDist);
    var vFOV = camera.fov * Math.PI / 180;
    var height = 2 * Math.tan( vFOV / 2 ) * cameraDist; // visible height

    var aspect = sceneWidth / sceneHeight;
    var width = height * aspect;

    var tilesize = 5;
    var wallWidth = Math.ceil(width / tilesize) + 4;
    var wallHeight = Math.ceil(height / tilesize) + 4;
    var wall = Wall.createWall(wallWidth, wallHeight, tilesize);
    scene.add(wall.mesh);

    var renderer = new Three.WebGLRenderer();
    renderer.setSize( sceneWidth, sceneHeight );

    scene.add(Lights.createDirectional(0xffaaff,1));

    scene.add(Lights.createAmbient(0x001100));

    var speed = 0.1;

    var render = function (t) {
        requestAnimationFrame(function () {
            render(t + speed);
        });
        renderer.render(scene, camera);
        wall.animate(t);
    };

    var raycaster = new Three.Raycaster();
    var mouse = new Three.Vector2();
    var click = function (xVal, yVal) {
        var xPos, yPos, p;
        mouse.x = (xVal * 2) - 1;
        mouse.y = -(yVal * 2) + 1;
        raycaster.setFromCamera( mouse, camera );
        var intersects = raycaster.intersectObjects( [wall.mesh] );
        if (intersects.length > 0) {
            p = intersects[0].face.a;
            xPos = Math.floor(p / wall.points.yPoints);
            yPos = p % wall.points.yPoints;
            wall.createRipple(xPos, yPos);
        }
    };

    return {
        click: click,
        renderer: renderer,
        scene: scene,
        camera: camera,
        render: render
    };

};

module.exports = {
    create: create
};

<|endoftext|>