<commit_before>(function() {

  this.Player = function() {

    var defaults = {
        videoId: null,
        playerClass: 'custom-player',
        width: 480,
        height: 270,
        autoPlay: null,
        controls: null,
        relatedVideos: 0,
        showInfo: null,
        wrap: null,
        wrapClass: 'custom-player-wrapper',
        playBtn: null,
        playBtnClass: 'play-btn',
        playBtnText: 'Play',
        pauseBtn: null,
        pauseBtnClass: 'pause-btn',
        pauseBtnText: 'Pause',
        mute: null,
        placement: null,
        videoContainer: null
    };

    // Add our defaults above into a global array of options
    if ( arguments[0] && typeof arguments[0] === 'object' ) {
      this.options = extendDefaults( defaults, arguments[0] );
    }

    if( readyState() ) {
      this.init();
    } else {
      // Run Player.init()
      document.addEventListener( 'DOMContentLoaded', ( this.init ).bind( this ), false);
    }

  };

  Player.prototype.init = function() {

    var mode;
    if ( this.options.element ) {
      mode = 'exists';
      this.video = this.videoExists();
    /*} else if ( this.options.wrap === 1 ) {
      mode = 'wrap';
      //this.addClasses(this.wrapper, ['hello', 'world']);
      this.video = this.videoGet(); */
    } else {
      mode = 'generate';
      this.video = this.videoGenerate();
    }

    this.appendYTDiv();

    if ( this.options.playBtn || this.options.pauseBtn ) {
      this.video = this.customControls( mode );
    }

    // Place Video on the page
    this.appendVideo();
    this.YTGenerate();
    this.assignListeners();

  };

  Player.prototype.appendYTDiv = function() {

    if ( this.options.videoContainer ) {
      this.youtubeDiv = this.video.querySelector('.' + this.options.videoContainer );
    } else {
      this.youtubeDiv = document.createElement( 'div' );
      this.video.appendChild( this.youtubeDiv );
    }

  };

  Player.prototype.YTGenerate = function() {

    var this_ = this,
        options = this_.options;

    var callback = ( function() {
      this_.player = new YT.Player( this.youtubeDiv, {
        videoId: options.videoId,
        height: options.height,
        width: options.width,
        playerVars: {
          autoplay: options.autoPlay,
          controls: options.controls,
          rel: options.relatedVideos,
          showinfo: options.showInfo,
        },
        events: {
          onReady: ( this_._onPlayerReady ).bind( this ),
          onStateChange: ( this_._onStateChange ).bind( this )
        }
      });

    }).bind( this );

    // Test if the youtube api is loaded
    if ( 'YT' in window ) {
      if ( window.YT.loaded === 0 ) {
        var oldonYouTubePlayerAPIReady = window.onYouTubePlayerAPIReady;
        window.onYouTubePlayerAPIReady = function() {
          if ( window.onYouTubePlayerAPIReady ) {
            oldonYouTubePlayerAPIReady();
          }
          callback();
        };
      } else {
        callback();
      }
    } else {
      window.YT = {
        loaded: 0
      };

      window.onYouTubePlayerAPIReady = function() {
        callback();
      };

      var tag = document.createElement( 'script' );
      var firstScriptTag = document.getElementsByTagName( 'script' )[0];

      tag.src = 'https://www.youtube.com/iframe_api';
      firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
    }

  };

  // Controls
  Player.prototype.customControls = function( mode ) {
    // Play button
    if ( !this.options.playBtn.nodeName ) {
      this.playBtn = this.playBtnGenerate();
    } else {
      this.playBtn = this.playBtnExists();
    }

    // Pause button
    if ( !this.options.pauseBtn.nodeName ) {
      this.pauseBtn = this.pauseBtnGenerate();
    } else {
      this.pauseBtn = this.pauseBtnExists();
    }

    // Custom Controls
    if ( this.options.playBtn || this.options.pauseBtn ) {
      var control = document.createElement( 'div' );
      control.className = 'custom-controls';

      if ( this.playBtn ) {
        control.appendChild( this.playBtn );
      }
      if ( this.pauseBtn ) {
        control.appendChild( this.pauseBtn );
      }
      // Add controls to the generated video
      this.video.appendChild( control );
    }

    return this.video;

  };

  // Play Button
  Player.prototype.playBtnExists = function() {

    return this.options.playBtnClass;

  };
  Player.prototype.playBtnGenerate = function() {

    var el = document.createElement( 'button' );
    el.className = this.options.playBtnClass;
    el.innerHTML = this.options.playBtnText;

    return el;

  };

  // Pause Button
  Player.prototype.pauseBtnExists = function() {

    return this.options.pauseBtnClass;

  };
  Player.prototype.pauseBtnGenerate = function() {

    var el = document.createElement( 'button' );
    el.className = this.options.pauseBtnClass;
    el.innerHTML = this.options.pauseBtnText;

    return el;

  };

  // Generate the class
  Player.prototype.videoGenerate = function() {

    var el = document.createElement( 'div' );
    el.id = this.options.videoId;
    el.className = this.options.playerClass;

    return el;

  };

  Player.prototype.videoExists = function() {

    return this.options.element;

  };

  // Player.prototype.videoGet = function() {
  //   return document.querySelector( this.options.wrapClass );
  // };

  Player.prototype.appendVideo = function() {

    document.body.appendChild( this.video );

  };

  // Events

  // Listeners
  Player.prototype.assignListeners = function() {

    this.video.addEventListener('click', function( event ) {

      if ( event.target.nodeName === 'BUTTON' ) {
        var matches = matchesPolyfill();
        if ( event.target[ matches ]( '.' + this.options.playBtnClass ) ) {
          this.player.playVideo();
        } else  if ( event.target[ matches ]( '.' + this.options.pauseBtnClass ) ) {
          this.player.pauseVideo();
        }
      }
    }.bind( this ));

  };

  // Player ready
  Player.prototype._onPlayerReady = function( event ) {

    if ( this.options.mute === 1 ) {
      event.target.mute();
    }

  };
  // Player state change
  Player.prototype._onStateChange = function( event ) {};

  // Private Methods

  // Build the necessary markup
  // and inject it into the document if needed
  Player.prototype.generateEl = function( el, id, className ) {

    var docFrag, element;

    docFrag = document.createDocumentFragment();
    element = document.createElement( el );

    if ( id ) {
      element.id = id;
    }
    if ( className ) {
      element.className = className;
    }

    docFrag.appendChild( element );

    if ( this.options.placement !== null ) {
      var selector = document.querySelector( this.options.placement );
      if ( !selector ) { throw new selectorError( selector ); }
      selector.appendChild( docFrag );
    } else {
      document.body.appendChild( docFrag );
    }

    function selectorError( value ) {

      this.message = 'Make sure your selector is on the page';
      this.toString = function() {
        return this.value + ' ' + this.message;
      };
    }

    return element;

  };

  // Utility method to extend defaults with user options
  function extendDefaults( source, properties ) {

    var property;
    for ( property in properties ) {
      if ( properties.hasOwnProperty( property ) ) {
        source[ property ] = properties[ property ];
      }
    }
    return source;

  }

  function matchesPolyfill( el ) {

    var matches = document.body.matches || document.body.webkitMatchesSelector || document.body.msMatchesSelector;
    return matches.name;

  }

  // Look for all elements that has a data-video-id
  // and populate an array
  var getStandalone = function() {
    var playerData = document.querySelectorAll( '[data-video-id]' );
    var standaloneVideos = [];

    // Cut up the array and spit out the available videos
    [].slice.call( playerData ).forEach(function( vid ) {
      var options = JSON.parse( JSON.stringify( vid.dataset ) );
      vid.id = options.videoId;
      options.element = vid;
      standaloneVideos.push( new Player( options ) );
    });

    return standaloneVideos;
  };

  function readyState() {
    return document.readyState === 'complete' || document.readyState === 'interactive';
  }

  if( readyState() ) {
    getStandalone();
  } else {
    document.addEventListener( 'DOMContentLoaded', getStandalone, false);
  }

})();
<commit_msg>Syntax and spacing<commit_after>(function() {

  this.Player = function() {

    var defaults = {
        videoId: null,
        playerClass: 'custom-player',
        width: 480,
        height: 270,
        autoPlay: null,
        controls: null,
        relatedVideos: 0,
        showInfo: null,
        wrap: null,
        wrapClass: 'custom-player-wrapper',
        playBtn: null,
        playBtnClass: 'play-btn',
        playBtnText: 'Play',
        pauseBtn: null,
        pauseBtnClass: 'pause-btn',
        pauseBtnText: 'Pause',
        mute: null,
        placement: null,
        videoContainer: null
    };

    // Add our defaults above into a global array of options
    if ( arguments[0] && typeof arguments[0] === 'object' ) {
      this.options = extendDefaults( defaults, arguments[0] );
    }

    if( readyState() ) {
      this.init();
    } else {
      // Run Player.init()
      document.addEventListener( 'DOMContentLoaded', ( this.init ).bind( this ), false);
    }

  };

  Player.prototype.init = function() {

    var mode;
    if ( this.options.element ) {
      mode = 'exists';
      this.video = this.videoExists();
    /*} else if ( this.options.wrap === 1 ) {
      mode = 'wrap';
      //this.addClasses(this.wrapper, ['hello', 'world']);
      this.video = this.videoGet(); */
    } else {
      mode = 'generate';
      this.video = this.videoGenerate();
    }

    this.appendYTDiv();

    if ( this.options.playBtn || this.options.pauseBtn ) {
      this.video = this.customControls( mode );
    }

    // Place Video on the page
    this.appendVideo();
    this.YTGenerate();
    this.assignListeners();

  };

  Player.prototype.appendYTDiv = function() {

    if ( this.options.videoContainer ) {
      this.youtubeDiv = this.video.querySelector('.' + this.options.videoContainer );
    } else {
      this.youtubeDiv = document.createElement( 'div' );
      this.video.appendChild( this.youtubeDiv );
    }

  };

  Player.prototype.YTGenerate = function() {

    var this_ = this,
        options = this_.options;

    var callback = ( function() {
      this_.player = new YT.Player( this.youtubeDiv, {
        videoId: options.videoId,
        height: options.height,
        width: options.width,
        playerVars: {
          autoplay: options.autoPlay,
          controls: options.controls,
          rel: options.relatedVideos,
          showinfo: options.showInfo
        },
        events: {
          onReady: ( this_._onPlayerReady ).bind( this ),
          onStateChange: ( this_._onStateChange ).bind( this )
        }
      });

    }).bind( this );

    // Test if the youtube api is loaded
    if ( 'YT' in window ) {
      if ( window.YT.loaded === 0 ) {
        var oldonYouTubePlayerAPIReady = window.onYouTubePlayerAPIReady;
        window.onYouTubePlayerAPIReady = function() {
          if ( window.onYouTubePlayerAPIReady ) {
            oldonYouTubePlayerAPIReady();
          }
          callback();
        };
      } else {
        callback();
      }
    } else {
      window.YT = {
        loaded: 0
      };

      window.onYouTubePlayerAPIReady = function() {
        callback();
      };

      var tag = document.createElement( 'script' );
      var firstScriptTag = document.getElementsByTagName( 'script' )[0];

      tag.src = 'https://www.youtube.com/iframe_api';
      firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
    }

  };

  // Controls
  Player.prototype.customControls = function( mode ) {
    // Play button
    if ( !this.options.playBtn.nodeName ) {
      this.playBtn = this.playBtnGenerate();
    } else {
      this.playBtn = this.playBtnExists();
    }

    // Pause button
    if ( !this.options.pauseBtn.nodeName ) {
      this.pauseBtn = this.pauseBtnGenerate();
    } else {
      this.pauseBtn = this.pauseBtnExists();
    }

    // Custom Controls
    if ( this.options.playBtn || this.options.pauseBtn ) {
      var control = document.createElement( 'div' );
      control.className = 'custom-controls';

      if ( this.playBtn ) {
        control.appendChild( this.playBtn );
      }
      if ( this.pauseBtn ) {
        control.appendChild( this.pauseBtn );
      }
      // Add controls to the generated video
      this.video.appendChild( control );
    }

    return this.video;

  };

  // Play Button
  Player.prototype.playBtnExists = function() {

    return this.options.playBtnClass;

  };
  Player.prototype.playBtnGenerate = function() {

    var el = document.createElement( 'button' );
    el.className = this.options.playBtnClass;
    el.innerHTML = this.options.playBtnText;

    return el;

  };

  // Pause Button
  Player.prototype.pauseBtnExists = function() {

    return this.options.pauseBtnClass;

  };
  Player.prototype.pauseBtnGenerate = function() {

    var el = document.createElement( 'button' );
    el.className = this.options.pauseBtnClass;
    el.innerHTML = this.options.pauseBtnText;

    return el;

  };

  // Generate the class
  Player.prototype.videoGenerate = function() {

    var el = document.createElement( 'div' );
    el.id = this.options.videoId;
    el.className = this.options.playerClass;

    return el;

  };

  Player.prototype.videoExists = function() {

    return this.options.element;

  };

  Player.prototype.videoGet = function() {

    return document.querySelector( this.options.wrapClass );

  };

  Player.prototype.appendVideo = function() {

    document.body.appendChild( this.video );

  };

  // Events

  // Listeners
  Player.prototype.assignListeners = function() {

    this.video.addEventListener('click', function( event ) {

      if ( event.target.nodeName === 'BUTTON' ) {
        var matches = matchesPolyfill();
        if ( event.target[ matches ]( '.' + this.options.playBtnClass ) ) {
          this.player.playVideo();
        } else  if ( event.target[ matches ]( '.' + this.options.pauseBtnClass ) ) {
          this.player.pauseVideo();
        }
      }
    }.bind( this ));

  };

  // Player ready
  Player.prototype._onPlayerReady = function( event ) {

    if ( this.options.mute === 1 ) {
      event.target.mute();
    }

  };
  // Player state change
  Player.prototype._onStateChange = function( event ) {};

  // Private Methods

  // Build the necessary markup
  // and inject it into the document if needed
  Player.prototype.generateEl = function( el, id, className ) {

    var docFrag, element;

    docFrag = document.createDocumentFragment();
    element = document.createElement( el );

    if ( id ) {
      element.id = id;
    }
    if ( className ) {
      element.className = className;
    }

    docFrag.appendChild( element );

    if ( this.options.placement !== null ) {
      var selector = document.querySelector( this.options.placement );
      if ( !selector ) { throw new selectorError( selector ); }
      selector.appendChild( docFrag );
    } else {
      document.body.appendChild( docFrag );
    }

    function selectorError( value ) {

      this.message = 'Make sure your selector is on the page';
      this.toString = function() {
        return this.value + ' ' + this.message;
      };
    }

    return element;

  };

  // Utility method to extend defaults with user options
  function extendDefaults( source, properties ) {

    var property;
    for ( property in properties ) {
      if ( properties.hasOwnProperty( property ) ) {
        source[ property ] = properties[ property ];
      }
    }
    return source;

  }

  function matchesPolyfill( el ) {

    var matches = document.body.matches || document.body.webkitMatchesSelector || document.body.msMatchesSelector;
    return matches.name;

  }

  // Look for all elements that has a data-video-id
  // and populate an array
  var getStandalone = function() {
    var playerData = document.querySelectorAll( '[data-video-id]' );
    var standaloneVideos = [];

    // Cut up the array and spit out the available videos
    [].slice.call( playerData ).forEach(function( vid ) {
      var options = JSON.parse( JSON.stringify( vid.dataset ) );
      vid.id = options.videoId;
      options.element = vid;
      standaloneVideos.push( new Player( options ) );
    });

    return standaloneVideos;
  };

  function readyState() {
    return document.readyState === 'complete' || document.readyState === 'interactive';
  }

  if( readyState() ) {
    getStandalone();
  } else {
    document.addEventListener( 'DOMContentLoaded', getStandalone, false);
  }

})();
<|endoftext|>


