<commit_before>var headless = require( 'headless' ),
	fs = require( 'fs' ),
	path = require( 'path' ),
	spawn = require( 'child_process' ).spawn,
	argue = {};

argue.firefox = function( br, uri, opts, cb ) {
	var prefs = '';

	opts.options = opts.options || [];

	if ( opts.proxy ) {
		var m = /^(?:http:\/\/)?([^:\/]+)(?::(\d+))?/.exec( opts.proxy ),
			host = JSON.stringify( m[ 1 ] ),
			port = m[ 2 ] || 80;

		prefs += [
			'"network.proxy.http", ' + host,
			'"network.proxy.http_port", ' + port,
			'"network.proxy.type", 1',
			'"browser.cache.disk.capacity", 0',
			'"browser.cache.disk.smart_size.enabled", false',
			'"browser.cache.disk.smart_size.first_run", false',
			'"browser.sessionstore.resume_from_crash", false',
			'"browser.startup.page", 0',
			'"network.proxy.no_proxies_on", ' + JSON.stringify( opts.noProxy || '' )
		].map( function( x ) {
			return 'user_pref(' + x + ');\n';
		} ).join( '' );
	}

	prefs += 'user_pref("browser.shell.checkDefaultBrowser", false);\n';

	var file = path.join( path.dirname( br.profile.file ), 'user.js' );

	fs.writeFile( file, prefs, function( err ) {
		if ( err ) {
			cb( err );
		} else {
			cb( null, opts.options.concat( [
				'--no-remote',
				'-P', br.profile.name,
				uri
			] ) );
		}
	} );
};

argue.ie = function( br, uri, opts, cb ) {
	cb( null, [ uri ] );
};

argue.safari = function( br, uri, opts, cb ) {
	cb( null, [ uri ] );
};

argue.chrome = function( br, uri, opts, cb ) {
	opts.options = opts.options || [];

	cb( null, opts.options.concat( [
		opts.proxy ? '--proxy-server=' + opts.proxy : null,
		br.profile ? '--user-data-dir=' + br.profile : null,
		'--disable-restore-session-state',
		'--no-default-browser-check',
		'--start-maximized',
		'--disable-default-apps',
		'--disable-sync',
		'--enable-fixed-layout',
		'--no-first-run',
		'--noerrdialogs ',
		uri
	] ).filter( Boolean ) );
};

argue.phantom = function( br, uri, opts, cb ) {
	var file = path.join( __dirname, '../res/phantom.js' );

	opts.options = opts.options || [];

	cb( null, opts.options.concat( [
		opts.proxy ? '--proxy=' + opts.proxy.replace( /^http:\/\//, '' ) : null,
		file,
		uri
	] ).filter( Boolean ) );
};

function copy( src, dest, cb ) {
	var rs = fs.createReadStream( src ),
		ws = fs.createWriteStream( dest ),
		called = false;

	function done( err ) {
		if ( !called ) {
			called = true;
			cb( err );
		}
	}

	rs.on( 'error', done );
	ws.on( 'error', done );
	ws.on( 'close', function() {
		done();
	} );

	rs.pipe( ws );
}

argue.opera = function( br, uri, opts, cb ) {
	var src = path.join( __dirname, '../res/operaprefs.ini' ),
		dest = path.join( br.profile, 'operaprefs.ini' ),
		options = {
			old: [
				br.profile ? '-pd ' + br.profile : null,
				'-nomail',
				uri
			],
			blink: [
				br.profile ? '--user-data-dir=' + br.profile : null,
				'--disable-restore-session-state',
				'--no-default-browser-check',
				'--start-maximized',
				'--disable-default-apps',
				'--disable-sync',
				'--enable-fixed-layout',
				'--no-first-run',
				'--noerrdialogs ',
				uri
			]
		};

	opts.options = opts.options || [];

	copy( src, dest, function( err ) {
		if ( err ) {
			cb( err );
		} else {
			cb( null, opts.options.concat( options[ major( br.version ) > 15 ? 'blink' : 'old' ] ).filter( Boolean ) );
		}
	} );
};

module.exports = function( config, name, version ) {
	var m = selectMatch( config, name, version );

	if ( !m ) {
		return;
	}

	return function( uri, opts, cb ) {
		if ( opts.headless && !m.headless ) {
			headless( function( err, proc, display ) {
				if ( err ) {
					return cb( err );
				}

				run( {
					DISPLAY: ':' + display
				} );
			} );
		} else {
			run( {} );
		}

		function run( env_ ) {
			var env = {},
				cwd = process.cwd();

			Object.keys( process.env ).forEach( function( key ) {
				env[ key ] = process.env[ key ];
			} );

			Object.keys( env_ ).forEach( function( key ) {
				env[ key ] = env_[ key ];
			} );

			argue[ m.type ]( m, uri, opts, function( err, args ) {
				if ( err ) {
					return cb( err );
				}

				if ( opts.noProxy && env.no_proxy === undefined ) {
					env.no_proxy = opts.noProxy;
				}

				if ( opts.proxy && env.http_proxy === undefined ) {
					env.http_proxy = opts.proxy;
				}

				if ( opts.proxy && env.HTTP_PROXY === undefined ) {
					env.HTTP_PROXY = opts.proxy;
				}

				switch ( process.platform ) {
					case 'win32':
						m.command = m.command.replace( /"/g, '' ); //Ensure all the quotes are removed
						cwd = require( 'path' ).dirname( m.command ); //Change directory to the app's base (Chrome)
						break;
					case 'darwin':
						if ( m.name !== 'firefox' && m.name !== 'phantom' ) { //Use the bin path under the hood
							/*
                            This creates a command line structure like this:
                            open --wait-apps --new --fresh -a /Path/To/Executable <url> --args <rest of app args>
                            */
							args.unshift( '--args' );
							args.unshift( args.pop() );
							args.unshift( m.command );
							args.unshift( '-a' );
							args.unshift( '--fresh' );
							args.unshift( '--new' );
							args.unshift( '--wait-apps' );
							m.command = 'open';
						}
						break;
				}

				cb( null, spawn( m.command, args, {
					env: env,
					cwd: cwd
				} ) );
			} );
		}
	};
};

function major( version ) {
	return +version.split( '.' )[ 0 ];
}

function selectMatch( config, name, version ) {
	var order = ( config.preference || [] ).concat( Object.keys( config.browsers ) ),
		matching,
		bs,
		i;

	function filter( bs ) {
		return bs.filter( function( b ) {
			return b.name === name && matches( b.version, version );
		} ).sort( function( a, b ) {
			return major( b.version ) - major( a.version );
		} );
	}

	for ( i = 0; i < order.length; i++ ) {
		bs = config.browsers[ order[ i ] ];

		matching = filter( bs );

		if ( matching.length ) {
			return matching[ 0 ];
		}
	}
}

function matches( version, pattern ) {
	if ( pattern === undefined || pattern === '*' ) {
		return true;
	}

	// todo: real semvers
	var vs = version.split( '.' ),
		ps = pattern.split( '.' ),
		i;

	for ( i = 0; i < ps.length; i++ ) {
		if ( ps[ i ] === 'x' || ps[ i ] === '*' ) {
			continue;
		}

		if ( ps[ i ] !== vs[ i ] ) {
			return false;
		}
	}

	return true;
}
<commit_msg>Resolved #2 - user can configure Firefox's preferences using options.prefs object.<commit_after>var headless = require( 'headless' ),
	fs = require( 'fs' ),
	path = require( 'path' ),
	spawn = require( 'child_process' ).spawn,
	argue = {};

function merge( dest, src ) {
	Object.keys( src ).forEach( function( name ) {
		dest[ name ] = src[ name ];
	} );

	return dest;
}

argue.firefox = function( br, uri, opts, cb ) {
	var file = path.join( path.dirname( br.profile.file ), 'user.js' ),
		prefs = {
			'browser.shell.checkDefaultBrowser': false,
			'browser.bookmarks.restore_default_bookmarks': false,
			'dom.disable_open_during_load': false,
			'dom.max_script_run_time': 0
		};

	opts.options = opts.options || [];

	if ( opts.proxy ) {
		var m = /^(?:http:\/\/)?([^:\/]+)(?::(\d+))?/.exec( opts.proxy ),
			host = JSON.stringify( m[ 1 ] ),
			port = m[ 2 ] || 80;

		merge( prefs, {
			'network.proxy.http': host,
			'network.proxy.http_port': +port,
			'network.proxy.type': 1,
			'browser.cache.disk.capacity': 0,
			'browser.cache.disk.smart_size.enabled': false,
			'browser.cache.disk.smart_size.first_run': false,
			'browser.sessionstore.resume_from_crash': false,
			'browser.startup.page': 0,
			'network.proxy.no_proxies_on': JSON.stringify( opts.noProxy || '' )
		} );
	}

	if ( opts.prefs ) {
		merge( prefs, opts.prefs );
	}

	prefs = Object.keys( prefs ).map( function( name ) {
		return 'user_pref("' + name + '", ' + prefs[ name ] + ');';
	} ).join( '\n' );

	fs.writeFile( file, prefs, function( err ) {
		if ( err ) {
			cb( err );
		} else {
			cb( null, opts.options.concat( [
				'--no-remote',
				'-P', br.profile.name,
				uri
			] ) );
		}
	} );
};

argue.ie = function( br, uri, opts, cb ) {
	cb( null, [ uri ] );
};

argue.safari = function( br, uri, opts, cb ) {
	cb( null, [ uri ] );
};

argue.chrome = function( br, uri, opts, cb ) {
	opts.options = opts.options || [];

	cb( null, opts.options.concat( [
		opts.proxy ? '--proxy-server=' + opts.proxy : null,
		br.profile ? '--user-data-dir=' + br.profile : null,
		'--disable-restore-session-state',
		'--no-default-browser-check',
		'--start-maximized',
		'--disable-default-apps',
		'--disable-sync',
		'--enable-fixed-layout',
		'--no-first-run',
		'--noerrdialogs ',
		uri
	] ).filter( Boolean ) );
};

argue.phantom = function( br, uri, opts, cb ) {
	var file = path.join( __dirname, '../res/phantom.js' );

	opts.options = opts.options || [];

	cb( null, opts.options.concat( [
		opts.proxy ? '--proxy=' + opts.proxy.replace( /^http:\/\//, '' ) : null,
		file,
		uri
	] ).filter( Boolean ) );
};

function copy( src, dest, cb ) {
	var rs = fs.createReadStream( src ),
		ws = fs.createWriteStream( dest ),
		called = false;

	function done( err ) {
		if ( !called ) {
			called = true;
			cb( err );
		}
	}

	rs.on( 'error', done );
	ws.on( 'error', done );
	ws.on( 'close', function() {
		done();
	} );

	rs.pipe( ws );
}

argue.opera = function( br, uri, opts, cb ) {
	var src = path.join( __dirname, '../res/operaprefs.ini' ),
		dest = path.join( br.profile, 'operaprefs.ini' ),
		options = {
			old: [
				br.profile ? '-pd ' + br.profile : null,
				'-nomail',
				uri
			],
			blink: [
				br.profile ? '--user-data-dir=' + br.profile : null,
				'--disable-restore-session-state',
				'--no-default-browser-check',
				'--start-maximized',
				'--disable-default-apps',
				'--disable-sync',
				'--enable-fixed-layout',
				'--no-first-run',
				'--noerrdialogs ',
				uri
			]
		};

	opts.options = opts.options || [];

	copy( src, dest, function( err ) {
		if ( err ) {
			cb( err );
		} else {
			cb( null, opts.options.concat( options[ major( br.version ) > 15 ? 'blink' : 'old' ] ).filter( Boolean ) );
		}
	} );
};

module.exports = function( config, name, version ) {
	var m = selectMatch( config, name, version );

	if ( !m ) {
		return;
	}

	return function( uri, opts, cb ) {
		if ( opts.headless && !m.headless ) {
			headless( function( err, proc, display ) {
				if ( err ) {
					return cb( err );
				}

				run( {
					DISPLAY: ':' + display
				} );
			} );
		} else {
			run( {} );
		}

		function run( env_ ) {
			var env = {},
				cwd = process.cwd();

			Object.keys( process.env ).forEach( function( key ) {
				env[ key ] = process.env[ key ];
			} );

			Object.keys( env_ ).forEach( function( key ) {
				env[ key ] = env_[ key ];
			} );

			argue[ m.type ]( m, uri, opts, function( err, args ) {
				if ( err ) {
					return cb( err );
				}

				if ( opts.noProxy && env.no_proxy === undefined ) {
					env.no_proxy = opts.noProxy;
				}

				if ( opts.proxy && env.http_proxy === undefined ) {
					env.http_proxy = opts.proxy;
				}

				if ( opts.proxy && env.HTTP_PROXY === undefined ) {
					env.HTTP_PROXY = opts.proxy;
				}

				switch ( process.platform ) {
					case 'win32':
						m.command = m.command.replace( /"/g, '' ); //Ensure all the quotes are removed
						cwd = require( 'path' ).dirname( m.command ); //Change directory to the app's base (Chrome)
						break;
					case 'darwin':
						if ( m.name !== 'firefox' && m.name !== 'phantom' ) { //Use the bin path under the hood
							/*
                            This creates a command line structure like this:
                            open --wait-apps --new --fresh -a /Path/To/Executable <url> --args <rest of app args>
                            */
							args.unshift( '--args' );
							args.unshift( args.pop() );
							args.unshift( m.command );
							args.unshift( '-a' );
							args.unshift( '--fresh' );
							args.unshift( '--new' );
							args.unshift( '--wait-apps' );
							m.command = 'open';
						}
						break;
				}

				cb( null, spawn( m.command, args, {
					env: env,
					cwd: cwd
				} ) );
			} );
		}
	};
};

function major( version ) {
	return +version.split( '.' )[ 0 ];
}

function selectMatch( config, name, version ) {
	var order = ( config.preference || [] ).concat( Object.keys( config.browsers ) ),
		matching,
		bs,
		i;

	function filter( bs ) {
		return bs.filter( function( b ) {
			return b.name === name && matches( b.version, version );
		} ).sort( function( a, b ) {
			return major( b.version ) - major( a.version );
		} );
	}

	for ( i = 0; i < order.length; i++ ) {
		bs = config.browsers[ order[ i ] ];

		matching = filter( bs );

		if ( matching.length ) {
			return matching[ 0 ];
		}
	}
}

function matches( version, pattern ) {
	if ( pattern === undefined || pattern === '*' ) {
		return true;
	}

	// todo: real semvers
	var vs = version.split( '.' ),
		ps = pattern.split( '.' ),
		i;

	for ( i = 0; i < ps.length; i++ ) {
		if ( ps[ i ] === 'x' || ps[ i ] === '*' ) {
			continue;
		}

		if ( ps[ i ] !== vs[ i ] ) {
			return false;
		}
	}

	return true;
}
<|endoftext|>


<commit_before>// function to load JSON file synchonously before d3 rendering

function loadJsonFileSynch(file){
    var ajaxresponse
    $.ajax({
        url: "data/"+file+".json",
        async: false,
        dataType: "json",
        success: function (response) {
            ajaxresponse= response;
        }
    });
    return ajaxresponse;
}

function generateCountryPieChart(id,datain){

    var data = [
        {"country":"Guinea","cases":datain["Guinea"][0].cases},
        {"country":"Liberia","cases":datain["Liberia"][0].cases},
        {"country":"Sierra Leone","cases":datain["Sierra Leone"][0].cases},
        {"country":"Nigeria","cases":datain["Nigeria"][0].cases}
    ];

    data.forEach(function(d) {
      d.cases = +d.cases;
    });

    var margin = {top: 0, right: 0, bottom: 0, left: 0},
        width = $(id).width() - margin.left - margin.right,
        height = $(id).height() - margin.top - margin.bottom,
        radius = Math.min(width, height) / 2;

    var arc = d3.svg.arc()
        .outerRadius(radius - 10)
        .innerRadius(0);

    var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) { return d.cases; });

    var svg = d3.select(id).append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var g = svg.selectAll(".arc")
        .data(pie(data))
        .enter().append("g")

    g.append("path")
        .attr("d", arc)
        .style("fill", function(d,i) { return color[d.data.country]; })
        .attr("id",function(d){
            return d.data.country.replace(/\s/g, '');
        })
        .on("click",function(d){
            transition(d.data.country);
        });

    g.append("text")
        .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
        .attr("dy", ".35em")
        .style("text-anchor", "middle")
        .text(function(d) {return d.data.country; });
}

function generateLineChart(id,datain){
    var margin = {top: 20, right: 20, bottom: 25, left: 50},
        width = $(id).width() - margin.left - margin.right,
        height = $(id).height() - margin.top - margin.bottom;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
            .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function(d) {
            return x(d.date);
        })
        .y(function(d) { return y(d.cases); });

    var line2 = d3.svg.line()
        .x(function(d) {
            return (x(d.date)); })
        .y(function(d) { return y(d.deaths); });

    var svg = d3.select(id).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    x.domain(d3.extent(datain, function(d) {
        return d.date; }));
    y.domain([0,d3.max(datain, function(d) { return d.cases; })]);

    svg.append("g")
        .attr("class", "xaxis axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "yaxis axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Cases");

    svg.append("path")
        .datum(datain)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill","none")
        .attr("stroke","steelblue")
        .attr("stroke-width","1px");

    svg.append("path")
        .datum(datain)
        .attr("class", "line2")
        .attr("d", line2)
        .attr("fill","none")
        .attr("stroke","red")
        .attr("stroke-width","1px");
}

function generateKeyStats(id,datain){
    var html = "
Population: "+datain["population"] + "
";
    html = html + "
Cases: "+datain["cases"] + "
";
    html = html + "
Deaths: "+datain["deaths"] + "
";
    html = html + "
Crude Mortality Rate: "+datain["mortality rate"] + "
";
    $(id).html(html);
}

function generateMedicalCentres(id,datain,filter){
    var html ="";
    if(filter==="Total"){
        var country =[];
        var countryTotals = [];
        datain.forEach(function(e){
            if($.inArray(e.Country, country)>-1){
                countryTotals[e.Country] = countryTotals[e.Country]+1;
            } else {
                country.push(e.Country);
                countryTotals[e.Country] = 1;
            }
        });

        country.forEach(function(e){
           html = html + "
" + e +": " + countryTotals[e]+"
";
        });
    } else {
        datain.forEach(function(e){
            if(e.Country === filter){
                html = html + "
" + e.Name + ", " + e.Town + ", " + e.Region + "
";
            }
        });
    }
    $(id).html(html);
}

function transitionPieChart(filter){
    if(filter==="Total"){
        d3.select("#Liberia").transition().duration(duration).style("fill",color["Liberia"]);
        d3.select("#SierraLeone").transition().duration(duration).style("fill",color["Sierra Leone"]);
        d3.select("#Guinea").transition().duration(duration).style("fill",color["Guinea"]);
        d3.select("#Nigeria").transition().duration(duration).style("fill",color["Nigeria"]);
    } else {
        d3.select("#Liberia").transition().duration(duration).style("fill","#cccccc");
        d3.select("#SierraLeone").transition().duration(duration).style("fill","#cccccc");
        d3.select("#Guinea").transition().duration(duration).style("fill","#cccccc");
        d3.select("#Nigeria").transition().duration(duration).style("fill","#cccccc");
        d3.select("#"+filter.replace(/\s/g, '')).transition().duration(duration).style("fill",color[filter]);
    }
}

function generateMap(){
    var margin = {top: 10, right: 10, bottom: 10, left: 10},
    width = $('#map').width() - margin.left - margin.right,
    height = 325;

    var projection = d3.geo.mercator()
        .center([0,5])
        .scale(1800);

    var svg = d3.select('#map').append("svg")
        .attr("width", width)
        .attr("height", height);

    var path = d3.geo.path()
        .projection(projection);

    var g = svg.append("g");

    g.selectAll("path")
        .data(regions.features)
        .enter()
        .append("path")
        .attr("d", path)
        .attr("stroke",'#aaaaaa')
        .attr("stroke-width","0px")
        .attr("fill",'#ffffff')
        .attr("id",function(d){return d.properties.NAME_REF.replace(/\s/g, '');})
        .attr("class","region")
        .append("svg:title")
        .text(function(d) { return d.properties.NAME_REF; });

    regionsAffected.forEach(function(e) {
        d3.select("#"+e.Region.replace(/\s/g, '')).attr("fill","#ff8f00");
    });

    var g = svg.append("g");

    g.selectAll("path")
        .data(westafrica.features)
        .enter()
        .append("path")
        .attr("d", path)
        .attr("stroke",'#aaaaaa')
        .attr("fill",'none')
        .attr("class","country");

    var mapLabels = svg.append("g");

    mapLabels.selectAll('text')
      .data(westafrica.features)
         .enter()
         .append("text")
         .attr("x", function(d,i){
                     return path.centroid(d)[0]-20;})
         .attr("y", function(d,i){
                     return path.centroid(d)[1];})
         .attr("dy", ".55em")
         .attr("class","maplabel")
         .style("font-size","12px")
         .attr("opacity",0.4)
         .text(function(d,i){
                      return d.properties.NAME;
                  });
}

function transitionLineChart(id,datain){

    var margin = {top: 20, right: 20, bottom: 25, left: 50},
        width = $(id).width() - margin.left - margin.right,
        height = $(id).height() - margin.top - margin.bottom;

    var parseDate = d3.time.format("%d/%m/%Y").parse;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
            .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.cases); });

    var line2 = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.deaths); });

    x.domain(d3.extent(datain, function(d) { return d.date; }));
    y.domain([0,d3.max(datain, function(d) { return d.cases; })]);

    d3.selectAll(".line")
        .datum(datain)
        .transition().duration(duration)
        .attr("d", line);

    d3.selectAll(".line2")
        .datum(datain)
        .transition().duration(duration)
        .attr("d", line2);

    d3.selectAll(".yaxis")
        .transition().duration(duration)
        .call(yAxis);

    d3.selectAll(".xaxis")
        .transition().duration(duration)
        .call(xAxis);
}

