<commit_before>// Global Marker Wrappers and Map
var globalMarkers = null;
var globalMap = null;
var markerCluster = null;

// Geographic bounds centered according to incident report locations
var geographicBounds = null;

// Initial map center coordinates
INITIAL_CENTER_LAT = 39.952;
INITIAL_CENTER_LONG = -75.195;
initial_coords = new google.maps.LatLng(INITIAL_CENTER_LAT, INITIAL_CENTER_LONG);

// Bounds for the Date Slider. End date is current date.
var startDate;
var endDate = new Date();

// Take a list of markers and a map, put them on the map, set the
// minimum date, and set the location bounds
function storeMarkerState(markers, map, minDate, bounds, oms) {
    globalMarkers = markers;
    globalMap = map;
    markerCluster = new MarkerClusterer(map, markers, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
    for (mw = 0; mw < globalMarkers.length; mw++)
    {
        (globalMarkers[mw]).setMap(globalMap);
        oms.addMarker(globalMarkers[mw]);

    }
    startDate = minDate;
    geographicBounds = bounds;
    map.fitBounds(bounds);
}

// Use Google geocoder to update geolocation given an address through
// the address search box
function update_center() {
    geocoder = new google.maps.Geocoder();
    address = $("#address").val();
    if (geocoder) {
        geocoder.geocode( { 'address': address},
        function(results, status) {
            if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
                $('#address_error').modal('show');
            }
            else if (status != google.maps.GeocoderStatus.OK) {
                $('#geocode_error').modal('show');
            }
            else {
                globalMap.setCenter(results[0].geometry.location);
            }
            /*$('.close.icon').on('click', function() {
                $(this).parent().hide();
            });*/
        });
    }
}

// Heavily inspired by https://jsfiddle.net/mi3afzal/ogsvzacz/2/
// Adds a "geolocate" button to the map.
function addLocationButton(map) {
	var controlDiv = document.createElement('div');

	var firstChild = document.createElement('button');
	firstChild.style.backgroundColor = '#fff';
	firstChild.style.border = 'none';
	firstChild.style.outline = 'none';
	firstChild.style.width = '28px';
	firstChild.style.height = '28px';
	firstChild.style.borderRadius = '2px';
	firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
	firstChild.style.cursor = 'pointer';
	firstChild.style.marginRight = '10px';
	firstChild.style.padding = '0px';
	firstChild.title = 'Your Location';
	controlDiv.appendChild(firstChild);

	var secondChild = document.createElement('div');
	secondChild.style.margin = '5px';
	secondChild.style.width = '18px';
	secondChild.style.height = '18px';
	secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
	secondChild.style.backgroundSize = '180px 18px';
	secondChild.style.backgroundPosition = '0px 0px';
	secondChild.style.backgroundRepeat = 'no-repeat';
	secondChild.id = 'you_location_img';
	firstChild.appendChild(secondChild);

	google.maps.event.addListener(map, 'dragend', function() {
		$('#you_location_img').css('background-position', '0px 0px');
	});

	firstChild.addEventListener('click', function() {
		var imgX = '0';
		var animationInterval = setInterval(function(){
			if(imgX == '-18') imgX = '0';
			else imgX = '-18';
			$('#you_location_img').css('background-position', imgX+'px 0px');
		}, 500);
		if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				map.setCenter(latlng);
				clearInterval(animationInterval);
				$('#you_location_img').css('background-position', '-144px 0px');
			});
		}
		else{
			clearInterval(animationInterval);
			$('#you_location_img').css('background-position', '0px 0px');
		}
	});

	controlDiv.index = 1;
	map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
}

function addCenterButton(map) {
    var centerDiv = document.createElement('div');

    var centerButton = document.createElement('button');
    centerButton.style.backgroundColor = '#fff';
    centerButton.style.border = 'none';
    centerButton.style.outline = 'none';
    centerButton.style.width = '28px';
    centerButton.style.height = '28px';
    centerButton.style.borderRadius = '2px';
    centerButton.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    centerButton.style.cursor = 'pointer';
    centerButton.style.marginBottom = '10px';
    centerButton.style.marginRight = '10px';
    centerButton.style.padding = '0px';
    centerButton.style.textAlign = 'center';
    centerButton.innerHTML = '  ';
    centerButton.value = 'Reports Center';
    centerButton.title = 'Reports Center';
    centerButton.id = 'centerButton';
    centerDiv.appendChild(centerButton);

    centerButton.addEventListener('click', function() {
        map.fitBounds(geographicBounds);
    });
    centerDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerDiv);
}

// Get address submit event
$(document).ready(function() {
    $('#addressForm').on('submit', function (event) {
        update_center();
        return false;
    });
});

function getNextDate(startDate) {
    startDate.setDate(startDate.getDate()+1);
    return startDate;
}

function filterDateRange() {
  var markersDisplayedOnMap = [];
  for (mw = 0; mw < globalMarkers.length; mw++) {
      if ((globalMarkers[mw].incidentDate.getTime() < startDate.getTime()) ||
          (globalMarkers[mw].incidentDate.getTime() >= endDate.getTime())) {
          globalMarkers[mw].setMap(null);
      }
      else
      {
          globalMarkers[mw].setMap(globalMap);
          markersDisplayedOnMap.push(globalMarkers[mw]);
      }
  }
  markerCluster.clearMarkers();
  markerCluster = new MarkerClusterer(map, markersDisplayedOnMap, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
}

function initializeDateRange() {
  $('#start-date').calendar({
    type: 'date',
    endCalendar: $('#end-date'),
    onChange: function (date, text, mode) {
      startDate = date;
      filterDateRange();
    }
  });

  $('#end-date').calendar({
    type: 'date',
    startCalendar: $('#start-date'),
    onChange: function (date, text, mode) {
      endDate = date;
      filterDateRange();
    }
  });

  // initializes the dates for the calendar
  $('#start-date').calendar('set date', startDate);
  $('#end-date').calendar('set date', endDate);
}

function filterMarkers(bounds) {
    var markersDisplayedOnMap = [];
    for (mw = 0; mw < globalMarkers.length; mw++) {
        if (bounds === null || bounds.contains(globalMarkers[mw].getPosition())) {
            globalMarkers[mw].setMap(globalMap);
            markersDisplayedOnMap.push(globalMarkers[mw]);
        } else {
            globalMarkers[mw].setMap(null);
        }
    }
    markerCluster.clearMarkers();
    markerCluster.addMarkers(markersDisplayedOnMap);
}
<commit_msg>Styled calendars to the right<commit_after>// Global Marker Wrappers and Map
var globalMarkers = null;
var globalMap = null;
var markerCluster = null;

// Geographic bounds centered according to incident report locations
var geographicBounds = null;

// Initial map center coordinates
INITIAL_CENTER_LAT = 39.952;
INITIAL_CENTER_LONG = -75.195;
initial_coords = new google.maps.LatLng(INITIAL_CENTER_LAT, INITIAL_CENTER_LONG);

// Bounds for the Date Slider. End date is current date.
var startDate;
var endDate = new Date();

// Take a list of markers and a map, put them on the map, set the
// minimum date, and set the location bounds
function storeMarkerState(markers, map, minDate, bounds, oms) {
    globalMarkers = markers;
    globalMap = map;
    markerCluster = new MarkerClusterer(map, markers, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
    for (mw = 0; mw < globalMarkers.length; mw++)
    {
        (globalMarkers[mw]).setMap(globalMap);
        oms.addMarker(globalMarkers[mw]);

    }
    startDate = minDate;
    geographicBounds = bounds;
    map.fitBounds(bounds);
}

// Use Google geocoder to update geolocation given an address through
// the address search box
function update_center() {
    geocoder = new google.maps.Geocoder();
    address = $("#address").val();
    if (geocoder) {
        geocoder.geocode( { 'address': address},
        function(results, status) {
            if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
                $('#address_error').modal('show');
            }
            else if (status != google.maps.GeocoderStatus.OK) {
                $('#geocode_error').modal('show');
            }
            else {
                globalMap.setCenter(results[0].geometry.location);
            }
            /*$('.close.icon').on('click', function() {
                $(this).parent().hide();
            });*/
        });
    }
}

// Heavily inspired by https://jsfiddle.net/mi3afzal/ogsvzacz/2/
// Adds a "geolocate" button to the map.
function addLocationButton(map) {
	var controlDiv = document.createElement('div');

	var firstChild = document.createElement('button');
	firstChild.style.backgroundColor = '#fff';
	firstChild.style.border = 'none';
	firstChild.style.outline = 'none';
	firstChild.style.width = '28px';
	firstChild.style.height = '28px';
	firstChild.style.borderRadius = '2px';
	firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
	firstChild.style.cursor = 'pointer';
	firstChild.style.marginRight = '10px';
	firstChild.style.padding = '0px';
	firstChild.title = 'Your Location';
	controlDiv.appendChild(firstChild);

	var secondChild = document.createElement('div');
	secondChild.style.margin = '5px';
	secondChild.style.width = '18px';
	secondChild.style.height = '18px';
	secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
	secondChild.style.backgroundSize = '180px 18px';
	secondChild.style.backgroundPosition = '0px 0px';
	secondChild.style.backgroundRepeat = 'no-repeat';
	secondChild.id = 'you_location_img';
	firstChild.appendChild(secondChild);

	google.maps.event.addListener(map, 'dragend', function() {
		$('#you_location_img').css('background-position', '0px 0px');
	});

	firstChild.addEventListener('click', function() {
		var imgX = '0';
		var animationInterval = setInterval(function(){
			if(imgX == '-18') imgX = '0';
			else imgX = '-18';
			$('#you_location_img').css('background-position', imgX+'px 0px');
		}, 500);
		if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				map.setCenter(latlng);
				clearInterval(animationInterval);
				$('#you_location_img').css('background-position', '-144px 0px');
			});
		}
		else{
			clearInterval(animationInterval);
			$('#you_location_img').css('background-position', '0px 0px');
		}
	});

	controlDiv.index = 1;
	map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
}