<commit_before>module.exports = function(config) {
	var async = require('async')
	  , crypto = require('crypto')
    , async = require('async')
    , request = require('request')
    , mongoose = require('mongoose')
    , moment = require('moment')
    , User = require('../models/user')
    , Device = require('../models/device')
    , Layer = require('../models/layer')
    , Feature = require('../models/feature')
    , Location = require('../models/location')
    , api = require('../api')
	  , fs = require('fs-extra');

	var timeout = 200000;

	var username = 'df00d591feb2c5478db826dfb5199dbb';
  var p***REMOVED***word = 'df00d591feb2c5478db826dfb5199dbb';
  var uid = '0e748bc5d2bacdf167731d93e30c21fc';

  var cryptoAlgorithm = 'aes256';
  var decipher = crypto.createDecipher(cryptoAlgorithm, config.key);
  username = decipher.update(username, 'hex', 'utf8') + decipher.final('utf8');
  decipher = crypto.createDecipher(cryptoAlgorithm, config.key);
  p***REMOVED***word = decipher.update(p***REMOVED***word, 'hex', 'utf8') + decipher.final('utf8');
  decipher = crypto.createDecipher(cryptoAlgorithm, config.key);
  uid = decipher.update(uid, 'hex', 'utf8') + decipher.final('utf8');

	var baseUrl = config.baseUrl;
	var token;

	var lastAttachmentTime = {};
	var lastFeatureTime = {};

	var featureLayers;

	var headers = {};

	var getToken = function(done) {
    console.log('getting token');

    var options = {
      url: baseUrl + '/api/login',
      json: {
        username: username,
        uid: uid,
        p***REMOVED***word: p***REMOVED***word
      }
    };

    request.post(options, function(err, res, body) {
      if (err) return done(err);

      if (res.statusCode != 200) return done(new Error('Error hitting login api, respose code: ' + res.statusCode));
      token = body.token;
      headers['Authorization'] = 'Bearer ' + body.token;
      done();
    });
  }

	var getLastAttachmentSyncTime = function(done) {
		fs.readJson("rage/.attachment_sync.json", function(err, readInLastAttachmentTime) {
	    lastAttachmentTime = readInLastAttachmentTime || {};
	    console.log('last', lastAttachmentTime);
	    done();
	  });

	}

	var getAllFeatureLayers = function(callback) {
		Layer.getLayers(function (err, layers) {
			// filter out non feature layers
			featureLayers = [];
			featureLayers = layers.filter(function(layer) {
				return layer.type == "Feature";
			});
      console.info('Syncing features for ' + featureLayers.length + ' layers');
      callback();
    });
	}

	var getFeaturesSince = function(startTime, layer, callback) {
		var options = {	};

		if (startTime) {
			var startTimePlusOne = moment(startTime).add('ms', 1);

			options.filter = {
				startDate: startTimePlusOne
			};
		}
		console.info('Getting features for layer ', layer);
		new api.Feature(layer).getAll(options, callback);
	}

	var getAttachmentsFromFeature = function(feature) {
		return feature.attachments || [];
	}

	var sortFeaturesByTimestamp = function(features) {
		return features.sort(function(a, b) {
			if (moment(a.properties.timestamp).isBefore(b.properties.timestamp))
		     return 1;
		  if (moment(a.properties.timestamp).isAfter(b.properties.timestamp))
		     return -1;
		  // a must be equal to b
		  return 0;
		});
	}

	var writeLastSyncTime = function(done) {
		fs.writeJson("rage/.attachment_sync.json", lastFeatureTime, done);
	}

	var appendErrorFile = function(string) {
		fs.writeJson("rage/.attachment_sync_errors.json", string, done);
	}

	// if this feature time is newer than we currently have
	// update the last feature time
	var updateLastFeatureTime = function(feature, layer) {
		if (feature.properties.timestamp) {
      var featureTime = moment(feature.properties.timestamp);
      if (!lastFeatureTime[layer.collectionName] || featureTime.isAfter(lastFeatureTime[layer.collectionName])) {
        lastFeatureTime[layer.collectionName] = featureTime;
      }
    }
	}

	var sequentiallySyncAttachments = function(features, layer, done) {

		console.info('syncing layer ' + layer.name);
		console.info('Sequentially syncing for ' + features.length + ' features');

		async.eachSeries(features, function(feature, done) {

			// get the attachments
			var attachments = getAttachmentsFromFeature(feature);

			var localDone = done;

			// sync each attachment
			pullAttachmentsCallbackWhenComplete(feature, layer, attachments, function(err) {
				if (!err) {
					console.info('successfully synced attachments for feature ' + feature.id + ' time is: ' + feature.properties.timestamp);
					updateLastFeatureTime(feature, layer);
				}
				localDone(err);
			});

		}, function(err) {
			done();
		});
	}

	var pullAttachmentsCallbackWhenComplete = function(feature, layer, attachments, callback) {
		console.info("syncing " + attachments.length + " attachments");
		async.eachSeries(feature.attachments, function(attachment, done) {

			var url = baseUrl + '/FeatureServer/'+
				layer.id + '/features/' +
				feature.id + '/attachments/' +
				attachment._id + '?access_token=' + token;
			var r = request(url);
			r.on('response', function (resp) {
				console.info('attachment response status code is ' + resp.statusCode);
				if (resp.statusCode == 200) {
				  r.pipe(fs.createWriteStream(config.attachmentBase + '/' + attachment.relativePath));
				  console.info('write the file for url ' + url + ' to ' + config.attachmentBase + '/' + attachment.relativePath);
				  done();
				} else if (resp.statusCode == 404) {
					// uhhh no data, hmmm
					console.info('no data for ' + url);
					done();
				} else {
					console.info('failed to sync with error code ' + resp.statusCode + ' url is ' + url);
					done(new Error('something bad happend'));
				}
			});
			r.on('error', function(resp) {
				done(new Error('more bad stuff happened'));
			});
		},
		function(err) {
			console.info(' error ', err);
			callback(err);
		});
	}

	var syncAttachments = function(done) {

		// global featureLayers is all the layers
		// loop the layers, get all the features for each layer then pull the
		// attachments for each feature

		async.eachSeries(featureLayers,
      function(layer, done) {
      	console.log('syncing attachments since ' + lastAttachmentTime[layer.collectionName]);
				// use that time to get the features since then
				var featuresToSync;
				getFeaturesSince(lastAttachmentTime[layer.collectionName], layer, function(features) {
					featuresToSync = features;
					console.log("features to sync is " + featuresToSync.length);
					// sort the features by timestamp
					featuresToSync = sortFeaturesByTimestamp(featuresToSync);

					sequentiallySyncAttachments(featuresToSync, layer, done);
				});
			},
			function(err) {
				done();
			}
		);
	}

	var doIt = function() {

		var token;

		  console.log('pulling data');

		  async.series({
		  	lastTime: getLastAttachmentSyncTime,
		    token: getToken,
		    layers: getAllFeatureLayers,
		    attachments: syncAttachments
		  },
		  function(err, results) {
		  	console.info('done syncing, setting up timeout');
			  writeLastSyncTime();
		    // all done each ran in order, results is now equal to: {token: 1, features: 2, etc...}
		    setTimeout(doIt, timeout);
		  });
	}

	doIt();
}<commit_msg>mkdirs before writing to the file<commit_after>module.exports = function(config) {
	var async = require('async')
	  , crypto = require('crypto')
    , async = require('async')
    , request = require('request')
    , mongoose = require('mongoose')
    , moment = require('moment')
    , User = require('../models/user')
    , Device = require('../models/device')
    , Layer = require('../models/layer')
    , Feature = require('../models/feature')
    , Location = require('../models/location')
    , api = require('../api')
    , require('path')
	  , fs = require('fs-extra');

	var timeout = 200000;

	var username = 'df00d591feb2c5478db826dfb5199dbb';
  var p***REMOVED***word = 'df00d591feb2c5478db826dfb5199dbb';
  var uid = '0e748bc5d2bacdf167731d93e30c21fc';

  var cryptoAlgorithm = 'aes256';
  var decipher = crypto.createDecipher(cryptoAlgorithm, config.key);
  username = decipher.update(username, 'hex', 'utf8') + decipher.final('utf8');
  decipher = crypto.createDecipher(cryptoAlgorithm, config.key);
  p***REMOVED***word = decipher.update(p***REMOVED***word, 'hex', 'utf8') + decipher.final('utf8');
  decipher = crypto.createDecipher(cryptoAlgorithm, config.key);
  uid = decipher.update(uid, 'hex', 'utf8') + decipher.final('utf8');

	var baseUrl = config.baseUrl;
	var token;

	var lastAttachmentTime = {};
	var lastFeatureTime = {};

	var featureLayers;

	var headers = {};

	var getToken = function(done) {
    console.log('getting token');

    var options = {
      url: baseUrl + '/api/login',
      json: {
        username: username,
        uid: uid,
        p***REMOVED***word: p***REMOVED***word
      }
    };

    request.post(options, function(err, res, body) {
      if (err) return done(err);

      if (res.statusCode != 200) return done(new Error('Error hitting login api, respose code: ' + res.statusCode));
      token = body.token;
      headers['Authorization'] = 'Bearer ' + body.token;
      done();
    });
  }

	var getLastAttachmentSyncTime = function(done) {
		fs.readJson("rage/.attachment_sync.json", function(err, readInLastAttachmentTime) {
	    lastAttachmentTime = readInLastAttachmentTime || {};
	    console.log('last', lastAttachmentTime);
	    done();
	  });

	}

	var getAllFeatureLayers = function(callback) {
		Layer.getLayers(function (err, layers) {
			// filter out non feature layers
			featureLayers = [];
			featureLayers = layers.filter(function(layer) {
				return layer.type == "Feature";
			});
      console.info('Syncing features for ' + featureLayers.length + ' layers');
      callback();
    });
	}

	var getFeaturesSince = function(startTime, layer, callback) {
		var options = {	};

		if (startTime) {
			var startTimePlusOne = moment(startTime).add('ms', 1);

			options.filter = {
				startDate: startTimePlusOne
			};
		}
		console.info('Getting features for layer ', layer);
		new api.Feature(layer).getAll(options, callback);
	}

	var getAttachmentsFromFeature = function(feature) {
		return feature.attachments || [];
	}

	var sortFeaturesByTimestamp = function(features) {
		return features.sort(function(a, b) {
			if (moment(a.properties.timestamp).isBefore(b.properties.timestamp))
		     return 1;
		  if (moment(a.properties.timestamp).isAfter(b.properties.timestamp))
		     return -1;
		  // a must be equal to b
		  return 0;
		});
	}

	var writeLastSyncTime = function(done) {
		fs.writeJson("rage/.attachment_sync.json", lastFeatureTime, done);
	}

	var appendErrorFile = function(string) {
		fs.writeJson("rage/.attachment_sync_errors.json", string, done);
	}

	// if this feature time is newer than we currently have
	// update the last feature time
	var updateLastFeatureTime = function(feature, layer) {
		if (feature.properties.timestamp) {
      var featureTime = moment(feature.properties.timestamp);
      if (!lastFeatureTime[layer.collectionName] || featureTime.isAfter(lastFeatureTime[layer.collectionName])) {
        lastFeatureTime[layer.collectionName] = featureTime;
      }
    }
	}

	var sequentiallySyncAttachments = function(features, layer, done) {

		console.info('syncing layer ' + layer.name);
		console.info('Sequentially syncing for ' + features.length + ' features');

		async.eachSeries(features, function(feature, done) {

			// get the attachments
			var attachments = getAttachmentsFromFeature(feature);

			var localDone = done;

			// sync each attachment
			pullAttachmentsCallbackWhenComplete(feature, layer, attachments, function(err) {
				if (!err) {
					console.info('successfully synced attachments for feature ' + feature.id + ' time is: ' + feature.properties.timestamp);
					updateLastFeatureTime(feature, layer);
				}
				localDone(err);
			});

		}, function(err) {
			done();
		});
	}

	var pullAttachmentsCallbackWhenComplete = function(feature, layer, attachments, callback) {
		console.info("syncing " + attachments.length + " attachments");
		async.eachSeries(feature.attachments, function(attachment, done) {

			var url = baseUrl + '/FeatureServer/'+
				layer.id + '/features/' +
				feature.id + '/attachments/' +
				attachment._id + '?access_token=' + token;
			var r = request(url);
			r.on('response', function (resp) {
				console.info('attachment response status code is ' + resp.statusCode);
				if (resp.statusCode == 200) {
					fs.mkdirsSync(path.dirname(config.attachmentBase + '/' + attachment.relativePath));
				  r.pipe(fs.createWriteStream(config.attachmentBase + '/' + attachment.relativePath));
				  console.info('write the file for url ' + url + ' to ' + config.attachmentBase + '/' + attachment.relativePath);
				  done();
				} else if (resp.statusCode == 404) {
					// uhhh no data, hmmm
					console.info('no data for ' + url);
					done();
				} else {
					console.info('failed to sync with error code ' + resp.statusCode + ' url is ' + url);
					done(new Error('something bad happend'));
				}
			});
			r.on('error', function(resp) {
				done(new Error('more bad stuff happened'));
			});
		},
		function(err) {
			console.info(' error ', err);
			callback(err);
		});
	}

	var syncAttachments = function(done) {

		// global featureLayers is all the layers
		// loop the layers, get all the features for each layer then pull the
		// attachments for each feature

		async.eachSeries(featureLayers,
      function(layer, done) {
      	console.log('syncing attachments since ' + lastAttachmentTime[layer.collectionName]);
				// use that time to get the features since then
				var featuresToSync;
				getFeaturesSince(lastAttachmentTime[layer.collectionName], layer, function(features) {
					featuresToSync = features;
					console.log("features to sync is " + featuresToSync.length);
					// sort the features by timestamp
					featuresToSync = sortFeaturesByTimestamp(featuresToSync);

					sequentiallySyncAttachments(featuresToSync, layer, done);
				});
			},
			function(err) {
				done();
			}
		);
	}

	var doIt = function() {

		var token;

		  console.log('pulling data');

		  async.series({
		  	lastTime: getLastAttachmentSyncTime,
		    token: getToken,
		    layers: getAllFeatureLayers,
		    attachments: syncAttachments
		  },
		  function(err, results) {
		  	console.info('done syncing, setting up timeout');
			  writeLastSyncTime();
		    // all done each ran in order, results is now equal to: {token: 1, features: 2, etc...}
		    setTimeout(doIt, timeout);
		  });
	}

	doIt();
}<|endoftext|>