function transitionTitles(filter){
    var title = filter;
    if(filter==="Total"){title = "West Africa";}
    $("#key_stats_title").html("Key Stats for " + title);
    $("#cul_tot_title").html("Cumulative Total for " + title);
}

function transitionMap(filter){
    if(filter==="Total"){
        var projection = d3.geo.mercator()
            .center([0,5])
            .scale(1800);
        var width = "0";
    }
    else {
        var width = "1";
    }
    if(filter==="Sierra Leone"){
        var projection = d3.geo.mercator()
            .center([-11,7.7])
            .scale(6000);
    }
    if(filter==="Guinea"){
        var projection = d3.geo.mercator()
            .center([-10,8.3])
            .scale(3200);
    }
    if(filter==="Liberia"){
        var projection = d3.geo.mercator()
            .center([-8,5])
            .scale(4000);
    }
    if(filter==="Nigeria"){
        var projection = d3.geo.mercator()
            .center([11,6])
            .scale(1800);
    }

    var path = d3.geo.path()
        .projection(projection);

    d3.selectAll('.country').transition().duration(duration)
            .attr('d', path).attr("stroke-width",width*2+1+"px");

    d3.selectAll('.region').transition().duration(duration)
            .attr('d', path).attr("stroke-width",width+"px");

    d3.selectAll('.maplabel').transition().duration(duration)
        .attr("x", function(d,i){
                     return path.centroid(d)[0]-20;})
        .attr("y", function(d,i){
                     return path.centroid(d)[1];});
}

function transition(filter){
    if(filter===currentFilter){filter="Total";}
    currentFilter=filter;
    transitionPieChart(filter);
    transitionLineChart("#line_total",casesAndDeaths[filter]);
    generateKeyStats("#key_stats",keyStats[filter]);
    transitionTitles(filter);
    transitionMap(filter);
    generateMedicalCentres("#medical_centres",medicalCentres,filter);
}

var currentFilter = "Total";
var color = {"Sierra Leone":"#5677fc","Liberia":"#e51c23","Guinea":"#ffeb3b","Nigeria":"#259b24"};
var duration = 1500;
var parseDate = d3.time.format("%d/%m/%Y").parse;
casesAndDeaths["Total"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Guinea"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Liberia"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Sierra Leone"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Nigeria"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});

generateCountryPieChart("#pie_country",casesAndDeaths);
generateLineChart("#line_total",casesAndDeaths["Total"]);
generateKeyStats("#key_stats",keyStats["Total"]);
generateMap();
generateMedicalCentres("#medical_centres",medicalCentres,"Total");<commit_msg>map country line width increased<commit_after>// function to load JSON file synchonously before d3 rendering

function loadJsonFileSynch(file){
    var ajaxresponse
    $.ajax({
        url: "data/"+file+".json",
        async: false,
        dataType: "json",
        success: function (response) {
            ajaxresponse= response;
        }
    });
    return ajaxresponse;
}

