<commit_before>/* global require, exports */
/* jshint -W116 */

var fs = require('fs'),
	process = require('process'),
	childProcess = require('child_process'),
    config = require('./config.js'),
    teamMembers = config.teamMembers,
	scrollbackProcesses = {};

var startScrollback = function(branch) {
	process.chdir(config.baseDir + 'scrollback-' + branch);
	scrollbackProcesses[branch] = childProcess.spawn('node index.js');
};

/*var stopScrollback = function(branch) {
	scrollbackProcesses[branch].kill();
	delete scrollbackProcesses[branch];
};*/

exports.createDomain = function(user, branch, pullRequestNo) {
    var port = 7000 + pullRequestNo;

	var copyFile = function (readPath, writePath, lineTransform, callback) {
        fs.readFile(readPath, function(err, data) {
            if (err) throw err;

			fs.writeFile(
				writePath,
				data.toString('utf-8').split("\n").map(lineTransform).join('\n'),
				function(err) {
					if (err) throw err;
					callback();
				}
			);
        });
	};

    if (teamMembers.indexOf(user) < 0) return;

	// First, check out this branch into a new directory.

	process.chdir(config.baseDir);
	childProcess.exec(
		'git clone --depth 1 --branch ' + branch +
		' https://github.com/scrollback/scrollback.git scrollback-' + branch, function (err) {
			if(err !== null) {
				console.log('Error occured while checking out ' + branch, err);
				return;
			}

			var createCallback = (function () {
				var numOps = 0;
				return function () {
					numOps++;
					return function () {
						numOps--;
						if(numOps === 0) startScrollback(branch);
					};
				};
			})();

			// copy and transform the nginx file
			copyFile(
				config.base_dir + 'scrollback-' + branch + '/tools/nginx.conf',
				config.nginx_dir + 'scrollback-' + branch + '.stage.scrollback.io',
				function (line) { // line transform function
					return line.replace(/$branch\b/g, branch).replace(/$port\b/g, port);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/server-config.sample.js',
				config.baseDir + 'scrollback-' + branch + '/server-config.js',
				function (line) { // line transform function
					return line.replace(/$branch\b/g, branch).replace(/$port\b/g, port);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/client-config.sample.js',
				config.baseDir + 'scrollback-' + branch + '/client-config.js',
				function (line) { // line transform function
					return line.replace(/$branch\b/g, branch);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);
		});
    };

/*exports.deleteDomain = function (user, branch) {
	stopScrollback(branch);
}*/
<commit_msg>regex correction<commit_after>/* global require, exports */
/* jshint -W116 */

var fs = require('fs'),
	process = require('process'),
	childProcess = require('child_process'),
    config = require('./config.js'),
    teamMembers = config.teamMembers,
	scrollbackProcesses = {};

var startScrollback = function(branch) {
	process.chdir(config.baseDir + 'scrollback-' + branch);
	scrollbackProcesses[branch] = childProcess.spawn('node index.js');
};

/*var stopScrollback = function(branch) {
	scrollbackProcesses[branch].kill();
	delete scrollbackProcesses[branch];
};*/

exports.createDomain = function(user, branch, pullRequestNo) {
    var port = 7000 + pullRequestNo;

	var copyFile = function (readPath, writePath, lineTransform, callback) {
        fs.readFile(readPath, function(err, data) {
            if (err) throw err;

			fs.writeFile(
				writePath,
				data.toString('utf-8').split("\n").map(lineTransform).join('\n'),
				function(err) {
					if (err) throw err;
					callback();
				}
			);
        });
	};

    if (teamMembers.indexOf(user) < 0) return;

	// First, check out this branch into a new directory.

	process.chdir(config.baseDir);
	childProcess.exec(
		'git clone --depth 1 --branch ' + branch +
		' https://github.com/scrollback/scrollback.git scrollback-' + branch, function (err) {
			if(err !== null) {
				console.log('Error occured while checking out ' + branch, err);
				return;
			}

			var createCallback = (function () {
				var numOps = 0;
				return function () {
					numOps++;
					return function () {
						numOps--;
						if(numOps === 0) startScrollback(branch);
					};
				};
			})();

			// copy and transform the nginx file
			copyFile(
				config.base_dir + 'scrollback-' + branch + '/tools/nginx.conf',
				config.nginx_dir + 'scrollback-' + branch + '.stage.scrollback.io',
				function (line) { // line transform function
					return line.replace(/\b\$branch\b/g, branch).replace(/\b\$port\b/g, port);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/server-config.sample.js',
				config.baseDir + 'scrollback-' + branch + '/server-config.js',
				function (line) { // line transform function
					return line.replace(/\b\$branch\b/g, branch).replace(/\b\$port\b/g, port);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);

			copyFile(
				config.baseDir + 'scrollback-' + branch + '/client-config.sample.js',
				config.baseDir + 'scrollback-' + branch + '/client-config.js',
				function (line) { // line transform function
					return line.replace(/\b\$branch\b/g, branch);
					// inside the file, write server_name $branch.stage.scrollack.io
				},
				createCallback()
			);
		});
    };

/*exports.deleteDomain = function (user, branch) {
	stopScrollback(branch);
}*/
<|endoftext|>


<commit_before>window.graph.graph = function(){
 	//get data
 	var days = [];

 	var hwResult;
	var hws = [0,0,0,0,0,0,0];
	window.api.get('planner/events/getWholeWeek/' + window.utils.formatDate_api(moment().add(i, "days").toDate()), function(result) {
 	    var hwResult = result.events;

 	    console.log(result.events.length);
	    var date = window.utils.formatDate_api(moment().toDate());
	    for (var i=0;i<result.events.length;i++){
    	console.log(i);
 			var iDate = window.utils.formatDate_api(moment(hwResult[i]["date"]).toDate());
 			console.log(iDate);
 	        var dayToAssign = (parseInt(iDate[8] + iDate[9])) - parseInt(date[8] + date[9]);console.log(dayToAssign);
 	        hws[dayToAssign] += 1;
 	    }
 	});

  	//set up axis for graph
  	switch (new Date().getDay()) {
  	    	case 0:
  			days = ["Sunday","Monday","Tuesday","Wensday","Thursday","Friday","Saturday"];
  			break;
  	    	case 1:
  			days = ["Monday","Tuesday","Wensday","Thursday","Friday","Saturday","Sunday"];
  			break;
  	    	case 2:
  			days = ["Tuesday","Wensday","Thursday","Friday","Saturday","Sunday","Monday"];
  			break;
 	    	case 3:
  			days = ["Wensday","Thursday","Friday","Saturday","Sunday","Monday","Tuesday"];
  			break;
  	    	case 4:
  			days = ["Thursday","Friday","Saturday","Sunday","Monday","Tuesday","Wensday"];
  			break;
 	    	case 5:
  			days = ["Friday","Saturday","Sunday","Monday","Tuesday","Wensday","Thursday"];
  			break;
  	    	case 6:
  			days = ["Saturday","Sunday","Monday","Tuesday","Wensday","Thursday","Friday"];
  			break;
  	}
  	//how do i include this '<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>''
	  var chart = new CanvasJS.Chart("chartContainer", {
		theme: "theme1",//theme1
		title:{
			  text: "Your Homework"
		},
		animationEnabled: true,   // change to true
		data: [
		{
			// Change type to "bar", "area", "spline", "pie",etc.
			type: "line",
			dataPoints: [
				{ label: days[0],  y: hws[0]  },
				{ label: days[1], y: hws[1]  },
				{ label: days[2], y: hws[2]  },
				{ label: days[3],  y: hws[3]  },
				{ label: days[4],  y: hws[4]  },
				{ label: days[5], y: hws[5]   },
				{ label: days[6], y: hws[6]   },
			]
		}
		]
	});
	chart.render();

  }
<commit_msg>Delete graphs.js<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node
var commands = {},
    basedir = process.env.HOME || __dirname,
    db = require('./db.js').open(basedir + '/.habits.json'),
    foreach = require('snippets').foreach;

/* Print duration */
function duration(time) {
	var total_secs = time / 1000,
	    days = Math.floor(total_secs/(24*3600)),
	    hours = Math.floor(total_secs/3600) - days*24,
	    minutes = Math.floor(total_secs/60) - hours*60 - days*24*60,
	    tokens = [];
	if(days !== 0) tokens.push(days + ' days');
	if(hours !== 0) tokens.push(hours +' hours');
	if(tokens.length === 0) tokens.push(minutes + ' minutes');
	return tokens.join(' ');
}

/* Event when database becomes ready */
db.on('ready', function() {
	if(!db.habits) {
		db.habits = [];
		db.commit(function(err) {
			if(err) console.error('Failed to commit: ' + err);
		});
	}
});

/* Help command */
commands.help = function() {
	console.log('Commands:');
	console.log('  list      -- list habits');
	console.log('  add HABIT -- add new habit');
	console.log('  trigger|do HABIT -- trigger habit');
};

/* Add habit */
commands.add = function(name) {
	db.whenReady(function() {
		db.habits.push({'name':name});
		db.commit(function(err) {
			if(err) console.error('Failed to commit: ' + err);
			else console.log('OK');
		});
	});
};

/* Trigger habit */
commands.trigger = function(name) {
	db.whenReady(function() {
		var habit;
		foreach(db.habits).each(function(obj) {
			if(obj.name.toLowerCase() === name.toLowerCase()) {
				habit = obj;
			}
		});

		if(!habit) {
			console.log('Could not find habit by name ' + name);
			return;
		}

		habit.last = (new Date()).getTime();
		db.commit(function(err) {
			if(err) console.error('Failed to commit: ' + err);
			else console.log('OK');
		});
	});
};

commands['do'] = commands.trigger;

/* List habits */
commands.list = function() {
	console.log('Habit | Last time');
	console.log('------+----------');
	db.whenReady(function() {
		foreach(db.habits).each(function(habit) {
			var last = new Date(),
			    now = new Date(),
			    msecs;
			if(habit.last) {
				last.setTime(habit.last);
				msecs = now.getTime() - last.getTime();
			}
			if(!habit.last) {
				console.log(habit.name + ' | Never done before');
			} else {
				console.log(habit.name + ' | ' + duration(msecs) + ' ago');
			}
		});
	});
};

/* */
(function() {
	var optimist = require('optimist'),
	    argv = optimist
	    .usage('Usage: $0 COMMAND [arguments]')
	    .argv,
	    name = argv._.shift(),
	    fn = commands[name];
	if(fn && commands.hasOwnProperty(name) && (typeof fn === 'function')) {
		commands[name].apply(commands, argv._);
	} else {
		console.error('Error: Unknown command: ' + name);
		optimist.showHelp();
	}
})();

/* EOF */
<commit_msg>Improved output<commit_after>#!/usr/bin/env node
var commands = {},
    basedir = process.env.HOME || __dirname,
    db = require('./db.js').open(basedir + '/.habits.json'),
    foreach = require('snippets').foreach,
	rpad = require('snippets').rpad;

/* Print duration */
function duration(time) {
	var total_secs = time / 1000,
	    days = Math.floor(total_secs/(24*3600)),
	    hours = Math.floor(total_secs/3600) - days*24,
	    minutes = Math.floor(total_secs/60) - hours*60 - days*24*60,
	    tokens = [];
	if(days !== 0) tokens.push(days + ' days');
	if(hours !== 0) tokens.push(hours +' hours');
	if(tokens.length === 0) tokens.push(minutes + ' minutes');
	return tokens.join(' ');
}

/* Event when database becomes ready */
db.on('ready', function() {
	if(!db.habits) {
		db.habits = [];
		db.commit(function(err) {
			if(err) console.error('Failed to commit: ' + err);
		});
	}
});

/* Help command */
commands.help = function() {
	console.log('Commands:');
	console.log('  list      -- list habits');
	console.log('  add HABIT -- add new habit');
	console.log('  trigger|do HABIT -- trigger habit');
};

/* Add habit */
commands.add = function(name) {
	db.whenReady(function() {
		db.habits.push({'name':name});
		db.commit(function(err) {
			if(err) console.error('Failed to commit: ' + err);
			else console.log('OK');
		});
	});
};

/* Trigger habit */
commands.trigger = function(name) {
	db.whenReady(function() {
		var habit;
		foreach(db.habits).each(function(obj) {
			if(obj.name.toLowerCase() === name.toLowerCase()) {
				habit = obj;
			}
		});

		if(!habit) {
			console.log('Could not find habit by name ' + name);
			return;
		}

		habit.last = (new Date()).getTime();
		db.commit(function(err) {
			if(err) console.error('Failed to commit: ' + err);
			else console.log('OK');
		});
	});
};

commands['do'] = commands.trigger;

/* List habits */
commands.list = function() {
	db.whenReady(function() {
		var habits = [], key_size;
		foreach(db.habits).each(function(habit) {
			var last = new Date(),
			    now = new Date(),
			    msecs;

			if(key_size === undefined) {
				key_size = habit.name.length;
			} else if(habit.name.length > key_size) {
				key_size = habit.name.length;
			}

			if(habit.last) {
				last.setTime(habit.last);
				msecs = now.getTime() - last.getTime();
				habits.push({'name':habit.name, 'last':habit.last, 'msecs':msecs});
			} else {
				habits.push({'name':habit.name});
			}
		});

		habits.sort(function(a, b) {
			var a_msecs = a.msecs || 0,
			    b_msecs = b.msecs || 0;
			return (a_msecs === b_msecs) ? 0 : ( (a_msecs < b_msecs) ? 1 : -1 );
		});

		console.log(rpad('Habit', key_size, ' ') + ' | Last time');
		console.log(rpad('', key_size, '-') + '-+----------');
		foreach(habits).each(function(habit) {
			if(!habit.msecs) {
				console.log(rpad(habit.name, key_size, ' ') + ' | ');
			} else {
				console.log(rpad(habit.name, key_size, ' ') + ' | ' + duration(habit.msecs) + ' ago');
			}
		});
	});

};

/* */
(function() {
	var optimist = require('optimist'),
	    argv = optimist
	    .usage('Usage: $0 COMMAND [arguments]')
	    .argv,
	    name = argv._.shift(),
	    fn = commands[name];
	if(fn && commands.hasOwnProperty(name) && (typeof fn === 'function')) {
		commands[name].apply(commands, argv._);
	} else {
		console.error('Error: Unknown command: ' + name);
		optimist.showHelp();
	}
})();

/* EOF */
<|endoftext|>


<commit_before>var hearts = function() {

	var heart_2_clicks = 0;

	function uniform_between(min, max) {
		return min + Math.floor(Math.random() * (max - min + 1));
	}

    function heart_3() {
        // cf. http://www.mathematische-basteleien.de/heart.htm#Calculated Hearts (6)
        var points1 = [];
        var points2 = [];
        d3.range(-2, 2, 0.01)
            .forEach(function(x) {
                var y_1 = Math.sqrt(Math.abs(x)) - Math.sqrt(3 - x*x),
                    y_2 = Math.sqrt(Math.abs(x)) + Math.sqrt(3 - x*x);
                points1.push({'x' : x, 'y' : y_1});
                points2.unshift({'x' : x, 'y' : y_2});
            });
        return points2.concat(points1);
    }

    function heart_1() {
        // cf. http://www.mathematische-basteleien.de/heart.htm#Calculated Hearts (3)
        var points = [];
        d3.range(-1, 1, 0.001)
            .forEach(function(t) {
                var abs_t = Math.abs(t),
	                cos_t = Math.cos(t),
	                sin_t = Math.sin(t),
	                x = sin_t * cos_t * Math.log(abs_t),
	                y = Math.sqrt(abs_t) * cos_t;
                points.push({'x':x, 'y':y});
            });
        return points;
    }

    function heart_2() {
        // cf. http://de.wikipedia.org/wiki/Benutzer:Georg-Johann
        var points = [];
        d3.range(-3, 3, 0.1)
            .forEach(function(t) {
                var x = 12*Math.sin(t) - 4*Math.sin(3*t),
                	y = 13*Math.cos(t)- 5*Math.cos(2*t) - 2*Math.cos(3*t) - Math.cos(4*t);
                points.push({'x':x, 'y':y});
            });
        return points;
    }

    function get_heart_curve(transform, generator) {
        var scale = 'scale' in transform ? transform.scale : [1,1],
            translate = 'translate' in transform ? transform.translate : [0,0],
            // Since the browser's coordinate axis is "inverted", the 180 deg rotation puts the heart straight.
            // Adding 180 also makes the rotation clockwise instead of counter-clockwise.
            rotation_deg = 'rotate' in transform ? 180 + transform.rotate : 180,
            rotation_rad = rotation_deg * Math.PI / 180,
            scale_x = scale[0],
            scale_y = scale[1],
            translate_x = translate[0],
            translate_y = translate[1],
            points = generator(),
            mapped_points = [];

        points.forEach(function(point) {
	        var x = point.x,
	        	y = point.y,
	        	// y - 0.321: in order to rotate with respect to the center (approx.) of the heart
	        	x_rot = x*Math.cos(rotation_rad) - (y)*Math.sin(rotation_rad),
	            y_rot = x*Math.sin(rotation_rad) + (y)*Math.cos(rotation_rad),
	            x_prime = translate_x + scale_x * x_rot,
	            y_prime = translate_y + scale_y * y_rot;
	        if(!isNaN(x_prime) && !isNaN(y_prime))
	            mapped_points.push({'x' : x_prime , 'y' : y_prime});
        });
        return mapped_points;
    }

    function get_svg_path_from(transform, generator) {
    	var curve = d3.svg.line()
						.x(function(d) {return d.x; })
						.y(function(d) {return d.y; })
						.interpolate('linear'),
			points = get_heart_curve(transform, generator);
    	return curve(points);
    }

    function draw_heart(svg, transform, generator) {
    	var path = get_svg_path_from(transform, generator);

    	return svg.append('path')
		        .attr('class', 'heart')
		        .attr('fill', 'red')
		        .style('cursor', 'pointer')
		        .attr('d', path);
    }

    function click_heart(svg, index) {
    	if(index == 1) {
    		var scale = uniform_between(20, 70),
    			random_scale = [scale, scale],
    			random_position = [uniform_between(10, 1200), uniform_between(10, 800)],
    			random_angle = uniform_between(0, 360),
    			transform = {'scale' : random_scale, 'translate' : random_position, 'rotate' : random_angle};
    			draw_heart(svg, transform, heart_1)
    				.attr('class', 'expendable_heart')
    				.attr('fill', 'hsl(' + Math.random()*50 + ',100%,50%)')
    				.on('click', function(d) {
    					d3.selectAll('.expendable_heart')
    						.transition()
    							.style('opacity',0)
    							.remove();
    				});
    	}
    	else if(index == 2) {
    		if(heart_2_clicks >= 3) {
    			d3.selectAll('.expendable_text')
    				.transition()
    					.style('opacity', 0)
    					.remove();
    			heart_2_clicks = 0;
    			return;
    		}

    		var values = [{'text':'Felices','x':0,'color':'black'},
    		              {'text':'siete', 'x':440, 'color':'red'},
    		              {'text':'meseees!', 'x':730,'color':'black'}
    		             ],
    			value = values[heart_2_clicks];

    		svg.append('text')
    			.attr('class', 'expendable_text')
    			.attr('x', 2000)
    			.attr('y', 550)
    			.attr('font-family', 'sans-serif')
    			.attr('font-size', 140)
    			.attr('fill', value.color)
    			.style('opacity', 0)
    			.text(value.text)
    			.transition()
    				.attr('x', value.x)
    				.style('opacity', 1)
    				.duration(3000);

    		heart_2_clicks++;
    	}
    	else if(index == 3) {
    		var heart_idx = uniform_between(1, 3),
    			heart = d3.select('#heart' + heart_idx);
    		heart
    			.transition()
    				.duration(2000)
    				.attr('fill', 'hsl(' + Math.random()*50 + ',100%,50%)');
    	}
    }

    var hearts = {
        draw : function() {
            var svg = d3.select('#main').append('svg'),
	            heart1_transform = {'scale' : [300,300], 'translate' : [150,300]},
	            heart2_transform = {'scale' : [7,7], 'translate' : [670,190]},
	            heart3_transform = {'scale' : [50,50], 'translate' : [1200,230]},
            	heart1 = draw_heart(svg, heart1_transform, heart_1),
            	heart2 = draw_heart(svg, heart2_transform, heart_2),
            	heart3 = draw_heart(svg, heart3_transform, heart_3);

            heart1
            	.datum(heart1_transform)
            	.attr('id', 'heart1')
	            .on('mouseover', function(d) {
	            	var temp_heart = draw_heart(svg, heart1_transform, heart_1);
	            	temp_heart
	            		.on('click', function(d) { click_heart(svg, 1); })
	            		.attr('fill', heart1.attr('fill'))
	            		.transition()
	            			.duration(750)
	            			.attr('d', get_svg_path_from({'scale':[5000,5000], 'translate' : [100,2200]}, heart_1))
	            			.style('opacity', 0)
	            			.remove();
	            })
	            .on('click', function(d) { click_heart(svg, 1); });

            heart2
            	.datum(heart2_transform)
            	.attr('id', 'heart2')
            	.on('mouseover', function(d) {
	            	var temp_heart = draw_heart(svg, heart2_transform, heart_2);
	            	temp_heart
	            		.on('click', function(d) { click_heart(svg, 2); })
	            		.attr('fill', heart2.attr('fill'))
	            		.transition()
	            			.duration(750)
	            			.attr('d', get_svg_path_from({'scale':[100,100], 'translate' : [670,500]}, heart_2))
	            			.style('opacity', 0)
	            			.remove();
	            })
	            .on('click', function(d) { click_heart(svg, 2); });

            heart3
            	.datum(heart3_transform)
            	.attr('id', 'heart3')
            	.on('mouseover', function(d) {
	            	var temp_heart = draw_heart(svg, heart3_transform, heart_3);
	            	temp_heart
	            		.on('click', function(d) { click_heart(svg, 3); })
	            		.attr('fill', heart3.attr('fill'))
	            		.transition()
	            			.duration(750)
	            			.attr('d', get_svg_path_from({'scale':[1000,1000], 'translate' : [1200,950]}, heart_3))
	            			.style('opacity', 0)
	            			.remove();
	            })
	            .on('click', function(d) { click_heart(svg, 3); });

        }
    };

    return hearts;
}();
<commit_msg>Update hearts.js<commit_after>var hearts = function() {

	var heart_2_clicks = 0;

	function uniform_between(min, max) {
		return min + Math.floor(Math.random() * (max - min + 1));
	}

    function heart_3() {
        // cf. http://www.mathematische-basteleien.de/heart.htm#Calculated Hearts (6)
        var points1 = [];
        var points2 = [];
        d3.range(-2, 2, 0.01)
            .forEach(function(x) {
                var y_1 = Math.sqrt(Math.abs(x)) - Math.sqrt(3 - x*x),
                    y_2 = Math.sqrt(Math.abs(x)) + Math.sqrt(3 - x*x);
                points1.push({'x' : x, 'y' : y_1});
                points2.unshift({'x' : x, 'y' : y_2});
            });
        return points2.concat(points1);
    }

    function heart_1() {
        // cf. http://www.mathematische-basteleien.de/heart.htm#Calculated Hearts (3)
        var points = [];
        d3.range(-1, 1, 0.001)
            .forEach(function(t) {
                var abs_t = Math.abs(t),
	                cos_t = Math.cos(t),
	                sin_t = Math.sin(t),
	                x = sin_t * cos_t * Math.log(abs_t),
	                y = Math.sqrt(abs_t) * cos_t;
                points.push({'x':x, 'y':y});
            });
        return points;
    }

    function heart_2() {
        // cf. http://de.wikipedia.org/wiki/Benutzer:Georg-Johann
        var points = [];
        d3.range(-3, 3, 0.1)
            .forEach(function(t) {
                var x = 12*Math.sin(t) - 4*Math.sin(3*t),
                	y = 13*Math.cos(t)- 5*Math.cos(2*t) - 2*Math.cos(3*t) - Math.cos(4*t);
                points.push({'x':x, 'y':y});
            });
        return points;
    }

    function get_heart_curve(transform, generator) {
        var scale = 'scale' in transform ? transform.scale : [1,1],
            translate = 'translate' in transform ? transform.translate : [0,0],
            // Since the browser's coordinate axis is "inverted", the 180 deg rotation puts the heart straight.
            // Adding 180 also makes the rotation clockwise instead of counter-clockwise.
            rotation_deg = 'rotate' in transform ? 180 + transform.rotate : 180,
            rotation_rad = rotation_deg * Math.PI / 180,
            scale_x = scale[0],
            scale_y = scale[1],
            translate_x = translate[0],
            translate_y = translate[1],
            points = generator(),
            mapped_points = [];

        points.forEach(function(point) {
	        var x = point.x,
	        	y = point.y,
	        	// y - 0.321: in order to rotate with respect to the center (approx.) of the heart
	        	x_rot = x*Math.cos(rotation_rad) - (y)*Math.sin(rotation_rad),
	            y_rot = x*Math.sin(rotation_rad) + (y)*Math.cos(rotation_rad),
	            x_prime = translate_x + scale_x * x_rot,
	            y_prime = translate_y + scale_y * y_rot;
	        if(!isNaN(x_prime) && !isNaN(y_prime))
	            mapped_points.push({'x' : x_prime , 'y' : y_prime});
        });
        return mapped_points;
    }

    function get_svg_path_from(transform, generator) {
    	var curve = d3.svg.line()
						.x(function(d) {return d.x; })
						.y(function(d) {return d.y; })
						.interpolate('linear'),
			points = get_heart_curve(transform, generator);
    	return curve(points);
    }

    function draw_heart(svg, transform, generator) {
    	var path = get_svg_path_from(transform, generator);

    	return svg.append('path')
		        .attr('class', 'heart')
		        .attr('fill', 'red')
		        .style('cursor', 'pointer')
		        .attr('d', path);
    }

    function click_heart(svg, index) {
    	if(index == 1) {
    		var scale = uniform_between(20, 70),
    			random_scale = [scale, scale],
    			random_position = [uniform_between(10, 1200), uniform_between(10, 800)],
    			random_angle = uniform_between(0, 360),
    			transform = {'scale' : random_scale, 'translate' : random_position, 'rotate' : random_angle};
    			draw_heart(svg, transform, heart_1)
    				.attr('class', 'expendable_heart')
    				.attr('fill', 'hsl(' + Math.random()*50 + ',100%,50%)')
    				.on('click', function(d) {
    					d3.selectAll('.expendable_heart')
    						.transition()
    							.style('opacity',0)
    							.remove();
    				});
    	}
    	else if(index == 2) {
    		if(heart_2_clicks >= 3) {
    			d3.selectAll('.expendable_text')
    				.transition()
    					.style('opacity', 0)
    					.remove();
    			heart_2_clicks = 0;
    			return;
    		}

    		var values = [{'text':'Felices','x':0,'color':'black'},
    		              {'text':'siete', 'x':440, 'color':'red'},
    		              {'text':'meseees!', 'x':730,'color':'black'}
    		             ],
    			value = values[heart_2_clicks];

    		svg.append('text')
    			.attr('class', 'expendable_text')
    			.attr('x', 2000)
    			.attr('y', 550)
    			.attr('font-family', 'sans-serif')
    			.attr('font-size', 140)
    			.attr('fill', value.color)
    			.style('opacity', 0)
    			.text(value.text)
    			.transition()
    				.attr('x', value.x)
    				.style('opacity', 1)
    				.duration(3000);

    		heart_2_clicks++;
    	}
    	else if(index == 3) {
    		var heart_idx = uniform_between(1, 3),
    			heart = d3.select('#heart' + heart_idx);
    		heart
    			.transition()
    				.duration(2000)
    				.attr('fill', 'hsl(' + Math.random()*50 + ',100%,50%)');
    	}
    }

    var hearts = {
        draw : function() {
            var svg = d3.select('#main').append('svg').attr('width', window.innerWidth).attr('height', window.innerHeight),
	            heart1_transform = {'scale' : [300,300], 'translate' : [150,300]},
	            heart2_transform = {'scale' : [7,7], 'translate' : [670,190]},
	            heart3_transform = {'scale' : [50,50], 'translate' : [1200,230]},
            	heart1 = draw_heart(svg, heart1_transform, heart_1),
            	heart2 = draw_heart(svg, heart2_transform, heart_2),
            	heart3 = draw_heart(svg, heart3_transform, heart_3);

            heart1
            	.datum(heart1_transform)
            	.attr('id', 'heart1')
	            .on('mouseover', function(d) {
	            	var temp_heart = draw_heart(svg, heart1_transform, heart_1);
	            	temp_heart
	            		.on('click', function(d) { click_heart(svg, 1); })
	            		.attr('fill', heart1.attr('fill'))
	            		.transition()
	            			.duration(750)
	            			.attr('d', get_svg_path_from({'scale':[5000,5000], 'translate' : [100,2200]}, heart_1))
	            			.style('opacity', 0)
	            			.remove();
	            })
	            .on('click', function(d) { click_heart(svg, 1); });

            heart2
            	.datum(heart2_transform)
            	.attr('id', 'heart2')
            	.on('mouseover', function(d) {
	            	var temp_heart = draw_heart(svg, heart2_transform, heart_2);
	            	temp_heart
	            		.on('click', function(d) { click_heart(svg, 2); })
	            		.attr('fill', heart2.attr('fill'))
	            		.transition()
	            			.duration(750)
	            			.attr('d', get_svg_path_from({'scale':[100,100], 'translate' : [670,500]}, heart_2))
	            			.style('opacity', 0)
	            			.remove();
	            })
	            .on('click', function(d) { click_heart(svg, 2); });

            heart3
            	.datum(heart3_transform)
            	.attr('id', 'heart3')
            	.on('mouseover', function(d) {
	            	var temp_heart = draw_heart(svg, heart3_transform, heart_3);
	            	temp_heart
	            		.on('click', function(d) { click_heart(svg, 3); })
	            		.attr('fill', heart3.attr('fill'))
	            		.transition()
	            			.duration(750)
	            			.attr('d', get_svg_path_from({'scale':[1000,1000], 'translate' : [1200,950]}, heart_3))
	            			.style('opacity', 0)
	            			.remove();
	            })
	            .on('click', function(d) { click_heart(svg, 3); });

        }
    };

    return hearts;
}();
<|endoftext|>


<commit_before>/*

il
ol
on
at

i-liş-kin
a-ra-sın-dan
e-di-len
ö-de-me
e-mir

iş-le-min
em-ri-nin

üst-te
alt-lık
alt
ilk
============================

şu
ve
bu

ve-rir
 ma-hi-ye-ti-ne
 sa-ğır
 ta-ra-fın-dan
 ta-li-mat

 bil-gi
 müş-te-ri
 ger-çek-leş-ti-ril-me-si-ne
 sağ-lam
 kal
 bit
 son

 borç-lan-mak
 fark-lı-laş-tır
 borç
 fark

Trak-ya
 prog-ram-cı
 spor
 spor-a
 spor-cu
 tren
 tren-e
 kral-lık
 kral-a
 kral-i-çe
*/

function hecele(klme)
{

  if (klme.length < 3)
    return klme;

  const hc = [
	{ ptrn: /^[aeiouöüıİ][^aeiouöüıİ0-9][aeiouöüıİ]/i,  uzn: 1 },
	{ ptrn: /^[aeiouöüıİ][^aeiouöüıİ0-9][^aeiouöüıİ0-9][aeiouöüıİ]/i,  uzn: 2 },
	{ ptrn: /^[aeiouöüıİ][^aeiouöüıİ0-9][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9])/i,  uzn: 3 },

	{ ptrn: /^[^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9][aeiouöüıİ]/i,  uzn: 2 },
	{ ptrn: /^[^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9][aeiouöüıİ])/i,  uzn: 3 },
	{ ptrn: /^[^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9])/i,  uzn: 4 },
	{ ptrn: /^[^aeiouöüıİ0-9][^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9])/i,  uzn: 4 }
  ];

  	var i = -1;
    while (++i < hc.length)
		if (hc[i].ptrn.test(klme))
			if (klme.length > hc[i].uzn)
				return klme.substr(0, hc[i].uzn) + "-" + hecele(klme.substr(hc[i].uzn));
			else
				return klme;

}

"İşleyen DEMİR IŞILdar farklılıklarımız Trakyada havalar nasıl".split(" ").map(hecele).join(" ")<commit_msg>no match durumu ekle<commit_after>/*

il
ol
on
at

i-liş-kin
a-ra-sın-dan
e-di-len
ö-de-me
e-mir

iş-le-min
em-ri-nin

üst-te
alt-lık
alt
ilk
============================

şu
ve
bu

ve-rir
 ma-hi-ye-ti-ne
 sa-ğır
 ta-ra-fın-dan
 ta-li-mat

 bil-gi
 müş-te-ri
 ger-çek-leş-ti-ril-me-si-ne
 sağ-lam
 kal
 bit
 son

 borç-lan-mak
 fark-lı-laş-tır
 borç
 fark

Trak-ya
 prog-ram-cı
 spor
 spor-a
 spor-cu
 tren
 tren-e
 kral-lık
 kral-a
 kral-i-çe
*/

function hecele(klme)
{

  if (klme.length < 3)
    return klme;

  const hc = [
    { ptrn: /^[aeiouöüıİ][^aeiouöüıİ0-9][aeiouöüıİ]/i,  uzn: 1 },
    { ptrn: /^[aeiouöüıİ][^aeiouöüıİ0-9][^aeiouöüıİ0-9][aeiouöüıİ]/i,  uzn: 2 },
    { ptrn: /^[aeiouöüıİ][^aeiouöüıİ0-9][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9])/i,  uzn: 3 },

    { ptrn: /^[^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9][aeiouöüıİ]/i,  uzn: 2 },
    { ptrn: /^[^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9][aeiouöüıİ])/i,  uzn: 3 },
    { ptrn: /^[^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9])/i,  uzn: 4 },
    { ptrn: /^[^aeiouöüıİ0-9][^aeiouöüıİ0-9][aeiouöüıİ][^aeiouöüıİ0-9]($|[^aeiouöüıİ0-9])/i,  uzn: 4 }
  ];

    var i = -1;
    while (++i < hc.length)
        if (hc[i].ptrn.test(klme))
            if (klme.length > hc[i].uzn)
                return klme.substr(0, hc[i].uzn) + "-" + hecele(klme.substr(hc[i].uzn));
            else
                return klme;

    return klme; // hiç match yok, olduğu gibi döndür
}