<commit_before>define('isr/player', ['jquery', 'isr', 'isr/config', 'isr/entity'], function($, Game, Config, Entity) {
   console.log('Entity')
   console.log(Entity)
   var $activeScene;
   var $activeCharacter;

   // current player position
   var playerMovState = {
      'x' : 0,
      'y' : 2,
      'facing' : 'up',
      // var to indicate if character is currently moving
      'moving' : false
   };
   var lives = 3;
   var startTime = 0;

   Game.director.on('scene:change', function(sceneName) {
      console.log('switched scene to ' +sceneName);
      $activeScene = $('#' + sceneName);
      $activeCharacter = $activeScene.find('#character');
   });

   $('body').keyup(function(e) {
      console.log('Player movement listener reporting to duty');
      var charPos = $activeCharacter.offset();
      // W || Arrow up
      var up = ~~((e.keyCode === 87) || (e.keyCode === 38));
      // S || Arrow down
      var down = ~~((e.keyCode === 83) || (e.keyCode === 40));
      // A || Arrow left
      var left = ~~((e.keyCode === 65) || (e.keyCode === 37));
      // D || Arrow right
      var right = ~~((e.keyCode === 68) || (e.keyCode === 39));
      // space for interaction
      var space = ~~(e.keyCode === 32);
      var direction;

      if (up) {
         direction = 'up';
      } else if (down) {
         direction = 'down';
      } else if (left) {
         direction = 'left';
      } else if (right) {
         direction = 'right';
      }

      /*var newPos = {
         left : charPos.left,
         top : charPos.top
      };*/

      // move player
      if (!playerMovState.moving && direction) {
        Entity.move({
           'elemMovState' : playerMovState,
           '$scene' : $activeScene,
           '$element' : $activeCharacter,
           'direction' : direction
        });
      }

      if (space) {
         doAction();
      }
      e.stopPropagation();
      e.preventDefault();
      e.stopImmediatePropagation();
      return false;
   });

   /**
    * Function to do stuff like fight or talk
    */
   var doAction = function() {
      // first check direction
      var targetTile = {
         x : playerMovState.x,
         y : playerMovState.y
      };
      switch(playerMovState.facing) {
         case 'up':
            targetTile.y += 1;
         break;
         case 'down':
            targetTile.y -= 1;
         break;
         case 'left':
            targetTile.x -= 1;
         break;
         case 'right':
            targetTile.y += 1;
         break;
      }
      // check if on there is sth on the tile the player is facing to interact with
      var interactableStuff = $activeScene.find('#x' + targetTile.x + '-y' + targetTile.y + ' .interactable');
      interactableStuff.each(function(index) {
         if ($(this).hasClass('attackable')) {
            // TODO do fancy animation
         } else if ($(this).hasClass('talkable')) {
            alert('Your are talking to someone');
         }
      });
      if (interactableStuff.length === 0) {
         //TODO add fancy sword swing into empty air
         alert('You successfully killed empty air');
      }
   };

   var decreaseLives = function() {
      lives--;
      if (lives === 0) {
         alert('Game over');
         location.reload();
      }
   };

   return {
      'playerMovState' : playerMovState,
      'decreaseLives' : decreaseLives
   };
}); <commit_msg>set player start coordinates per scene + save coords per scene<commit_after>define('isr/player', ['jquery', 'isr', 'isr/config', 'isr/entity'], function($, Game, Config, Entity) {
   var $activeScene;
   var $activeCharacter;
   var scenePlayer = {
      'church' : {'x': 8, 'y' : 9},
      'family' : {'x': 8, 'y' : 9},
      'temple-1' : {'x': 8, 'y' : 9},
      'temple-2' : {'x': 8, 'y' : 9},
      'war-1' : {'x': 0, 'y' : 3},
      'war-2' : {'x': 0, 'y' : 3}
   };
   // current player position
   var playerMovState = {
      'x' : 0,
      'y' : 2,
      'facing' : 'up',
      // var to indicate if character is currently moving
      'moving' : false
   };
   var lives = 3;
   var startTime = 0;

   Game.director.on('scene:change', function(sceneName) {
      // save current player pos to scenePlayer
      if ($activeScene) {
         scenePlayer[$activeScene[0].id].x = playerMovState.x;
         scenePlayer[$activeScene[0].id].y = playerMovState.y;
      }
      console.log('switched scene to ' +sceneName);
      $activeScene = $('#' + sceneName);

      $activeCharacter = $activeScene.find('.character');
      // get last player pos of player of this scene
      playerMovState.x = scenePlayer[sceneName].x;
      playerMovState.y = scenePlayer[sceneName].y;
      $activeCharacter.offset({
         'left' : playerMovState.x * Config.tiles.width,
         'top' : playerMovState.y * Config.tiles.height
      });
   });

   $('body').keyup(function(e) {
      console.log('Player movement listener reporting to duty');
      var charPos = $activeCharacter.offset();
      // W || Arrow up
      var up = ~~((e.keyCode === 87) || (e.keyCode === 38));
      // S || Arrow down
      var down = ~~((e.keyCode === 83) || (e.keyCode === 40));
      // A || Arrow left
      var left = ~~((e.keyCode === 65) || (e.keyCode === 37));
      // D || Arrow right
      var right = ~~((e.keyCode === 68) || (e.keyCode === 39));
      // space for interaction
      var space = ~~(e.keyCode === 32);
      var direction;

      if (up) {
         direction = 'up';
      } else if (down) {
         direction = 'down';
      } else if (left) {
         direction = 'left';
      } else if (right) {
         direction = 'right';
      }

      /*var newPos = {
         left : charPos.left,
         top : charPos.top
      };*/

      // move player
      if (!playerMovState.moving && direction) {
        Entity.move({
           'elemMovState' : playerMovState,
           '$scene' : $activeScene,
           '$element' : $activeCharacter,
           'direction' : direction,
           'callback' : function() {
              // trigger global playerMoved and scene specific playerMoved events
              Game.director.currentScene.trigger('playerMoved', playerMovState);
              Game.director.trigger('playerMoved', playerMovState);
           }
        });
      }

      if (space) {
         doAction();
      }
      e.stopPropagation();
      e.preventDefault();
      e.stopImmediatePropagation();
      return false;
   });

   /**
    * Function to do stuff like fight or talk
    */
   var doAction = function() {
      // first check direction
      var targetTile = {
         x : playerMovState.x,
         y : playerMovState.y
      };
      switch(playerMovState.facing) {
         case 'up':
            targetTile.y += 1;
         break;
         case 'down':
            targetTile.y -= 1;
         break;
         case 'left':
            targetTile.x -= 1;
         break;
         case 'right':
            targetTile.y += 1;
         break;
      }
      // check if on there is sth on the tile the player is facing to interact with
      var interactableStuff = $activeScene.find('#x' + targetTile.x + '-y' + targetTile.y + ' .interactable');
      interactableStuff.each(function(index) {
         if ($(this).hasClass('attackable')) {
            // TODO do fancy animation
         } else if ($(this).hasClass('talkable')) {
            alert('Your are talking to someone');
         }
      });
      if (interactableStuff.length === 0) {
         //TODO add fancy sword swing into empty air
         alert('You successfully killed empty air');
      }
   };

   var decreaseLives = function() {
      lives--;
      if (lives === 0) {
         alert('Game over');
         location.reload();
      }
   };

   return {
      'playerMovState' : playerMovState,
      'decreaseLives' : decreaseLives
   };
}); <|endoftext|>