function addCenterButton(map) {
    var centerDiv = document.createElement('div');

    var centerButton = document.createElement('button');
    centerButton.style.backgroundColor = '#fff';
    centerButton.style.border = 'none';
    centerButton.style.outline = 'none';
    centerButton.style.width = '28px';
    centerButton.style.height = '28px';
    centerButton.style.borderRadius = '2px';
    centerButton.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    centerButton.style.cursor = 'pointer';
    centerButton.style.marginBottom = '10px';
    centerButton.style.marginRight = '10px';
    centerButton.style.padding = '0px';
    centerButton.style.textAlign = 'center';
    centerButton.innerHTML = '  ';
    centerButton.value = 'Reports Center';
    centerButton.title = 'Reports Center';
    centerButton.id = 'centerButton';
    centerDiv.appendChild(centerButton);

    centerButton.addEventListener('click', function() {
        map.fitBounds(geographicBounds);
    });
    centerDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerDiv);
}

// Get address submit event
$(document).ready(function() {
    $('#addressForm').on('submit', function (event) {
        update_center();
        return false;
    });
});

function getNextDate(startDate) {
    startDate.setDate(startDate.getDate()+1);
    return startDate;
}

function filterDateRange() {
  var markersDisplayedOnMap = [];
  for (mw = 0; mw < globalMarkers.length; mw++) {
      if ((globalMarkers[mw].incidentDate.getTime() < startDate.getTime()) ||
          (globalMarkers[mw].incidentDate.getTime() >= endDate.getTime())) {
          globalMarkers[mw].setMap(null);
      }
      else
      {
          globalMarkers[mw].setMap(globalMap);
          markersDisplayedOnMap.push(globalMarkers[mw]);
      }
  }
  markerCluster.clearMarkers();
  markerCluster = new MarkerClusterer(map, markersDisplayedOnMap, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
}

function initializeDateRange() {
  $('#start-date').calendar({
    type: 'date',
    endCalendar: $('#end-date'),
    popupOptions: {
      position: 'right center',
      lastResort: 'right center',
      prefer: 'right',
      hideOnScroll: false
    },
    onChange: function (date, text, mode) {
      startDate = date;
      filterDateRange();
    }
  });

  $('#end-date').calendar({
    type: 'date',
    startCalendar: $('#start-date'),
    popupOptions: {
      position: 'right center',
      lastResort: 'right center',
      prefer: 'right',
      hideOnScroll: false
    },
    onChange: function (date, text, mode) {
      endDate = date;
      filterDateRange();
    }
  });

  // initializes the dates for the calendar
  $('#start-date').calendar('set date', startDate);
  $('#end-date').calendar('set date', endDate);
}

function filterMarkers(bounds) {
    var markersDisplayedOnMap = [];
    for (mw = 0; mw < globalMarkers.length; mw++) {
        if (bounds === null || bounds.contains(globalMarkers[mw].getPosition())) {
            globalMarkers[mw].setMap(globalMap);
            markersDisplayedOnMap.push(globalMarkers[mw]);
        } else {
            globalMarkers[mw].setMap(null);
        }
    }
    markerCluster.clearMarkers();
    markerCluster.addMarkers(markersDisplayedOnMap);
}
<|endoftext|>


<commit_before>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012-2013 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs          = require('fs'),
    http        = require('http'),
    https       = require('https'),
    url         = require('url'),
    Readable    = require('stream').Readable,
    stringify   = require('qs').stringify,
    multipart   = require('./multipart'),
    auth        = require('./auth');

//////////////////////////////////////////
// variabilia
//////////////////////////////////////////

var version     = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debugging   = !!process.env.DEBUG;

try { var unzip = require('zlib').unzip } catch(e) { /* unzip not supported */ }

var user_agent = 'Needle/' + version;
user_agent    += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')';

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol';

var debug = function(str, obj) {
  if (debugging)
    console.log(str, obj);
}

//////////////////////////////////////////
// content type parsers
//////////////////////////////////////////

var parsers = {
  'application/json': function(data, callback){
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback){
    var xml_parser = new xml2js.Parser({ explicitRoot: true, explicitArray: false });
    xml_parser.parseString(data, function(err, result){
      callback(err, err ? data : result); // return original if err failed
    });
  };
  parsers['text/xml'] = parsers['application/xml'];
  parsers['application/rss+xml'] = parsers['application/xml'];
} catch(e) { /* xml2js not found */ }

//////////////////////////////////////////
// defaults
//////////////////////////////////////////

var defaults = {
  accept          : '*/*',
  connection      : 'close',
  user_agent      : user_agent,
  follow          : 0,
  decode_response : true,
  parse_response  : true,
  timeout         : 10000,
  encoding        : 'utf8',
  boundary        : '--------------------NODENEEDLEHTTPCLIENT'
}

//////////////////////////////////////////
// the main act
//////////////////////////////////////////

var Needle = {

  request: function(method, uri, data, options, callback){

    var self     = this;
    var callback = (typeof options == 'function') ? options : callback;
    var options  = options || {};

    // if no 'http' is found on URL, prepend it
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts       : {},
      proxy           : options.proxy,
      output          : options.output,
      encoding        : options.encoding || (options.multipart ? 'binary' : defaults.encoding),
      decode_response : options.decode === false ? false : defaults.decode_response,
      parse_response  : options.parse === false ? false : defaults.parse_response,
      follow          : options.follow === true ? 10 : typeof options.follow == 'number' ? options.follow : defaults.follow,
      timeout         : (typeof options.timeout == 'number') ? options.timeout : defaults.timeout
    }

    // if any of node's TLS options are passed, let them be passed to https.request()
    node_tls_opts.split(' ').forEach(function(key){
      if (typeof options[key] != 'undefined') {
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept'     : options.accept     || defaults.accept,
      'Connection' : options.connection || defaults.connection,
      'User-Agent' : options.user_agent || defaults.user_agent
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password) {
      if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) {
        config.credentials = [options.username, options.password];
      } else {
        var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
        config.headers[auth_header] = auth.basic(options.username, options.password);
      }
    }

    if (data) {
      if (options.multipart) {
        var boundary = options.boundary || defaults.boundary;
        return multipart.build(data, boundary, function(err, body){
          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);
        });

      } else {
        var post_data = (typeof(data) === 'string') ? data :
            options.json ? JSON.stringify(data) : stringify(data);

        if (!config.headers['Content-Type']) {
          config.headers['Content-Type'] = options.json
          ? 'application/json'
          : 'application/x-www-form-urlencoded';
        }

        post_data = new Buffer(post_data, config.encoding)
        config.headers['Content-Length'] = post_data.length;
      }
    }

    return this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config){
    var opts      = config.base_opts, proxy = config.proxy;
    var remote    = proxy ? url.parse(proxy) : url.parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;
    opts.headers['Host'] = proxy ? url.parse(uri).hostname : remote.hostname;

    return opts;
  },

  get_auth_header: function(header, credentials, request_opts) {
    var type = header.split(' ')[0],
        user = credentials[0],
        pass = credentials[1];

    if (type == 'Digest') {
      return auth.digest(header, user, pass, request_opts.method, request_opts.path);
    } else if (type == 'Basic') {
      return auth.basic(user, pass);
    }
  },

  send_request: function(count, method, uri, config, post_data, callback){

    var timer,
        self = this,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    if (Readable && !config.out) {
      config.out = new Readable();
      config.out.on('error', function(er){ /* noop */ })
    }

    debug('Making request #' + count, request_opts);
    var request = protocol.request(request_opts, function(resp){

      var headers = resp.headers;
      debug('Got response', headers);
      if (timer) clearTimeout(timer);

      // if redirect code is found, send a GET request to that location if enabled via 'follow' option
      if ([301, 302].indexOf(resp.statusCode) != -1 && headers.location) {
        if (count <= config.follow)
          return self.send_request(++count, 'GET', url.resolve(uri, headers.location), config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Max redirects reached. Possible loop in: ' + headers.location));
      }

      // if authentication is requested and credentials were not passed, resend request if we have user/pass
      if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
        if (!config.headers['Authorization']) { // only if authentication hasn't been sent
          var auth_header = self.get_auth_header(headers['www-authenticate'], config.credentials, request_opts);

          if (auth_header) {
            config.headers['Authorization'] = auth_header;
            return self.send_request(count, method, uri, config, post_data, callback);
          }
        }
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(headers['content-encoding']),
          mime = self.parse_content_type(headers['content-type']);

      var response_opts = {
        output       : config.output,
        parse        : config.parse_response, // parse XML or JSON
        content_type : mime.type,
        text         : mime.type && mime.type.indexOf('text/') != -1,
        charset      : mime.charset
      }

      if (response_opts.text)
        response_opts.decode = config.decode_response; // only allow iconv decoding on text bodies

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk){
        chunks.push(chunk);
        if (config.out) config.out.push(chunk);
        length += chunk.length;
        // debug('Got ' + length + ' bytes.')
      });

      resp.on('end', function(){
        if (config.out) config.out.push(null); // close readable out stream

        // build the body by merging all the chunks we received
        var pos = 0;
        resp.bytes = length;
        resp.body  = new Buffer(resp.bytes);
        for (var i = 0, len = chunks.length; i < len; i++) {
          (new Buffer(chunks[i])).copy(resp.body, pos);
          pos += chunks[i].length;
        }

        // if no unzip support, or no deflated body requested, return
        if (!compressed || typeof unzip == 'undefined')
          return self.response_end(response_opts, resp, callback);

        unzip(resp.body, function(err, buff){
          if (!err && buff) resp.body = buff; // only if no errors
          self.response_end(response_opts, resp, callback);
        });

      });

    });

    // unless timeout was disabled, set a timeout to abort the request
    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      debug('Request error', err);
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error('Unknown error when making request.'));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

    return config.out || request;
  },

  parse_content_type: function(header){
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, resp, callback){
    if (!callback) return; // no point in going ahead

    var handle_output = function(err, final){
      if (final) resp.body = final;

      if (err || !opts.output || resp.statusCode != 200)
        return callback(err, resp, resp.body);

      // err is nil and output requested, so write to file
      fs.writeFile(opts.output, resp.body, function(e){
        callback(e, resp, resp.body);
      })
    }

    // if there's a parser for the content type received, process it
    if (opts.parse && parsers[opts.content_type]) {
      parsers[opts.content_type](resp.body.toString(), handle_output);
    } else {
      // if charset is not UTF-8 and decode option is true, transmogrify it
      if (opts.decode && opts.charset && !opts.charset.match(/utf-?8$/i))
        resp.body = require('iconv-lite').decode(resp.body, opts.charset);

      handle_output(null, opts.text ? resp.body.toString() : resp.body);
    }

  }

}