"İşleyen DEMİR IŞILdar farklılıklarımız Trakyada havalar nasıl".split(" ").map(hecele).join(" ")<|endoftext|>


<commit_before>(function(global, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else {
        global.hermes = factory();
    }
})(window, function() {

    const callbacks = {};

    function on(name, callback) {
        if (!(name in callbacks)) {
            callbacks[name] = [];
        }
        callbacks[name].push(callback);
    }

    function off(name, callback) {
        if (name in callbacks) {
            if (typeof callback === 'function') {
                const index = callbacks[name].indexOf(callback);
                callbacks[name].splice(index, 1);
            }
            if (typeof callback !== 'function' || callbacks[name].length === 0) {
                delete callbacks[name];
            }
        }
    }

    function broadcast(name, data) {
        if (name in callbacks) {
            callbacks[name].forEach((callback) => callback(data));
        }
    }

    function broadcastChannelApiFactory() {
        /**
         *  The BroadcastChannel API allows simple communication between
         *  browsing contexts (including tabs), sort of like a PubSub that
         *  works across different tabs. This is the ideal solution for
         *  messaging between different tabs, but it is relatively new.
         *
         *  Support table for BroadcastChannel: http://caniuse.com/#feat=broadcastchannel
         **/

        const channel = new BroadcastChannel('hermes');
        channel.onmessage = (e) => broadcast(e.data.name, e.data.data);

        function send(name, data, includeSelf=false) {
            channel.postMessage({ name, data });
            if (includeSelf) {
                broadcast(name, data);
            }
        }

        return { on, off, send };
    }

    function sharedWorkerApiFactory() {
        /**
         *  A SharedWorker is a script that is run by the browser in the
         *  background. Different browsing contexts (including tabs) from the
         *  same origin have shared accesss to the SharedWorker instance and
         *  can communicate with it. We are taking advantage of these features
         *  to use it as a messaging channel which simply forwards messages it
         *  receives to the other connected tabs.
         *
         *  Support table for SharedWorker: http://caniuse.com/#feat=sharedworkers
         **/

        const selector = '[src$="hermes.js"],[src$="hermes.min.js"]';
        const script = document.querySelector(selector);
        const scriptUrl = new URL(script.src);
        const workerPath = scriptUrl.pathname
            .replace(/hermes(\.min)?\.js/, 'hermes-worker$1.js');

        const worker = new SharedWorker(workerPath, 'hermes');

        worker.port.start();
        worker.port.onmessage = (e) => broadcast(e.data.name, e.data.data);

        function send(name, data, includeSelf=false) {
            worker.port.postMessage({ name, data });
            if (includeSelf) {
                broadcast(name, data);
            }
        }

        return { on, off, send };
    }

    function localStorageApiFactory() {
        /**
         *  The localStorage is a key-value pair storage, and browser tabs from
         *  the same origin have shared access to it. Whenever something
         *  changes in the localStorage, the window object emits the `storage`
         *  event in the other tabs letting them know about the change.
         *
         *  Support table for localStorage: http://caniuse.com/#search=webstorage
         **/

        const storage = window.localStorage;
        const prefix = '__hermes:';
        const queue = {};

        window.addEventListener('storage', (e) => {
            if (e.key.startsWith(prefix) && e.oldValue === null) {
                const name = e.key.replace(prefix, '');
                const data = JSON.parse(e.newValue);
                broadcast(name, data);
            }
        });

        window.addEventListener('storage', (e) => {
            if (e.key.startsWith(prefix) && e.newValue === null) {
                const name = e.key.replace(prefix, '');
                if (name in queue) {
                    send(name, queue[name].shift());
                    if (queue[name].length === 0) {
                        delete queue[name];
                    }
                }
            }
        });

        function send(name, data, includeSelf=false) {
            const key = prefix + name;
            if (storage.getItem(key) === null) {
                storage.setItem(key, JSON.stringify(data));
                storage.removeItem(key);
                if (includeSelf) {
                    broadcast(name, data);
                }
            } else {
                // The queueing system ensures that multiple calls to the send
                // function using the same name does not override each other's
                // values and makes sure that the next value is sent only when
                // the previous one has already been deleted from the storage.
                // NOTE: This could just be trying to solve a problem that is
                // very unlikely to occur.
                if (!(key) in queue) {
                    queue[key] = [];
                }
                queue[key].push(data);
            }
        }

        return { on, off, send };
    }

    function emptyApiFactory() {
        /**
         *  When the browser does not support any of the APIs that we're using
         *  for messaging, just present an empty api that does just gives
         *  warnings regarding the lack of support.
         **/

        function noop() {
            console.warn('Hermes messaging is not supported.');
        }

        return { on: noop, off: noop, send: noop };
    }

    if ('BroadcastChannel' in window) {
        return broadcastChannelApiFactory();
    } else if ('SharedWorker' in window) {
        return sharedWorkerApiFactory();
    } else if ('localStorage' in window) {
        return localStorageApiFactory();
    } else {
        return emptyApiFactory();
    }

});
<commit_msg>remove use of startsWith because babel cannot transpile it<commit_after>(function(global, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else {
        global.hermes = factory();
    }
})(window, function() {

    const callbacks = {};

    function on(name, callback) {
        if (!(name in callbacks)) {
            callbacks[name] = [];
        }
        callbacks[name].push(callback);
    }

    function off(name, callback) {
        if (name in callbacks) {
            if (typeof callback === 'function') {
                const index = callbacks[name].indexOf(callback);
                callbacks[name].splice(index, 1);
            }
            if (typeof callback !== 'function' || callbacks[name].length === 0) {
                delete callbacks[name];
            }
        }
    }

    function broadcast(name, data) {
        if (name in callbacks) {
            callbacks[name].forEach((callback) => callback(data));
        }
    }

    function broadcastChannelApiFactory() {
        /**
         *  The BroadcastChannel API allows simple communication between
         *  browsing contexts (including tabs), sort of like a PubSub that
         *  works across different tabs. This is the ideal solution for
         *  messaging between different tabs, but it is relatively new.
         *
         *  Support table for BroadcastChannel: http://caniuse.com/#feat=broadcastchannel
         **/

        const channel = new BroadcastChannel('hermes');
        channel.onmessage = (e) => broadcast(e.data.name, e.data.data);

        function send(name, data, includeSelf=false) {
            channel.postMessage({ name, data });
            if (includeSelf) {
                broadcast(name, data);
            }
        }

        return { on, off, send };
    }

    function sharedWorkerApiFactory() {
        /**
         *  A SharedWorker is a script that is run by the browser in the
         *  background. Different browsing contexts (including tabs) from the
         *  same origin have shared accesss to the SharedWorker instance and
         *  can communicate with it. We are taking advantage of these features
         *  to use it as a messaging channel which simply forwards messages it
         *  receives to the other connected tabs.
         *
         *  Support table for SharedWorker: http://caniuse.com/#feat=sharedworkers
         **/

        const selector = '[src$="hermes.js"],[src$="hermes.min.js"]';
        const script = document.querySelector(selector);
        const scriptUrl = new URL(script.src);
        const workerPath = scriptUrl.pathname
            .replace(/hermes(\.min)?\.js/, 'hermes-worker$1.js');

        const worker = new SharedWorker(workerPath, 'hermes');

        worker.port.start();
        worker.port.onmessage = (e) => broadcast(e.data.name, e.data.data);

        function send(name, data, includeSelf=false) {
            worker.port.postMessage({ name, data });
            if (includeSelf) {
                broadcast(name, data);
            }
        }

        return { on, off, send };
    }

    function localStorageApiFactory() {
        /**
         *  The localStorage is a key-value pair storage, and browser tabs from
         *  the same origin have shared access to it. Whenever something
         *  changes in the localStorage, the window object emits the `storage`
         *  event in the other tabs letting them know about the change.
         *
         *  Support table for localStorage: http://caniuse.com/#search=webstorage
         **/

        const storage = window.localStorage;
        const prefix = '__hermes:';
        const queue = {};

        window.addEventListener('storage', (e) => {
            if (e.key.indexOf(prefix) === 0 && e.oldValue === null) {
                const name = e.key.replace(prefix, '');
                const data = JSON.parse(e.newValue);
                broadcast(name, data);
            }
        });

        window.addEventListener('storage', (e) => {
            if (e.key.indexOf(prefix) === 0 && e.newValue === null) {
                const name = e.key.replace(prefix, '');
                if (name in queue) {
                    send(name, queue[name].shift());
                    if (queue[name].length === 0) {
                        delete queue[name];
                    }
                }
            }
        });

        function send(name, data, includeSelf=false) {
            const key = prefix + name;
            if (storage.getItem(key) === null) {
                storage.setItem(key, JSON.stringify(data));
                storage.removeItem(key);
                if (includeSelf) {
                    broadcast(name, data);
                }
            } else {
                // The queueing system ensures that multiple calls to the send
                // function using the same name does not override each other's
                // values and makes sure that the next value is sent only when
                // the previous one has already been deleted from the storage.
                // NOTE: This could just be trying to solve a problem that is
                // very unlikely to occur.
                if (!(key) in queue) {
                    queue[key] = [];
                }
                queue[key].push(data);
            }
        }

        return { on, off, send };
    }

    function emptyApiFactory() {
        /**
         *  When the browser does not support any of the APIs that we're using
         *  for messaging, just present an empty api that does just gives
         *  warnings regarding the lack of support.
         **/

        function noop() {
            console.warn('Hermes messaging is not supported.');
        }

        return { on: noop, off: noop, send: noop };
    }

    if ('BroadcastChannel' in window) {
        return broadcastChannelApiFactory();
    } else if ('SharedWorker' in window) {
        return sharedWorkerApiFactory();
    } else if ('localStorage' in window) {
        return localStorageApiFactory();
    } else {
        return emptyApiFactory();
    }

});
<|endoftext|>