<commit_before>var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var async = require('async');
var execFile = require('child_process').execFile;
var hb = require('handlebars');

module.exports = {
    name:'template',
    description:'A command to allow generic, template driven creation of new services and apps',
    example:'bosco template | bosco template add|remove <githubRepo> | bosco template new <templateName> <serviceName>',
    cmd:cmd
}

function cmd(bosco, args, next) {
  var action = args.shift();
  if(action == 'create') { return newServiceFromTemplate(bosco, args, next); }
  if(action == 'add') { return addTemplate(bosco, args, next); }
  if(action == 'remove') { return removeTemplate(bosco, args, next); }
  listTemplates(bosco, next);
}

function listTemplates(bosco, next) {

  var templates = bosco.config.get('templates');

  bosco.log('Your current templates are:');
  _.each(templates, function(template) {
    bosco.log(' - ' + template.green);
  });

  bosco.log('Use the command: ' + 'bosco template add <githubRepo>'.green + ' to add to your template list.')
  if(next) { next(); }

}

function newServiceFromTemplate(bosco, args, next) {

    var templates = bosco.config.get('templates') || [];

    var templateRepoName = args.shift();
    var targetServiceName = args.shift();
    var targetServicePort = args.shift();

    if(!templateRepoName || !targetServiceName || !targetServicePort) {
        return bosco.log('You need to specify a template, a target service name and a port: ' + 'bosco template create <githubRepo> <serviceName> <port>'.green);
    }

    var template = _.filter(templates, function(item) { return item.match(new RegExp(templateRepoName)); })[0];

    if(!template) {
      bosco.log('Couldnt find a service that matched: ' + templateRepoName.red);
      return listTemplates(bosco, next);
    }

    bosco.log('Creating new service: ' + targetServiceName.green + ' from template: ' + template.green);

    var gitCmd = 'git';
    var host   = bosco.config.get('github:host') || 'github.com';
    host       = "git@" + host + ":";

    var gitOptions = ['clone','--depth=1','git@github.com:' + template, targetServiceName];

    var serviceDirectory = path.resolve('.', targetServiceName);

    async.series([
      async.apply(execCmd, bosco, gitCmd, gitOptions, path.resolve('.')),
      async.apply(execCmd, bosco, 'rm',['-rf','.git'], serviceDirectory),
      async.apply(execCmd, bosco, 'git',['init'], serviceDirectory),
      async.apply(copyTemplateFiles, bosco, targetServiceName, targetServicePort, serviceDirectory),
      async.apply(execCmd, bosco, 'rm',['-rf','templates'], serviceDirectory),
      async.apply(execCmd, bosco, 'rm',['-f','bosco-templates.json'], serviceDirectory),
      async.apply(execCmd, bosco, 'git',['add','--all','.'], serviceDirectory),
      async.apply(execCmd, bosco, 'git',['commit','-m','First commit'], serviceDirectory)
    ], function(err) {
      if(err) {
        return bosco.error(err.message);
      }
      bosco.log('Complete!');
    });

}

function copyTemplateFiles(bosco, serviceName, port, serviceDirectory, next) {

  var templateFiles = require(path.join(serviceDirectory, 'bosco-templates.json'));
  var variables = {
    serviceName: serviceName,
    serviceShortName: getShortName(serviceName),
    user: bosco.config.get('github:user'),
    port: port
  }
  async.map(templateFiles, function(template, cb) {
    if(!template.source || !template.destination) {
      return cb(new Error('You must specify both a source and destination'));
    }

    bosco.log('Applying template for file: ' + template.destination.green);

    try {
      var destination = hb.compile(template.destination)(variables);
      var source = hb.compile(template.source)(variables);
      var templateContent = fs.readFileSync(path.join(serviceDirectory, source));
      var outputContent = hb.compile(templateContent.toString())(variables);
      fs.writeFileSync(path.join(serviceDirectory, destination), outputContent);
    } catch(ex) {
      bosco.error('There has been an error applying the templates, check the configuration of the template project.');
      return cb(ex);
    }

    cb();

  }, next);

}

function getShortName(service) {
  service = service.replace(/^app\-/,'');
  service = service.replace(/^service\-/,'');
  return service;
}

function addTemplate(bosco, args, next) {

    var templates = bosco.config.get('templates') || [];
    var templateRepo = args.shift();

    templates.push(templateRepo);
    bosco.config.set('templates', _.uniq(templates));

    bosco.config.save(function() {
      bosco.log('Added new template.');
      if(next) { next(); }
    });

}

function removeTemplate(bosco, args, next) {

    var templates = bosco.config.get('templates') || [];
    var templateRepo = args.shift();

    _.pull(templates, templateRepo);

    bosco.config.set('templates', templates);

    bosco.config.save(function() {
      bosco.log('Removed any matching templates.');
      if(next) { next(); }
    });

}

function execCmd(bosco, cmd, params, cwd, next) {
  execFile(cmd, params, {
    cwd: cwd
  }, function(err, stdout, stderr) {
      next(err, stdout + stderr);
  });
}

<commit_msg>allowing the definition of custom git host for repositories through configuration<commit_after>var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var async = require('async');
var execFile = require('child_process').execFile;
var hb = require('handlebars');

module.exports = {
    name:'template',
    description:'A command to allow generic, template driven creation of new services and apps',
    example:'bosco template | bosco template add|remove <githubRepo> | bosco template new <templateName> <serviceName>',
    cmd:cmd
}

function cmd(bosco, args, next) {
  var action = args.shift();
  if(action == 'create') { return newServiceFromTemplate(bosco, args, next); }
  if(action == 'add') { return addTemplate(bosco, args, next); }
  if(action == 'remove') { return removeTemplate(bosco, args, next); }
  listTemplates(bosco, next);
}

function listTemplates(bosco, next) {

  var templates = bosco.config.get('templates');

  bosco.log('Your current templates are:');
  _.each(templates, function(template) {
    bosco.log(' - ' + template.green);
  });

  bosco.log('Use the command: ' + 'bosco template add <githubRepo>'.green + ' to add to your template list.')
  if(next) { next(); }

}

function newServiceFromTemplate(bosco, args, next) {

    var templates = bosco.config.get('templates') || [];

    var templateRepoName = args.shift();
    var targetServiceName = args.shift();
    var targetServicePort = args.shift();

    if(!templateRepoName || !targetServiceName || !targetServicePort) {
        return bosco.log('You need to specify a template, a target service name and a port: ' + 'bosco template create <githubRepo> <serviceName> <port>'.green);
    }

    var template = _.filter(templates, function(item) { return item.match(new RegExp(templateRepoName)); })[0];

    if(!template) {
      bosco.log('Couldnt find a service that matched: ' + templateRepoName.red);
      return listTemplates(bosco, next);
    }

    bosco.log('Creating new service: ' + targetServiceName.green + ' from template: ' + template.green);

    var gitCmd = 'git';
    var host   = bosco.config.get('github:host') || 'github.com';
    host       = "git@" + host + ":";

    var gitOptions = ['clone','--depth=1', host + template, targetServiceName];

    var serviceDirectory = path.resolve('.', targetServiceName);

    async.series([
      async.apply(execCmd, bosco, gitCmd, gitOptions, path.resolve('.')),
      async.apply(execCmd, bosco, 'rm',['-rf','.git'], serviceDirectory),
      async.apply(execCmd, bosco, 'git',['init'], serviceDirectory),
      async.apply(copyTemplateFiles, bosco, targetServiceName, targetServicePort, serviceDirectory),
      async.apply(execCmd, bosco, 'rm',['-rf','templates'], serviceDirectory),
      async.apply(execCmd, bosco, 'rm',['-f','bosco-templates.json'], serviceDirectory),
      async.apply(execCmd, bosco, 'git',['add','--all','.'], serviceDirectory),
      async.apply(execCmd, bosco, 'git',['commit','-m','First commit'], serviceDirectory)
    ], function(err) {
      if(err) {
        return bosco.error(err.message);
      }
      bosco.log('Complete!');
    });

}

function copyTemplateFiles(bosco, serviceName, port, serviceDirectory, next) {

  var templateFiles = require(path.join(serviceDirectory, 'bosco-templates.json'));
  var variables = {
    serviceName: serviceName,
    serviceShortName: getShortName(serviceName),
    user: bosco.config.get('github:user'),
    port: port
  }
  async.map(templateFiles, function(template, cb) {
    if(!template.source || !template.destination) {
      return cb(new Error('You must specify both a source and destination'));
    }

    bosco.log('Applying template for file: ' + template.destination.green);

    try {
      var destination = hb.compile(template.destination)(variables);
      var source = hb.compile(template.source)(variables);
      var templateContent = fs.readFileSync(path.join(serviceDirectory, source));
      var outputContent = hb.compile(templateContent.toString())(variables);
      fs.writeFileSync(path.join(serviceDirectory, destination), outputContent);
    } catch(ex) {
      bosco.error('There has been an error applying the templates, check the configuration of the template project.');
      return cb(ex);
    }

    cb();

  }, next);

}

function getShortName(service) {
  service = service.replace(/^app\-/,'');
  service = service.replace(/^service\-/,'');
  return service;
}

function addTemplate(bosco, args, next) {

    var templates = bosco.config.get('templates') || [];
    var templateRepo = args.shift();

    templates.push(templateRepo);
    bosco.config.set('templates', _.uniq(templates));

    bosco.config.save(function() {
      bosco.log('Added new template.');
      if(next) { next(); }
    });

}