function generateCountryPieChart(id,datain){

    var data = [
        {"country":"Guinea","cases":datain["Guinea"][0].cases},
        {"country":"Liberia","cases":datain["Liberia"][0].cases},
        {"country":"Sierra Leone","cases":datain["Sierra Leone"][0].cases},
        {"country":"Nigeria","cases":datain["Nigeria"][0].cases}
    ];

    data.forEach(function(d) {
      d.cases = +d.cases;
    });

    var margin = {top: 0, right: 0, bottom: 0, left: 0},
        width = $(id).width() - margin.left - margin.right,
        height = $(id).height() - margin.top - margin.bottom,
        radius = Math.min(width, height) / 2;

    var arc = d3.svg.arc()
        .outerRadius(radius - 10)
        .innerRadius(0);

    var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) { return d.cases; });

    var svg = d3.select(id).append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var g = svg.selectAll(".arc")
        .data(pie(data))
        .enter().append("g")

    g.append("path")
        .attr("d", arc)
        .style("fill", function(d,i) { return color[d.data.country]; })
        .attr("id",function(d){
            return d.data.country.replace(/\s/g, '');
        })
        .on("click",function(d){
            transition(d.data.country);
        });

    g.append("text")
        .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
        .attr("dy", ".35em")
        .style("text-anchor", "middle")
        .text(function(d) {return d.data.country; });
}

function generateLineChart(id,datain){
    var margin = {top: 20, right: 20, bottom: 25, left: 50},
        width = $(id).width() - margin.left - margin.right,
        height = $(id).height() - margin.top - margin.bottom;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
            .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function(d) {
            return x(d.date);
        })
        .y(function(d) { return y(d.cases); });

    var line2 = d3.svg.line()
        .x(function(d) {
            return (x(d.date)); })
        .y(function(d) { return y(d.deaths); });

    var svg = d3.select(id).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    x.domain(d3.extent(datain, function(d) {
        return d.date; }));
    y.domain([0,d3.max(datain, function(d) { return d.cases; })]);

    svg.append("g")
        .attr("class", "xaxis axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "yaxis axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Cases");

    svg.append("path")
        .datum(datain)
        .attr("class", "line")
        .attr("d", line)
        .attr("fill","none")
        .attr("stroke","steelblue")
        .attr("stroke-width","1px");

    svg.append("path")
        .datum(datain)
        .attr("class", "line2")
        .attr("d", line2)
        .attr("fill","none")
        .attr("stroke","red")
        .attr("stroke-width","1px");
}

function generateKeyStats(id,datain){
    var html = "
Population: "+datain["population"] + "
";
    html = html + "
Cases: "+datain["cases"] + "
";
    html = html + "
Deaths: "+datain["deaths"] + "
";
    html = html + "
Crude Mortality Rate: "+datain["mortality rate"] + "
";
    $(id).html(html);
}

function generateMedicalCentres(id,datain,filter){
    var html ="";
    if(filter==="Total"){
        var country =[];
        var countryTotals = [];
        datain.forEach(function(e){
            if($.inArray(e.Country, country)>-1){
                countryTotals[e.Country] = countryTotals[e.Country]+1;
            } else {
                country.push(e.Country);
                countryTotals[e.Country] = 1;
            }
        });

        country.forEach(function(e){
           html = html + "
" + e +": " + countryTotals[e]+"
";
        });
    } else {
        datain.forEach(function(e){
            if(e.Country === filter){
                html = html + "
" + e.Name + ", " + e.Town + ", " + e.Region + "
";
            }
        });
    }
    $(id).html(html);
}

function transitionPieChart(filter){
    if(filter==="Total"){
        d3.select("#Liberia").transition().duration(duration).style("fill",color["Liberia"]);
        d3.select("#SierraLeone").transition().duration(duration).style("fill",color["Sierra Leone"]);
        d3.select("#Guinea").transition().duration(duration).style("fill",color["Guinea"]);
        d3.select("#Nigeria").transition().duration(duration).style("fill",color["Nigeria"]);
    } else {
        d3.select("#Liberia").transition().duration(duration).style("fill","#cccccc");
        d3.select("#SierraLeone").transition().duration(duration).style("fill","#cccccc");
        d3.select("#Guinea").transition().duration(duration).style("fill","#cccccc");
        d3.select("#Nigeria").transition().duration(duration).style("fill","#cccccc");
        d3.select("#"+filter.replace(/\s/g, '')).transition().duration(duration).style("fill",color[filter]);
    }
}

function generateMap(){
    var margin = {top: 10, right: 10, bottom: 10, left: 10},
    width = $('#map').width() - margin.left - margin.right,
    height = 325;

    var projection = d3.geo.mercator()
        .center([0,5])
        .scale(1800);

    var svg = d3.select('#map').append("svg")
        .attr("width", width)
        .attr("height", height);

    var path = d3.geo.path()
        .projection(projection);

    var g = svg.append("g");

    g.selectAll("path")
        .data(regions.features)
        .enter()
        .append("path")
        .attr("d", path)
        .attr("stroke",'#aaaaaa')
        .attr("stroke-width","0px")
        .attr("fill",'#ffffff')
        .attr("id",function(d){return d.properties.NAME_REF.replace(/\s/g, '');})
        .attr("class","region")
        .append("svg:title")
        .text(function(d) { return d.properties.NAME_REF; });

    regionsAffected.forEach(function(e) {
        d3.select("#"+e.Region.replace(/\s/g, '')).attr("fill","#ff8f00");
    });

    var g = svg.append("g");

    g.selectAll("path")
        .data(westafrica.features)
        .enter()
        .append("path")
        .attr("d", path)
        .attr("stroke",'#aaaaaa')
        .attr("fill",'none')
        .attr("class","country");

    var mapLabels = svg.append("g");

    mapLabels.selectAll('text')
      .data(westafrica.features)
         .enter()
         .append("text")
         .attr("x", function(d,i){
                     return path.centroid(d)[0]-20;})
         .attr("y", function(d,i){
                     return path.centroid(d)[1];})
         .attr("dy", ".55em")
         .attr("class","maplabel")
         .style("font-size","12px")
         .attr("opacity",0.4)
         .text(function(d,i){
                      return d.properties.NAME;
                  });
}

function transitionLineChart(id,datain){

    var margin = {top: 20, right: 20, bottom: 25, left: 50},
        width = $(id).width() - margin.left - margin.right,
        height = $(id).height() - margin.top - margin.bottom;

    var parseDate = d3.time.format("%d/%m/%Y").parse;

    var x = d3.time.scale()
        .range([0, width]);

    var y = d3.scale.linear()
            .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.cases); });

    var line2 = d3.svg.line()
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.deaths); });

    x.domain(d3.extent(datain, function(d) { return d.date; }));
    y.domain([0,d3.max(datain, function(d) { return d.cases; })]);

    d3.selectAll(".line")
        .datum(datain)
        .transition().duration(duration)
        .attr("d", line);

    d3.selectAll(".line2")
        .datum(datain)
        .transition().duration(duration)
        .attr("d", line2);

    d3.selectAll(".yaxis")
        .transition().duration(duration)
        .call(yAxis);

    d3.selectAll(".xaxis")
        .transition().duration(duration)
        .call(xAxis);
}

function transitionTitles(filter){
    var title = filter;
    if(filter==="Total"){title = "West Africa";}
    $("#key_stats_title").html("Key Stats for " + title);
    $("#cul_tot_title").html("Cumulative Total for " + title);
}

function transitionMap(filter){
    if(filter==="Total"){
        var projection = d3.geo.mercator()
            .center([0,5])
            .scale(1800);
        var width = "0";
    }
    else {
        var width = "1";
    }
    if(filter==="Sierra Leone"){
        var projection = d3.geo.mercator()
            .center([-11,7.7])
            .scale(6000);
    }
    if(filter==="Guinea"){
        var projection = d3.geo.mercator()
            .center([-10,8.3])
            .scale(3200);
    }
    if(filter==="Liberia"){
        var projection = d3.geo.mercator()
            .center([-8,5])
            .scale(4000);
    }
    if(filter==="Nigeria"){
        var projection = d3.geo.mercator()
            .center([11,6])
            .scale(1800);
    }

    var path = d3.geo.path()
        .projection(projection);

    d3.selectAll('.country').transition().duration(duration)
            .attr('d', path).attr("stroke-width",width*3+1+"px");

    d3.selectAll('.region').transition().duration(duration)
            .attr('d', path).attr("stroke-width",width+"px");

    d3.selectAll('.maplabel').transition().duration(duration)
        .attr("x", function(d,i){
                     return path.centroid(d)[0]-20;})
        .attr("y", function(d,i){
                     return path.centroid(d)[1];});
}

function transition(filter){
    if(filter===currentFilter){filter="Total";}
    currentFilter=filter;
    transitionPieChart(filter);
    transitionLineChart("#line_total",casesAndDeaths[filter]);
    generateKeyStats("#key_stats",keyStats[filter]);
    transitionTitles(filter);
    transitionMap(filter);
    generateMedicalCentres("#medical_centres",medicalCentres,filter);
}