<commit_before>var hobbes = function () {
  // About hobbes
  var version = '0.1';

  return {
    version: version
  };
}();

require('hobbes/parser');
<commit_msg>Goals<commit_after>// TODO
//  - HTML- und CLI-Umgebungen
//  - Vernuenftige Grammatik
//  - Anschliessend Laufzeit-Umgebung nachfuegen

var hobbes = function () {
  // About hobbes
  var version = '0.1';

  return {
    version: version
  };
}();

require('hobbes/parser');
<|endoftext|>


<commit_before>var patientId = 0;
var therapyId = 0;

$(document).ready(function () {

	$('.select-patient').click(function () {
		// get id and name
		patientId = $(this).attr('data-id');
		$('.patient-selected').html($(this).attr('data-name'));

		// open next page
		$('#page-one').slideUp(500);
		$('#page-two').slideDown(500);
	});

	$('#go-back-to-select-patient').click(function () {
		// open prev page
		$('#page-one').slideDown(500);
		$('#page-two').slideUp(500);
	});

	$('.select-therapy').click(function () {
		// get id and name
		therapyId = $(this).attr('data-id');
		$('.therapy-selected').html($(this).attr('data-name'));

		// open next page
		$('#page-two').slideUp(500);
		$('#page-three').slideDown(500);
	});

	$('#go-back-to-select-therapy').click(function () {
		// open prev page
		$('#page-two').slideDown(500);
		$('#page-three').slideUp(500);
	});

	$('#view-available-appointments').click(function () {
		// hide buttons
		$(this).slideUp(300);
		$('#go-back-to-select-therapy').hide();

		// show calendar

        var calendar  =
		$('.calendar').show().fullCalendar({
            header: {

                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'

            },

            defaultView: 'agendaWeek',
            editable: true,
            selectable:true,
            selectHelper: true,

            select: function(start, end, allDay)
            {
                var title = prompt('Event Title:');

                if (title)
                {
                    calendar.fullCalendar('renderEvent',
                        {
                            title: title,
                            start: start,
                            end: end,
                            allDay: allDay
                        },
                        true // make the event "stick"
                    );
                }
                calendar.fullCalendar('unselect');
            }

        });

	});

	// datatables
	setUpDataTable('#patients-table', 0, [[1, 1], [1, 1], [1, 1], [0, 0]]);
	setUpDataTable('#therapies-table', 0, [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1], [0, 0]]);
});<commit_msg>Can now add events to the calendar<commit_after>var patientId = 0;
var therapyId = 0;