exports.version = version;

exports.defaults = function(obj) {
  for (var key in obj) {
    if (defaults[key] && typeof obj[key] != 'undefined')
      defaults[key] = obj[key];
  }
  return defaults;
}

exports.head   = function(uri, options, callback){
  return Needle.request('HEAD', uri, null, options, callback);
}

exports.get    = function(uri, options, callback){
  return Needle.request('GET', uri, null, options, callback);
}

exports.post   = function(uri, data, options, callback){
  return Needle.request('POST', uri, data, options, callback);
}

exports.put    = function(uri, data, options, callback){
  return Needle.request('PUT', uri, data, options, callback);
}

exports.delete = function(uri, data, options, callback){
  return Needle.request('DELETE', uri, data, options, callback);
}

exports.request = function(method, uri, data, opts, callback) {
  return Needle.request(method.toUpperCase(), uri, data, opts, callback);
};
<commit_msg>Beautification.<commit_after>//////////////////////////////////////////
// Needle -- Node.js HTTP Client
// Written by Tomás Pollak <tomas@forkhq.com>
// (c) 2012-2013 - Fork Ltd.
// MIT Licensed
//////////////////////////////////////////

var fs          = require('fs'),
    http        = require('http'),
    https       = require('https'),
    url         = require('url'),
    Readable    = require('stream').Readable,
    stringify   = require('qs').stringify,
    multipart   = require('./multipart'),
    auth        = require('./auth');

//////////////////////////////////////////
// variabilia
//////////////////////////////////////////

var version     = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()).version,
    debugging   = !!process.env.DEBUG;

try { var unzip = require('zlib').unzip } catch(e) { /* unzip not supported */ }

var user_agent = 'Needle/' + version;
user_agent    += ' (Node.js ' + process.version + '; ' + process.platform + ' ' + process.arch + ')';

var node_tls_opts = 'agent pfx key passphrase cert ca ciphers rejectUnauthorized secureProtocol';

var debug = function(str, obj) {
  if (debugging)
    console.log(str, obj);
}

//////////////////////////////////////////
// content type parsers
//////////////////////////////////////////

var parsers = {
  'application/json': function(data, callback) {
    try {
      callback(null, data && JSON.parse(data));
    } catch(e) {
      callback(e, data);
    }
  }
};

try {
  var xml2js = require('xml2js');
  parsers['application/xml'] = function(data, callback) {
    var xml_parser = new xml2js.Parser({ explicitRoot: true, explicitArray: false });
    xml_parser.parseString(data, function(err, result) {
      callback(err, err ? data : result); // return original if err failed
    });
  };
  parsers['text/xml'] = parsers['application/xml'];
  parsers['application/rss+xml'] = parsers['application/xml'];
} catch(e) { /* xml2js not found */ }

//////////////////////////////////////////
// defaults
//////////////////////////////////////////

var defaults = {
  accept          : '*/*',
  connection      : 'close',
  user_agent      : user_agent,
  follow          : 0,
  decode_response : true,
  parse_response  : true,
  timeout         : 10000,
  encoding        : 'utf8',
  boundary        : '--------------------NODENEEDLEHTTPCLIENT'
}

//////////////////////////////////////////
// the main act
//////////////////////////////////////////

var Needle = {

  request: function(method, uri, data, options, callback) {

    var self     = this;
    var callback = (typeof options == 'function') ? options : callback;
    var options  = options || {};

    // if no 'http' is found on URL, prepend it
    if (uri.indexOf('http') == -1) uri = 'http://' + uri;

    var config = {
      base_opts       : {},
      proxy           : options.proxy,
      output          : options.output,
      encoding        : options.encoding || (options.multipart ? 'binary' : defaults.encoding),
      decode_response : options.decode === false ? false : defaults.decode_response,
      parse_response  : options.parse === false ? false : defaults.parse_response,
      follow          : options.follow === true ? 10 : typeof options.follow == 'number' ? options.follow : defaults.follow,
      timeout         : (typeof options.timeout == 'number') ? options.timeout : defaults.timeout
    }

    // if any of node's TLS options are passed, let them be passed to https.request()
    node_tls_opts.split(' ').forEach(function(key) {
      if (typeof options[key] != 'undefined') {
        config.base_opts[key] = options[key];
        if (typeof options.agent == 'undefined')
          config.base_opts.agent = false; // otherwise tls options are skipped
      }
    });

    config.headers = {
      'Accept'     : options.accept     || defaults.accept,
      'Connection' : options.connection || defaults.connection,
      'User-Agent' : options.user_agent || defaults.user_agent
    }

    if (options.compressed && typeof unzip != 'undefined')
      config.headers['Accept-Encoding'] = 'gzip,deflate';

    for (var h in options.headers)
      config.headers[h] = options.headers[h];

    if (options.username && options.password) {
      if (options.auth && (options.auth == 'auto' || options.auth == 'digest')) {
        config.credentials = [options.username, options.password];
      } else {
        var auth_header = options.proxy ? 'Proxy-Authorization' : 'Authorization';
        config.headers[auth_header] = auth.basic(options.username, options.password);
      }
    }

    if (data) {
      if (options.multipart) {
        var boundary = options.boundary || defaults.boundary;
        return multipart.build(data, boundary, function(err, body) {
          if (err) throw(err);
          config.headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
          config.headers['Content-Length'] = body.length;
          self.send_request(1, method, uri, config, body, callback);
        });

      } else {
        var post_data = (typeof(data) === 'string') ? data :
            options.json ? JSON.stringify(data) : stringify(data);

        if (!config.headers['Content-Type']) {
          config.headers['Content-Type'] = options.json
          ? 'application/json'
          : 'application/x-www-form-urlencoded';
        }

        post_data = new Buffer(post_data, config.encoding)
        config.headers['Content-Length'] = post_data.length;
      }
    }

    return this.send_request(1, method, uri, config, post_data, callback);
  },

  get_request_opts: function(method, uri, config) {
    var opts      = config.base_opts, proxy = config.proxy;
    var remote    = proxy ? url.parse(proxy) : url.parse(uri);

    opts.protocol = remote.protocol;
    opts.host     = remote.hostname;
    opts.port     = remote.port || (remote.protocol == 'https:' ? 443 : 80);
    opts.path     = proxy ? uri : remote.pathname + (remote.search || '');
    opts.method   = method;
    opts.headers  = config.headers;
    opts.headers['Host'] = proxy ? url.parse(uri).hostname : remote.hostname;

    return opts;
  },

  get_auth_header: function(header, credentials, request_opts) {
    var type = header.split(' ')[0],
        user = credentials[0],
        pass = credentials[1];

    if (type == 'Digest') {
      return auth.digest(header, user, pass, request_opts.method, request_opts.path);
    } else if (type == 'Basic') {
      return auth.basic(user, pass);
    }
  },

  send_request: function(count, method, uri, config, post_data, callback) {

    var timer,
        self = this,
        request_opts = this.get_request_opts(method, uri, config),
        protocol = request_opts.protocol == 'https:' ? https : http;

    if (Readable && !config.out) {
      config.out = new Readable();
      config.out.on('error', function(er) { /* noop */ })
    }

    debug('Making request #' + count, request_opts);
    var request = protocol.request(request_opts, function(resp) {

      var headers = resp.headers;
      debug('Got response', headers);
      if (timer) clearTimeout(timer);

      // if redirect code is found, send a GET request to that location if enabled via 'follow' option
      if ([301, 302].indexOf(resp.statusCode) != -1 && headers.location) {
        if (count <= config.follow)
          return self.send_request(++count, 'GET', url.resolve(uri, headers.location), config, null, callback);
        else if (config.follow > 0)
          return callback(new Error('Max redirects reached. Possible loop in: ' + headers.location));
      }

      // if authentication is requested and credentials were not passed, resend request if we have user/pass
      if (resp.statusCode == 401 && headers['www-authenticate'] && config.credentials) {
        if (!config.headers['Authorization']) { // only if authentication hasn't been sent
          var auth_header = self.get_auth_header(headers['www-authenticate'], config.credentials, request_opts);

          if (auth_header) {
            config.headers['Authorization'] = auth_header;
            return self.send_request(count, method, uri, config, post_data, callback);
          }
        }
      }

      var chunks = [], length = 0,
          compressed = /gzip|deflate/.test(headers['content-encoding']),
          mime = self.parse_content_type(headers['content-type']);

      var response_opts = {
        output       : config.output,
        parse        : config.parse_response, // parse XML or JSON
        content_type : mime.type,
        text         : mime.type && mime.type.indexOf('text/') != -1,
        charset      : mime.charset
      }

      if (response_opts.text)
        response_opts.decode = config.decode_response; // only allow iconv decoding on text bodies

    // response.setEncoding(response_opts.utf8 ? 'utf8' : 'binary');

      resp.on('data', function(chunk) {
        chunks.push(chunk);
        if (config.out) config.out.push(chunk);
        length += chunk.length;
        // debug('Got ' + length + ' bytes.')
      });

      resp.on('end', function() {
        if (config.out) config.out.push(null); // close readable out stream

        // build the body by merging all the chunks we received
        var pos = 0;
        resp.bytes = length;
        resp.body  = new Buffer(resp.bytes);
        for (var i = 0, len = chunks.length; i < len; i++) {
          (new Buffer(chunks[i])).copy(resp.body, pos);
          pos += chunks[i].length;
        }

        // if no unzip support, or no deflated body requested, return
        if (!compressed || typeof unzip == 'undefined')
          return self.response_end(response_opts, resp, callback);

        unzip(resp.body, function(err, buff) {
          if (!err && buff) resp.body = buff; // only if no errors
          self.response_end(response_opts, resp, callback);
        });

      });

    });

    // unless timeout was disabled, set a timeout to abort the request
    if (config.timeout > 0) {
      timer = setTimeout(function() {
        request.abort();
      }, config.timeout)
    }

    request.on('error', function(err) {
      debug('Request error', err);
      if (timer) clearTimeout(timer);
      if (callback) callback(err || new Error('Unknown error when making request.'));
    });

    if (post_data) request.write(post_data, config.encoding);
    request.end();

    return config.out || request;
  },

  parse_content_type: function(header) {
    if (!header || header == '') return {};

    var charset = 'iso-8859-1', arr = header.split(';');
    try { charset = arr[1].match(/charset=(.+)/)[1] } catch (e) { /* not found */ }

    return { type: arr[0], charset: charset };
  },

  response_end: function(opts, resp, callback) {
    if (!callback) return; // no point in going ahead

    var handle_output = function(err, final) {
      if (final) resp.body = final;

      if (err || !opts.output || resp.statusCode != 200)
        return callback(err, resp, resp.body);

      // err is nil and output requested, so write to file
      fs.writeFile(opts.output, resp.body, function(e) {
        callback(e, resp, resp.body);
      })
    }

    // if there's a parser for the content type received, process it
    if (opts.parse && parsers[opts.content_type]) {
      parsers[opts.content_type](resp.body.toString(), handle_output);
    } else {
      // if charset is not UTF-8 and decode option is true, transmogrify it
      if (opts.decode && opts.charset && !opts.charset.match(/utf-?8$/i))
        resp.body = require('iconv-lite').decode(resp.body, opts.charset);

      handle_output(null, opts.text ? resp.body.toString() : resp.body);
    }

  }

}