var currentFilter = "Total";
var color = {"Sierra Leone":"#5677fc","Liberia":"#e51c23","Guinea":"#ffeb3b","Nigeria":"#259b24"};
var duration = 1500;
var parseDate = d3.time.format("%d/%m/%Y").parse;
casesAndDeaths["Total"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Guinea"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Liberia"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Sierra Leone"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});
casesAndDeaths["Nigeria"].forEach(function(d){
    d.date = parseDate(d.date);
    d.cases = +d.cases;
    d.deaths = +d.deaths;
});

generateCountryPieChart("#pie_country",casesAndDeaths);
generateLineChart("#line_total",casesAndDeaths["Total"]);
generateKeyStats("#key_stats",keyStats["Total"]);
generateMap();
generateMedicalCentres("#medical_centres",medicalCentres,"Total");<|endoftext|>


<commit_before>/**
 * Add the capability to load CMD modules in node environment
 * @author lifesinger@gmail.com
 */

var fs = require("fs")
var path = require("path")
var vm = require("vm")
var normalize = require("./winos").normalize

var moduleStack = []
var uriCache = {}
var nativeLoad

runSeaJS("../dist/sea-debug.js")
hackNative()
attach()
keep()
seajs.config({ cwd: normalize(process.cwd()) + "/" })

function runSeaJS(filepath) {
  var code = fs.readFileSync(path.join(__dirname, filepath), "utf8")
  code = code.replace("})(this);", "})(exports);")

  // Run "sea.js" code in a fake browser environment
  var sandbox = require("./sandbox")
  vm.runInNewContext(code, sandbox, "sea-debug.vm")

  global.seajs = sandbox.exports.seajs
  global.define = sandbox.exports.define
}

function hackNative() {
  var Module = module.constructor
  nativeLoad = Module._load

  Module._load = function(request, parent, isMain) {
    var exports = nativeLoad(request, parent, isMain)

    var _filename = Module._resolveFilename(request, parent)
    var filename = normalize(_filename)

    var mod = seajs.cache[filename]
    if (mod) {
      if (mod.status < 4) { // < STATUS_EXECUTING
        seajs.Module.load([filename], function() {})
      }
      exports = Module._cache[_filename] = mod.exports
    }

    return exports
  }

  var _compile = Module.prototype._compile

  Module.prototype._compile = function(content, filename) {
    moduleStack.push(this)
    try {
      return _compile.call(this, content, filename)
    }
    finally {
      moduleStack.pop()
    }
  }
}

function attach() {
  seajs.on("request", requestListener)
  seajs.on("define", defineListener)
}

function requestListener(data) {
  var requestUri = pure(data.requestUri)
  var ext = path.extname(requestUri)
  //process.stdout.write("requestUri = " + requestUri + "\n")

  if (ext === ".js") {
    // Use native `require` instead of script-inserted version
    nativeLoad(requestUri)
    data.callback()
    data.requested = true
  }
  // Throw error if this function is the last request handler
  else if (seajs.events["request"].length === 1) {
    throw new Error("Do NOT support to load this file in node environment: "
        + requestUri)
  }
}

function defineListener(data) {
  if (!data.uri) {
    var derivedUri = normalize(moduleStack[moduleStack.length - 1].id)
    data.uri = uriCache[derivedUri] || derivedUri
  }
}

function keep() {
  var _off = seajs.off

  seajs.off = function() {
    _off()
    attach()
    return seajs
  }
}

function pure(uri) {
  // Remove timestamp etc
  var ret = uri.replace(/\?.*$/, "")

  // Cache it
  if (ret !== uri) {
    uriCache[ret] = uri
  }
  return ret
}

<commit_msg>Update code for data changing<commit_after>/**
 * Add the capability to load CMD modules in node environment
 * @author lifesinger@gmail.com
 */

var fs = require("fs")
var path = require("path")
var vm = require("vm")
var normalize = require("./winos").normalize

var moduleStack = []
var uriCache = {}
var nativeLoad

runSeaJS("../dist/sea-debug.js")
hackNative()
attach()
keep()
seajs.config({ cwd: normalize(process.cwd()) + "/" })

function runSeaJS(filepath) {
  var code = fs.readFileSync(path.join(__dirname, filepath), "utf8")
  code = code.replace("})(this);", "})(exports);")

  // Run "sea.js" code in a fake browser environment
  var sandbox = require("./sandbox")
  vm.runInNewContext(code, sandbox, "sea-debug.vm")

  global.seajs = sandbox.exports.seajs
  global.define = sandbox.exports.define
}

function hackNative() {
  var Module = module.constructor
  nativeLoad = Module._load

  Module._load = function(request, parent, isMain) {
    var exports = nativeLoad(request, parent, isMain)

    var _filename = Module._resolveFilename(request, parent)
    var filename = normalize(_filename)

    var mod = seajs.cache[filename]
    if (mod) {
      if (mod.status < 4) { // < STATUS_EXECUTING
        seajs.Module.load([filename], function() {})
      }
      exports = Module._cache[_filename] = mod.exports
    }

    return exports
  }

  var _compile = Module.prototype._compile

  Module.prototype._compile = function(content, filename) {
    moduleStack.push(this)
    try {
      return _compile.call(this, content, filename)
    }
    finally {
      moduleStack.pop()
    }
  }
}

function attach() {
  seajs.on("request", requestListener)
  seajs.on("define", defineListener)
}

function requestListener(data) {
  var requestUri = pure(data.requestUri)
  var ext = path.extname(requestUri)
  //process.stdout.write("requestUri = " + requestUri + "\n")

  if (ext === ".js") {
    // Use native `require` instead of script-inserted version
    nativeLoad(requestUri)
    data.callback()
    data.requested = true
  }
  // Throw error if this function is the last request handler
  else if (seajs.data.events["request"].length === 1) {
    throw new Error("Do NOT support to load this file in node environment: "
        + requestUri)
  }
}

function defineListener(data) {
  if (!data.uri) {
    var derivedUri = normalize(moduleStack[moduleStack.length - 1].id)
    data.uri = uriCache[derivedUri] || derivedUri
  }
}

function keep() {
  var _off = seajs.off

  seajs.off = function() {
    _off()
    attach()
    return seajs
  }
}

function pure(uri) {
  // Remove timestamp etc
  var ret = uri.replace(/\?.*$/, "")

  // Cache it
  if (ret !== uri) {
    uriCache[ret] = uri
  }
  return ret
}

<|endoftext|>


<commit_before>function randint(start, end) {
	return Math.floor(Math.random() * (end - start + 1) + start);
}

function toHSL(color) {
	return d3.hsl(color[0], color[1] / 100, color[2] / 100);
}

function combineColors(colors) {
	if (colors.length === 0)
		return [0, 0, 0];
	var total = [0, 0, 0];
	for (var i = 0; color = colors[i]; ++i) {
		var hsl = toHSL(color);
		var lab = d3.lab(hsl);
		total[0] += lab.l;
		total[1] += lab.a;
		total[2] += lab.b;
	}
	for (var j = 0; j < total.length; ++j)
		total[j] /= colors.length;
	var result = d3.lab(total[0], total[1], total[2]);
	var hsl = d3.hsl(result);
	return [hsl.h, hsl.s * 100, hsl.l * 100];
	/*if (colors.length === 0)
		return [0, 0, 0];
	var color = [colors[0][0], colors[0][1], colors[0][2]];
	for (var i = 1; i < colors.length; ++i) {
		var newColor = [colors[i][0], colors[i][1], colors[i][2]];
		if ((Math.max(newColor[0], color[0]) - Math.min(newColor[0], color[0])) > 180)
			newColor[0] += 360;
		var lumin1 = color[1] / 100, lumin2 = newColor[1] / 100, total = lumin1 + lumin2;
		if (total == 0)
			total = 1;
		color[0] = (color[0] * (lumin1 / total) + newColor[0] * (lumin2 / total)) % 360;
		color[1] = (color[1] + newColor[1]) / 2;
		color[2] = (color[2] + newColor[2]) / 2;
	}
	return color;*/

}

function Rect(x, y, w, h) {
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
}

Rect.prototype.center = function(x, y) {
	var hw = this.w / 2;
	var hh = this.h / 2;
	this.x = (x - hw);
	this.y = (y - hh);
}

Rect.prototype.colliderect = function(r) {
	if (this.x > (r.x + r.w))
		return false;
	else if (r.x > (this.x + this.w))
		return false;
	else if (this.y > (r.y + r.h))
		return false;
	else if (r.y > (this.y + this.h))
		return false;
	return true;
}

Rect.prototype.contains = function(r) {
	return this.x < r.x && (this.x + this.w) > (r.x + r.w) && this.y < r.y && (this.y + this.h) > (r.y + r.h);
}

Rect.prototype.move = function(x, y) {
	this.x += x;
	this.y += y;
}

Rect.prototype.clamp = function(r) {
	if (this.x < r.x)
		this.x = r.x;
	else if ((this.x + this.w) > (r.x + r.w))
		this.x = r.x + r.w - this.w;
	else if (this.y < r.y)
		this.y = r.y;
	else if ((this.y + this.h) > (r.y + r.h))
		this.y = r.y + r.h - this.h;
}

function Sprite() {
}

Sprite.prototype.formatColor = function() {
	return 'hsl(' + this.color[0] + ',' + this.color[1] + '%,' + this.color[2] + '%)';
}

Sprite.prototype.draw = function() {
	var r = this.rect;
	main.rect(r.x, r.y, r.w, r.h, this.formatColor());
}

function Wall(x, y, w, h, color) {
	this.rect = new Rect(x, y, w, h);
	this.color = this.generateColor();
}
Wall.prototype = Object.create(Sprite.prototype);
Wall.prototype.constructor = Sprite;

Wall.prototype.generateColor = function() {
	var colors = [];
	var n = randint(2, 3);
	for (var i = 0; i < n; ++i) {
		var color = main.colors[randint(0, main.colors.length - 1)];
		colors.push(color);
	}
	return combineColors(colors);
}

Wall.prototype.colorClose = function(color) {
	var thisLab = toHSL(this.color);
	var otherLab = toHSL(this.color);
	var distance = Math.pow(thisLab.l - otherLab.l, 2) + Math.pow(thisLab.a - otherLab.a, 2) + Math.pow(thisLab.b - otherLab.b, 2);
	return distance < Math.pow(10, 2);
}

Wall.prototype.update = function(p) {
	if (p.rect.colliderect(this.rect)) {
		if (this.colorClose(p.color)) {
			return true;
		}
	}
	return false;
}

function Ball(move, color, x, y) {
	this.rect = new Rect(0, 0, 10, 10);
	this.rect.center(x, y);
	this.color = color;
	this.x = move[0];
	this.y = move[1]
	this.trapped = false
	this.angle = Math.atan2(this.y, this.x);
}
Ball.prototype = Object.create(Sprite.prototype);
Ball.prototype.constructor = Sprite;

Ball.prototype.reassign = function() {
    var b = [[255, 255, 0], [200, main.state.width - 30]];
    var r0 = Math.random();
    var r1 = Math.floor(Math.random() * main.state.width);
    if (r0 < 0.25)
        b = [[0, 255, 0], [30, r1]];
    else if (r0 < 0.5)
        b = [[0, 255, 255], [r1, 30]];
    else if (r0 < 0.75)
        b = [[255, 0, 0], [main.state.width - 30, r1]];
    else
		b = [[255, 255, 0], [r1, main.state.width - 30]];
	this.rect.center(b[1][0], b[1][1]);
    this.angle = Math.atan2(this.y, this.x);
}

Ball.prototype.update = function(paddle, walls) {
	var that = this;
	var screen = new Rect(0, 0, main.state.width, main.state.height);
	if (!screen.contains(this.rect))
		this.reassign();
	paddle.rects.forEach(function(r) {
		if (that.rect.colliderect(r[0]) && !paddle.down && !paddle.rect.contains(that.rect)) {
			if (r[1][0])
				that.x = r[1][0] * Math.abs(that.x);
			if (r[1][1])
				that.y = r[1][1] * Math.abs(that.y);
		}
	});

	if (paddle.rect.colliderect(this.rect)) {
		if (paddle.down) {
			if (!this.trapped) {
				++main.metrics.ballsCaught;
			}
			this.trapped = true;
		} else {
			this.trapped = false;
			this.x += main.mouse.relX / 5;
			this.y += main.mouse.relY / 5;
		}
	}

	if ((this.x > 5) || (this.x < -5))
		this.x -= Math.sign(this.x) * 3;
	if ((this.y > 5) || (this.y < -5))
		this.y -= Math.sign(this.y) * 3;
	this.rect.move(this.x, this.y);
	if (this.trapped)
		this.rect.center(main.mouse.x, main.mouse.y);
}

function Paddle() {
	this.rect = new Rect(0, 0, 40, 40);
	this.rect.center(200, 200);
	this.color = [0, 0, 0];
	this.down = false;
	this.screen = new Rect(0, 0, main.state.width, main.state.height);
}
Paddle.prototype = Object.create(Sprite.prototype);
Paddle.prototype.constructor = Sprite;

Paddle.prototype.update = function(balls) {
	if (this.down !== main.mouse.down) {
		console.log('Mouse is now ' + (main.mouse.down ? 'down': 'up'));
		if (main.mouse.down)
			++main.metrics.timesDown;
		else
			++main.metrics.timesUp;
	}
	this.down = main.mouse.down;
	main.mouse.x = Math.min(Math.max(main.mouse.x, this.rect.w / 2), main.state.width - this.rect.w / 2);
	main.mouse.y = Math.min(Math.max(main.mouse.y, this.rect.h / 2), main.state.height - this.rect.h / 2);
	this.rect.center(main.mouse.x, main.mouse.y);
	//this.rect.clamp(screen);
	this.leftside = [new Rect(this.rect.x, this.rect.y + 5, 5, 30), [-1, 0]];
	this.rightside = [new Rect(this.rect.x + this.rect.w - 5, this.rect.y + 5, 5, 30), [1, 0]];
	this.topside = [new Rect(this.rect.x + 5, this.rect.y, 30, 5), [0, -1]];
	this.bottomside = [new Rect(this.rect.x + 5, this.rect.y + this.rect.h - 5, 30, 5), [0, 1]];
	this.rects = [this.leftside, this.rightside, this.topside, this.bottomside];

	var colors = [],  n = 0;
	for (var i = 0, b; b = balls[i]; ++i) {
		if (!b.trapped)
			continue;
		colors.push(b.color);
	}

	this.color = combineColors(colors);
}

function Game() {
	main.metrics.start = (new Date).getTime();
    var lw = new Wall(0, 0, 10, main.state.height);
    var tw = new Wall(0, 0, main.state.width, 10);
    var rw = new Wall(main.state.width - 10, 0, 10, main.state.height);
    var bw = new Wall(0, main.state.height - 10, main.state.width, 10);
    this.walls = [lw, tw, rw, bw];

    this.balls = [];
    this.p = new Paddle();

	var color = 0;
    for (var x = -1; x < 3; ++x) {
		for (var y = -1; y < 3; ++y) {
			var y2 = y;
            if (y2 === 0)
				y2 = randint(1, 5);
            var c = main.colors[color++];
			if (color >= main.colors.length)
				color = 0;
            var b = new Ball([randint(-3, 3), y2], c, 200, 200);
            this.balls.push(b);
		}
	}
}

Game.prototype.update = function() {
	// pos = list(pygame.mouse.get_pos())
	// pos[0] += joy_offset[0]
	// pos[1] += joy_offset[1]
	// pygame.mouse.set_pos(pos)

	main.mouse.x += main.state.joyX;
    main.mouse.y += main.state.joyY;

	main.clear();
	this.walls.forEach(function(w) {
		w.draw();
	});

	this.balls.forEach(function(b) {
		b.draw();
	});

	this.p.draw(this.b);
	this.p.update(this.balls);
	var that = this;

	this.walls.forEach(function(w) {
		var result = w.update(that.p);
		if (result) {
			that.walls = _.filter(that.walls, function(v){return v !== w;});
		}
	});

	if (this.walls.length === 0) {
		main.metrics.end = (new Date).getTime();
		main.recordMetrics();
		window.location.replace('win.html')
	}

	this.balls.forEach(function(b) {
		b.update(that.p, that.walls);
	});

}

<commit_msg>updating JND<commit_after>function randint(start, end) {
	return Math.floor(Math.random() * (end - start + 1) + start);
}

function toHSL(color) {
	return d3.hsl(color[0], color[1] / 100, color[2] / 100);
}

function combineColors(colors) {
	if (colors.length === 0)
		return [0, 0, 0];
	var total = [0, 0, 0];
	for (var i = 0; color = colors[i]; ++i) {
		var hsl = toHSL(color);
		var lab = d3.lab(hsl);
		total[0] += lab.l;
		total[1] += lab.a;
		total[2] += lab.b;
	}
	for (var j = 0; j < total.length; ++j)
		total[j] /= colors.length;
	var result = d3.lab(total[0], total[1], total[2]);
	var hsl = d3.hsl(result);
	return [hsl.h, hsl.s * 100, hsl.l * 100];
	/*if (colors.length === 0)
		return [0, 0, 0];
	var color = [colors[0][0], colors[0][1], colors[0][2]];
	for (var i = 1; i < colors.length; ++i) {
		var newColor = [colors[i][0], colors[i][1], colors[i][2]];
		if ((Math.max(newColor[0], color[0]) - Math.min(newColor[0], color[0])) > 180)
			newColor[0] += 360;
		var lumin1 = color[1] / 100, lumin2 = newColor[1] / 100, total = lumin1 + lumin2;
		if (total == 0)
			total = 1;
		color[0] = (color[0] * (lumin1 / total) + newColor[0] * (lumin2 / total)) % 360;
		color[1] = (color[1] + newColor[1]) / 2;
		color[2] = (color[2] + newColor[2]) / 2;
	}
	return color;*/

}

function Rect(x, y, w, h) {
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
}

Rect.prototype.center = function(x, y) {
	var hw = this.w / 2;
	var hh = this.h / 2;
	this.x = (x - hw);
	this.y = (y - hh);
}

Rect.prototype.colliderect = function(r) {
	if (this.x > (r.x + r.w))
		return false;
	else if (r.x > (this.x + this.w))
		return false;
	else if (this.y > (r.y + r.h))
		return false;
	else if (r.y > (this.y + this.h))
		return false;
	return true;
}

Rect.prototype.contains = function(r) {
	return this.x < r.x && (this.x + this.w) > (r.x + r.w) && this.y < r.y && (this.y + this.h) > (r.y + r.h);
}

Rect.prototype.move = function(x, y) {
	this.x += x;
	this.y += y;
}

Rect.prototype.clamp = function(r) {
	if (this.x < r.x)
		this.x = r.x;
	else if ((this.x + this.w) > (r.x + r.w))
		this.x = r.x + r.w - this.w;
	else if (this.y < r.y)
		this.y = r.y;
	else if ((this.y + this.h) > (r.y + r.h))
		this.y = r.y + r.h - this.h;
}

function Sprite() {
}

Sprite.prototype.formatColor = function() {
	return 'hsl(' + this.color[0] + ',' + this.color[1] + '%,' + this.color[2] + '%)';
}

Sprite.prototype.draw = function() {
	var r = this.rect;
	main.rect(r.x, r.y, r.w, r.h, this.formatColor());
}

function Wall(x, y, w, h, color) {
	this.rect = new Rect(x, y, w, h);
	this.color = this.generateColor();
}
Wall.prototype = Object.create(Sprite.prototype);
Wall.prototype.constructor = Sprite;

Wall.prototype.generateColor = function() {
	var colors = [];
	var n = randint(2, 3);
	for (var i = 0; i < n; ++i) {
		var color = main.colors[randint(0, main.colors.length - 1)];
		colors.push(color);
	}
	return combineColors(colors);
}

Wall.prototype.colorClose = function(color) {
	var thisLab = toHSL(this.color);
	var otherLab = toHSL(this.color);
	var distance = Math.pow(thisLab.l - otherLab.l, 2) + Math.pow(thisLab.a - otherLab.a, 2) + Math.pow(thisLab.b - otherLab.b, 2);
	return distance < Math.pow(2, 2);
}

Wall.prototype.update = function(p) {
	if (p.rect.colliderect(this.rect)) {
		if (this.colorClose(p.color)) {
			return true;
		}
	}
	return false;
}

function Ball(move, color, x, y) {
	this.rect = new Rect(0, 0, 10, 10);
	this.rect.center(x, y);
	this.color = color;
	this.x = move[0];
	this.y = move[1]
	this.trapped = false
	this.angle = Math.atan2(this.y, this.x);
}
Ball.prototype = Object.create(Sprite.prototype);
Ball.prototype.constructor = Sprite;

Ball.prototype.reassign = function() {
    var b = [[255, 255, 0], [200, main.state.width - 30]];
    var r0 = Math.random();
    var r1 = Math.floor(Math.random() * main.state.width);
    if (r0 < 0.25)
        b = [[0, 255, 0], [30, r1]];
    else if (r0 < 0.5)
        b = [[0, 255, 255], [r1, 30]];
    else if (r0 < 0.75)
        b = [[255, 0, 0], [main.state.width - 30, r1]];
    else
		b = [[255, 255, 0], [r1, main.state.width - 30]];
	this.rect.center(b[1][0], b[1][1]);
    this.angle = Math.atan2(this.y, this.x);
}

Ball.prototype.update = function(paddle, walls) {
	var that = this;
	var screen = new Rect(0, 0, main.state.width, main.state.height);
	if (!screen.contains(this.rect))
		this.reassign();
	paddle.rects.forEach(function(r) {
		if (that.rect.colliderect(r[0]) && !paddle.down && !paddle.rect.contains(that.rect)) {
			if (r[1][0])
				that.x = r[1][0] * Math.abs(that.x);
			if (r[1][1])
				that.y = r[1][1] * Math.abs(that.y);
		}
	});

	if (paddle.rect.colliderect(this.rect)) {
		if (paddle.down) {
			if (!this.trapped) {
				++main.metrics.ballsCaught;
			}
			this.trapped = true;
		} else {
			this.trapped = false;
			this.x += main.mouse.relX / 5;
			this.y += main.mouse.relY / 5;
		}
	}

	if ((this.x > 5) || (this.x < -5))
		this.x -= Math.sign(this.x) * 3;
	if ((this.y > 5) || (this.y < -5))
		this.y -= Math.sign(this.y) * 3;
	this.rect.move(this.x, this.y);
	if (this.trapped)
		this.rect.center(main.mouse.x, main.mouse.y);
}

function Paddle() {
	this.rect = new Rect(0, 0, 40, 40);
	this.rect.center(200, 200);
	this.color = [0, 0, 0];
	this.down = false;
	this.screen = new Rect(0, 0, main.state.width, main.state.height);
}
Paddle.prototype = Object.create(Sprite.prototype);
Paddle.prototype.constructor = Sprite;

Paddle.prototype.update = function(balls) {
	if (this.down !== main.mouse.down) {
		console.log('Mouse is now ' + (main.mouse.down ? 'down': 'up'));
		if (main.mouse.down)
			++main.metrics.timesDown;
		else
			++main.metrics.timesUp;
	}
	this.down = main.mouse.down;
	main.mouse.x = Math.min(Math.max(main.mouse.x, this.rect.w / 2), main.state.width - this.rect.w / 2);
	main.mouse.y = Math.min(Math.max(main.mouse.y, this.rect.h / 2), main.state.height - this.rect.h / 2);
	this.rect.center(main.mouse.x, main.mouse.y);
	//this.rect.clamp(screen);
	this.leftside = [new Rect(this.rect.x, this.rect.y + 5, 5, 30), [-1, 0]];
	this.rightside = [new Rect(this.rect.x + this.rect.w - 5, this.rect.y + 5, 5, 30), [1, 0]];
	this.topside = [new Rect(this.rect.x + 5, this.rect.y, 30, 5), [0, -1]];
	this.bottomside = [new Rect(this.rect.x + 5, this.rect.y + this.rect.h - 5, 30, 5), [0, 1]];
	this.rects = [this.leftside, this.rightside, this.topside, this.bottomside];

	var colors = [],  n = 0;
	for (var i = 0, b; b = balls[i]; ++i) {
		if (!b.trapped)
			continue;
		colors.push(b.color);
	}

	this.color = combineColors(colors);
}

function Game() {
	main.metrics.start = (new Date).getTime();
    var lw = new Wall(0, 0, 10, main.state.height);
    var tw = new Wall(0, 0, main.state.width, 10);
    var rw = new Wall(main.state.width - 10, 0, 10, main.state.height);
    var bw = new Wall(0, main.state.height - 10, main.state.width, 10);
    this.walls = [lw, tw, rw, bw];

    this.balls = [];
    this.p = new Paddle();

	var color = 0;
    for (var x = -1; x < 3; ++x) {
		for (var y = -1; y < 3; ++y) {
			var y2 = y;
            if (y2 === 0)
				y2 = randint(1, 5);
            var c = main.colors[color++];
			if (color >= main.colors.length)
				color = 0;
            var b = new Ball([randint(-3, 3), y2], c, 200, 200);
            this.balls.push(b);
		}
	}
}

Game.prototype.update = function() {
	// pos = list(pygame.mouse.get_pos())
	// pos[0] += joy_offset[0]
	// pos[1] += joy_offset[1]
	// pygame.mouse.set_pos(pos)

	main.mouse.x += main.state.joyX;
    main.mouse.y += main.state.joyY;

	main.clear();
	this.walls.forEach(function(w) {
		w.draw();
	});

	this.balls.forEach(function(b) {
		b.draw();
	});

	this.p.draw(this.b);
	this.p.update(this.balls);
	var that = this;

	this.walls.forEach(function(w) {
		var result = w.update(that.p);
		if (result) {
			that.walls = _.filter(that.walls, function(v){return v !== w;});
		}
	});

	if (this.walls.length === 0) {
		main.metrics.end = (new Date).getTime();
		main.recordMetrics();
		window.location.replace('win.html')
	}

	this.balls.forEach(function(b) {
		b.update(that.p, that.walls);
	});

}

<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var debug = require('debug')('wpcom:tag');

/**
 * Tag methods
 *
 * @param {String} [slug]
 * @param {String} sid site id
 * @param {WPCOM} wpcom
 * @api public
 */

function Tag(slug, sid, wpcom) {
  if (!sid) {
    throw new Error('`side id` is not correctly defined');
  }

  if (!(this instanceof Tag)) {
    return new Tag(slug, sid, wpcom);
  }

  this.wpcom = wpcom;
  this._sid = sid;
  this._slug = slug;
}

/**
 * Set tag `slug`
 *
 * @param {String} slug
 * @api public
 */

Tag.prototype.slug = function (slug) {
  this._slug = slug;
};

/**
 * Get tag
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Tag.prototype.get = function (query, fn) {
  var path = '/sites/' + this._sid + '/tags/slug:' + this._slug;
  return this.wpcom.sendRequest(path, query, null, fn);
};

/**
 * Add tag
 *
 * @param {Object} body
 * @param {Function} fn
 * @api public
 */

Tag.prototype.add = function (body, fn) {
  var path = '/sites/' + this._sid + '/tags/new';
  return this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn);
};