$(document).ready(function () {

    $('.select-patient').click(function () {
        // get id and name
        patientId = $(this).attr('data-id');
        $('.patient-selected').html($(this).attr('data-name'));

        // open next page
        $('#page-one').slideUp(500);
        $('#page-two').slideDown(500);
    });

    $('#go-back-to-select-patient').click(function () {
        // open prev page
        $('#page-one').slideDown(500);
        $('#page-two').slideUp(500);
    });

    $('.select-therapy').click(function () {
        // get id and name
        therapyId = $(this).attr('data-id');
        $('.therapy-selected').html($(this).attr('data-name'));

        // open next page
        $('#page-two').slideUp(500);
        $('#page-three').slideDown(500);
    });

    $('#go-back-to-select-therapy').click(function () {
        // open prev page
        $('#page-two').slideDown(500);
        $('#page-three').slideUp(500);
    });

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
    $('#view-available-appointments').click(function () {
        // hide buttons
        $(this).slideUp(300);
        $('#go-back-to-select-therapy').hide();

        // show calendar

        var calendar =
            $('.calendar').show().fullCalendar({
                header: {

                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,agendaWeek,agendaDay'

                },

                defaultView: 'agendaWeek',
                editable: true,
                selectable: true,
                selectHelper: true,

                select: function (start, end, allDay) {
                    var title = prompt('Event Title:');

                    if (title) {
                        calendar.fullCalendar('renderEvent',
                            {
                                title: title,
                                start: start,
                                end: end,
                                allDay: allDay
                            },
                            true // make the event "stick"
                        );
                    }
                    calendar.fullCalendar('unselect');
                },

                events: [
                    {
                        title:  'My Event',
                        start:  '2015-03-10T14:30:00',
                        end  : '2015-03-10T16:30:00',
                        allDay: false
                    }
                    // other events here...
                ],
                timeFormat: 'H(:mm)'

            });

    });

    // datatables
    setUpDataTable('#patients-table', 0, [[1, 1], [1, 1], [1, 1], [0, 0]]);
    setUpDataTable('#therapies-table', 0, [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1], [0, 0]]);
});<|endoftext|>