exports.version = version;

exports.defaults = function(obj) {
  for (var key in obj) {
    if (defaults[key] && typeof obj[key] != 'undefined')
      defaults[key] = obj[key];
  }
  return defaults;
}

exports.head   = function(uri, options, callback) {
  return Needle.request('HEAD', uri, null, options, callback);
}

exports.get    = function(uri, options, callback) {
  return Needle.request('GET', uri, null, options, callback);
}

exports.post   = function(uri, data, options, callback) {
  return Needle.request('POST', uri, data, options, callback);
}

exports.put    = function(uri, data, options, callback) {
  return Needle.request('PUT', uri, data, options, callback);
}

exports.delete = function(uri, data, options, callback) {
  return Needle.request('DELETE', uri, data, options, callback);
}

exports.request = function(method, uri, data, opts, callback) {
  return Needle.request(method.toUpperCase(), uri, data, opts, callback);
};
<|endoftext|>


<commit_before>
var ReactWeather = React.createClass({
  getInitialState: function() {
    return {
      userLocation: 'London'
    };
  },

  componentDidMount: function() {
    var self = this;
    self._getCityWeather('London', function(result) {
      console.log(result);
      if ( self.isMounted() ) {
        self.setState({
          temp: result.coord.lat
        });
      }
    });
  },

  _getCityWeather: function(city, cb) {
    var url = 'http://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=2de143494c0b295cca9337e1e96b00e0'
    $.get(url, cb);
  },

  render: function () {
    var state = this.state;
    console.log(state);
    return (

AAAA: {state.temp}

    );
  }
});

ReactDOM.render(
  <ReactWeather />,
  document.getElementById('ReactWeather')
);

/*
var url = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=2de143494c0b295cca9337e1e96b00e0'
$.get(url, function(data) {
  console.log(data);
});
*/
//Иконки: http://openweathermap.org/img/w/10d.png<commit_msg>R: _getCityWeather<commit_after>
var ReactWeather = React.createClass({
  getInitialState: function() {
    return {
      userLocation: 'London'
    };
  },

  componentDidMount: function() {
    var self = this;
    self._getCityWeather('London', function(result) {
      console.log(result);
      if ( self.isMounted() ) {
        self.setState({
          temp: result.coord.lat
        });
      }
    });
  },

  _getCityWeather: function(city, cb) {
    var appid = '2de143494c0b295cca9337e1e96b00e0';
    var url = 'http://api.openweathermap.org/data/2.5/weather';

    $.get(url, {q: city, appid: appid}, cb);
  },

  render: function () {
    var state = this.state;
    console.log(state);
    return (

AAAA: {state.temp}

    );
  }
});

ReactDOM.render(
  <ReactWeather />,
  document.getElementById('ReactWeather')
);

/*
var url = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=2de143494c0b295cca9337e1e96b00e0'
$.get(url, function(data) {
  console.log(data);
});
*/
//Иконки: http://openweathermap.org/img/w/10d.png<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: '<json:package/component.json>',

    meta: {
        file: "quo",
        banner: '/* <%= pkg.name %> v<%= pkg.version %> - <%= grunt.template.today("m/d/yyyy") %>\n' +
                '   <%= pkg.homepage %>\n' +
                '   Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>' +
                ' - Licensed <%= _.pluck(pkg.license, "type").join(", ") %> */'
    },

    resources: {
        coffee: ['src/**/*.coffee', 'spec/**/*.coffee'],
        js: ['build/**/quo.js',
            'build/**/quo.core.js',
            'build/**/quo.environment.js',
            'build/**/quo.query.js',
            'build/**/quo.style.js',
            'build/**/quo.element.js',
            'build/**/quo.output.js',
            'build/**/quo.ajax.js',
            'build/**/quo.events.js',
            'build/**/quo.gestures.js']
    },

    coffee: {
      app: {
        src: ['<config:resources.coffee>'],
        dest: 'build',
        options: {
            bare: true,
            preserve_dirs: true
        }
      }
    },

    concat: {
      js: {
        src: ['<banner>', '<config:resources.js>'],
        dest: 'package/<%=meta.file%>.js'
      }
    },

    min: {
      js: {
        src: ['<banner>', 'package/<%=meta.file%>.js'],
        dest: 'package/<%=meta.file%>.min.js'
      }
    },

    watch: {
      files: ['<config:resources.coffee>'],
      tasks: 'coffee concat min'
    },

    uglify: {}
  });

  grunt.loadNpmTasks('grunt-coffee');

  // Default task.
  grunt.registerTask('default', 'coffee concat min');

};
<commit_msg>Change endpoint files<commit_after>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: '<json:package/component.json>',

    meta: {
        file: "quo",
        banner: '/* <%= pkg.name %> v<%= pkg.version %> - <%= grunt.template.today("m/d/yyyy") %>\n' +
                '   <%= pkg.homepage %>\n' +
                '   Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>' +
                ' - Licensed <%= _.pluck(pkg.license, "type").join(", ") %> */'
    },

    resources: {
        coffee: ['src/**/*.coffee', 'spec/**/*.coffee'],
        js: ['build/**/quo.js',
            'build/**/quo.core.js',
            'build/**/quo.environment.js',
            'build/**/quo.query.js',
            'build/**/quo.style.js',
            'build/**/quo.element.js',
            'build/**/quo.output.js',
            'build/**/quo.ajax.js',
            'build/**/quo.events.js',
            'build/**/quo.gestures.js']
    },

    coffee: {
      app: {
        src: ['<config:resources.coffee>'],
        dest: 'build',
        options: {
            bare: true,
            preserve_dirs: true
        }
      }
    },

    concat: {
      js: {
        src: ['<banner>', '<config:resources.js>'],
        dest: 'package/<%=meta.file%>.debug.js'
      }
    },

    min: {
      js: {
        src: ['<banner>', 'package/<%=meta.file%>.js'],
        dest: 'package/<%=meta.file%>.js'
      }
    },

    watch: {
      files: ['<config:resources.coffee>'],
      tasks: 'coffee concat min'
    },

    uglify: {}
  });

  grunt.loadNpmTasks('grunt-coffee');

  // Default task.
  grunt.registerTask('default', 'coffee concat min');

};
<|endoftext|>


<commit_before>/**
 * @class Gistie
 * @classdesc pulls notebooks from GitHub gists and propagates cells on the page
 * @param {number} gistID Gist numeric id
 */
Gistie = function(gistID) {
  // Don't need oauthentication if only using gists
  this.gh = new Github({});

  // gist API
  this.gistAPI = this.gh.getGist(gistID);

  // Read the gist itself
  this.gistAPI.read(this._read.bind(this));

};

/**
 * String.includes polyfill
 */
if (!String.prototype.includes) {
  String.prototype.includes = function() {'use strict';
    return String.prototype.indexOf.apply(this, arguments) !== -1;
  };
}