/**
 * Edit tag
 *
 * @param {Object} body
 * @param {Function} fn
 * @api public
 */

Tag.prototype.update = function (body, fn) {
  var path = '/sites/' + this._sid + '/tags/slug:' + this._slug;
  return this.wpcom.sendRequest({ path: path, method: 'post' }, null, body, fn);
};

/**
 * Delete tag
 *
 * @param {Function} fn
 * @api public
 */

Tag.prototype['delete'] = Tag.prototype.del = function (fn) {
  var path = '/sites/' + this._sid + '/tags/slug:' + this._slug + '/delete';
  return this.wpcom.sendRequest({ path: path, method: 'post' }, null, null, fn);
};

/**
 * Expose `Tag` module
 */

module.exports = Tag;<commit_msg>tag: use `require` module<commit_after>
/**
 * Module dependencies.
 */

var request = require('./util/request');
var debug = require('debug')('wpcom:tag');

/**
 * Tag methods
 *
 * @param {String} [slug]
 * @param {String} sid site id
 * @param {WPCOM} wpcom
 * @api public
 */

function Tag(slug, sid, wpcom) {
  if (!sid) {
    throw new Error('`side id` is not correctly defined');
  }

  if (!(this instanceof Tag)) {
    return new Tag(slug, sid, wpcom);
  }

  this.wpcom = wpcom;
  this._sid = sid;
  this._slug = slug;
}

/**
 * Set tag `slug`
 *
 * @param {String} slug
 * @api public
 */

Tag.prototype.slug = function (slug) {
  this._slug = slug;
};

/**
 * Get tag
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Tag.prototype.get = function (query, fn) {
  var path = '/sites/' + this._sid + '/tags/slug:' + this._slug;
  return request.get(this.wpcom, null, path, query, fn);
};

/**
 * Add tag
 *
 * @param {Object} [query]
 * @param {Object} body
 * @param {Function} fn
 * @api public
 */