<commit_before>/**
 * Created by pc on 27/01/2016.
 */

var Fact = require('./Fact');
var Logics = require('./Logics');

Solver = {

    evaluateRuleSet: function(rs, facts) {
        var newCons, cons = [];
        for (var key in rs) {
            newCons = this.evaluateThroughRestriction(rs[key], facts);
            cons = Logics.uniques(cons, newCons);
        }
        return cons;
    },

    evaluateThroughRestriction: function(rule, facts) {
        var causesToMap, i = 0,
            consequences = [];
        rule.orderCausesByMostRestrictive();
        causesToMap = [rule.causes[i]];

        while (i < rule.causes.length) {
            causesToMap = this.replaceNextCauses(causesToMap, rule.causes[i+1], facts);
            i++;
        }

        for (var i = 0; i < causesToMap.length; i++) {
            var causedBy = [];
            for (var k = 0; k < rule.causes.length; k++) {
                causedBy.push(this.replaceMapping(causesToMap[i], rule.causes[k]).toString());
            }
            for (var j = 0; j < rule.consequences.length; j++) {
                consequences.push(this.replaceMapping(causesToMap[i], rule.consequences[j], causedBy));
            }
        }

        return consequences;
    },

    replaceNextCauses: function(currentCauses, nextCause, facts) {
        var replacedNextCauses = [],
            mappings = [];
        for (var i = 0; i < currentCauses.length; i++) {
            for (var j = 0; j < facts.length; j++) {
                var mapping = currentCauses[i].mapping,
                    replacedNextCause,
                    newMapping;
                if (mapping === undefined) {
                    mapping = {};
                }

                newMapping = this.factMatchesCause(facts[j], currentCauses[i], mapping);
                if (newMapping) {
                    if (nextCause) {
                        replacedNextCause = this.replaceMapping(newMapping, nextCause);
                        replacedNextCause.mapping = newMapping;
                        replacedNextCauses.push(replacedNextCause);
                    } else {
                        mappings.push(newMapping);
                    }
                }
            }
        }

        if(nextCause) {
            return replacedNextCauses;
        } else {
            return mappings;
        }
    },

    factMatchesCause: function(fact, cause, mapping) {
        var localMapping = {}; // Generates new mapping

        if (Logics.isVariable(cause.subject)) {
            if (mapping[cause.subject] && (mapping[cause.subject] != fact.subject)) {
                return false;
            } else {
                localMapping[cause.subject] = fact.subject;
            }
        } else {
            if (fact.subject != cause.subject) {
                return false;
            }
        }

        if (Logics.isVariable(cause.predicate)) {
            if (mapping[cause.predicate] && (mapping[cause.predicate] != fact.predicate)) {
                return false;
            } else {
                localMapping[cause.predicate] = fact.predicate;
            }
        } else {
            if (fact.predicate != cause.predicate) {
                return false;
            }
        }

        if (Logics.isVariable(cause.object)) {
            if (mapping[cause.object] && (mapping[cause.object] != fact.object)) {
                return false;
            } else {
                localMapping[cause.object] = fact.object;
            }
        } else {
            if (fact.object != cause.object) {
                return false;
            }
        }

        for (var key in mapping) {
            localMapping[key] = mapping[key];
        }

        return localMapping;
    },

    replaceMappingOnElement: function(elem, mapping) {
        if(Logics.isVariable(elem)) {
            if (mapping[elem] !== undefined) {
                return mapping[elem]
            }
        }
        return elem;
    },

    replaceMapping: function(mapping, unReplacedFact, causedBy) {
        var replacedFact = new Fact(),
            replacedCauses = [];
        if (mapping == {}) {
            return unReplacedFact;
        }

        if (causedBy) {
            replacedFact.causedBy = [causedBy];
            replacedFact.explicit = false;
        }

        replacedFact.subject = this.replaceMappingOnElement(unReplacedFact.subject, mapping);
        replacedFact.predicate = this.replaceMappingOnElement(unReplacedFact.predicate, mapping);
        replacedFact.object = this.replaceMappingOnElement(unReplacedFact.object, mapping);

        return replacedFact;
    }
};

module.exports = Solver;<commit_msg>Updated graph support on the Solver<commit_after>/**
 * Created by pc on 27/01/2016.
 */

var Fact = require('./Fact');
var Logics = require('./Logics');

Solver = {

    evaluateRuleSet: function(rs, facts) {
        var newCons, cons = [];
        for (var key in rs) {
            newCons = this.evaluateThroughRestriction(rs[key], facts);
            cons = Logics.uniques(cons, newCons);
        }
        return cons;
    },

    evaluateThroughRestriction: function(rule, facts) {
        var causesToMap, i = 0,
            consequences = [];
        rule.orderCausesByMostRestrictive();
        causesToMap = [rule.causes[i]];

        while (i < rule.causes.length) {
            causesToMap = this.replaceNextCauses(causesToMap, rule.causes[i+1], facts);
            i++;
        }

        for (var i = 0; i < causesToMap.length; i++) {
            var causedBy = [],
                consequenceGraphs = [];
            for (var k = 0; k < rule.causes.length; k++) {
                causedBy.push(this.replaceMapping(causesToMap[i], rule.causes[k]).toString());
                consequenceGraphs = Logics.uniques(consequenceGraphs, causesToMap[i].graphs);
            }
            for (var j = 0; j < rule.consequences.length; j++) {
                consequences.push(this.replaceMapping(causesToMap[i], rule.consequences[j], causedBy, consequenceGraphs));
            }
        }

        return consequences;
    },

    replaceNextCauses: function(currentCauses, nextCause, facts) {
        var replacedNextCauses = [],
            mappings = [];
        for (var i = 0; i < currentCauses.length; i++) {
            for (var j = 0; j < facts.length; j++) {
                var mapping = currentCauses[i].mapping,
                    replacedNextCause,
                    newMapping;
                if (mapping === undefined) {
                    mapping = {};
                }

                newMapping = this.factMatchesCause(facts[j], currentCauses[i], mapping);
                if (newMapping) {
                    if (nextCause) {
                        replacedNextCause = this.replaceMapping(newMapping, nextCause);
                        replacedNextCause.mapping = newMapping;
                        replacedNextCauses.push(replacedNextCause);
                    } else {
                        mappings.push(newMapping);
                    }
                }
            }
        }

        if(nextCause) {
            return replacedNextCauses;
        } else {
            return mappings;
        }
    },

    factMatchesCause: function(fact, cause, mapping) {
        var localMapping = {}; // Generates new mapping

        if (Logics.isVariable(cause.subject)) {
            if (mapping[cause.subject] && (mapping[cause.subject] != fact.subject)) {
                return false;
            } else {
                localMapping[cause.subject] = fact.subject;
            }
        } else {
            if (fact.subject != cause.subject) {
                return false;
            }
        }

        if (Logics.isVariable(cause.predicate)) {
            if (mapping[cause.predicate] && (mapping[cause.predicate] != fact.predicate)) {
                return false;
            } else {
                localMapping[cause.predicate] = fact.predicate;
            }
        } else {
            if (fact.predicate != cause.predicate) {
                return false;
            }
        }

        if (Logics.isVariable(cause.object)) {
            if (mapping[cause.object] && (mapping[cause.object] != fact.object)) {
                return false;
            } else {
                localMapping[cause.object] = fact.object;
            }
        } else {
            if (fact.object != cause.object) {
                return false;
            }
        }

        for (var key in mapping) {
            localMapping[key] = mapping[key];
        }

        if (localMapping.graphs) {
            localMapping.graphs = Logics.uniques(localMapping.graphs, fact.graphs);
        } else {
            localMapping.graphs = [];
        }

        return localMapping;
    },

    replaceMappingOnElement: function(elem, mapping) {
        if(Logics.isVariable(elem)) {
            if (mapping[elem] !== undefined) {
                return mapping[elem]
            }
        }
        return elem;
    },

    replaceMapping: function(mapping, unReplacedFact, causedBy, graphs) {
        var replacedFact = new Fact(),
            replacedCauses = [];
        if (mapping == {}) {
            return unReplacedFact;
        }

        if (causedBy) {
            replacedFact.causedBy = [causedBy];
            replacedFact.explicit = false;
        }

        if (graphs) {
            replacedFact.graphs = graphs;
        }

        replacedFact.subject = this.replaceMappingOnElement(unReplacedFact.subject, mapping);
        replacedFact.predicate = this.replaceMappingOnElement(unReplacedFact.predicate, mapping);
        replacedFact.object = this.replaceMappingOnElement(unReplacedFact.object, mapping);

        return replacedFact;
    }
};

module.exports = Solver;<|endoftext|>


<commit_before>var https = require("https");
var polyline = require('polyline');
var configs = require('./config');

//=========User defined information===============
//list of Hubway Stations
var stations = [{name:"Vassar",  location:[42.355701, -71.103954]},     //Vassar
                {name:"Mass Ave",location:[42.358090, -71.093176]},   //Mass Ave
                {name:"Stata",   location:[42.361989, -71.092061]},      //Stata
                {name:"Ames",    location:[42.362536, -71.088188]},       //Ames
                {name:"Kendall", location:[42.362482, -71.085124]}];   //Kendall

//Starting point
var origin = {name:"Next House",location:[42.355005, -71.101438]}
;
//Indices of origin states (could be computed)
var originStations = [0,1];

//==========Computed arrays=======================
var bikingDestinations = stations.slice(0);   //locations to bike to
var bikingOrigins = [];        //locations to bike from
for(var o=0; o<originStations.length; o++){
  //add each origin station to bikingOrigins
  bikingOrigins.push(stations[o]);
  //remove each origin stations from bikingDestinations
  bikingDestinations.splice(bikingDestinations.indexOf(stations[originStations[o]]),1);
}

var walkingOrigins = bikingDestinations.slice(0);
walkingOrigins.unshift(origin);
//=================================================

var base_url = "https://maps.googleapis.com/maps/api/distancematrix/json?"
base_url+="key="+configs.api_key+"&";

var initialWalking = {};
var stationBiking = {};

getMatrix(getLocationList(bikingOrigins),getLocationList([origin]),"walking",function(matrix){
  initialWalking = matrix.slice(0);
  for(var row = 0; row<originStations.length;row++){
    initialWalking[row] = [];
    var time = matrix[row][0];
    for(var element = 0; element<bikingDestinations.length;element++){
        initialWalking[row].unshift(time);
    }
    initialWalking[row].unshift(0);
  }
});

getMatrix(getLocationList(bikingOrigins),getLocationList(bikingDestinations),"biking",function(matrix){
  stationBiking = matrix;
  for(var row = 0; row<stationBiking.length;row++){
    stationBiking[row].unshift(0);
  }
});