function removeTemplate(bosco, args, next) {

    var templates = bosco.config.get('templates') || [];
    var templateRepo = args.shift();

    _.pull(templates, templateRepo);

    bosco.config.set('templates', templates);

    bosco.config.save(function() {
      bosco.log('Removed any matching templates.');
      if(next) { next(); }
    });

}

function execCmd(bosco, cmd, params, cwd, next) {
  execFile(cmd, params, {
    cwd: cwd
  }, function(err, stdout, stderr) {
      next(err, stdout + stderr);
  });
}

<|endoftext|>


<commit_before>exports.commands = {
	k: 'kick',
	kick: function (target, room, user) {
		if (!target) return;
		target = this.splitTarget(target);
		var targetUser = this.targetUser;
		if (!targetUser || !targetUser.connected) {
			return this.sendReply("User " + this.targetUsername + " not found.");
		}
		if (!this.can('kick', targetUser, room)) return false;
		var msg = "kicked by " + user.name + (target ? " (" + target + ")" : "") + ".";
		this.addModCommand("" + targetUser.name + " was " + msg);
		targetUser.popup("You have been " + msg);
		targetUser.leaveRoom(room);
	}
};
<commit_msg>Clean up kick.js<commit_after>exports.commands = {
	k: 'kick',
	kick: function (target, room, user) {
		if (!this.can('kick', targetUser, room)) return false;
		if (!this.canTalk()) return false;
		if (!target) return this.sendReply("Usage: /kick [user], [reason]");
		target = this.splitTarget(target);
		var targetUser = this.targetUser;
		if (!targetUser || !targetUser.connected) return this.sendReply("User " + this.targetUsername + " not found.");
		var msg = "kicked by " + user.name + (target ? " (" + target + ")" : "") + ".";
		this.addModCommand(targetUser.name + " was " + msg);
		targetUser.popup("You have been " + msg);
		targetUser.leaveRoom(room.id);
	}
};
<|endoftext|>


<commit_before>import React from 'react';
import { Modal, Button, Popover, Tooltip, OverlayTrigger} from 'react-bootstrap';
import { BrowserRouter, Route, Link, Redirect } from 'react-router-dom';

export class SignUp extends React.Component {

  constructor(props) {
    console.log("SignUp constructor");
    super(props);
    this.close = this.close.bind(this);
    this.state = {show: true};
  }

  close() {
    this.setState({show: false});
  }

  componentWillUnmount() {
    console.log('will unmount');
  }

  render() {
    if (!this.state.show) {
      return <Redirect to="/" />
    }

    const popover = (
      <Popover id="modal-popover" title="popover">
        very popover. such engagement
      </Popover>
    );

    const tooltip = (
      <Tooltip id="modal-tooltip">
        wow.
      </Tooltip>
    );

    return (

        <Modal show={this.state.show} onHide={this.close}>
          <Modal.Header closeButton>
            <Modal.Title>Modal heading</Modal.Title>
          </Modal.Header>
          <Modal.Body>

Text in a modal

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

Popover in a modal

there is a <OverlayTrigger overlay={popover}>popover</OverlayTrigger> here

Tooltips in a modal

there is a <OverlayTrigger overlay={tooltip}>tooltip</OverlayTrigger> here

Overflowing text to show scroll behavior

Sign Up Now

          </Modal.Body>
          <Modal.Footer>
            <Button type="button" onClick={this.close}>Close</Button>
          </Modal.Footer>
        </Modal>

    )
  }
}

<commit_msg>Use history.goBack() instead of Redirect<commit_after>import React from 'react';
import { Col, Form, FormControl, FormGroup, Navbar, Modal, Button, Popover, Tooltip, OverlayTrigger} from 'react-bootstrap';

export class SignUp extends React.Component {

  constructor(props) {
    super(props);
    this.close = this.close.bind(this);
    this.signup = this.signup.bind(this);
    this.state = {show: true};
  }

  close() {
    this.setState({show: false});
  }

  signup() {
    console.log('signup submit');
  }

  render() {
    if (!this.state.show) {
      this.props.history.goBack();
    }

    return (
      <Modal show={this.state.show} onHide={this.close}>
        <Modal.Header closeButton>
          <Modal.Title>New Account</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Navbar.Form>
            <Form horizontal onSubmit={this.signup}>
              <FormGroup>
                <Col sm={10}>
                  <FormControl type="text" placeholder="Email" ref="email" />
                </Col>
              </FormGroup>
              <FormGroup>
                <Col sm={10}>
                  <FormControl type="password" placeholder="Password" ref="password" />
                </Col>
              </FormGroup>
              <FormGroup>
                <Col sm={10}>
                  <Button type="submit">Submit</Button>
                </Col>
              </FormGroup>
            </Form>
          </Navbar.Form>
        </Modal.Body>
      </Modal>
    )
  }
}

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2.view',
  name: 'RecipricalSearch', // Correct spelling: "reciprocal"
  extends: 'foam.u2.Element', // TODO: make be a View

  requires: [
    'foam.u2.search.SearchManager'
  ],

  imports: [
    'dao'
  ],

  exports: [
    'as filterController',
    'as data'
  ],

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      name: 'data'
    },
    {
      class: 'Array',
      name: 'filters',
      factory: null,
      expression: function(dao) {
        var of = dao && dao.of;

        if ( ! of ) return [];

        return of.model_.searchColumns || of.model_.tableColumns ||
            of.getAxiomsByClass(foam.core.Property)
                .filter(function(p) { return ! p.hidden })
                .map(foam.core.Property.NAME.f);
      }
    }
  ],

  methods: [
    function initE() {
      var self = this;

      // TODO: Add "n of m selected" header.
      this.
        add(this.slot(function(filters) {
          var searchManager = self.SearchManager.create({
            dao$: self.dao$,
            predicate$: self.data$
          });

          var e = this.E('div');

          e.onDetach(searchManager);

          e.forEach(filters, function(f) {
            // TODO: See if this can be cleaned up somehow, if searchView didn't require the proprety explicitly, or
            // could find the search manager via the context and add itself to that.
            var axiom = self.dao.of.getAxiomByName(f);
            var spec  = axiom.searchView;
            var view  = foam.u2.ViewSpec.createView(spec, { property: axiom, dao: self.dao }, this, this.__subSubContext__);

            searchManager.add(view);
            this
              .start()
                .addClass(self.myClass('filter-header'))
                .add(axiom.label)
              .end()
              .start(view)
                .addClass(self.myClass('filter'))
            .end()
          });

          return e;
        }, this.filters$), this.CLEAR);
    },

    function addFilter(key) {
      this.filters = this.filters.concat(key);
    },

    function removeFilter(key) {
      this.filters = this.filters.filter(function(k) {
        return key !== k;
      });
    }
  ],

  actions: [
    {
      name: 'clear',
      code: function() {
        this.data = undefined;
        this.filters = this.filters.slice();
      }
    }
  ]
});
<commit_msg>Added selected x of y count to RSearch.<commit_after>/**
 * @license
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2.view',
  name: 'RecipricalSearch', // Correct spelling: "reciprocal"
  extends: 'foam.u2.Element', // TODO: make be a View

  requires: [
    'foam.u2.search.SearchManager'
  ],

  imports: [
    'dao'
  ],

  exports: [
    'as filterController',
    'as data'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function CSS() {/*
        ^count {
          font-size: 16pt;
          color: #555;
        }
      */}
    })
  ],

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      name: 'data'
    },
    {
      class: 'Array',
      name: 'filters',
      factory: null,
      expression: function(dao) {
        var of = dao && dao.of;

        if ( ! of ) return [];

        return of.model_.searchColumns || of.model_.tableColumns ||
            of.getAxiomsByClass(foam.core.Property)
                .filter(function(p) { return ! p.hidden })
                .map(foam.core.Property.NAME.f);
      }
    },
    {
      class: 'Int',
      name: 'selectedCount'
    },
    {
      class: 'Int',
      name: 'totalCount'
    },
  ],

  methods: [
    function initE() {
      var self = this;

      this.dao.on.sub(this.updateTotalCount);
      this.updateTotalCount();

      this.
        add(this.slot(function(filters) {
          var searchManager = self.SearchManager.create({
            dao$: self.dao$,
            predicate$: self.data$
          });

//          searchManager.filteredDAO.on.sub(self.updateSelectedCount);
          searchManager.filteredDAO$.sub(self.updateSelectedCount);
          self.updateSelectedCount(0,0,0,searchManager.filteredDAO$);

          var e = this.E('div');

          e.onDetach(searchManager);

          e.forEach(filters, function(f) {
            // TODO: See if this can be cleaned up somehow, if searchView didn't require the proprety explicitly, or
            // could find the search manager via the context and add itself to that.
            var axiom = self.dao.of.getAxiomByName(f);
            var spec  = axiom.searchView;
            var view  = foam.u2.ViewSpec.createView(spec, { property: axiom, dao: self.dao }, this, this.__subSubContext__);

            searchManager.add(view);
            this
              .start()
                .addClass(self.myClass('filter-header'))
                .add(axiom.label)
              .end()
              .start(view)
                .addClass(self.myClass('filter'))
            .end()
          });

          return e;
        }, this.filters$))
        .start()
          .addClass(self.myClass('count'))
          .add(self.selectedCount$, ' of ', self.totalCount$, ' selected')
        .end()
        .start(this.CLEAR).style({float: 'right'}).end();
    },

    function addFilter(key) {
      this.filters = this.filters.concat(key);
    },

    function removeFilter(key) {
      this.filters = this.filters.filter(function(k) {
        return key !== k;
      });
    }
  ],

  actions: [
    {
      name: 'clear',
      code: function() {
        this.data = undefined;
        this.filters = this.filters.slice();
      }
    }
  ],

  /*
  reactions: [
    [ 'data', 'on', 'updateTotalCount' ]
  ],
  */

  listeners: [
    {
      name: 'updateTotalCount',
      isFramed: true,
      code: function() {
        this.dao.select(foam.mlang.sink.Count.create()).then(function(c) {
          this.totalCount = c.value;
        }.bind(this));
      }
    },
    {
      name: 'updateSelectedCount',
      isFramed: true,
      code: function(_, __, ___, dao) {
        dao.get().select(foam.mlang.sink.Count.create()).then(function(c) {
          this.selectedCount = c.value;
        }.bind(this));
      }
    }
  ]
});
<|endoftext|>


<commit_before>import videojs from 'video.js';
import {version as VERSION} from '../package.json';

// Default options for the plugin.
const defaults = {};

// Cross-compatibility for Video.js 5 and 6.
const registerPlugin = videojs.registerPlugin || videojs.plugin;
// const dom = videojs.dom || videojs;

/**
 * Checks whether the clip should be ended.
 *
 * @function onPlayerTimeUpdate
 *
 */
const onPlayerTimeUpdate = function() {
  const curr = this.currentTime();

  if (curr < 0) {
    this.currentTime(0);
    this.play();
  }
  if (this._offsetEnd > 0 && curr > (this._offsetEnd - this._offsetStart)) {
    this.off('timeupdate', onPlayerTimeUpdate);
    this.pause();
    this.trigger('ended');

    // Re-bind to timeupdate next time the video plays
    this.one('play', () => {
      this.on('timeupdate', onPlayerTimeUpdate);
    });

    if (!this._restartBeginning) {
      this.currentTime(this._offsetEnd - this._offsetStart);
    } else {
      this.trigger('loadstart');
      this.currentTime(0);
    }
  }
};
/**
 * Function to invoke when the player is ready.
 *
 * This is a great place for your plugin to initialize itself. When this
 * function is called, the player will have its DOM and child components
 * in place.
 *
 * @function onPlayerReady
 * @param    {Player} player
 *           A Video.js player.
 * @param    {Object} [options={}]
 *           An object of options left to the plugin author to define.
 */
const onPlayerReady = (player, options) => {
  player.one('play', () => {
    player.on('timeupdate', onPlayerTimeUpdate);
  });
};