/**
 * Implements the callback for a Github.gist.read, intended to be bound to
 * `this`, which is bound in the constructor (this._read.bind(this)) call to read
 * @param error
 * @param {Object} Github gist
 */
Gistie.prototype._read = function(err, gist) {
  this.gist = gist;
  console.log(this.gist);
  this.files = gist.files;

  for (var filename in gist.files) {
    if(!gist.files.hasOwnProperty(filename)) {
      continue;
    }

    var file = gist.files[filename];

    filename = filename.toLowerCase();

    if (filename.includes('.ipynb')) {
      this._renderFile(file, this.renderNotebook);
    } else if (filename.includes('.md')){
      this._renderFile(file, this.renderMarkdown);
    } else if (filename.includes('.rmd')) {
      this._renderFile(file, this.renderRMarkdown);
    }
  }
};

Gistie.prototype._renderFile = function(file, cb) {
  if (file.truncated) {
    console.log("File truncated, fetching raw URL");
    $.ajax({
      url: file.raw_url,
      success: cb.bind(this)
    });
  } else {
    console.log("File small enough to render straight from gist API");
    cb(file.content);
  }
};

/**
 * Tickles the notebook server's contents API to sneakily upload data
 *
 * resp = requests.put("http://127.0.0.1:8888/user/neNUk0HdyfGm/api/contents/that.py",
 *                     json={'type': 'file', 'format': 'text', 'content': "import this"})
 */
upload = function(base_server, filepath, content) {
  fetch(base_server + filepath, {
    method: 'put',
    body: JSON.stringify({
      type: 'file',
      format: 'text', // TODO: This is definitely an assumption...
      content: content
    }),
    headers: {
      'Accept': 'application/json'
    }
  });
};

Gistie.prototype.renderMarkdown = function(markdown) {
  var $container = $('#container');
  $container.empty();
  var renderer = new marked.Renderer();

  var kernel_name;

  // TODO: Something sensible about language detection
  // For now, just accept the last rendered code cell as the language
  // TODO: mapping from language -> kernel_name

  // Here we override to bring Thebe flavored cells
  renderer.code = function(code, language) {
    kernel_name = language;
    return '
' + code + '
\n';
  };

  marked.setOptions({
    renderer: renderer,
  });

  var html = marked(markdown);
  var el = $container.append(html);

  this.thebe = new Thebe({
    url: "https://tmp31.tmpnb.org",
    kernel_name: kernel_name || "python3"
  });

};

function splitFrontMatter(doc) {
  var re = /^(-{3}(?:\n|\r)([\w\W]+?)-{3})?([\w\W]*)*/;
  var results = re.exec(doc);

  return {
    "front": jsyaml.load(results[2]),
    "markdown": results[3]
  };

}