setTimeout(function(){
  console.log("Walking to origin station(s): "+JSON.stringify(initialWalking));
  console.log("Biking between stations:      "+JSON.stringify(stationBiking));
},2000);
/*
for(p in points){
  //get walking
  getMatrix([p],walkingOrigins,"walking",function(matrix){
    var tmp = addMatrices(stationBiking,matrix);
    var times = addMatrices(tmp,initialWalking);
  });
}
*/

function getLocationList(a){
  var out = [];
  for(var c=0;c<a.length;c++){
    out[out.length] = a[c].location;
  }
  return out;
}

function getMatrix(origins,destinations,mode,callback){
  var origin = "enc:"+polyline.encode(origins)+":";
  var destinations = "enc:"+polyline.encode(destinations)+":";
  var req_url = base_url;
  req_url += "origins="+origin+"&";
  req_url += "destinations="+destinations+"&";
  req_url += "mode="+mode;
  //console.log(req_url);

  https.get(req_url,function(res){
    var data = "";
    res.on('data', function(chunk){
      data+=chunk;
    });
    res.on('end',function(){
      var obj = JSON.parse(data);
      console.log("Request status: "+obj.status);
      obj = obj.rows;
      var matrix = [[]];
      for(var row = 0; row < obj.length; row++){
        matrix[row] = [];
        for(var element = 0; element < obj[row].elements.length; element++){
          matrix[row][element] = obj[row].elements[element].duration.value;
        }
      }
      callback(matrix);
    });
  });
}
<commit_msg>Added functional addMatries and evaluatePoint functions<commit_after>var https = require("https");
var polyline = require('polyline');
var configs = require('./config');

//=========User defined information===============
//list of Hubway Stations
var stations = [{name:"Vassar",  location:[42.355701, -71.103954]},     //Vassar
                {name:"Mass Ave",location:[42.358090, -71.093176]},   //Mass Ave
                {name:"Stata",   location:[42.361989, -71.092061]},      //Stata
                {name:"Ames",    location:[42.362536, -71.088188]},       //Ames
                {name:"Kendall", location:[42.362482, -71.085124]}];   //Kendall

//Starting point
var origin = {name:"Next House",location:[42.355005, -71.101438]}
;
//Indices of origin states (could be computed)
var originStations = [0,1];

//==========Computed arrays=======================
var bikingDestinations = stations.slice(0);   //locations to bike to
var bikingOrigins = [];        //locations to bike from
for(var o=0; o<originStations.length; o++){
  //add each origin station to bikingOrigins
  bikingOrigins.push(stations[o]);
  //remove each origin stations from bikingDestinations
  bikingDestinations.splice(bikingDestinations.indexOf(stations[originStations[o]]),1);
}

var walkingOrigins = bikingDestinations.slice(0);
walkingOrigins.unshift(origin);
//=================================================

var base_url = "https://maps.googleapis.com/maps/api/distancematrix/json?"
base_url+="key="+configs.api_key+"&";

var initialWalking = {};
var stationBiking = {};
var sumTimes = {};

getMatrix(getLocationList(bikingOrigins),getLocationList([origin]),"walking",function(matrix){
  initialWalking = matrix.slice(0);
  for(var row = 0; row<originStations.length;row++){
    initialWalking[row] = [];
    var time = matrix[row][0];
    for(var element = 0; element<bikingDestinations.length;element++){
        initialWalking[row].unshift(time);
    }
    initialWalking[row].unshift(0);
  }
});

getMatrix(getLocationList(bikingOrigins),getLocationList(bikingDestinations),"biking",function(matrix){
  stationBiking = matrix;
  for(var row = 0; row<stationBiking.length;row++){
    stationBiking[row].unshift(0);
  }
});

setTimeout(function(){
  console.log("Walking to origin station(s): "+JSON.stringify(initialWalking));
  console.log("Biking between stations:      "+JSON.stringify(stationBiking));
  sumTimes = addMatrices(initialWalking,stationBiking);
  evaluatePoint([42.355720, -71.100298]);
  evaluatePoint([42.361151, -71.089666]);
},2000);
/*
for(p in points){
  //get walking
  getMatrix([p],walkingOrigins,"walking",function(matrix){
    var tmp = addMatrices(stationBiking,matrix);
    var times = addMatrices(tmp,initialWalking);
  });
}
*/

function evaluatePoint(location){
  var l = getLocationList(bikingDestinations);
  l.unshift(origin.location);

  getMatrix([location],l,"walking",function(matrix){
    var fullMatrix = [];
    //need to match dimensions
    for(var i = 0; i < originStations.length;i++){
      fullMatrix.push(matrix[0]);
    }

    console.log(JSON.stringify(addMatrices(sumTimes,fullMatrix)));
  });
}

function addMatrices(a,b){
  if(a.length!=b.length || a[0].length!=b[0].length){
    console.log("Matrix dimensions don't match!");
    return null;
  }
  var out = [];
  for(var row = 0; row<a.length; row++){
    out[row] = [];
    for(var el = 0; el<a[0].length; el++){
      out[row].push(a[row][el]+b[row][el]);
    }
  }
  return out;
}

function getLocationList(a){
  var out = [];
  for(var c=0;c<a.length;c++){
    out[out.length] = a[c].location;
  }
  return out;
}

function getMatrix(origins,destinations,mode,callback){
  var origin = "enc:"+polyline.encode(origins)+":";
  var destinations = "enc:"+polyline.encode(destinations)+":";
  var req_url = base_url;
  req_url += "origins="+origin+"&";
  req_url += "destinations="+destinations+"&";
  req_url += "mode="+mode;
  //console.log(req_url);

  https.get(req_url,function(res){
    var data = "";
    res.on('data', function(chunk){
      data+=chunk;
    });
    res.on('end',function(){
      var obj = JSON.parse(data);
      console.log("Request status: "+obj.status);
      obj = obj.rows;
      var matrix = [[]];
      for(var row = 0; row < obj.length; row++){
        matrix[row] = [];
        for(var element = 0; element < obj[row].elements.length; element++){
          matrix[row][element] = obj[row].elements[element].duration.value;
        }
      }
      callback(matrix);
    });
  });
}
<|endoftext|>


<commit_before>var socket = io();
var gamemode = null,
    input_type = null;

function main() {
    // create, initiate and append game canvas
    username = window.prompt("Enter a username", "Username");
    init(); // initiate game objects
    //$(document).keydown(keyDown); //add keylisteners
    //$(document).keyup(keyUp);
    //draw();
}

function init() {
    socket.emit('add user', username);
}
socket.on('initialize', function(data){
    gamemode=data.mode;
    input_type = data.input_type;
    switch(input_type):{
        case ('gameboy'):{

            break;
        }
        case ('wasd'):{

            break;
        }
        default:{

            break;
        }
    }
});
window.beforeunload = function(){
    socket.emit("disconnect", {});
}
main();<commit_msg>Latest Commit from sublime text<commit_after>var socket = io();
var gamemode = null,
    input_type = null;

function main() {
    // create, initiate and append game canvas
    username = window.prompt("Enter a username", "Username");
    init(); // initiate game objects
    //$(document).keydown(keyDown); //add keylisteners
    //$(document).keyup(keyUp);
    //draw();
}

function init() {
    socket.emit('add user', username);
}
socket.on('initialize', function(data) {
    gamemode = data.mode;
    input_type = data.input_type;
    switch (input_type): {
        case ('gameboy'):
            {
                break;
            }
        case ('wasd'):
            {
                break;
            }
            default: {
                break;
            }
    }
});
window.beforeunload = function() {
    socket.emit("disconnect", {});
}
main();<|endoftext|>


<commit_before>---
layout: default
install:
  devDependencies: ['mocha']
---
  <%= indent(include("assert-function.js")) %>
  <%= indent(include("assert-object.js")) %>
  <%= indent(include("assert-error.js")) %><commit_msg>don't indent<commit_after>---
layout: default
install:
  devDependencies: ['mocha']
---
  <%= include("assert-function.js") %>
  <%= include("assert-object.js") %>
  <%= include("assert-error.js") %><|endoftext|>


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

function parentPath(x) { return x.match(/(\/[\w_-]+)+\/[\w_-]+$/)[1]; }

var _ = require('underscore');
var util = require('util');
var assert = require('assert');

function SchoolsDB (db, config) {
	this.db = db;
	this.cfg = config;
}
util.inherits(SchoolsDB, require('./objects.js').DBSubsystemBase);

function adminlistContainsUser(admins, user) {
	return _.chain(admins).filter(function(a) { return a.status == 'admin' && a.adminid == user.id; }).value().length == 0;
}

function _reqschooladm (f, soft) {
	var soft = soft || false;

	return function(query, user, access, cb) {
		var forward = _.bind(function() { return _.bind(f, this)(query, user, access, cb); }, this);
		if (access.has('schooldb') || (soft && !query.schoolid))
			return forward();

		assert.ok(this.loadSchoolAdmins);

		this.loadSchoolAdmins(query.schoolid, function(adminlist) {
			if (adminlistContainsUser(adminlist, user))
				cb('permission-denied');
			else
				forward();
		});
	};
}

// only internal
SchoolsDB.prototype.loadSchoolAdmins = function(schoolid, cb) {
	this.query('SELECT sa.schoolid AS schoolid, sa.uid AS adminid, sa.status AS status, users.name AS adminname ' +
		'FROM schools AS c ' +
		'JOIN schools AS p ON c.path LIKE CONCAT(p.path, "%") OR p.id = c.id ' +
		'JOIN schooladmins AS sa ON sa.schoolid = p.id ' +
		'JOIN users ON users.id = sa.uid ' +
		'WHERE c.id = ?', [schoolid], cb);
};

SchoolsDB.prototype.loadSchoolInfo = function(lookfor, user, access, cb) {
	this.query('SELECT schools.id, schools.name, schools.path, descpage, eventid, type, targetid, time, srcuser, json, url AS banner FROM schools ' +
		'LEFT JOIN events ON events.targetid = schools.id AND events.type = "school-create" ' +
		'LEFT JOIN httpresources ON httpresources.groupassoc = schools.id AND httpresources.role = "schools.banner" ' +
		'WHERE ? IN (schools.id, schools.path, schools.name) ' +
		'LIMIT 1', [lookfor], function(res) {
		if (res.length == 0)
			return cb('get-school-info-notfound');

		var s = res[0];
		s.parentPath = null;

		assert.ok(s.eventid);

		this.loadSchoolAdmins(s.id, function(admins) {
			s.admins = admins;

			this.query('SELECT * FROM schools AS c WHERE c.path LIKE ?', [s.path + '/%'], function(subschools) {
			this.query('SELECT c.*,u.name AS username,u.id AS uid, url AS profilepic, trustedhtml ' +
				'FROM ecomments AS c '+
				'LEFT JOIN users AS u ON c.commenter = u.id ' +
				'LEFT JOIN httpresources ON httpresources.user = c.commenter AND httpresources.role = "profile.image" '+
				'WHERE c.eventid = ?',
				[s.eventid],
				function(comments) {
				s.comments = comments;
				s.subschools = subschools;

				this.query('SELECT oh.stocktextid AS stockid, oh.stockname, ' +
					'SUM(ABS(money)) AS moneysum, ' +
					'SUM(ABS(money) / (UNIX_TIMESTAMP() - buytime)) AS wsum '+
					'FROM orderhistory AS oh ' +
					'JOIN schoolmembers AS sm ON sm.uid = oh.userid AND sm.jointime < oh.buytime AND sm.schoolid = ? ' +
					'GROUP BY stocktextid ORDER BY wsum DESC', [s.id], function(popular) {
					s.popularStocks = popular.splice(0, 10);

					if (s.path.replace(/[^\/]/g, '').length != 1) { // need higher-level
						s.parentPath = parentPath(s.path);
						this.loadSchoolInfo(s.parentPath, user, access, function(code, result) {
							assert.equal(code, 'get-school-info-success');

							s.parentSchool = result;

							cb('get-school-info-success', s);
						});
					} else {
						cb('get-school-info-success', s);
					}
				});
			});
			});
		});
	});
};