/**
 * A video.js plugin.
 *
 * In the plugin function, the value of `this` is a video.js `Player`
 * instance. You cannot rely on the player being in a "ready" state here,
 * depending on how the plugin is invoked. This may or may not be important
 * to you; if not, remove the wait for "ready"!
 *
 * @function offset
 * @param    {Object} [options={}]
 *           An object of options left to the plugin author to define.
 */
const offset = function(options) {
  options = options || {};
  const Player = this.constructor;

  this._offsetStart = parseFloat(options.start || '0');
  this._offsetEnd = parseFloat(options.end || '0');
  this._restartBeginning = options.restart_beginning || false;

  if (!Player.__super__ || !Player.__super__.__offsetInit) {
    Player.__super__ = {
      __offsetInit: true,
      duration: Player.prototype.duration,
      currentTime: Player.prototype.currentTime,
      bufferedPercent: Player.prototype.bufferedPercent,
      remainingTime: Player.prototype.remainingTime,
      buffered: Player.prototype.buffered
    };

    Player.prototype.duration = function() {
      if (this._offsetEnd !== undefined && this._offsetStart !== undefined) {
        if (this._offsetEnd > 0) {
          return this._offsetEnd - this._offsetStart;
        }
        return Player.__super__.duration.apply(this, arguments) - this._offsetStart;
      }
      return Player.__super__.duration.apply(this, arguments);
    };

    Player.prototype.currentTime = function(seconds) {
      if (seconds !== undefined) {
        if (this._offsetStart !== undefined) {
          return Player.__super__.currentTime
            .call(this, seconds + this._offsetStart);
        }
        return Player.__super__.currentTime.call(this, seconds);
      }

      if (this._offsetStart !== undefined) {
        return Player.__super__.currentTime
          .apply(this) - this._offsetStart;
      }
      return Player.__super__.currentTime.apply(this);
    };

    Player.prototype.remainingTime = function() {
      return this.duration() - this.currentTime();
    };

    Player.prototype.startOffset = function() {
      return this._offsetStart;
    };

    Player.prototype.endOffset = function() {
      if (this._offsetEnd > 0) {
        return this._offsetEnd;
      }
      return this.duration();
    };

    Player.prototype.buffered = function() {
      const buff = Player.__super__.buffered.call(this);
      const ranges = [];

      for (let i = 0; i < buff.length; i++) {
        ranges[i] = [
          Math.max(0, buff.start(i) - this._offsetStart),
          Math.min(Math.max(0, buff.end(i) - this._offsetStart), this.duration())
        ];
      }

      return videojs.createTimeRanges(ranges);
    };
  }

  this.ready(() => {
    onPlayerReady(this, videojs.mergeOptions(defaults, options));
  });
};

// Register the plugin with video.js.
registerPlugin('offset', offset);
// Include the version number.
offset.VERSION = VERSION;

export default offset;
<commit_msg>fix: update currentTime value in Video.js cache<commit_after>import videojs from 'video.js';
import {version as VERSION} from '../package.json';

// Default options for the plugin.
const defaults = {};

// Cross-compatibility for Video.js 5 and 6.
const registerPlugin = videojs.registerPlugin || videojs.plugin;
// const dom = videojs.dom || videojs;

/**
 * Checks whether the clip should be ended.
 *
 * @function onPlayerTimeUpdate
 *
 */
const onPlayerTimeUpdate = function() {
  const curr = this.currentTime();

  if (curr < 0) {
    this.currentTime(0);
    this.play();
  }
  if (this._offsetEnd > 0 && curr > (this._offsetEnd - this._offsetStart)) {
    this.off('timeupdate', onPlayerTimeUpdate);
    this.pause();
    this.trigger('ended');

    // Re-bind to timeupdate next time the video plays
    this.one('play', () => {
      this.on('timeupdate', onPlayerTimeUpdate);
    });

    if (!this._restartBeginning) {
      this.currentTime(this._offsetEnd - this._offsetStart);
    } else {
      this.trigger('loadstart');
      this.currentTime(0);
    }
  }
};
/**
 * Function to invoke when the player is ready.
 *
 * This is a great place for your plugin to initialize itself. When this
 * function is called, the player will have its DOM and child components
 * in place.
 *
 * @function onPlayerReady
 * @param    {Player} player
 *           A Video.js player.
 * @param    {Object} [options={}]
 *           An object of options left to the plugin author to define.
 */
const onPlayerReady = (player, options) => {
  player.one('play', () => {
    player.on('timeupdate', onPlayerTimeUpdate);
  });
};

/**
 * A video.js plugin.
 *
 * In the plugin function, the value of `this` is a video.js `Player`
 * instance. You cannot rely on the player being in a "ready" state here,
 * depending on how the plugin is invoked. This may or may not be important
 * to you; if not, remove the wait for "ready"!
 *
 * @function offset
 * @param    {Object} [options={}]
 *           An object of options left to the plugin author to define.
 */
const offset = function(options) {
  options = options || {};
  const Player = this.constructor;

  this._offsetStart = parseFloat(options.start || '0');
  this._offsetEnd = parseFloat(options.end || '0');
  this._restartBeginning = options.restart_beginning || false;

  if (!Player.__super__ || !Player.__super__.__offsetInit) {
    Player.__super__ = {
      __offsetInit: true,
      duration: Player.prototype.duration,
      currentTime: Player.prototype.currentTime,
      bufferedPercent: Player.prototype.bufferedPercent,
      remainingTime: Player.prototype.remainingTime,
      buffered: Player.prototype.buffered
    };

    Player.prototype.duration = function() {
      if (this._offsetEnd !== undefined && this._offsetStart !== undefined) {
        if (this._offsetEnd > 0) {
          return this._offsetEnd - this._offsetStart;
        }
        return Player.__super__.duration.apply(this, arguments) - this._offsetStart;
      }
      return Player.__super__.duration.apply(this, arguments);
    };

    Player.prototype.currentTime = function(seconds) {
      if (seconds !== undefined) {
        if (this._offsetStart !== undefined) {
          return Player.__super__.currentTime
            .call(this, seconds + this._offsetStart);
        }
        return Player.__super__.currentTime.call(this, seconds);
      }

      if (this._offsetStart !== undefined) {
        const t = Player.__super__.currentTime
          .apply(this) - this._offsetStart;

        this.getCache().currentTime = t;
        return t;
      }
      return Player.__super__.currentTime.apply(this);
    };

    Player.prototype.remainingTime = function() {
      return this.duration() - this.currentTime();
    };

    Player.prototype.startOffset = function() {
      return this._offsetStart;
    };

    Player.prototype.endOffset = function() {
      if (this._offsetEnd > 0) {
        return this._offsetEnd;
      }
      return this.duration();
    };

    Player.prototype.buffered = function() {
      const buff = Player.__super__.buffered.call(this);
      const ranges = [];

      for (let i = 0; i < buff.length; i++) {
        ranges[i] = [
          Math.max(0, buff.start(i) - this._offsetStart),
          Math.min(Math.max(0, buff.end(i) - this._offsetStart), this.duration())
        ];
      }

      return videojs.createTimeRanges(ranges);
    };
  }

  this.ready(() => {
    onPlayerReady(this, videojs.mergeOptions(defaults, options));
  });
};

// Register the plugin with video.js.
registerPlugin('offset', offset);
// Include the version number.
offset.VERSION = VERSION;

export default offset;
<|endoftext|>


<commit_before>var fs = require('fs');
var selectors;

function writeIconCSS() {
        fs.appendFile('config/custom.css', selectors);
}

exports.commands = {
        sfis: function (target, room, user) {
                if (!this.can('eval'));

                var args = target.split(',');
                if (args.length < 3) return this.parse('/help seticon');
                var username = toId(args.shift());
                var image = 'background: rgba(244, 244, 244, 0.8) url("' + args.shift().trim() + '") right no-repeat;';
                selectors = '\n\n' + '  #' + toId(args.shift()) + '-userlist-user-' + username;
                args.forEach(function (room) {
                        selectors += ', #' + toId(room) + '-userlist-user-' + username;
                });
                selectors += ' { \n' + '    ' + image +  '\n  }';

                this.privateModCommand("(" + user.name + " has set an icon to " + username + ")");
                writeIconCSS();
        },
        seticonhelp: ["/sfis [username], [image], [room 1], [room 2], etc. - Sets an icon to a user in chosen rooms. Credits goes to Master Float in this."]
};
<commit_msg>Update sfis.js<commit_after>HA! If you expect me to give you this code, think again.
<|endoftext|>


<commit_before>'use strict';

const querystring = require('querystring');
const Util = require('../helpers/jakduk_util');
const config = require('../config/environment');
const _ = require('lodash');
const i18n = require('i18n');

module.exports = function () {
  return function defaultContext(req, res, next) {
    req.api.getUserInfo().then(response => {
      if (response.statusCode === 200) {
        req.userInfo = response.data;
      } else if (req.cookies[config.tokenCookieName]) {
        Util.clearSession(res);
      }

      req.isAuthenticated = !!req.userInfo;
      if (req.isAuthenticated) {
        res.locals.isAdmin = req.userInfo.roles.some(role => role === 'ROLE_ROOT');
        req.isAdmin = res.locals.isAdmin;
      }

      _.extend(res.locals, {
        redir: `?redir=${querystring.escape(req.url)}`,
        layout: 'layout',
        userInfo: req.userInfo,
        isAuthenticated: req.isAuthenticated,
        isIE: /trident|msie/i.test(req.headers['user-agent']),
        meta: {
          twitter: {
            card: 'summary'
          },
          og: {
            description: i18n.__('about.jakduk'),
            url: `${config.origin}req.path`,
            image: `${config.origin}/jakduk/img/logo_256.png`,
            type: 'website'
          },
          facebook: {
            appId: config.facebook.clientID
          }
        }
      });

      next();
    }).catch(err => next(err));
  };
};
<commit_msg>document 캐시 제외<commit_after>'use strict';

const querystring = require('querystring');
const Util = require('../helpers/jakduk_util');
const config = require('../config/environment');
const _ = require('lodash');
const i18n = require('i18n');

module.exports = function () {
  return function defaultContext(req, res, next) {
    req.api.getUserInfo().then(response => {
      if (response.statusCode === 200) {
        req.userInfo = response.data;
      } else if (req.cookies[config.tokenCookieName]) {
        Util.clearSession(res);
      }

      req.isAuthenticated = !!req.userInfo;
      if (req.isAuthenticated) {
        res.locals.isAdmin = req.userInfo.roles.some(role => role === 'ROLE_ROOT');
        req.isAdmin = res.locals.isAdmin;
      }

      _.extend(res.locals, {
        redir: `?redir=${querystring.escape(req.url)}`,
        layout: 'layout',
        userInfo: req.userInfo,
        isAuthenticated: req.isAuthenticated,
        isIE: /trident|msie/i.test(req.headers['user-agent']),
        meta: {
          twitter: {
            card: 'summary'
          },
          og: {
            description: i18n.__('about.jakduk'),
            url: `${config.origin}req.path`,
            image: `${config.origin}/jakduk/img/logo_256.png`,
            type: 'website'
          },
          facebook: {
            appId: config.facebook.clientID
          }
        }
      });

      res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
      next();
    }).catch(err => next(err));
  };
};
<|endoftext|>


<commit_before>const mongoose = require('mongoose');
const _ = require('lodash');
const moment = require('moment');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

const CleaningWeekSchema = new Schema({
  weekNumber: {
    type: Number,
    required: true,
  },
  year: {
    type: Number,
    required: true
  },
  confirmations: {
    type: [{
      type: String,
      enum: ['max', 'tom', 'steve']
    }],
    default: []
  }
});

CleaningWeekSchema.methods = {
  async confirm(name) {
    return await this.update({ $addToSet: { confirmations: name } });
  }
};