Tag.prototype.add = function (query, body, fn) {
  var path = '/sites/' + this._sid + '/tags/new';
  return request.post(this.wpcom, null, path, query, body, fn);
};

/**
 * Edit tag
 *
 * @param {Object} [query]
 * @param {Object} body
 * @param {Function} fn
 * @api public
 */

Tag.prototype.update = function (query, body, fn) {
  var path = '/sites/' + this._sid + '/tags/slug:' + this._slug;
  return request.put(this.wpcom, null, path, query, body, fn);
};

/**
 * Delete tag
 *
 * @param {Object} [query]
 * @param {Function} fn
 * @api public
 */

Tag.prototype['delete'] = Tag.prototype.del = function (query, fn) {
  var path = '/sites/' + this._sid + '/tags/slug:' + this._slug + '/delete';
  return request.del(this.wpcom, null, path, query, fn);
};

/**
 * Expose `Tag` module
 */

module.exports = Tag;<|endoftext|>


<commit_before>/* Copyright 2012 The Go Authors.  All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function() {
"use strict";

var slides, editor, $editor, $output;
var slide = null;
var slidenum = 0;

// manage translations
function L(k) {
	if (tr[k]) {
		return tr[k];
	} else {
		console.log("translation missing for: "+k);
		return "(no translation for "+k+")";
	}
}

function init() {
	var $tocdiv = $('
').insertBefore('#slides').hide();
	$tocdiv.append($('
'+L('toc')+'
'));
	var $toc = $('
').appendTo($tocdiv);
	$("#tocbtn").click(toggleToc);

	slides = $("div.slide");
	slides.each(function(i, slide) {
		var $s = $(slide).hide();

		var $h2 = $s.find("h2").first();
		var $nav;
		if ($h2.length > 0) {
			$("
").addClass("clear").insertAfter($h2);
			$nav = $("
").addClass("nav");
			if (i > 0) {
				$nav.append($("◀").click(function() {
					show(i-1);
					return false;
				}).attr("href", "#"+(i)).attr("title", L('prev')));
			} else {
				$nav.append($("◀"));
			}
			if (i+1 < slides.length) {
				$nav.append($("▶").click(function() {
					show(i+1);
					return false;
				}).attr("href", "#"+(i+2)).attr("title", L('next')));
			} else {
				$nav.append($("▶"));
			}
			$nav.insertBefore($h2);

			var thisI = i;
			var $entry = $("").text($h2.text()).click(function() {
				show(thisI);
			}).attr('href', '#'+(i+1));
			$toc.append($entry);
			$entry.wrap('
');

		}
	});

	// set up playground editor
	editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
		theme: "plain",
		matchBrackets: true,
		indentUnit: 4,
		tabSize: 4,
		indentWithTabs: false,
		mode: "text/x-go",
		lineNumbers: true,
		extraKeys: {
			"Shift-Enter": function() {
				run();
			}
		}
	});
	$editor = $(editor.getWrapperElement()).attr('id', 'code');
	$output = $('#output');

	$('#more').click(function() {
		$('.controls').toggleClass('expanded');
		return false;
	});
	$('html').click(function() {
		$('.controls').removeClass('expanded');
	});

	$('#run').click(function() {
		run();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#reset').click(function() {
		reset();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#kill').click(function() {
		kill();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#format').click(function() {
		format();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglesyntax').click(function() {
		if (editor.getOption('theme') === 'default') {
			editor.setOption('theme', 'plain');
			$('#togglesyntax').text(L('syntax')+': '+L('off'));
		} else {
			editor.setOption('theme', 'default');
			$('#togglesyntax').text(L('syntax')+': '+L('on'));
		}
		setcookie('theme', editor.getOption('theme'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglelineno').click(function() {
		if (editor.getOption('lineNumbers')) {
			editor.setOption('lineNumbers', false);
			$('#togglelineno').text(L('lineno')+': '+L('off'));
		} else {
			editor.setOption('lineNumbers', true);
			$('#togglelineno').text(L('lineno')+': '+L('on'));
		}
		setcookie('lineno', editor.getOption('lineNumbers'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	if (getcookie('lineno') != ""+editor.getOption('lineNumbers')) {
		$('#togglelineno').trigger('click');
	} else {
		$('#togglelineno').text(L('lineno')+': '+L('on'));
	}

	if (getcookie('theme') != ""+editor.getOption('theme')) {
		$('#togglesyntax').trigger('click');
	} else {
		$('#togglesyntax').text(L('syntax')+': '+L('on'));
	}

	// set these according to lang.js
	$('#run').text(L('run'));
	$('#reset').text(L('reset'));
	$('#format').text(L('format'));
	$('#kill').text(L('kill'));
	$('#tocbtn').attr('title', L('toc'));
}

function toggleToc() {
	if ($('#toc').is(':visible')) {
		show(slidenum);
	} else {
		$('#slides, #workspace, #slidenum').hide();
		$('#toc').show();
	}
	return false;
}

function show(i) {
	if(i < 0 || i >= slides.length) {
		return;
	}

	// if a slide is already onscreen, hide it and store its code
	if(slide !== null) {
		var $oldSlide = $(slide).hide();
		if (!$oldSlide.hasClass("nocode")) {
			save(slidenum);
		}
	}

	$('#toc').hide();
	$('#slidenum, #slides').show();

	// switch to new slide
	slidenum = i;
	$("#slidenum").text(i+1);
	slide = slides[i];
	var $s = $(slide).show();

	// load stored code, or hide code box
	if ($s.hasClass("nocode")) {
		$('#workspace').hide();
	} else {
		$('#workspace').show();
		$output.empty();
		editor.setValue(load(i) || $s.find('div.source').text());
		editor.focus();
	}

	// update url fragment
	var url = location.href;
	var j = url.indexOf("#");
	if(j >= 0) {
		url = url.substr(0, j);
	}
	url += "#" + (slidenum+1).toString();
	location.href = url;
}

function reset() {
	editor.setValue($(slide).find('div.source').text());
	save(slidenum);
}

var pageData = {};

function save(page) {
	pageData[page] = editor.getValue();
	return true;
}

function load(page) {
	var data = pageData[page];
	if (data) {
		return data;
	}
	return false;
}

function urlSlideNumber(url) {
	var i = url.indexOf("#");
	if(i < 0) {
		return 0;
	}
	var frag = decodeURIComponent(url.substr(i+1));
	if(/^\d+$/.test(frag)) {
		i = parseInt(frag, 10);
		if(i-1 < 0 || i-1 >= slides.length) {
			return 0;
		}
		return i-1;
	}
	return 0;
}

function pageUpDown(event) {
	var e = window.event || event;
	if (e.keyCode === 33) { // page up
		e.preventDefault();
		show(slidenum-1);
		return false;
	}
	if (e.keyCode === 34) { // page down
		e.preventDefault();
		show(slidenum+1);
		return false;
	}
	return true;
}

$(document).ready(function() {
	init();
	if (location.href.indexOf('#') < 0) {
		show(0);
	} else {
		show(urlSlideNumber(location.href));
	}
	document.onkeydown = pageUpDown;
});

$(window).unload(function() {
	save(slidenum);
});

var runFunc, stopFunc;

function body() {
	return editor.getValue();
}
function loading() {
	$output.html('
'+L('waiting')+'
');
}
function run() {
	$output.empty();
	var $pre = $('
').appendTo($output);
	stopFunc = runFunc(body(), $pre[0]);
}

function kill() {
	if (stopFunc) stopFunc();
}

var seq = 0;

function format() {
	seq++;
	var cur = seq;
	loading();
	$.ajax("/fmt", {
		data: {"body": body()},
		type: "POST",
		dataType: "json",
		success: function(data) {
			if (seq !== cur) {
				return;
			}
			$output.empty();
			if (data.Error) {
				$('
').text(data.Error).appendTo($output);
				highlightErrors(data.Error);
			} else {
				editor.setValue(data.Body);
			}
		},
		error: function() {
			$('
').text(L('errcomm')).appendTo($output);
		}
	});
}

function highlightErrors(text) {
	if (!editor || !text) {
		return;
	}
	var errorRe = /[a-z0-9]+\.go:([0-9]+):/g;
	var result;
	while ((result = errorRe.exec(text)) !== null) {
		var line = result[1]*1-1;
		editor.setLineClass(line, null, 'errLine');
	}
	editor.setOption('onChange', function() {
		for (var i = 0; i < editor.lineCount(); i++) {
			editor.setLineClass(i, null, null);
		}
		editor.setOption('onChange', null);
	});
}

// Nasty hack to make this function available to playground.js and socket.js.
window.highlightErrors = highlightErrors;

function getcookie(name) {
	if (document.cookie.length > 0) {
		var start = document.cookie.indexOf(name + '=');
		if (start >= 0) {
			start += name.length + 1;
			var end = document.cookie.indexOf(';', start);
			if (end < 0) {
				end = document.cookie.length;
			}
			return decodeURIComponent(document.cookie.substring(start, end));
		}
	}
	return null;
}

function setcookie(name, value, expire) {
	var expdate = new Date();
	expdate.setDate(expdate.getDate() + expire);
	document.cookie = name + '=' + encodeURIComponent(value) +
		((expire === undefined) ? '' : ';expires=' + expdate.toGMTString());
}

if (window.connectPlayground) {
	runFunc = window.connectPlayground("ws://localhost:3999/socket");
} else {
	// If this message is logged,
	// we have neglected to include socket.js or playground.js.
	console.log("No playground transport available.");
}

}());
<commit_msg>go-tour: turn syntax highlighting off by default<commit_after>/* Copyright 2012 The Go Authors.  All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function() {
"use strict";

var slides, editor, $editor, $output;
var slide = null;
var slidenum = 0;

// manage translations
function L(k) {
	if (tr[k]) {
		return tr[k];
	} else {
		console.log("translation missing for: "+k);
		return "(no translation for "+k+")";
	}
}

function init() {
	var $tocdiv = $('
').insertBefore('#slides').hide();
	$tocdiv.append($('
'+L('toc')+'
'));
	var $toc = $('
').appendTo($tocdiv);
	$("#tocbtn").click(toggleToc);

	slides = $("div.slide");
	slides.each(function(i, slide) {
		var $s = $(slide).hide();

		var $h2 = $s.find("h2").first();
		var $nav;
		if ($h2.length > 0) {
			$("
").addClass("clear").insertAfter($h2);
			$nav = $("
").addClass("nav");
			if (i > 0) {
				$nav.append($("◀").click(function() {
					show(i-1);
					return false;
				}).attr("href", "#"+(i)).attr("title", L('prev')));
			} else {
				$nav.append($("◀"));
			}
			if (i+1 < slides.length) {
				$nav.append($("▶").click(function() {
					show(i+1);
					return false;
				}).attr("href", "#"+(i+2)).attr("title", L('next')));
			} else {
				$nav.append($("▶"));
			}
			$nav.insertBefore($h2);

			var thisI = i;
			var $entry = $("").text($h2.text()).click(function() {
				show(thisI);
			}).attr('href', '#'+(i+1));
			$toc.append($entry);
			$entry.wrap('
');

		}
	});

	// set up playground editor
	editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
		theme: "default",
		matchBrackets: true,
		indentUnit: 4,
		tabSize: 4,
		indentWithTabs: false,
		mode: "text/x-go",
		lineNumbers: true,
		extraKeys: {
			"Shift-Enter": function() {
				run();
			}
		}
	});
	$editor = $(editor.getWrapperElement()).attr('id', 'code');
	$output = $('#output');

	$('#more').click(function() {
		$('.controls').toggleClass('expanded');
		return false;
	});
	$('html').click(function() {
		$('.controls').removeClass('expanded');
	});

	$('#run').click(function() {
		run();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#reset').click(function() {
		reset();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#kill').click(function() {
		kill();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#format').click(function() {
		format();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglesyntax').click(function() {
		if (editor.getOption('theme') === 'default') {
			editor.setOption('theme', 'plain');
			$('#togglesyntax').text(L('syntax')+': '+L('off'));
		} else {
			editor.setOption('theme', 'default');
			$('#togglesyntax').text(L('syntax')+': '+L('on'));
		}
		setcookie('theme', editor.getOption('theme'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglelineno').click(function() {
		if (editor.getOption('lineNumbers')) {
			editor.setOption('lineNumbers', false);
			$('#togglelineno').text(L('lineno')+': '+L('off'));
		} else {
			editor.setOption('lineNumbers', true);
			$('#togglelineno').text(L('lineno')+': '+L('on'));
		}
		setcookie('lineno', editor.getOption('lineNumbers'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	if (getcookie('lineno') != ""+editor.getOption('lineNumbers')) {
		$('#togglelineno').trigger('click');
	} else {
		$('#togglelineno').text(L('lineno')+': '+L('on'));
	}

	if (getcookie('theme') != ""+editor.getOption('theme')) {
		$('#togglesyntax').trigger('click');
	} else {
		$('#togglesyntax').text(L('syntax')+': '+L('on'));
	}

	// set these according to lang.js
	$('#run').text(L('run'));
	$('#reset').text(L('reset'));
	$('#format').text(L('format'));
	$('#kill').text(L('kill'));
	$('#tocbtn').attr('title', L('toc'));
}

function toggleToc() {
	if ($('#toc').is(':visible')) {
		show(slidenum);
	} else {
		$('#slides, #workspace, #slidenum').hide();
		$('#toc').show();
	}
	return false;
}

function show(i) {
	if(i < 0 || i >= slides.length) {
		return;
	}

	// if a slide is already onscreen, hide it and store its code
	if(slide !== null) {
		var $oldSlide = $(slide).hide();
		if (!$oldSlide.hasClass("nocode")) {
			save(slidenum);
		}
	}

	$('#toc').hide();
	$('#slidenum, #slides').show();

	// switch to new slide
	slidenum = i;
	$("#slidenum").text(i+1);
	slide = slides[i];
	var $s = $(slide).show();

	// load stored code, or hide code box
	if ($s.hasClass("nocode")) {
		$('#workspace').hide();
	} else {
		$('#workspace').show();
		$output.empty();
		editor.setValue(load(i) || $s.find('div.source').text());
		editor.focus();
	}

	// update url fragment
	var url = location.href;
	var j = url.indexOf("#");
	if(j >= 0) {
		url = url.substr(0, j);
	}
	url += "#" + (slidenum+1).toString();
	location.href = url;
}

function reset() {
	editor.setValue($(slide).find('div.source').text());
	save(slidenum);
}

var pageData = {};

function save(page) {
	pageData[page] = editor.getValue();
	return true;
}

function load(page) {
	var data = pageData[page];
	if (data) {
		return data;
	}
	return false;
}

function urlSlideNumber(url) {
	var i = url.indexOf("#");
	if(i < 0) {
		return 0;
	}
	var frag = decodeURIComponent(url.substr(i+1));
	if(/^\d+$/.test(frag)) {
		i = parseInt(frag, 10);
		if(i-1 < 0 || i-1 >= slides.length) {
			return 0;
		}
		return i-1;
	}
	return 0;
}

function pageUpDown(event) {
	var e = window.event || event;
	if (e.keyCode === 33) { // page up
		e.preventDefault();
		show(slidenum-1);
		return false;
	}
	if (e.keyCode === 34) { // page down
		e.preventDefault();
		show(slidenum+1);
		return false;
	}
	return true;
}

$(document).ready(function() {
	init();
	if (location.href.indexOf('#') < 0) {
		show(0);
	} else {
		show(urlSlideNumber(location.href));
	}
	document.onkeydown = pageUpDown;
});

$(window).unload(function() {
	save(slidenum);
});

var runFunc, stopFunc;

function body() {
	return editor.getValue();
}
function loading() {
	$output.html('
'+L('waiting')+'
');
}
function run() {
	$output.empty();
	var $pre = $('
').appendTo($output);
	stopFunc = runFunc(body(), $pre[0]);
}

function kill() {
	if (stopFunc) stopFunc();
}

var seq = 0;

function format() {
	seq++;
	var cur = seq;
	loading();
	$.ajax("/fmt", {
		data: {"body": body()},
		type: "POST",
		dataType: "json",
		success: function(data) {
			if (seq !== cur) {
				return;
			}
			$output.empty();
			if (data.Error) {
				$('
').text(data.Error).appendTo($output);
				highlightErrors(data.Error);
			} else {
				editor.setValue(data.Body);
			}
		},
		error: function() {
			$('
').text(L('errcomm')).appendTo($output);
		}
	});
}

function highlightErrors(text) {
	if (!editor || !text) {
		return;
	}
	var errorRe = /[a-z0-9]+\.go:([0-9]+):/g;
	var result;
	while ((result = errorRe.exec(text)) !== null) {
		var line = result[1]*1-1;
		editor.setLineClass(line, null, 'errLine');
	}
	editor.setOption('onChange', function() {
		for (var i = 0; i < editor.lineCount(); i++) {
			editor.setLineClass(i, null, null);
		}
		editor.setOption('onChange', null);
	});
}

// Nasty hack to make this function available to playground.js and socket.js.
window.highlightErrors = highlightErrors;

function getcookie(name) {
	if (document.cookie.length > 0) {
		var start = document.cookie.indexOf(name + '=');
		if (start >= 0) {
			start += name.length + 1;
			var end = document.cookie.indexOf(';', start);
			if (end < 0) {
				end = document.cookie.length;
			}
			return decodeURIComponent(document.cookie.substring(start, end));
		}
	}
	return null;
}

function setcookie(name, value, expire) {
	var expdate = new Date();
	expdate.setDate(expdate.getDate() + expire);
	document.cookie = name + '=' + encodeURIComponent(value) +
		((expire === undefined) ? '' : ';expires=' + expdate.toGMTString());
}

if (window.connectPlayground) {
	runFunc = window.connectPlayground("ws://localhost:3999/socket");
} else {
	// If this message is logged,
	// we have neglected to include socket.js or playground.js.
	console.log("No playground transport available.");
}

}());
<|endoftext|>


<commit_before>/* Copyright 2012 The Go Authors.  All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function() {
"use strict";

var slides, editor, $editor, $output;
var slide = null;
var slidenum = 0;

// manage translations
function L(k) {
	if (tr[k]) {
		return tr[k];
	} else {
		console.log("translation missing for: "+k);
		return "(no translation for "+k+")";
	}
}

function init() {
	var $tocdiv = $('
').insertBefore('#slides').hide();
	$tocdiv.append($('
'+L('toc')+'
'));
	var $toc = $('
').appendTo($tocdiv);
	$("#tocbtn").click(toggleToc);

	slides = $("div.slide");
	slides.each(function(i, slide) {
		var $s = $(slide).hide();

		var $h2 = $s.find("h2").first();
		var $nav;
		if ($h2.length > 0) {
			$("
").addClass("clear").insertAfter($h2);
			$nav = $("
").addClass("nav");
			if (i > 0) {
				$nav.append($("◀").click(function() {
					show(i-1);
					return false;
				}).attr("href", "#"+(i)).attr("title", L('prev')));
			} else {
				$nav.append($("◀"));
			}
			if (i+1 < slides.length) {
				$nav.append($("▶").click(function() {
					show(i+1);
					return false;
				}).attr("href", "#"+(i+2)).attr("title", L('next')));
			} else {
				$nav.append($("▶"));
			}
			$nav.insertBefore($h2);

			var thisI = i;
			var $entry = $("").text($h2.text()).click(function() {
				show(thisI);
			}).attr('href', '#'+(i+1));
			$toc.append($entry);
			$entry.wrap('
');

		}
	});

	// set up playground editor
	editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
		theme: "default",
		matchBrackets: true,
		indentUnit: 4,
		tabSize: 4,
		indentWithTabs: false,
		mode: "text/x-go",
		lineNumbers: true,
		extraKeys: {
			"Shift-Enter": function() {
				run();
			}
		}
	});
	$editor = $(editor.getWrapperElement()).attr('id', 'code');
	$output = $('#output');

	$('#more').click(function() {
		$('.controls').toggleClass('expanded');
		return false;
	});
	$('html').click(function() {
		$('.controls').removeClass('expanded');
	});

	$('#run').click(function() {
		run();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#reset').click(function() {
		reset();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#kill').click(function() {
		kill();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#format').click(function() {
		format();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglesyntax').click(function() {
		if (editor.getOption('theme') === 'default') {
			editor.setOption('theme', 'plain');
			$('#togglesyntax').text(L('syntax')+': '+L('off'));
		} else {
			editor.setOption('theme', 'default');
			$('#togglesyntax').text(L('syntax')+': '+L('on'));
		}
		setcookie('theme', editor.getOption('theme'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglelineno').click(function() {
		if (editor.getOption('lineNumbers')) {
			editor.setOption('lineNumbers', false);
			$('#togglelineno').text(L('lineno')+': '+L('off'));
		} else {
			editor.setOption('lineNumbers', true);
			$('#togglelineno').text(L('lineno')+': '+L('on'));
		}
		setcookie('lineno', editor.getOption('lineNumbers'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	if (getcookie('lineno') != ""+editor.getOption('lineNumbers')) {
		$('#togglelineno').trigger('click');
	} else {
		$('#togglelineno').text(L('lineno')+': '+L('on'));
	}

	if (getcookie('theme') != ""+editor.getOption('theme')) {
		$('#togglesyntax').trigger('click');
	} else {
		$('#togglesyntax').text(L('syntax')+': '+L('on'));
	}

	// set these according to lang.js
	$('#run').text(L('run'));
	$('#reset').text(L('reset'));
	$('#format').text(L('format'));
	$('#kill').text(L('kill'));
	$('#tocbtn').attr('title', L('toc'));
	$('#run').attr('title', L('compile'));
	$('#more').attr('title', L('more'));
}

function toggleToc() {
	if ($('#toc').is(':visible')) {
		show(slidenum);
	} else {
		$('#slides, #workspace, #slidenum').hide();
		$('#toc').show();
	}
	return false;
}

function show(i) {
	if(i < 0 || i >= slides.length) {
		return;
	}

	// if a slide is already onscreen, hide it and store its code
	if(slide !== null) {
		var $oldSlide = $(slide).hide();
		if (!$oldSlide.hasClass("nocode")) {
			save(slidenum);
		}
	}

	$('#toc').hide();
	$('#slidenum, #slides').show();

	// switch to new slide
	slidenum = i;
	$("#slidenum").text(i+1);
	slide = slides[i];
	var $s = $(slide).show();

	// load stored code, or hide code box
	if ($s.hasClass("nocode")) {
		$('#workspace').hide();
		$('#wrap').addClass('full-width');
	} else {
		$('#wrap').removeClass('full-width');
		$('#workspace').show();
		$output.empty();
		editor.setValue(load(i) || $s.find('div.source').text());
		editor.focus();
	}

	// update url fragment
	var url = location.href;
	var j = url.indexOf("#");
	if(j >= 0) {
		url = url.substr(0, j);
	}
	url += "#" + (slidenum+1).toString();
	location.href = url;
}

function reset() {
	editor.setValue($(slide).find('div.source').text());
	save(slidenum);
}

var pageData = {};

function save(page) {
	pageData[page] = editor.getValue();
	return true;
}

function load(page) {
	var data = pageData[page];
	if (data) {
		return data;
	}
	return false;
}

function urlSlideNumber(url) {
	var i = url.indexOf("#");
	if(i < 0) {
		return 0;
	}
	var frag = decodeURIComponent(url.substr(i+1));
	if(/^\d+$/.test(frag)) {
		i = parseInt(frag, 10);
		if(i-1 < 0 || i-1 >= slides.length) {
			return 0;
		}
		return i-1;
	}
	return 0;
}

function pageUpDown(event) {
	var e = window.event || event;
	if (e.keyCode === 33) { // page up
		e.preventDefault();
		show(slidenum-1);
		return false;
	}
	if (e.keyCode === 34) { // page down
		e.preventDefault();
		show(slidenum+1);
		return false;
	}
	return true;
}

$(document).ready(function() {
	init();
	if (location.href.indexOf('#') < 0) {
		show(0);
	} else {
		show(urlSlideNumber(location.href));
	}
	document.onkeydown = pageUpDown;
});

$(window).unload(function() {
	save(slidenum);
});

var runFunc, stopFunc;

function body() {
	return editor.getValue();
}
function loading() {
	$output.html('
'+L('waiting')+'
');
}
function run() {
	loading();
	stopFunc = runFunc(body(), $output.find("pre")[0]);
}

function kill() {
	if (stopFunc) stopFunc();
}

var seq = 0;

function format() {
	seq++;
	var cur = seq;
	loading();
	$.ajax("/fmt", {
		data: {"body": body()},
		type: "POST",
		dataType: "json",
		success: function(data) {
			if (seq !== cur) {
				return;
			}
			$output.empty();
			if (data.Error) {
				$('
').text(data.Error).appendTo($output);
				highlightErrors(data.Error);
			} else {
				editor.setValue(data.Body);
			}
		},
		error: function() {
			$('
').text(L('errcomm')).appendTo($output);
		}
	});
}

function highlightErrors(text) {
	if (!editor || !text) {
		return;
	}
	var errorRe = /[a-z0-9]+\.go:([0-9]+):/g;
	var result;
	while ((result = errorRe.exec(text)) !== null) {
		var line = result[1]*1-1;
		editor.setLineClass(line, null, 'errLine');
	}
	editor.setOption('onChange', function() {
		for (var i = 0; i < editor.lineCount(); i++) {
			editor.setLineClass(i, null, null);
		}
		editor.setOption('onChange', null);
	});
}

// Nasty hack to make this function available to playground.js and socket.js.
window.highlightErrors = highlightErrors;

function getcookie(name) {
	if (document.cookie.length > 0) {
		var start = document.cookie.indexOf(name + '=');
		if (start >= 0) {
			start += name.length + 1;
			var end = document.cookie.indexOf(';', start);
			if (end < 0) {
				end = document.cookie.length;
			}
			return decodeURIComponent(document.cookie.substring(start, end));
		}
	}
	return null;
}

function setcookie(name, value, expire) {
	var expdate = new Date();
	expdate.setDate(expdate.getDate() + expire);
	document.cookie = name + '=' + encodeURIComponent(value) +
		((expire === undefined) ? '' : ';expires=' + expdate.toGMTString());
}

if (window.connectPlayground) {
	runFunc = window.connectPlayground(window.socketAddr);
} else {
	// If this message is logged,
	// we have neglected to include socket.js or playground.js.
	console.log("No playground transport available.");
}

}());
<commit_msg>go-tour: trim spaces around source code before displaying<commit_after>/* Copyright 2012 The Go Authors.  All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
(function() {
"use strict";

var slides, editor, $editor, $output;
var slide = null;
var slidenum = 0;

// manage translations
function L(k) {
	if (tr[k]) {
		return tr[k];
	} else {
		console.log("translation missing for: "+k);
		return "(no translation for "+k+")";
	}
}

function init() {
	var $tocdiv = $('
').insertBefore('#slides').hide();
	$tocdiv.append($('
'+L('toc')+'
'));
	var $toc = $('
').appendTo($tocdiv);
	$("#tocbtn").click(toggleToc);

	slides = $("div.slide");
	slides.each(function(i, slide) {
		var $s = $(slide).hide();

		var $h2 = $s.find("h2").first();
		var $nav;
		if ($h2.length > 0) {
			$("
").addClass("clear").insertAfter($h2);
			$nav = $("
").addClass("nav");
			if (i > 0) {
				$nav.append($("◀").click(function() {
					show(i-1);
					return false;
				}).attr("href", "#"+(i)).attr("title", L('prev')));
			} else {
				$nav.append($("◀"));
			}
			if (i+1 < slides.length) {
				$nav.append($("▶").click(function() {
					show(i+1);
					return false;
				}).attr("href", "#"+(i+2)).attr("title", L('next')));
			} else {
				$nav.append($("▶"));
			}
			$nav.insertBefore($h2);

			var thisI = i;
			var $entry = $("").text($h2.text()).click(function() {
				show(thisI);
			}).attr('href', '#'+(i+1));
			$toc.append($entry);
			$entry.wrap('
');

		}
	});

	// set up playground editor
	editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
		theme: "default",
		matchBrackets: true,
		indentUnit: 4,
		tabSize: 4,
		indentWithTabs: false,
		mode: "text/x-go",
		lineNumbers: true,
		extraKeys: {
			"Shift-Enter": function() {
				run();
			}
		}
	});
	$editor = $(editor.getWrapperElement()).attr('id', 'code');
	$output = $('#output');

	$('#more').click(function() {
		$('.controls').toggleClass('expanded');
		return false;
	});
	$('html').click(function() {
		$('.controls').removeClass('expanded');
	});

	$('#run').click(function() {
		run();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#reset').click(function() {
		reset();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#kill').click(function() {
		kill();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#format').click(function() {
		format();
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglesyntax').click(function() {
		if (editor.getOption('theme') === 'default') {
			editor.setOption('theme', 'plain');
			$('#togglesyntax').text(L('syntax')+': '+L('off'));
		} else {
			editor.setOption('theme', 'default');
			$('#togglesyntax').text(L('syntax')+': '+L('on'));
		}
		setcookie('theme', editor.getOption('theme'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	$('#togglelineno').click(function() {
		if (editor.getOption('lineNumbers')) {
			editor.setOption('lineNumbers', false);
			$('#togglelineno').text(L('lineno')+': '+L('off'));
		} else {
			editor.setOption('lineNumbers', true);
			$('#togglelineno').text(L('lineno')+': '+L('on'));
		}
		setcookie('lineno', editor.getOption('lineNumbers'), 14);
		$('.controls').removeClass('expanded');
		return false;
	});

	if (getcookie('lineno') != ""+editor.getOption('lineNumbers')) {
		$('#togglelineno').trigger('click');
	} else {
		$('#togglelineno').text(L('lineno')+': '+L('on'));
	}

	if (getcookie('theme') != ""+editor.getOption('theme')) {
		$('#togglesyntax').trigger('click');
	} else {
		$('#togglesyntax').text(L('syntax')+': '+L('on'));
	}

	// set these according to lang.js
	$('#run').text(L('run'));
	$('#reset').text(L('reset'));
	$('#format').text(L('format'));
	$('#kill').text(L('kill'));
	$('#tocbtn').attr('title', L('toc'));
	$('#run').attr('title', L('compile'));
	$('#more').attr('title', L('more'));
}

function toggleToc() {
	if ($('#toc').is(':visible')) {
		show(slidenum);
	} else {
		$('#slides, #workspace, #slidenum').hide();
		$('#toc').show();
	}
	return false;
}

function show(i) {
	if(i < 0 || i >= slides.length) {
		return;
	}

	// if a slide is already onscreen, hide it and store its code
	if(slide !== null) {
		var $oldSlide = $(slide).hide();
		if (!$oldSlide.hasClass("nocode")) {
			save(slidenum);
		}
	}

	$('#toc').hide();
	$('#slidenum, #slides').show();

	// switch to new slide
	slidenum = i;
	$("#slidenum").text(i+1);
	slide = slides[i];
	var $s = $(slide).show();

	// load stored code, or hide code box
	if ($s.hasClass("nocode")) {
		$('#workspace').hide();
		$('#wrap').addClass('full-width');
	} else {
		$('#wrap').removeClass('full-width');
		$('#workspace').show();
		$output.empty();
		editor.setValue(load(i) || $s.find('div.source').text().trim());
		editor.focus();
	}

	// update url fragment
	var url = location.href;
	var j = url.indexOf("#");
	if(j >= 0) {
		url = url.substr(0, j);
	}
	url += "#" + (slidenum+1).toString();
	location.href = url;
}

function reset() {
	editor.setValue($(slide).find('div.source').text().trim());
	save(slidenum);
}

var pageData = {};

function save(page) {
	pageData[page] = editor.getValue();
	return true;
}

function load(page) {
	var data = pageData[page];
	if (data) {
		return data;
	}
	return false;
}

function urlSlideNumber(url) {
	var i = url.indexOf("#");
	if(i < 0) {
		return 0;
	}
	var frag = decodeURIComponent(url.substr(i+1));
	if(/^\d+$/.test(frag)) {
		i = parseInt(frag, 10);
		if(i-1 < 0 || i-1 >= slides.length) {
			return 0;
		}
		return i-1;
	}
	return 0;
}

function pageUpDown(event) {
	var e = window.event || event;
	if (e.keyCode === 33) { // page up
		e.preventDefault();
		show(slidenum-1);
		return false;
	}
	if (e.keyCode === 34) { // page down
		e.preventDefault();
		show(slidenum+1);
		return false;
	}
	return true;
}

$(document).ready(function() {
	init();
	if (location.href.indexOf('#') < 0) {
		show(0);
	} else {
		show(urlSlideNumber(location.href));
	}
	document.onkeydown = pageUpDown;
});

$(window).unload(function() {
	save(slidenum);
});

var runFunc, stopFunc;

function body() {
	return editor.getValue();
}
function loading() {
	$output.html('
'+L('waiting')+'
');
}
function run() {
	loading();
	stopFunc = runFunc(body(), $output.find("pre")[0]);
}

function kill() {
	if (stopFunc) stopFunc();
}

var seq = 0;

function format() {
	seq++;
	var cur = seq;
	loading();
	$.ajax("/fmt", {
		data: {"body": body()},
		type: "POST",
		dataType: "json",
		success: function(data) {
			if (seq !== cur) {
				return;
			}
			$output.empty();
			if (data.Error) {
				$('
').text(data.Error).appendTo($output);
				highlightErrors(data.Error);
			} else {
				editor.setValue(data.Body);
			}
		},
		error: function() {
			$('
').text(L('errcomm')).appendTo($output);
		}
	});
}

function highlightErrors(text) {
	if (!editor || !text) {
		return;
	}
	var errorRe = /[a-z0-9]+\.go:([0-9]+):/g;
	var result;
	while ((result = errorRe.exec(text)) !== null) {
		var line = result[1]*1-1;
		editor.setLineClass(line, null, 'errLine');
	}
	editor.setOption('onChange', function() {
		for (var i = 0; i < editor.lineCount(); i++) {
			editor.setLineClass(i, null, null);
		}
		editor.setOption('onChange', null);
	});
}

// Nasty hack to make this function available to playground.js and socket.js.
window.highlightErrors = highlightErrors;

function getcookie(name) {
	if (document.cookie.length > 0) {
		var start = document.cookie.indexOf(name + '=');
		if (start >= 0) {
			start += name.length + 1;
			var end = document.cookie.indexOf(';', start);
			if (end < 0) {
				end = document.cookie.length;
			}
			return decodeURIComponent(document.cookie.substring(start, end));
		}
	}
	return null;
}

function setcookie(name, value, expire) {
	var expdate = new Date();
	expdate.setDate(expdate.getDate() + expire);
	document.cookie = name + '=' + encodeURIComponent(value) +
		((expire === undefined) ? '' : ';expires=' + expdate.toGMTString());
}

if (window.connectPlayground) {
	runFunc = window.connectPlayground(window.socketAddr);
} else {
	// If this message is logged,
	// we have neglected to include socket.js or playground.js.
	console.log("No playground transport available.");
}

}());
<|endoftext|>


<commit_before>module.exports = {
  activate: function(state) {
    return atom.workspaceView.command("tag:closeTag", (function(_this) {
      return function() {
        return _this.closeTag();
      };
    })(this));
  },
  closeTag: function() {
    var editor = atom.workspace.activePaneItem;
    var cursorPos = editor.getCursor().getBufferPosition();
    var buffer = editor.getTextInBufferRange([[0, 0], cursorPos]);

    var getClosingTag = function (str) {
      var tokens = str.split('<');
      if (tokens.length == 0) {
        return '';
      }
      tokens.reverse();

      var getTag = function (token) {
        return token.substring(0, token.search('>'));
      }

      var skip = null;
      for (var i in tokens) {
        var token = tokens[i];
        var tag = getTag(token);
        if (tag !== undefined && tag.length > 0) {
          if (tag.substring(0, 1) != '/') {
            if (skip == null) {
              return '</' + tag + '>';
            } else if (skip == tag) {
              skip = null;
            }
          } else {
            if (skip === null) {
              skip = tag.substring(1);
            }
          }
        }
      }
      return '';
    }

    editor.insertText(getClosingTag(buffer));
  }
};
<commit_msg>Dealing for self-closing elements.<commit_after>module.exports = {
  activate: function(state) {
    return atom.workspaceView.command("tag:closeTag", (function(_this) {
      return function() {
        return _this.closeTag();
      };
    })(this));
  },
  closeTag: function() {
    var editor = atom.workspace.activePaneItem;
    var cursorPos = editor.getCursor().getBufferPosition();
    var buffer = editor.getTextInBufferRange([[0, 0], cursorPos]);
    var voidElements = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'];

    var getClosingTag = function (str) {
      var tokens = str.split('<');
      if (tokens.length == 0) {
        return '';
      }
      tokens.reverse();

      var getTag = function (token) {
        return token.substring(0, token.search(' |>'));
      }

      var isVoidElement = function(tag) {
        tag = tag.trim();
        if (tag.substr(tag.length - 1) == '/') {
          return true;
        }

        tag = tag.toLowerCase();
        if (voidElements.indexOf(tag) >= 0) {
          return true;
        }

        return false;
      }

      var skip = null;
      for (var i in tokens) {
        var token = tokens[i];
        var tag = getTag(token);
        if (tag !== undefined && tag.length > 0 && !isVoidElement(tag)) {
          if (tag.substring(0, 1) != '/') {
            if (skip == null) {
              return '</' + tag + '>';
            } else if (skip == tag) {
              skip = null;
            }
          } else {
            if (skip === null) {
              skip = tag.substring(1);
            }
          }
        }
      }
      return '';
    }

    editor.insertText(getClosingTag(buffer));
  }
};
<|endoftext|>