SchoolsDB.prototype.getSchoolInfo = function(query, user, access, cb) {
	this.loadSchoolInfo(query.lookfor, user, access, cb);
};

SchoolsDB.prototype.changeDescription = _reqschooladm(function(query, user, access, cb) {
	this.query('UPDATE schools SET descpage = ? WHERE id = ?', [query.descpage, query.schoolid], function() {
		cb('school-change-description-success');
	});
});

SchoolsDB.prototype.changeMemberStatus = _reqschooladm(function(query, user, access, cb) {
	this.query('UPDATE schoolmembers SET pending = 0 WHERE schoolid = ? AND uid = ?', [query.schoolid, query.uid], function() {
		if (query.newstatus == 'member') {
			this.query('DELETE FROM schooladmins WHERE uid = ? AND schoolid = ?', [query.uid, query.schoolid], function() {
				cb('school-change-member-status-success');
			});
		} else {
			this.query('REPLACE INTO schooladmins (schoolid, uid, status) VALUES(?, ?, ?)', [query.schoolid, query.uid, query.status], function() {
				cb('school-change-member-status-success');
			});
		}
	});
});

SchoolsDB.prototype.deleteComment = _reqschooladm(function(query, user, access, cb) {
	this.query('SELECT c.commentid AS cid FROM ecomments AS c ' +
		'JOIN events AS e ON e.eventid = c.eventid ' +
		'WHERE c.commentid = ? AND e.targetid = ? AND e.type = "school-create"',
		[query.commentid, query.schoolid], function(res) {
		if (res.length == 0)
			return cb('permission-denied');

		assert.ok(res.length == 1 && res[0].cid == query.commentid);

		this.query('UPDATE ecomments SET comment = ?, trustedhtml = 1 WHERE commentid = ?',
			['Dieser Kommentar wurde durch die Gruppenadministratoren gelöscht.', query.commentid], function() {
			cb('school-delete-comment-success');
		});
	});
});

SchoolsDB.prototype.kickUser = _reqschooladm(function(query, user, access, cb) {
	this.query('DELETE FROM schoolmembers WHERE uid = ? AND schoolid = ?',
		[query.uid, query.schoolid], function() {
		this.query('DELETE FROM schooladmins WHERE uid = ? AND schoolid = ?',
			[query.uid, query.schoolid], function() {
			cb('school-kick-user-success');
		});
	});
});

SchoolsDB.prototype.createSchool = function(query, user, access, cb_) {
	if (!query.schoolpath)
		query.schoolpath = '/' + query.schoolname.replace(/[^\w_-]/g, '');

	this.locked(['userdb'], cb_, function(cb) {
		this.query('SELECT COUNT(*) AS c FROM schools WHERE path = ?', [query.schoolpath], function(r) {
			assert.equal(r.length, 1);
			if (r[0].c == 1 || !query.schoolname.trim() ||
				!/^(\/[\w_-]+)+$/.test(query.schoolpath)) {
				return cb('create-school-already-exists');
			}

			var createCB = _.bind(function() {
				this.query('INSERT INTO schools (name,path) VALUES(?,?)', [query.schoolname,query.schoolpath], function(res) {
					this.feed({'type': 'school-create', 'targetid': res.insertId, 'srcuser': user.id});

					cb('create-school-success');
				});
			}, this);

			if (query.schoolpath.replace(/[^\/]/g, '').length == 1)
				createCB();
			else this.query('SELECT COUNT(*) AS c FROM schools WHERE path = ?', [parentPath(query.schoolpath)], function(r) {
				assert.equal(r.length, 1);
				if (r[0].c != 1)
					return cb('create-school-missing-parent');

				createCB();
			});
		});
	});
};

SchoolsDB.prototype.publishBanner = function(query, user, access, FileStorageDB, cb) {
	query.__groupassoc__ = query.schoolid;
	query.role = 'schools.banner';

	_reqschooladm(_.bind(FileStorageDB.publish, FileStorageDB))(query, user, access, cb);
};

SchoolsDB.prototype.createInviteLink = function(query, user, access, UserDB, cb) {
	_reqschooladm(_.bind(UserDB.createInviteLink, UserDB), true)(query, user, access, cb);
};

exports.SchoolsDB = SchoolsDB;

})();
<commit_msg><commit_after>(function () { "use strict";

function parentPath(x) { return x.match(/(\/[\w_-]+)+\/[\w_-]+$/)[1]; }

var _ = require('underscore');
var util = require('util');
var assert = require('assert');

function SchoolsDB (db, config) {
	this.db = db;
	this.cfg = config;
}
util.inherits(SchoolsDB, require('./objects.js').DBSubsystemBase);

function adminlistContainsUser(admins, user) {
	return _.chain(admins).filter(function(a) { return a.status == 'admin' && a.adminid == user.id; }).value().length == 0;
}

function _reqschooladm (f, soft) {
	var soft = soft || false;

	return _.bind(function(query, user, access, cb) {
		var forward = _.bind(function() { return _.bind(f, this)(query, user, access, cb); }, this);
		if (access.has('schooldb') || (soft && !query.schoolid))
			return forward();

		assert.ok(this.loadSchoolAdmins);

		this.loadSchoolAdmins(query.schoolid, function(adminlist) {
			if (adminlistContainsUser(adminlist, user))
				cb('permission-denied');
			else
				forward();
		});
	}, this);
}

// only internal
SchoolsDB.prototype.loadSchoolAdmins = function(schoolid, cb) {
	this.query('SELECT sa.schoolid AS schoolid, sa.uid AS adminid, sa.status AS status, users.name AS adminname ' +
		'FROM schools AS c ' +
		'JOIN schools AS p ON c.path LIKE CONCAT(p.path, "%") OR p.id = c.id ' +
		'JOIN schooladmins AS sa ON sa.schoolid = p.id ' +
		'JOIN users ON users.id = sa.uid ' +
		'WHERE c.id = ?', [schoolid], cb);
};

SchoolsDB.prototype.loadSchoolInfo = function(lookfor, user, access, cb) {
	this.query('SELECT schools.id, schools.name, schools.path, descpage, eventid, type, targetid, time, srcuser, json, url AS banner FROM schools ' +
		'LEFT JOIN events ON events.targetid = schools.id AND events.type = "school-create" ' +
		'LEFT JOIN httpresources ON httpresources.groupassoc = schools.id AND httpresources.role = "schools.banner" ' +
		'WHERE ? IN (schools.id, schools.path, schools.name) ' +
		'LIMIT 1', [lookfor], function(res) {
		if (res.length == 0)
			return cb('get-school-info-notfound');

		var s = res[0];
		s.parentPath = null;

		assert.ok(s.eventid);

		this.loadSchoolAdmins(s.id, function(admins) {
			s.admins = admins;

			this.query('SELECT * FROM schools AS c WHERE c.path LIKE ?', [s.path + '/%'], function(subschools) {
			this.query('SELECT c.*,u.name AS username,u.id AS uid, url AS profilepic, trustedhtml ' +
				'FROM ecomments AS c '+
				'LEFT JOIN users AS u ON c.commenter = u.id ' +
				'LEFT JOIN httpresources ON httpresources.user = c.commenter AND httpresources.role = "profile.image" '+
				'WHERE c.eventid = ?',
				[s.eventid],
				function(comments) {
				s.comments = comments;
				s.subschools = subschools;

				this.query('SELECT oh.stocktextid AS stockid, oh.stockname, ' +
					'SUM(ABS(money)) AS moneysum, ' +
					'SUM(ABS(money) / (UNIX_TIMESTAMP() - buytime)) AS wsum '+
					'FROM orderhistory AS oh ' +
					'JOIN schoolmembers AS sm ON sm.uid = oh.userid AND sm.jointime < oh.buytime AND sm.schoolid = ? ' +
					'GROUP BY stocktextid ORDER BY wsum DESC', [s.id], function(popular) {
					s.popularStocks = popular.splice(0, 10);

					if (s.path.replace(/[^\/]/g, '').length != 1) { // need higher-level
						s.parentPath = parentPath(s.path);
						this.loadSchoolInfo(s.parentPath, user, access, function(code, result) {
							assert.equal(code, 'get-school-info-success');

							s.parentSchool = result;

							cb('get-school-info-success', s);
						});
					} else {
						cb('get-school-info-success', s);
					}
				});
			});
			});
		});
	});
};

SchoolsDB.prototype.getSchoolInfo = function(query, user, access, cb) {
	this.loadSchoolInfo(query.lookfor, user, access, cb);
};

SchoolsDB.prototype.changeDescription = _reqschooladm(function(query, user, access, cb) {
	this.query('UPDATE schools SET descpage = ? WHERE id = ?', [query.descpage, query.schoolid], function() {
		cb('school-change-description-success');
	});
});

SchoolsDB.prototype.changeMemberStatus = _reqschooladm(function(query, user, access, cb) {
	this.query('UPDATE schoolmembers SET pending = 0 WHERE schoolid = ? AND uid = ?', [query.schoolid, query.uid], function() {
		if (query.newstatus == 'member') {
			this.query('DELETE FROM schooladmins WHERE uid = ? AND schoolid = ?', [query.uid, query.schoolid], function() {
				cb('school-change-member-status-success');
			});
		} else {
			this.query('REPLACE INTO schooladmins (schoolid, uid, status) VALUES(?, ?, ?)', [query.schoolid, query.uid, query.status], function() {
				cb('school-change-member-status-success');
			});
		}
	});
});

SchoolsDB.prototype.deleteComment = _reqschooladm(function(query, user, access, cb) {
	this.query('SELECT c.commentid AS cid FROM ecomments AS c ' +
		'JOIN events AS e ON e.eventid = c.eventid ' +
		'WHERE c.commentid = ? AND e.targetid = ? AND e.type = "school-create"',
		[query.commentid, query.schoolid], function(res) {
		if (res.length == 0)
			return cb('permission-denied');

		assert.ok(res.length == 1 && res[0].cid == query.commentid);

		this.query('UPDATE ecomments SET comment = ?, trustedhtml = 1 WHERE commentid = ?',
			['Dieser Kommentar wurde durch die Gruppenadministratoren gelöscht.', query.commentid], function() {
			cb('school-delete-comment-success');
		});
	});
});

SchoolsDB.prototype.kickUser = _reqschooladm(function(query, user, access, cb) {
	this.query('DELETE FROM schoolmembers WHERE uid = ? AND schoolid = ?',
		[query.uid, query.schoolid], function() {
		this.query('DELETE FROM schooladmins WHERE uid = ? AND schoolid = ?',
			[query.uid, query.schoolid], function() {
			cb('school-kick-user-success');
		});
	});
});

SchoolsDB.prototype.createSchool = function(query, user, access, cb_) {
	if (!query.schoolpath)
		query.schoolpath = '/' + query.schoolname.replace(/[^\w_-]/g, '');

	this.locked(['userdb'], cb_, function(cb) {
		this.query('SELECT COUNT(*) AS c FROM schools WHERE path = ?', [query.schoolpath], function(r) {
			assert.equal(r.length, 1);
			if (r[0].c == 1 || !query.schoolname.trim() ||
				!/^(\/[\w_-]+)+$/.test(query.schoolpath)) {
				return cb('create-school-already-exists');
			}

			var createCB = _.bind(function() {
				this.query('INSERT INTO schools (name,path) VALUES(?,?)', [query.schoolname,query.schoolpath], function(res) {
					this.feed({'type': 'school-create', 'targetid': res.insertId, 'srcuser': user.id});

					cb('create-school-success');
				});
			}, this);

			if (query.schoolpath.replace(/[^\/]/g, '').length == 1)
				createCB();
			else this.query('SELECT COUNT(*) AS c FROM schools WHERE path = ?', [parentPath(query.schoolpath)], function(r) {
				assert.equal(r.length, 1);
				if (r[0].c != 1)
					return cb('create-school-missing-parent');

				createCB();
			});
		});
	});
};

SchoolsDB.prototype.publishBanner = function(query, user, access, FileStorageDB, cb) {
	query.__groupassoc__ = query.schoolid;
	query.role = 'schools.banner';

	_.bind(_reqschooladm, this)(_.bind(FileStorageDB.publish, FileStorageDB))(query, user, access, cb);
};

SchoolsDB.prototype.createInviteLink = function(query, user, access, UserDB, cb) {
	_.bind(_reqschooladm, this)(_.bind(UserDB.createInviteLink, UserDB), true)(query, user, access, cb);
};

exports.SchoolsDB = SchoolsDB;

})();
<|endoftext|>