CleaningWeekSchema.statics = {
  async getCurrentWeek() {
    let today = moment();
    if (today.day() === 0) {
      today = today.subtract(1, 'day');
    }

    const weekNumber = today.week();
    const year = today.year();

    const week = await this.findOne({ weekNumber, year });

    return week || this.create({ weekNumber, year });
  },

  async confirmCurrentWeek(name) {
    const currentWeek = await this.getCurrentWeek();
    await currentWeek.confirm(name);

    return this.getCurrentWeek();
  }
}

const CleaningWeek = mongoose.model('CleaningWeek', CleaningWeekSchema);

module.exports = CleaningWeek;
<commit_msg>use isoweek<commit_after>const mongoose = require('mongoose');
const _ = require('lodash');
const moment = require('moment');
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

const CleaningWeekSchema = new Schema({
  weekNumber: {
    type: Number,
    required: true,
  },
  year: {
    type: Number,
    required: true
  },
  confirmations: {
    type: [{
      type: String,
      enum: ['max', 'tom', 'steve']
    }],
    default: []
  }
});

CleaningWeekSchema.methods = {
  async confirm(name) {
    return await this.update({ $addToSet: { confirmations: name } });
  }
};

CleaningWeekSchema.statics = {
  async getCurrentWeek() {
    let today = moment();
    if (today.day() === 0) {
      today = today.subtract(1, 'day');
    }

    const weekNumber = today.isoWeek();
    const year = today.year();

    const week = await this.findOne({ weekNumber, year });

    return week || this.create({ weekNumber, year });
  },

  async confirmCurrentWeek(name) {
    const currentWeek = await this.getCurrentWeek();
    await currentWeek.confirm(name);

    return this.getCurrentWeek();
  }
}

const CleaningWeek = mongoose.model('CleaningWeek', CleaningWeekSchema);

module.exports = CleaningWeek;
<|endoftext|>


<commit_before>import extend from 'extend'
import Rails from './rails'