Gistie.prototype.renderRMarkdown = function(rmarkdown) {
  var $container = $('#container');
  $container.empty();

  var matter = splitFrontMatter(rmarkdown);

  var front = matter.front;
  var markdown = matter.markdown;

  var titleComponents = [];

  if (front.title) {
    $container.append('
' + front.title + '
');
    titleComponents.push(front.title);
  }
  if (front.author) {
    $container.append('
' + front.author + '
');
    titleComponents.push(front.author);
  }
  if (front.date) {
    $container.append('
' + front.date + '
');
    titleComponents.push(front.date);
  }

  document.title = titleComponents.join(' - ');

  var renderer = new marked.Renderer();

  // Here we override to bring Thebe flavored cells
  renderer.code = function(code, chunkHeader) {
    // TODO: validate chunkHeader
    // TODO: extract chunkOptions
    return '
' + code + '
\n';
  };

  marked.setOptions({
    renderer: renderer,
  });

  var html = marked(markdown);
  var el = $container.append(html);

  this.thebe = new Thebe({
    url: "https://tmp31.tmpnb.org",
    kernel_name: "ir"
  });

};

/**
 * Render a notebook on the DOM. Likely ugly.
 * @param {Object} notebook Jupyter Notebook document
 */
Gistie.prototype.renderNotebook = function(notebook) {
  // TODO: Check that it's really a notebook (existence of content key)
  console.log("Rendering notebook");

  notebook = JSON.parse(notebook);

  var $container = $('#container');
  $container.empty();

  var cell;

  if (notebook.hasOwnProperty('worksheets')) {
    // Slight conversion from < v4 notebook to v4
    notebook.cells = notebook.worksheets[0].cells;
    for (cellID = 0; cellID < notebook.cells.length; cellID++ ) {
      cell = notebook.cells[cellID];
      cell.source = cell.input;
    }
  }

  for (cellID = 0; cellID < notebook.cells.length; cellID++ ) {
    cell = notebook.cells[cellID];
    if (cell.source && cell.cell_type) {
      if (cell.cell_type == 'code') {
        var code;

        if (typeof cell.source === 'string') {
          code = cell.source;
        } else { // Assume list of source cells
          code = cell.source.join('');
        }

        // Raw
 cells with source for thebe to process
        $container.append('
' + code + '
\n');
      } else if (cell.cell_type == 'markdown') {
        var markdown;

        if (typeof cell.source === 'string') {
          markdown = cell.source;
        } else { // Assume list of source cells
          markdown = cell.source.join('');
        }

        // Little blocks of markdown everywhere
        var html = marked(markdown);
        var el = $container.append('
' + html + '
');

        // Render LaTeX
        //MathJax.Hub.Queue(["Typeset", MathJax.Hub, el[0]]);

      } else {
        console.log("Unknown cell type: " + cell.cell_type);
      }

    } else {
      console.log("No cell source and/or cell_type: ");
      console.log(cell);
    }
  }
  MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

  var kernel_name;
  try {
    kernel_name = notebook.metadata.kernelspec.name;
  } catch(e) {
    // If a kernel wasn't detected, go with python3
    kernel_name = "python3";
  }

  this.thebe = new Thebe({
    url: "https://tmp28.tmpnb.org",
    kernel_name: kernel_name || "python3"
  });
};

/**
 * Utility funciton to set up Gistie on the page
 */
gistexec = function( ) {
  var params = getUrlParams();

  if (!params.gistID) {
    return;
  }

  //Init MathJax
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"] ],
          displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
          processEscapes: true,
          processEnvironments: true
      },
      // Center justify equations in code and markdown cells. Elsewhere
      // we use CSS to left justify single line equations in code cells.
      displayAlign: 'center',
      "HTML-CSS": {
          availableFonts: [],
          imageFont: null,
          preferredFont: null,
          webFont: "STIX-Web",
          //styles: {'.MathJax_Display': {"margin": 0}},
          linebreaks: { automatic: true }
      }
  });
  MathJax.Hub.Configured();

  if (params.gistID) {
    return new Gistie(params.gistID);
  }
};

/**
 * Returns a bare object of the URL's query parameters.
 * You can pass just a query string rather than a complete URL.
 * The default URL is the current page.
 *
 * From: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
 */
var getUrlParams = function(url) {
    // http://stackoverflow.com/a/23946023/2407309
    if (typeof url == 'undefined') {
        url = window.location.search;
    }
    url = url.split('#')[0]; // Discard fragment identifier.
    var queryString = url.split('?')[1];
    if (!queryString) {
        if (url.search('=') !== false) {
            queryString = url;
        }
    }
    var urlParams = {};
    if (queryString) {
        var keyValuePairs = queryString.split('&');
        for (var i = 0; i < keyValuePairs.length; i++) {
            var keyValuePair = keyValuePairs[i].split('=');
            var paramName = keyValuePair[0];
            var paramValue = keyValuePair[1] || '';
            urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '));
        }
    }
    return urlParams;
}; // getUrlParams
<commit_msg>Switch to tmp23<commit_after>/**
 * @class Gistie
 * @classdesc pulls notebooks from GitHub gists and propagates cells on the page
 * @param {number} gistID Gist numeric id
 */
Gistie = function(gistID) {
  // Don't need oauthentication if only using gists
  this.gh = new Github({});

  // gist API
  this.gistAPI = this.gh.getGist(gistID);

  // Read the gist itself
  this.gistAPI.read(this._read.bind(this));

};

/**
 * String.includes polyfill
 */
if (!String.prototype.includes) {
  String.prototype.includes = function() {'use strict';
    return String.prototype.indexOf.apply(this, arguments) !== -1;
  };
}

/**
 * Implements the callback for a Github.gist.read, intended to be bound to
 * `this`, which is bound in the constructor (this._read.bind(this)) call to read
 * @param error
 * @param {Object} Github gist
 */
Gistie.prototype._read = function(err, gist) {
  this.gist = gist;
  console.log(this.gist);
  this.files = gist.files;

  for (var filename in gist.files) {
    if(!gist.files.hasOwnProperty(filename)) {
      continue;
    }

    var file = gist.files[filename];

    filename = filename.toLowerCase();

    if (filename.includes('.ipynb')) {
      this._renderFile(file, this.renderNotebook);
    } else if (filename.includes('.md')){
      this._renderFile(file, this.renderMarkdown);
    } else if (filename.includes('.rmd')) {
      this._renderFile(file, this.renderRMarkdown);
    }
  }
};

Gistie.prototype._renderFile = function(file, cb) {
  if (file.truncated) {
    console.log("File truncated, fetching raw URL");
    $.ajax({
      url: file.raw_url,
      success: cb.bind(this)
    });
  } else {
    console.log("File small enough to render straight from gist API");
    cb(file.content);
  }
};

/**
 * Tickles the notebook server's contents API to sneakily upload data
 *
 * resp = requests.put("http://127.0.0.1:8888/user/neNUk0HdyfGm/api/contents/that.py",
 *                     json={'type': 'file', 'format': 'text', 'content': "import this"})
 */
upload = function(base_server, filepath, content) {
  fetch(base_server + filepath, {
    method: 'put',
    body: JSON.stringify({
      type: 'file',
      format: 'text', // TODO: This is definitely an assumption...
      content: content
    }),
    headers: {
      'Accept': 'application/json'
    }
  });
};

Gistie.prototype.renderMarkdown = function(markdown) {
  var $container = $('#container');
  $container.empty();
  var renderer = new marked.Renderer();

  var kernel_name;

  // TODO: Something sensible about language detection
  // For now, just accept the last rendered code cell as the language
  // TODO: mapping from language -> kernel_name

  // Here we override to bring Thebe flavored cells
  renderer.code = function(code, language) {
    kernel_name = language;
    return '
' + code + '
\n';
  };

  marked.setOptions({
    renderer: renderer,
  });

  var html = marked(markdown);
  var el = $container.append(html);

  this.thebe = new Thebe({
    url: "https://tmp31.tmpnb.org",
    kernel_name: kernel_name || "python3"
  });

};

function splitFrontMatter(doc) {
  var re = /^(-{3}(?:\n|\r)([\w\W]+?)-{3})?([\w\W]*)*/;
  var results = re.exec(doc);

  return {
    "front": jsyaml.load(results[2]),
    "markdown": results[3]
  };

}

Gistie.prototype.renderRMarkdown = function(rmarkdown) {
  var $container = $('#container');
  $container.empty();

  var matter = splitFrontMatter(rmarkdown);

  var front = matter.front;
  var markdown = matter.markdown;

  var titleComponents = [];

  if (front.title) {
    $container.append('
' + front.title + '
');
    titleComponents.push(front.title);
  }
  if (front.author) {
    $container.append('
' + front.author + '
');
    titleComponents.push(front.author);
  }
  if (front.date) {
    $container.append('
' + front.date + '
');
    titleComponents.push(front.date);
  }

  document.title = titleComponents.join(' - ');

  var renderer = new marked.Renderer();

  // Here we override to bring Thebe flavored cells
  renderer.code = function(code, chunkHeader) {
    // TODO: validate chunkHeader
    // TODO: extract chunkOptions
    return '
' + code + '
\n';
  };

  marked.setOptions({
    renderer: renderer,
  });

  var html = marked(markdown);
  var el = $container.append(html);

  this.thebe = new Thebe({
    url: "https://tmp31.tmpnb.org",
    kernel_name: "ir"
  });

};

/**
 * Render a notebook on the DOM. Likely ugly.
 * @param {Object} notebook Jupyter Notebook document
 */
Gistie.prototype.renderNotebook = function(notebook) {
  // TODO: Check that it's really a notebook (existence of content key)
  console.log("Rendering notebook");

  notebook = JSON.parse(notebook);

  var $container = $('#container');
  $container.empty();

  var cell;

  if (notebook.hasOwnProperty('worksheets')) {
    // Slight conversion from < v4 notebook to v4
    notebook.cells = notebook.worksheets[0].cells;
    for (cellID = 0; cellID < notebook.cells.length; cellID++ ) {
      cell = notebook.cells[cellID];
      cell.source = cell.input;
    }
  }

  for (cellID = 0; cellID < notebook.cells.length; cellID++ ) {
    cell = notebook.cells[cellID];
    if (cell.source && cell.cell_type) {
      if (cell.cell_type == 'code') {
        var code;

        if (typeof cell.source === 'string') {
          code = cell.source;
        } else { // Assume list of source cells
          code = cell.source.join('');
        }

        // Raw
 cells with source for thebe to process
        $container.append('
' + code + '
\n');
      } else if (cell.cell_type == 'markdown') {
        var markdown;

        if (typeof cell.source === 'string') {
          markdown = cell.source;
        } else { // Assume list of source cells
          markdown = cell.source.join('');
        }

        // Little blocks of markdown everywhere
        var html = marked(markdown);
        var el = $container.append('
' + html + '
');

        // Render LaTeX
        //MathJax.Hub.Queue(["Typeset", MathJax.Hub, el[0]]);

      } else {
        console.log("Unknown cell type: " + cell.cell_type);
      }

    } else {
      console.log("No cell source and/or cell_type: ");
      console.log(cell);
    }
  }
  MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

  var kernel_name;
  try {
    kernel_name = notebook.metadata.kernelspec.name;
  } catch(e) {
    // If a kernel wasn't detected, go with python3
    kernel_name = "python3";
  }

  this.thebe = new Thebe({
    url: "https://tmp23.tmpnb.org",
    kernel_name: kernel_name || "python3"
  });
};

/**
 * Utility funciton to set up Gistie on the page
 */
gistexec = function( ) {
  var params = getUrlParams();

  if (!params.gistID) {
    return;
  }

  //Init MathJax
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"] ],
          displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
          processEscapes: true,
          processEnvironments: true
      },
      // Center justify equations in code and markdown cells. Elsewhere
      // we use CSS to left justify single line equations in code cells.
      displayAlign: 'center',
      "HTML-CSS": {
          availableFonts: [],
          imageFont: null,
          preferredFont: null,
          webFont: "STIX-Web",
          //styles: {'.MathJax_Display': {"margin": 0}},
          linebreaks: { automatic: true }
      }
  });
  MathJax.Hub.Configured();

  if (params.gistID) {
    return new Gistie(params.gistID);
  }
};

/**
 * Returns a bare object of the URL's query parameters.
 * You can pass just a query string rather than a complete URL.
 * The default URL is the current page.
 *
 * From: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
 */
var getUrlParams = function(url) {
    // http://stackoverflow.com/a/23946023/2407309
    if (typeof url == 'undefined') {
        url = window.location.search;
    }
    url = url.split('#')[0]; // Discard fragment identifier.
    var queryString = url.split('?')[1];
    if (!queryString) {
        if (url.search('=') !== false) {
            queryString = url;
        }
    }
    var urlParams = {};
    if (queryString) {
        var keyValuePairs = queryString.split('&');
        for (var i = 0; i < keyValuePairs.length; i++) {
            var keyValuePair = keyValuePairs[i].split('=');
            var paramName = keyValuePair[0];
            var paramValue = keyValuePair[1] || '';
            urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '));
        }
    }
    return urlParams;
}; // getUrlParams
<|endoftext|>


<commit_before>const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
const sourcemaps = require('gulp-sourcemaps');
const imagemin = require('gulp-imagemin');
const cache = require('gulp-cache');
const del = require('del');
const runSequence = require('run-sequence');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const ngAnnotate = require('gulp-ng-annotate');
const plumber = require('gulp-plumber');
const gnf = require('gulp-npm-files');
const image = require('gulp-image');
const pngquant = require('imagemin-pngquant');
const webstandards = require('gulp-webstandards');

gulp.task('default', () => {
  runSequence('clean:dist', 'copyNpmDependenciesOnly', 'copy', 'images', 'angularjs', 'watch');
});

gulp.task('clean:dist', () => {
  return del.sync(['dist']);
});

gulp.task('copyNpmDependenciesOnly', () => {
  gulp.src(gnf(), {base:'./'}).pipe(gulp.dest('./dist'));
});

gulp.task('scss', () => {
  return gulp.src('CSS/*.scss')
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(gulp.dest('dist/CSS'))
    .pipe(browserSync.reload({
      stream: true
    }));
});

gulp.task('images', () => {
  return gulp.src('IMG/**')
  .pipe(cache(imagemin({
            progressive: true,
            use: [pngquant()]
        })))
  .pipe(gulp.dest('dist/IMG'));
});

gulp.task('angularjs', () => {
  gulp.src(['JS/app.js', 'JS/**/*.js'])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist/JS'));
});

gulp.task('browserSync', () => {
  browserSync.init({
    server: {
      baseDir: 'dist'
    },
    reloadDelay: 1000,
    port: 8000
  });
});

gulp.task('copy', () => {
  return gulp
    .src(['index.html',
    '.htaccess',
    'JSON/**',
    'TEMPLATES/**'],
    {
      base: './'
    })
    .pipe(gulp.dest('dist/'));
});

gulp.task('watch', ['scss', 'browserSync'], () => {
  gulp.watch('CSS/*.scss', ['scss']);
  gulp.watch(['index.html', 'JSON/**', 'TEMPLATES/**'], ['copy']).on('change', browserSync.reload);
  gulp.watch('JS/**/*js', ['angularjs']).on('change', browserSync.reload);
});

gulp.task('webstandards', () => {
    return gulp.src('dist/**').pipe(webstandards());
});
<commit_msg>Make a build function for production<commit_after>const gulp = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
const sourcemaps = require('gulp-sourcemaps');
const imagemin = require('gulp-imagemin');
const cache = require('gulp-cache');
const del = require('del');
const runSequence = require('run-sequence');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const ngAnnotate = require('gulp-ng-annotate');
const plumber = require('gulp-plumber');
const gnf = require('gulp-npm-files');
const image = require('gulp-image');
const pngquant = require('imagemin-pngquant');
const webstandards = require('gulp-webstandards');

gulp.task('default', () => {
  runSequence('clean:dist', 'copyNpmDependenciesOnly', 'copy', 'images', 'angularjs', 'watch');
});

gulp.task('build', () =>  {
  runSequence('clean:dist', 'copyNpmDependenciesOnly', 'copy', 'images', 'angularjs');
});

gulp.task('clean:dist', () => {
  return del.sync(['dist']);
});

gulp.task('copyNpmDependenciesOnly', () => {
  gulp.src(gnf(), {base:'./'}).pipe(gulp.dest('./dist'));
});

gulp.task('scss', () => {
  return gulp.src('CSS/*.scss')
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(sass({
      outputStyle: 'compressed'
    }))
    .pipe(gulp.dest('dist/CSS'))
    .pipe(browserSync.reload({
      stream: true
    }));
});

gulp.task('images', () => {
  return gulp.src('IMG/**')
  .pipe(cache(imagemin({
            progressive: true,
            use: [pngquant()]
        })))
  .pipe(gulp.dest('dist/IMG'));
});

gulp.task('angularjs', () => {
  gulp.src(['JS/app.js', 'JS/**/*.js'])
    .pipe(plumber())
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist/JS'));
});

gulp.task('browserSync', () => {
  browserSync.init({
    server: {
      baseDir: 'dist'
    },
    reloadDelay: 1000,
    port: 8000
  });
});

gulp.task('copy', () => {
  return gulp
    .src(['index.html',
    '.htaccess',
    'JSON/**',
    'TEMPLATES/**'],
    {
      base: './'
    })
    .pipe(gulp.dest('dist/'));
});

gulp.task('watch', ['scss', 'browserSync'], () => {
  gulp.watch('CSS/*.scss', ['scss']);
  gulp.watch(['index.html', 'JSON/**', 'TEMPLATES/**'], ['copy']).on('change', browserSync.reload);
  gulp.watch('JS/**/*js', ['angularjs']).on('change', browserSync.reload);
});

gulp.task('webstandards', () => {
    return gulp.src('dist/**').pipe(webstandards());
});
<|endoftext|>


<commit_before>var canvas,context;
var stopGame=false;
var requestID;

// A cross-browser requestAnimationFrame and cancelAnimationFrame
// See https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
var requestAnimFrame = (function(){
		return window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function(callback){
			return window.setTimeout(callback, 1000 / 60);
		};
	})();

var cancelAnimFrame = (function(){
		return window.cancelAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function(){
			window.clearTimeout(requestID);
		};
	})();

var wall = function(x){
	this.x = x;
	this.width = 50;
	this.gapWidth = 100;
	this.upperBorder = Math.floor(Math.random()*375) + 25;
	this.lowerBorder = this.upperBorder + this.gapWidth;
	this.lowerHeight = 500 - this.lowerBorder;

	this.renew = function(){
		this.x += 1250;
		this.upperBorder = Math.floor(Math.random()*375) + 25;
		this.lowerBorder = this.upperBorder + this.gapWidth;
		this.lowerHeight = 500 - this.lowerBorder;
		step = step * 1.2;
		score++;
		};

	this.move = function(step){
		this.x -= step;
		if (this.x <= -this.width){
			this.renew();
		};
	}
};

function collision(me,obj){
		if ((me.x<=obj.x+obj.width) && (me.x+me.width>=obj.x) && ((me.y<=obj.upperBorder) || (me.y+me.height>=obj.lowerBorder))){
			return true;
		} else{
		return false;
	}
}

//Array of scene objects
var objects = new Array();
var step, score;
function init() {
	step = 2;
	score = 0;
	//Creating main character
	objects[0] = {
		x : 25,
		y : 225,
		height: 50,
		width: 50,
		myStep: 0,
		move : function(step){
			if (this.y+step<=450 && this.y+step>=0){
				this.y += step;
			};
		}
	};
	//Creating walls
	for (i=1;i<=5;i++){
		objects[i] = new wall(i*250);
	};
}

function updateScene(dt){
	for (i=1;i<=5;i++){
		objects[i].move(step);
	};
	//i'll leave it here for the first time
	objects[0].myStep = 0;
	if (38 in keysPressed) objects[0].myStep -= 150;
	if (40 in keysPressed) objects[0].myStep += 150;
	//Crappy...
	objects[0].move(step*0.9*objects[0].myStep*dt);
}

function drawObjectsInit(c){
	//Clean canvas
	c.fillStyle = "#FFFFFF";
	c.fillRect(0,0,800,500);

	//Main character
	c.fillStyle = "#FF0000";
	c.fillRect(objects[0].x,objects[0].y,objects[0].width,objects[0].height);

	//Walls
	c.fillStyle = "#000000";
	for (i=1;i<=5;i++){
		c.fillRect(objects[i].x,0,objects[i].width,objects[i].upperBorder);
		c.fillRect(objects[i].x,objects[i].lowerBorder,objects[i].width,objects[i].lowerHeight);
	}

	//Score
	c.fillStyle = "#0000FF";
	c.font = "25px Comic Sans MS";
	var scoreText = "Score: "+score.toString();
	c.fillText(scoreText,680,25);
};

function drawObjects(c){
	//Clean canvas
	c.fillStyle = "#FFFFFF";
	c.fillRect(0,0,800,500);

	//Main character
	if (objects[0].myStep > 0)
	{
		//up
		c.fillStyle = "#FFFFFF";
	}
	else
	{
		if (objects[0].myStep < 0)
		{
			//down
			c.fillStyle = "#FFFFFF";
		}
	}
	c.fillRect(objects[0].x,objects[0].y,objects[0].width,objects[0].height);
	c.fillStyle = "#FF0000";
	c.fillRect(objects[0].x,objects[0].y,objects[0].width,objects[0].height);

	//Walls
	c.fillStyle = "#000000";
	for (i=1;i<=5;i++){
		c.fillRect(objects[i].x,0,objects[i].width,objects[i].upperBorder);
		c.fillRect(objects[i].x,objects[i].lowerBorder,objects[i].width,objects[i].lowerHeight);
	}

	//Score
	c.fillStyle = "#0000FF";
	c.font = "25px Comic Sans MS";
	var scoreText = "Score: "+score.toString();
	c.fillText(scoreText,680,25);
};

var lastTime;
function mainLoop(){
	if (stopGame) return true;

	var now = Date.now();
    var dt = (now - lastTime) / 1000.0;

	updateScene(dt);
	drawObjects(context);
	for (i=0;i<=5;i++){
		if (collision(objects[0],objects[i])) {
			context.fillStyle = "#FF0000";
			context.font = "30px Comic Sans MS";
			context.fillText("Game Over!",350,250);
			return true;
		}
	}
	lastTime=now;
	requestID = requestAnimFrame(mainLoop);
}

//Input handling

var keysPressed = {};

addEventListener("keydown", function (e) {
	keysPressed[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
	delete keysPressed[e.keyCode];
}, false);

window.onload = function(){
canvas = document.getElementById('canvas');
context = canvas.getContext("2d");
document.getElementById("stop").onclick = function(){stopGame = true};
document.getElementById("again").onclick = function(){
	stopGame = true;
	if (requestID) {
       cancelAnimFrame(requestID);
       requestID = undefined;
    }
	init();
	drawObjectsInit(context);
	stopGame = false;
	mainLoop()
};
init();
drawObjectsInit(context);
mainLoop();
}
<commit_msg>Revert "Merge commit '51c3d81847362857f0134a66f23d4b5aba237f5a'"<commit_after>var canvas,context;
var stopGame=false;
var requestID;

// A cross-browser requestAnimationFrame and cancelAnimationFrame
// See https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
var requestAnimFrame = (function(){
		return window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function(callback){
			return window.setTimeout(callback, 1000 / 60);
		};
	})();

var cancelAnimFrame = (function(){
		return window.cancelAnimationFrame ||
		window.webkitRequestAnimationFrame ||
		window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame ||
		window.msRequestAnimationFrame ||
		function(){
			window.clearTimeout(requestID);
		};
	})();

var wall = function(x){
	this.x = x;
	this.dx = 0;
	this.width = 50;
	this.gapWidth = 100;
	this.upperBorder = Math.floor(Math.random()*375) + 25;
	this.lowerBorder = this.upperBorder + this.gapWidth;
	this.lowerHeight = 500 - this.lowerBorder;

	this.renew = function(){
		this.x += 1250;
		this.upperBorder = Math.floor(Math.random()*375) + 25;
		this.lowerBorder = this.upperBorder + this.gapWidth;
		this.lowerHeight = 500 - this.lowerBorder;
		step = step * 1.2;
		score++;
		};

	this.move = function(step){
		this.x -= step;
		this.dx = -step;
		if (this.x <= -this.width){
			this.renew();
		};
	}
};

function collision(me,obj){
		if ((me.x<=obj.x+obj.width) && (me.x+me.width>=obj.x) && ((me.y<=obj.upperBorder) || (me.y+me.height>=obj.lowerBorder))){
			return true;
		} else{
		return false;
	}
}

//Array of scene objects
var objects = new Array();
var step, score;
function init() {
	step = 2;
	score = 0;
	//Creating main character
	objects[0] = {
		x : 25,
		dx : 0,
		y : 225,
		dy : 0,
		height: 50,
		width: 50,
		myStep: 0,
		move : function(step){
			if (this.y+step<=450 && this.y+step>=0){
				this.y += step;
				this.dy = step;
			};
		}
	};
	//Creating walls
	for (i=1;i<=5;i++){
		objects[i] = new wall(i*250);
	};
}

function updateScene(dt){
	for (i=1;i<=5;i++){
		objects[i].move(step);
	};
	//i'll leave it here for the first time
	objects[0].myStep = 0;
	if (38 in keysPressed) objects[0].myStep -= 150;
	if (40 in keysPressed) objects[0].myStep += 150;
	//Crappy...
	objects[0].move(Math.round(step*0.9*objects[0].myStep*dt));
}

function drawObjectsInit(c){
	//Clean canvas
	c.fillStyle = "#FFFFFF";
	c.fillRect(0,0,800,500);

	//Main character
	c.fillStyle = "#FF0000";
	c.fillRect(objects[0].x,objects[0].y,objects[0].width,objects[0].height);

	//Walls
	c.fillStyle = "#000000";
	for (i=1;i<=5;i++){
		c.fillRect(objects[i].x,0,objects[i].width,objects[i].upperBorder);
		c.fillRect(objects[i].x,objects[i].lowerBorder,objects[i].width,objects[i].lowerHeight);
	}

	//Score
	c.fillStyle = "#0000FF";
	c.font = "25px Comic Sans MS";
	var scoreText = "Score: "+score.toString();
	c.fillText(scoreText,680,25);
};

function drawObjects(c){
	//Clean canvas
	//c.fillStyle = "#FFFFFF";
	//c.fillRect(0,0,800,500);

	//Main character
	if (objects[0].dy > 0)
	{
	    //down
	    c.fillStyle = "#FFFFFF";
	    c.fillRect(objects[0].x,objects[0].y-objects[0].dy,objects[0].width,objects[0].dy);
	    c.fillStyle = "#FF0000";
	    c.fillRect(objects[0].x,objects[0].y+objects[0].height-objects[0].dy,objects[0].width,objects[0].dy);
	}
	else
	{
		if (objects[0].dy < 0)
		{
			//up
			c.fillStyle = "#FFFFFF";
			c.fillRect(objects[0].x,objects[0].y+objects[0].height-objects[0].dy,objects[0].width,objects[0].dy);
			c.fillStyle = "#FF0000";
			c.fillRect(objects[0].x,objects[0].y-objects[0].dy,objects[0].width,objects[0].dy);
		}
	}
	/*c.fillRect(objects[0].x,objects[0].y,objects[0].width,objects[0].height);
	c.fillStyle = "#FF0000";
	c.fillRect(objects[0].x,objects[0].y,objects[0].width,objects[0].height);*/

	//Walls
	c.fillStyle = "#FFFFFF";
	for (i=1;i<=5;i++){
		c.fillRect(objects[i].x+objects[0].width-objects[i].dx,0,objects[i].dx,objects[i].upperBorder);
		c.fillRect(objects[i].x+objects[0].width-objects[i].dx,objects[i].lowerBorder,objects[i].dx,objects[i].lowerHeight);
	}
	c.fillStyle = "#000000";
	for (i=1;i<=5;i++){
		c.fillRect(objects[i].x,0,objects[i].dx,objects[i].upperBorder);
		c.fillRect(objects[i].x,objects[i].lowerBorder,objects[i].dx,objects[i].lowerHeight);
	}

	//Score
	c.fillStyle = "#0000FF";
	c.font = "25px Comic Sans MS";
	var scoreText = "Score: "+score.toString();
	c.fillText(scoreText,680,25);
};

var lastTime;
function mainLoop(){
	if (stopGame) return true;

	var now = Date.now();
    var dt = (now - lastTime) / 1000.0;

	updateScene(dt);
	drawObjects(context);
	for (i=0;i<=5;i++){
		if (collision(objects[0],objects[i])) {
			context.fillStyle = "#FF0000";
			context.font = "30px Comic Sans MS";
			context.fillText("Game Over!",350,250);
			return true;
		}
	}
	lastTime=now;
	requestID = requestAnimFrame(mainLoop);
}

//Input handling

var keysPressed = {};

addEventListener("keydown", function (e) {
	keysPressed[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
	delete keysPressed[e.keyCode];
}, false);

window.onload = function(){
canvas = document.getElementById('canvas');
context = canvas.getContext("2d");
document.getElementById("stop").onclick = function(){stopGame = true};
document.getElementById("again").onclick = function(){
	stopGame = true;
	if (requestID) {
       cancelAnimFrame(requestID);
       requestID = undefined;
    }
	init();
	drawObjectsInit(context);
	stopGame = false;
	mainLoop()
};
init();
drawObjectsInit(context);
mainLoop();
}
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:coverphoto.jquery.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      dist: {
        src: ['<banner:meta.banner>', '<file_strip_banner:build/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    min: {
      dist: {
        src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    qunit: {
      files: ['test/**/*.html']
    },
    lint: {
      files: ['grunt.js', 'test/**/*.js']
    },
    watch: {
      files: ['<config:lint.files>','<config:coffeelint.app.files>'],
      tasks: 'coffee lint coffeelint qunit'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    uglify: {},
    coffee: {
      compile: {
        files: {
          'build/coverphoto.js': ['<config:coffeelint.app.files>']
        }
      }
    },
    coffeelint: {
      app: {
        files: ['src/**/*.coffee']
      }
    },
    eco_amd: {
      files: 'src/templats/**/*.eco'
    }
  });

  // Default task.
  grunt.registerTask('default', 'eco_amd lint qunit concat min');
  grunt.loadNpmTasks('grunt-contrib');
  grunt.loadNpmTasks('grunt-coffeelint');
  grunt.loadNpmTasks('grunt-eco-amd');

};
<commit_msg>Adding jst, concat and clean tasks<commit_after>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:coverphoto.jquery.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      dist: {
        src: ['<banner:meta.banner>', '<file_strip_banner:build/<%= pkg.name %>.js>'],
        dest: 'dist/<%= pkg.name %>.js'
      },
      app: {
        src: ['build/tmp/coverphoto-templates.js', 'build/tmp/coverphoto-plugin.js'],
        dest: 'build/coverphoto.js'
      }
    },
    min: {
      dist: {
        src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    qunit: {
      files: ['test/**/*.html']
    },
    lint: {
      files: ['grunt.js', 'test/**/*.js']
    },
    watch: {
      files: ['<config:lint.files>','<config:coffeelint.app.files>'],
      tasks: 'coffee jst concat:app clean:app lint coffeelint qunit'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    uglify: {},
    coffee: {
      compile: {
        files: {
          'build/tmp/coverphoto-plugin.js': ['<config:coffeelint.app.files>']
        }
      }
    },
    coffeelint: {
      app: {
        files: ['src/**/*.coffee']
      }
    },
    jst: {
      app: {
        options: {
          namespace: 'coverphotoTemplates'
        },
        files: {
          'build/tmp/coverphoto-templates.js': ['src/templates/**/*.jst']
        }
      }
    },
    clean: {
      app: {
        src: ["build/tmp"]
      }
    }
  });

  // Default task.
  grunt.registerTask('default', 'coffee jst concat:app clean:app lint qunit concat:dist min');
  grunt.loadNpmTasks('grunt-contrib');
  grunt.loadNpmTasks('grunt-coffeelint');
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var server = require('gulp-express');
var browserify = require('gulp-browserify');

gulp.task('lint', function() {
    return gulp.src('lib/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('scripts', function() {
    return gulp.src('lib/main.js')
        .pipe(browserify())
        .pipe(rename('Aubengine.js'))
        .pipe(gulp.dest('dist'))
        .pipe(rename('Aubengine.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

gulp.task('watch', function() {
  gulp.watch('lib/*.js', ['scripts']);
});

gulp.task('default', ['scripts', 'lint', 'watch']);
<commit_msg>changed main compilation<commit_after>var gulp       = require('gulp');
var jshint     = require('gulp-jshint');
var sass       = require('gulp-sass');
var concat     = require('gulp-concat');
var uglify     = require('gulp-uglify');
var rename     = require('gulp-rename');
var server     = require('gulp-express');
var browserify = require('gulp-browserify');

gulp.task('lint', function() {
    return gulp.src('lib/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('scripts', function() {
    return gulp.src('lib/Aubengine.js')
        .pipe(rename('Aubengine.js'))
        .pipe(browserify())
        .pipe(gulp.dest('dist'))
        .pipe(rename('Aubengine.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist'));
});

gulp.task('watch', function() {
  gulp.watch('lib/*.js', ['scripts']);
});

gulp.task('default', ['scripts', 'lint', 'watch']);
<|endoftext|>


<commit_before>/* Create Stand Alone waterfall diagrams and integrate on your workflow/CI.

Author : Vignesh Shanmugam
License :MIt

data - Pass the Resource timings data as array in the below format,
data : [
	{
		URL : 'ww.example.com/main.css',
		dnsStart : '', ....
	},
	{

	}
]

*/

import NavTiming from './plugins/navtimings';
import ResTiming from './plugins/restimings';

(function(w,d){
	var COLORS = {
		blocked: '#cdcdcd',
		dns: '#1f7c83',
		tcp: '#e58226',
		ssl: '#D566DF',
		ttfb: '#5fdd5f',
		download: '#4189d7',
		error : '#FF0000'
	}
	var p = w.performance || w.msPerformance || w.webkitPerformance || w.mozPerformance,
		entries = [],
		navTiming = NavTiming(d,p);

	//Current URL - Navigation Timing
	if(navTiming){
		entries.push(navTiming);
	}
	//Resources - Resource Timing
	entries = ResTiming(p,entries);
	drawWaterfall(entries);

	function drawWaterfall(entries){

	}

})(window,window.document);
<commit_msg>IIFE Issue<commit_after>/* Create Stand Alone waterfall diagrams and integrate on your workflow/CI.

Author : Vignesh Shanmugam
License :MIt

data - Pass the Resource timings data as array in the below format,
data : [
	{
		URL : 'ww.example.com/main.css',
		dnsStart : '', ....
	},
	{

	}
]

*/

import NavTiming from './plugins/navtimings';
import ResTiming from './plugins/restimings';

;(function(w,d){
	var COLORS = {
		blocked: '#cdcdcd',
		dns: '#1f7c83',
		tcp: '#e58226',
		ssl: '#D566DF',
		ttfb: '#5fdd5f',
		download: '#4189d7',
		error : '#FF0000'
	}
	var p = w.performance || w.msPerformance || w.webkitPerformance || w.mozPerformance,
		entries = [],
		navTiming = NavTiming(d,p);

	//Current URL - Navigation Timing
	if(navTiming){
		entries.push(navTiming);
	}
	//Resources - Resource Timing
	entries = ResTiming(p,entries);
	drawWaterfall(entries);

	function drawWaterfall(entries){

	}

})(window,window.document);
<|endoftext|>