<commit_before>var bittorrentTracker = require('bittorrent-tracker');
var LRU               = require('lru-cache');
var parseTorrent      = require('parse-torrent');

// ----------------------------------------------------------------------------

exports.cache = new LRU({
  max:    7500,
  maxAge: 60 * 60 * 1000,
  scrape: true
});

// ----------------------------------------------------------------------------

function scrape(magnetLink, callback) {
  var parsedMagnedLink = parseTorrent(magnetLink);
  if (!parsedMagnedLink) {
    callback('Invalid magnet', null);
    return;
  }
  var client = new bittorrentTracker(new Buffer('01234567890123456789'), 6881, parsedMagnedLink);

  // client.on('error', function(err) {
  //   console.log(err);
  //   client.destroy();
  //   callback(err, null);
  // });

  // client.on('warning', function(err) {
  //   console.log(err);
  //   client.destroy();
  //   callback(err, null);
  // });

  client.on('scrape', function(data) {
    client.destroy();
    callback(null, { seeds: data.complete, peers: data.incomplete });
  });

  client.scrape();
}

// ----------------------------------------------------------------------------

exports.scrape = function(magnetLink, callback) {
  var startTime        = new Date().getTime();
  var parsedMagnedLink = parseTorrent(magnetLink);

  var key   = parsedMagnedLink.infoHash;
  var value = exports.cache.peek(key);

  // Value doesn't exist in cache, force update
  if (!value) {
    scrape(magnetLink, function(err, results) {
      if (err) {
        console.log('[BTRT][ERR][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn);
        callback(err, null);
      } else {
        console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
        exports.cache.set(key, results);
        callback(null, results);
      }
    });
  } else {
    var getValue = exports.cache.get(key);
    if (!getValue) {
      // Value is outdated, try and update it
      scrape(magnetLink, function(err, results) {
        if (err) {
          // Failed to update, return previous value
          console.log('[BTRT][FLB][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + value.seeds + ' P:' + value.peers + ')');
          exports.cache.set(key, value);
          callback(null, value);
        } else {
          // Update cache and return new value
          console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
          exports.cache.set(key, results);
          callback(null, results);
        }
      });
    } else {
      // Value is still in cache
      // console.log('[BTRT][MEM][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + getValue.seeds + ' P:' + getValue.peers + ')');
      callback(null, getValue);
    }
  }
}

// ----------------------------------------------------------------------------

function getDuration(startTime) {
  var duration = ((new Date().getTime() - startTime) / 1000.0).toFixed(1);
  if (duration < 10.0) {
    duration = '0' + duration;
  }
  return duration;
}
<commit_msg>Fixed crash with invalid magnet links<commit_after>var bittorrentTracker = require('bittorrent-tracker');
var LRU               = require('lru-cache');
var parseTorrent      = require('parse-torrent');

// ----------------------------------------------------------------------------

exports.cache = new LRU({
  max:    7500,
  maxAge: 60 * 60 * 1000,
  scrape: true
});

// ----------------------------------------------------------------------------

function scrape(magnetLink, callback) {
  try {
    var client = new bittorrentTracker(new Buffer('01234567890123456789'), 6881, parseTorrent(magnetLink));

    // client.on('error', function(err) {
    //   console.log(err);
    //   client.destroy();
    //   callback(err, null);
    // });

    // client.on('warning', function(err) {
    //   console.log(err);
    //   client.destroy();
    //   callback(err, null);
    // });

    client.on('scrape', function(data) {
      client.destroy();
      callback(null, { seeds: data.complete, peers: data.incomplete });
    });

    client.scrape();
  } catch (err)
  {
    callback(err, null);
  }
}

// ----------------------------------------------------------------------------

exports.scrape = function(magnetLink, callback) {
  var startTime        = new Date().getTime();
  var parsedMagnedLink = parseTorrent(magnetLink);

  var key   = parsedMagnedLink.infoHash;
  var value = exports.cache.peek(key);

  // Value doesn't exist in cache, force update
  if (!value) {
    scrape(magnetLink, function(err, results) {
      if (err) {
        console.log('[BTRT][ERR][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn);
        callback(err, null);
      } else {
        console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
        exports.cache.set(key, results);
        callback(null, results);
      }
    });
  } else {
    var getValue = exports.cache.get(key);
    if (!getValue) {
      // Value is outdated, try and update it
      scrape(magnetLink, function(err, results) {
        if (err) {
          // Failed to update, return previous value
          console.log('[BTRT][FLB][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + value.seeds + ' P:' + value.peers + ')');
          exports.cache.set(key, value);
          callback(null, value);
        } else {
          // Update cache and return new value
          console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
          exports.cache.set(key, results);
          callback(null, results);
        }
      });
    } else {
      // Value is still in cache
      // console.log('[BTRT][MEM][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + getValue.seeds + ' P:' + getValue.peers + ')');
      callback(null, getValue);
    }
  }
}

// ----------------------------------------------------------------------------

function getDuration(startTime) {
  var duration = ((new Date().getTime() - startTime) / 1000.0).toFixed(1);
  if (duration < 10.0) {
    duration = '0' + duration;
  }
  return duration;
}
<|endoftext|>


<commit_before>var config = require('./config').scraper;
var request = require('request');
var cheerio = require('cheerio');
var mysql = require('mysql');
var connections = mysql.createPool(config.db);
var winston = require('winston');

if (config.logfile != null) {
  winston.add(winston.transports.File, { filename: config.logfile });
  winston.remove(winston.transports.Console);
} // else default to STDOUT

var scrapeMedalsTable = function() {
  winston.info(new Date(), "Beginning scrape from " + config.url);

  request(config.url, function(error, response, html) {
    if (error) {
      winston.error(error);
      return;
    }

    var $ = cheerio.load(html);

    if ($('.wikitable').length == 0) {
      winston.error("Unable to find .wikitable in scraped html");
      return;
    }

    $('.wikitable').each(function(i, element) {
      if($(this).children('caption').html().indexOf("medal table") != -1) {
        var medalsTable = {"standings" : []};

        $(this).children('tr').each(function(i, element) {
          var tds = $(this).children('td');
          var country = $(this).children('th').children('a').html();
          if (country != null)
            country = country.replace(/["']/g, "");
          else
            return;
          var golds = parseInt(tds.slice(1).html());
          var silvers = parseInt(tds.slice(2).html());
          var bronzes = parseInt(tds.slice(3).html());

          medalsTable.standings.push({
            "country" : country,
            "golds" : golds,
            "silvers" : silvers,
            "bronzes" : bronzes
          });
        });

        // each() is synchronous so we can trust its callbacks have finished executing
        if (medalsTable.standings.length == 0) {
          winston.error("No data found in scraped html");
          return;
        } else {
          return storeMedalsTable(medalsTable);
        }
      }
    });
  });
};

var storeMedalsTable = function(medalTable) {
  // convert into nested array for multi-row INSERT
  var values = [];
  for (var i=0; i<medalTable.standings.length; ++i) {
    var row = medalTable.standings[i];

    if (config.nameCorrections[row.country] != null)
      row.country = config.nameCorrections[row.country];

    values.push([row.country, row.golds, row.silvers, row.bronzes]);
  }

  connections.getConnection(function(err, connection) {
    connection.beginTransaction(function(err) {
      if (err) {
        winston.error(err);
        connection.release();
        return;
      }

      connection.query('DELETE FROM country_standings', function(err, rows) {
        if (err) {
          winston.error(err);
          return connection.rollback(function() {connection.release();});
        }

        connection.query('INSERT INTO country_standings (country, golds, silvers, bronzes) VALUES ?', [values], function(err, rows) {
          if (err) {
            winston.error(err);
            return connection.rollback(function() {connection.release();});
          }

          connection.query('CALL calculate_team_standings', function(err, rows, fields) {
            if (err) {
              winston.error(err);
              return connection.rollback(function() {connection.release();});
            }

            return connection.commit(function() {
              winston.info(new Date(), "Completed scrape");
              connection.release();
            });
          });
        });
      });
    });
  });
};

// run immediately on startup
scrapeMedalsTable();

// run periodically
setInterval(scrapeMedalsTable, config.interval);

var handleExit = function() {
  winston.info('scraper.js shutting down');
  process.exit();
};

process.on('SIGINT', handleExit);
process.on('SIGTERM', handleExit);
process.on('exit', handleExit);
<commit_msg>Fix to cope with multirow on scraped table<commit_after>var config = require('./config').scraper;
var request = require('request');
var cheerio = require('cheerio');
var mysql = require('mysql');
var connections = mysql.createPool(config.db);
var winston = require('winston');

if (config.logfile != null) {
  winston.add(winston.transports.File, { filename: config.logfile });
  winston.remove(winston.transports.Console);
} // else default to STDOUT

var scrapeMedalsTable = function() {
  winston.info(new Date(), "Beginning scrape from " + config.url);

  request(config.url, function(error, response, html) {
    if (error) {
      winston.error(error);
      return;
    }

    var $ = cheerio.load(html);

    if ($('.wikitable').length == 0) {
      winston.error("Unable to find .wikitable in scraped html");
      return;
    }

    $('.wikitable').each(function(i, element) {
      if($(this).children('caption').html().indexOf("medal table") != -1) {
        var medalsTable = {"standings" : []};

        $(this).children('tr').each(function(i, element) {
          var tds = $(this).children('td');
          var country = $(this).children('th').children('a').html();
          if (country != null)
            country = country.replace(/["']/g, "");
          else
            return;
          var golds = parseInt(tds.slice(-4).html());
          var silvers = parseInt(tds.slice(-3).html());
          var bronzes = parseInt(tds.slice(-2).html());

          medalsTable.standings.push({
            "country" : country,
            "golds" : golds,
            "silvers" : silvers,
            "bronzes" : bronzes
          });
        });

        // each() is synchronous so we can trust its callbacks have finished executing
        if (medalsTable.standings.length == 0) {
          winston.error("No data found in scraped html");
          return;
        } else {
          return storeMedalsTable(medalsTable);
        }
      }
    });
  });
};

var storeMedalsTable = function(medalTable) {
  // convert into nested array for multi-row INSERT
  var values = [];
  for (var i=0; i<medalTable.standings.length; ++i) {
    var row = medalTable.standings[i];

    if (config.nameCorrections[row.country] != null)
      row.country = config.nameCorrections[row.country];

    values.push([row.country, row.golds, row.silvers, row.bronzes]);
  }

  connections.getConnection(function(err, connection) {
    connection.beginTransaction(function(err) {
      if (err) {
        winston.error(err);
        connection.release();
        return;
      }

      connection.query('DELETE FROM country_standings', function(err, rows) {
        if (err) {
          winston.error(err);
          return connection.rollback(function() {connection.release();});
        }

        connection.query('INSERT INTO country_standings (country, golds, silvers, bronzes) VALUES ?', [values], function(err, rows) {
          if (err) {
            winston.error(err);
            return connection.rollback(function() {connection.release();});
          }

          connection.query('CALL calculate_team_standings', function(err, rows, fields) {
            if (err) {
              winston.error(err);
              return connection.rollback(function() {connection.release();});
            }

            return connection.commit(function() {
              winston.info(new Date(), "Completed scrape");
              connection.release();
            });
          });
        });
      });
    });
  });
};

// run immediately on startup
scrapeMedalsTable();

// run periodically
setInterval(scrapeMedalsTable, config.interval);

var handleExit = function() {
  winston.info('scraper.js shutting down');
  process.exit();
};

process.on('SIGINT', handleExit);
process.on('SIGTERM', handleExit);
process.on('exit', handleExit);
<|endoftext|>