// NOTE: `source` and `watch` are node-glob options hashes. e.g. gulp.src(source.glob, source.options)
const PresetRails = {
  baseDirectories: ['./'],
  javascripts: {
    source: {
      glob: 'application.js',
      options: {cwd: 'app/assets/javascripts'}
    },
    watch: {options: {cwd: 'app/assets/javascripts'}},
    dest: 'public/javascripts'
  },
  stylesheets: {
    source: {options: {cwd: 'app/assets/stylesheets'}},
    watch: {options: {cwd: 'app/assets/stylesheets'}},
    dest: 'public/stylesheets'
  },
  images: {
    source: {options: {cwd: 'app/assets/images'}},
    watch: {options: {cwd: 'app/assets/images'}},
    dest: 'public/images'
  },
  digest: {
    source: {options: {cwd: 'public'}},
    watch: {options: {cwd: 'public'}},
    dest: 'public/digest'
  }
}
const PresetNodeLib = {
  baseDirectories: ['./'],
  javascripts: {
    source: {
      glob: 'index.js',
      options: {cwd: 'lib'}
    },
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  stylesheets: {
    source: {options: {cwd: 'lib'}},
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  images: {
    source: {options: {cwd: 'lib'}},
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  digest: {
    source: {options: {cwd: 'dist'}},
    watch: {options: {cwd: 'dist'}},
    dest: 'dist/digest'
  }
}

const PresetNodeSrc = {
  baseDirectories: ['./'],
  javascripts: {
    source: {
      glob: 'index.js',
      options: {cwd: 'src'}
    },
    watch: {options: {cwd: 'src'}},
    dest: 'dist'
  },
  stylesheets: {
    source: {options: {cwd: 'src'}},
    watch: {options: {cwd: 'src'}},
    dest: 'dist'
  },
  images: {
    source: {options: {cwd: 'lib'}},
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  digest: {
    source: {options: {cwd: 'dist'}},
    watch: {options: {cwd: 'dist'}},
    dest: 'dist/digest'
  }
}

const Preset = class {
  static nodeLib(overrides = {}) {
    return extend(true, {}, PresetNodeLib, overrides)
  }

  static nodeSrc(overrides = {}) {
    return extend(true, {}, PresetNodeSrc, overrides)
  }

  static rails(overrides = {}) {

    return extend(true, {}, PresetRails, Rails.baseDirectories(), overrides)
  }
}
export default Preset
<commit_msg>with rails, yield separate debug and digest directories under the base public/assets.  With the companion gem, this gives the greatest servability with external static file servers and provides clear separation of concerns.<commit_after>import extend from 'extend'
import Rails from './rails'

// NOTE: `source` and `watch` are node-glob options hashes. e.g. gulp.src(source.glob, source.options)
const PresetRails = {
  baseDirectories: ['./'],
  javascripts: {
    source: {
      glob: 'application.js',
      options: {cwd: 'app/assets/javascripts'}
    },
    watch: {options: {cwd: 'app/assets/javascripts'}},
    dest: 'public/assets/debug'
  },
  stylesheets: {
    source: {options: {cwd: 'app/assets/stylesheets'}},
    watch: {options: {cwd: 'app/assets/stylesheets'}},
    dest: 'public/assets/debug'
  },
  images: {
    source: {options: {cwd: 'app/assets/images'}},
    watch: {options: {cwd: 'app/assets/images'}},
    dest: 'public/assets/debug'
  },
  digest: {
    source: {options: {cwd: 'public/assets/debug'}},
    watch: {options: {cwd: 'public/assets/debug'}},
    dest: 'public/assets/digest'
  }
}
const PresetNodeLib = {
  baseDirectories: ['./'],
  javascripts: {
    source: {
      glob: 'index.js',
      options: {cwd: 'lib'}
    },
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  stylesheets: {
    source: {options: {cwd: 'lib'}},
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  images: {
    source: {options: {cwd: 'lib'}},
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  digest: {
    source: {options: {cwd: 'dist'}},
    watch: {options: {cwd: 'dist'}},
    dest: 'dist/digest'
  }
}

const PresetNodeSrc = {
  baseDirectories: ['./'],
  javascripts: {
    source: {
      glob: 'index.js',
      options: {cwd: 'src'}
    },
    watch: {options: {cwd: 'src'}},
    dest: 'dist'
  },
  stylesheets: {
    source: {options: {cwd: 'src'}},
    watch: {options: {cwd: 'src'}},
    dest: 'dist'
  },
  images: {
    source: {options: {cwd: 'lib'}},
    watch: {options: {cwd: 'lib'}},
    dest: 'dist'
  },
  digest: {
    source: {options: {cwd: 'dist'}},
    watch: {options: {cwd: 'dist'}},
    dest: 'dist/digest'
  }
}

const Preset = class {
  static nodeLib(overrides = {}) {
    return extend(true, {}, PresetNodeLib, overrides)
  }

  static nodeSrc(overrides = {}) {
    return extend(true, {}, PresetNodeSrc, overrides)
  }

  static rails(overrides = {}) {

    return extend(true, {}, PresetRails, Rails.baseDirectories(), overrides)
  }
}
export default Preset
<|endoftext|>


<commit_before>'use strict';
var mongoose = require('mongoose')
	, _ = require('lodash')
	, moment = require('moment')
	, CronJob = require('cron').CronJob
	, Q = require('q')
	, OperationalHours = require('../api/operationalHours/operationalHours.model')
	, Ride = require('../api/ride/ride.model')
	, WaitTime = require('../api/waitTime/waitTime.model');

require('moment-range');
require('moment-timezone');

exports.start = function(parkAPI, parkId) {
	console.log('Start logging Disneyland wait times...');
	var job = new CronJob('00 */10 * * * *', function() {
		getData(parkAPI, parkId);
	}, function() {
		console.log('done');
	}, true, 'America/Los_Angeles');
	job.start();
};

function getData(parkAPI, parkId) {
	console.log('Start checking');
	console.log('Check time at:' + moment().tz('America/Los_Angeles').format('ddd, h:mmA'));
	checkDate(parkAPI, parkId).then(function(operationalHours) {
		console.log('hours received');
		var range = moment.range(moment(operationalHours.openingTime).tz('America/Los_Angeles'), moment(operationalHours.closingTime).tz('America/Los_Angeles'));
		if(range.contains(moment().tz('America/Los_Angeles'))) {
			console.log('Within park operating hours');
			console.log('Checking wait times...');
			checkAndRecordWaitTimes(parkAPI, parkId);
		} else {
			var openingHour = moment(operationalHours.openingTime).tz('America/Los_Angeles').format('ddd, h:mmA');
			var closingHour = moment(operationalHours.closingTime).tz('America/Los_Angeles').format('ddd, h:mmA');
			var currentHour = moment().tz('America/Los_Angeles').format('ddd, h:mmA');
			console.log('Park is closed: ' + openingHour + ' - ' + closingHour + '. It is currently ' + currentHour);
		}
	}, function() {
		console.log('oops');
	});
}

function checkDate(parkAPI, parkId) {
	console.log('checking date');
	var deferred = Q.defer();
	OperationalHours.findOne({
		park: parkId,
		date: {
			$gte: moment().tz('America/Los_Angeles').startOf('day').toDate(),
			$lte: moment().tz('America/Los_Angeles').endOf('day').toDate()
		}
	}, function(err, operationalHours) {
		if(err) {
			console.log('checkDate error');
			deferred.reject(err);
		}
		if(operationalHours) {
			deferred.resolve(operationalHours);
		} else {
			parkAPI.GetOpeningTimes(function(err, data) {
				if (err) {
					deferred.reject();
					return console.error("Error fetching Magic Kingdom schedule: " + err);
				}
				_.each(data, function(day) {
					OperationalHours.create({
						park: parkId,
						date: moment(day.date).toDate(),
						openingTime: moment(day.openingTime).toDate(),
						closingTime: moment(day.closingTime).toDate()
					}, function(err, operationalHours) {
						if(err) {
							deferred.reject(err);
							return;
						}
						if(moment().tz('America/Los_Angeles').dayOfYear() === moment(operationalHours.date).tz('America/Los_Angeles').dayOfYear()) {
							deferred.resolve(operationalHours);
						}
					});
				});
			});
		}
	});
	return deferred.promise;
}

function checkAndRecordWaitTimes(parkAPI, parkId) {
	parkAPI.GetWaitTimes(function(err, data) {
		if (err) {
			return console.error("Error fetching Magic Kingdom wait times: " + err);
		}
		var promises = [];
		_.each(data, function(rideData) {
			if(_.indexOf([
				'353305',
				'353313',
				'353315',
				'353309',
				'353321',
				'353329',
				'353335',
				'353351',
				'353353',
				'353395',
				'353461',
				'393385',
				'18237344',
				'17328049',
				'16581435',
				'17945184',
				'353339'], rideData.id) >= 0) {
				return;
			}

			var deferred = Q.defer();
			promises.push(deferred.promise);
			var startTime, endTime;
			if(rideData.fastPassWindow && rideData.fastPassWindow.startDate && rideData.fastPassWindow.endDate) {
				startTime = rideData.fastPassWindow.startDate.split(':');
				endTime = rideData.fastPassWindow.endDate.split(':');
			}

			Ride.findOrCreate({
				id: rideData.id,
				name: rideData.name,
				park: parkId
			}, _.noop);

			var waitTime = new WaitTime({
				park: parkId,
				id: rideData.id,
				name: rideData.name,
				fastPass: rideData.fastPass,
				active: rideData.active,
				minutes: rideData.waitTime,
				date: new Date(),
				fastPassWindow: {
					startDate: startTime ? moment().tz('America/Los_Angeles').hours(startTime[0]).minutes(startTime[1]).seconds(0) : undefined,
					endDate: endTime ? moment().tz('America/Los_Angeles').hours(endTime[0]).minutes(endTime[1]).seconds(0) : undefined
				}
			});
			waitTime.save(function(error) {
				if(error) {
					return deferred.reject();
				}
				return deferred.resolve();
			});
		});
		Q.all(promises).then(function() {
			console.log('Wait times recorded');
		}, function() {
			console.log('There was a problem recording wait times');
		});
	});
}
<commit_msg>fixing date<commit_after>'use strict';
var mongoose = require('mongoose')
	, _ = require('lodash')
	, moment = require('moment')
	, CronJob = require('cron').CronJob
	, Q = require('q')
	, OperationalHours = require('../api/operationalHours/operationalHours.model')
	, Ride = require('../api/ride/ride.model')
	, WaitTime = require('../api/waitTime/waitTime.model');

require('moment-range');
require('moment-timezone');

exports.start = function(parkAPI, parkId) {
	console.log('Start logging Disneyland wait times...');
	var job = new CronJob('00 */10 * * * *', function() {
		getData(parkAPI, parkId);
	}, function() {
		console.log('done');
	}, true, 'America/Los_Angeles');
	job.start();
};

function getData(parkAPI, parkId) {
	console.log('Start checking');
	console.log('Check time at:' + moment().tz('America/Los_Angeles').format('ddd, h:mmA'));
	checkDate(parkAPI, parkId).then(function(operationalHours) {
		console.log('hours received');
		var range = moment.range(moment(operationalHours.openingTime).tz('America/Los_Angeles'), moment(operationalHours.closingTime).tz('America/Los_Angeles'));
		if(range.contains(moment().tz('America/Los_Angeles'))) {
			console.log('Within park operating hours');
			console.log('Checking wait times...');
			checkAndRecordWaitTimes(parkAPI, parkId);
		} else {
			var openingHour = moment(operationalHours.openingTime).tz('America/Los_Angeles').format('ddd, h:mmA');
			var closingHour = moment(operationalHours.closingTime).tz('America/Los_Angeles').format('ddd, h:mmA');
			var currentHour = moment().tz('America/Los_Angeles').format('ddd, h:mmA');
			console.log('Park is closed: ' + openingHour + ' - ' + closingHour + '. It is currently ' + currentHour);
		}
	}, function() {
		console.log('oops');
	});
}

function checkDate(parkAPI, parkId) {
	console.log('checking date');
	var deferred = Q.defer();
	OperationalHours.findOne({
		park: parkId,
		date: {
      $gte: moment().tz('America/Los_Angeles').startOf('day'),
      $lt: moment().tz('America/Los_Angeles').endOf('day')
		}
	}, function(err, operationalHours) {
		if(err) {
			console.log('checkDate error');
			deferred.reject(err);
		}
		if(operationalHours) {
			deferred.resolve(operationalHours);
		} else {
			parkAPI.GetOpeningTimes(function(err, data) {
				if (err) {
					deferred.reject();
					return console.error("Error fetching Magic Kingdom schedule: " + err);
				}
				_.each(data, function(day) {
					OperationalHours.create({
						park: parkId,
						date: moment(day.date).toDate(),
						openingTime: moment(day.openingTime).toDate(),
						closingTime: moment(day.closingTime).toDate()
					}, function(err, operationalHours) {
						if(err) {
							deferred.reject(err);
							return;
						}
						if(moment().tz('America/Los_Angeles').dayOfYear() === moment(operationalHours.date).tz('America/Los_Angeles').dayOfYear()) {
							deferred.resolve(operationalHours);
						}
					});
				});
			});
		}
	});
	return deferred.promise;
}

function checkAndRecordWaitTimes(parkAPI, parkId) {
	parkAPI.GetWaitTimes(function(err, data) {
		if (err) {
			return console.error("Error fetching Magic Kingdom wait times: " + err);
		}
		var promises = [];
		_.each(data, function(rideData) {
			if(_.indexOf([
				'353305',
				'353313',
				'353315',
				'353309',
				'353321',
				'353329',
				'353335',
				'353351',
				'353353',
				'353395',
				'353461',
				'393385',
				'18237344',
				'17328049',
				'16581435',
				'17945184',
				'353339'], rideData.id) >= 0) {
				return;
			}

			var deferred = Q.defer();
			promises.push(deferred.promise);
			var startTime, endTime;
			if(rideData.fastPassWindow && rideData.fastPassWindow.startDate && rideData.fastPassWindow.endDate) {
				startTime = rideData.fastPassWindow.startDate.split(':');
				endTime = rideData.fastPassWindow.endDate.split(':');
			}

			Ride.findOrCreate({
				id: rideData.id,
				name: rideData.name,
				park: parkId
			}, _.noop);

			var waitTime = new WaitTime({
				park: parkId,
				id: rideData.id,
				name: rideData.name,
				fastPass: rideData.fastPass,
				active: rideData.active,
				minutes: rideData.waitTime,
				date: new Date(),
				fastPassWindow: {
					startDate: startTime ? moment().tz('America/Los_Angeles').hours(startTime[0]).minutes(startTime[1]).seconds(0) : undefined,
					endDate: endTime ? moment().tz('America/Los_Angeles').hours(endTime[0]).minutes(endTime[1]).seconds(0) : undefined
				}
			});
			waitTime.save(function(error) {
				if(error) {
					return deferred.reject();
				}
				return deferred.resolve();
			});
		});
		Q.all(promises).then(function() {
			console.log('Wait times recorded');
		}, function() {
			console.log('There was a problem recording wait times');
		});
	});
}
<|endoftext|>


<commit_before>
/**
 * ## Glad Tokenizer
 *```
 * var tokenizer = require('glad').tokenizer;
 *
 * tokenizer.generate(6); // <-- 6 character token
 * tokenizer.generate(256); // <-- 256 character token
 *
 * var myTokenizer = tokenizer.create('0123456789');
 * myTokenizer.generate(6) // 6 character token of '0123456789' characters
 *```
 */

function rand (max) {
    return Math.floor(Math.random()*max);
}

function generate(salt, size){
    var key = '';
    var sl = salt.length;
    while ( size -- ) {
        var rnd = rand(sl);
        key += salt[rnd]
    }
    return key
}

var randomToken = function(salt, size){
    return isNaN(size) ? undefined : size < 1 ? undefined : generate(salt, size)
};

randomToken.gen = createGenerator;

function createGenerator (salt) {
    salt = typeof salt  == 'string' && salt.length > 0 ? salt :  'ABCDEFGHIJKLMNOPQRSTUVWXYZ-0987654321_abcdefghijklmnopqrstuvwxyz';
    var temp = randomToken.bind(randomToken, salt);
    temp.salt = function(){ return salt; };
    temp.create = createGenerator;
    temp.gen = createGenerator;
    return temp;
}

module.exports.generate = createGenerator();
module.exports.create = createGenerator;
<commit_msg>Reformatting<commit_after>
/**
 * ## Glad Tokenizer
 *```
 * var tokenizer = require('glad').tokenizer;
 *
 * tokenizer.generate(6); // <-- 6 character token
 * tokenizer.generate(256); // <-- 256 character token
 *
 * var myTokenizer = tokenizer.create('0123456789');
 * myTokenizer.generate(6) // 6 character token of '0123456789' characters
 *```
 */

function rand (max) {
    return Math.floor(Math.random()*max);
}

function generate(salt, size){
    var key = '';
    var sl = salt.length;
    while ( size -- ) {
        var rnd = rand(sl);
        key += salt[rnd];
    }
    return key;
}

var randomToken = function(salt, size){
    return isNaN(size) ? undefined : (size < 1) ? undefined : generate(salt, size);
};

randomToken.gen = createGenerator;

function createGenerator (salt) {
    var temp;

    salt = ( (typeof salt  === 'string') && (salt.length > 0) ) ? salt :  'ABCDEFGHIJKLMNOPQRSTUVWXYZ-0987654321_abcdefghijklmnopqrstuvwxyz';
    temp = randomToken.bind(randomToken, salt);
    temp.salt = function(){ return salt; };
    temp.create = createGenerator;
    temp.gen = createGenerator;
    return temp;
}

module.exports.generate = createGenerator();
module.exports.create = createGenerator;
<|endoftext|>


<commit_before>String.prototype.replaceAll = function(search, replace)
{
    //if replace is not sent, return original string otherwise it will
    //replace search string with 'undefined'.
    if (replace === undefined) {
        return this.toString();
    }

    return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};

// GitHub is using pjax to reload the page. This means the browser will not detect the page change event
// We need to trigger our plugin when a page change occurs
$(document).on('pjax:end', function() {
  injectPage();
});

injectPage();

function injectPage(){
  var splittedURL = window.location.pathname.split("/");
  var isCommitListPage = splittedURL.indexOf("commits") > -1;
  //Only inject on pages related to a project, and are not a commit listing
  if(splittedURL.length > 2 && !isCommitListPage){
    var repoFromLink = splittedURL[2];

    listRepositories(function(repos){
        var repos = repos.filter(repo => repo.scm == repoFromLink);
        if(repos){
          processRepo(repos);
        }
    });
  }
}

function processRepo(repos){
  var pageRelativeIssueId = 0;
  var components = $(".comment-body, .commit-title, .commit-desc, .js-issue-title");

  for(var componentIndex = 0; componentIndex < components.length; componentIndex++){
    var commentBody = $(components[componentIndex]);
    var splittedBody = commentBody.text().toString().split(" ");
    for( var i in splittedBody){
      var text = splittedBody[i];
      for(var j in repos){
        var repo = repos[j];
        if (splittedBody[i].indexOf(repo.keyword) > -1){
          //Clean the link from some symbols usually added to destinguish issue-id from commit message
          var issueId = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll(")", "").replaceAll("(", "").replaceAll("#", "").trim();
          var newId = pageRelativeIssueId++;
          commentBody.html(commentBody.html().replace(text.trim(), '' + text + ''));
          issuePreviewer.enableIssuePreview(repo, issueId, newId);
        }
      }
    }
  }

}
<commit_msg>Ignore part if it is already a link<commit_after>String.prototype.replaceAll = function(search, replace)
{
    //if replace is not sent, return original string otherwise it will
    //replace search string with 'undefined'.
    if (replace === undefined) {
        return this.toString();
    }

    return this.replace(new RegExp('[' + search + ']', 'g'), replace);
};

// GitHub is using pjax to reload the page. This means the browser will not detect the page change event
// We need to trigger our plugin when a page change occurs
$(document).on('pjax:end', function() {
  injectPage();
});

injectPage();

function injectPage(){
  var splittedURL = window.location.pathname.split("/");
  var isCommitListPage = splittedURL.indexOf("commits") > -1;
  //Only inject on pages related to a project, and are not a commit listing
  if(splittedURL.length > 2 && !isCommitListPage){
    var repoFromLink = splittedURL[2];

    listRepositories(function(repos){
        var repos = repos.filter(repo => repo.scm == repoFromLink);
        if(repos){
          processRepo(repos);
        }
    });
  }
}

function processRepo(repos){
  var pageRelativeIssueId = 0;
  var components = $(".comment-body, .commit-title, .commit-desc, .js-issue-title");

  for(var componentIndex = 0; componentIndex < components.length; componentIndex++){
    var commentBody = $(components[componentIndex]);
    var splittedBody = commentBody.text().toString().split(" ");
    for( var i in splittedBody){
      var text = splittedBody[i];
      for(var j in repos){
        var repo = repos[j];
        if (splittedBody[i].indexOf(repo.keyword) > -1){
          if(text.indexOf(repo.targetURL) > -1){
            //ignore this part since it already contains a proper link
            continue;
          }
          //Clean the link from some symbols usually added to destinguish issue-id from commit message
          var issueId = text.replaceAll("[", "").replaceAll("\\]", "").replaceAll(")", "").replaceAll("(", "").replaceAll("#", "").trim();
          var newId = pageRelativeIssueId++;
          commentBody.html(commentBody.html().replace(text.trim(), '' + text + ''));
          issuePreviewer.enableIssuePreview(repo, issueId, newId);
        }
      }
    }
  }

}
<|endoftext|>