<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var APP = {

	Player: function () {

		var scope = this;

		var loader = new THREE.ObjectLoader();
		var camera, scene, renderer;

		var vr, controls, effect;

		var events = {};

		this.dom = undefined;

		this.width = 500;
		this.height = 500;

		this.load = function ( json ) {

			vr = json.project.vr;

			renderer = new THREE.WebGLRenderer( { antialias: true } );
			renderer.setClearColor( 0x000000 );
			renderer.setPixelRatio( window.devicePixelRatio );
			this.dom = renderer.domElement;

			this.setScene( loader.parse( json.scene ) );
			this.setCamera( loader.parse( json.camera ) );

			events = {
				init: [],
				start: [],
				stop: [],
				keydown: [],
				keyup: [],
				mousedown: [],
				mouseup: [],
				mousemove: [],
				touchstart: [],
				touchend: [],
				touchmove: [],
				update: []
			};

			var scriptWrapParams = 'player,renderer,scene';
			var scriptWrapResultObj = {};
			for ( var eventKey in events ) {
				scriptWrapParams += ',' + eventKey;
				scriptWrapResultObj[ eventKey ] = eventKey;
			}
			var scriptWrapResult =
					JSON.stringify( scriptWrapResultObj ).replace( /\"/g, '' );

			for ( var uuid in json.scripts ) {

				var object = scene.getObjectByProperty( 'uuid', uuid, true );

				var scripts = json.scripts[ uuid ];

				for ( var i = 0; i < scripts.length; i ++ ) {

					var script = scripts[ i ];

					var functions = ( new Function( scriptWrapParams,
							script.source + '\nreturn ' + scriptWrapResult+ ';' ).bind( object ) )( this, renderer, scene );

					for ( var name in functions ) {

						if ( functions[ name ] === undefined ) continue;

						if ( events[ name ] === undefined ) {

							console.warn( 'APP.Player: event type not supported (', name, ')' );
							continue;

						}

						events[ name ].push( functions[ name ].bind( object ) );

					}

				}

			}

			dispatch( events.init, arguments );

		};

		this.setCamera = function ( value ) {

			camera = value;
			camera.aspect = this.width / this.height;
			camera.updateProjectionMatrix();

			if ( vr === true ) {

				if ( camera.parent === null ) {

					// camera needs to be in the scene so camera2 matrix updates

					scene.add( camera );

				}

				var camera2 = camera.clone();
				camera.add( camera2 );

				camera = camera2;

				controls = new THREE.VRControls( camera );
				effect = new THREE.VREffect( renderer );

				document.addEventListener( 'keyup', function ( event ) {

					switch ( event.keyCode ) {
						case 90:
							controls.zeroSensor();
							break;
					}

				} );

				this.dom.addEventListener( 'dblclick', function () {

					effect.setFullScreen( true );

				} );

			}

		};

		this.setScene = function ( value ) {

			scene = value;

		},

		this.setSize = function ( width, height ) {

			if ( renderer._fullScreen ) return;

			this.width = width;
			this.height = height;

			camera.aspect = this.width / this.height;
			camera.updateProjectionMatrix();

			renderer.setSize( width, height );

		};

		var dispatch = function ( array, event ) {

			for ( var i = 0, l = array.length; i < l; i ++ ) {

				try {

					array[ i ]( event );

				} catch (e) {

					console.error( ( e.message || e ), ( e.stack || "" ) );

				}

			}

		};

		var prevTime, request;

		var animate = function ( time ) {

			request = requestAnimationFrame( animate );

			dispatch( events.update, { time: time, delta: time - prevTime } );

			if ( vr === true ) {

				controls.update();
				effect.render( scene, camera );

			} else {

				renderer.render( scene, camera );

			}

			prevTime = time;

		};

		this.play = function () {

			document.addEventListener( 'keydown', onDocumentKeyDown );
			document.addEventListener( 'keyup', onDocumentKeyUp );
			document.addEventListener( 'mousedown', onDocumentMouseDown );
			document.addEventListener( 'mouseup', onDocumentMouseUp );
			document.addEventListener( 'mousemove', onDocumentMouseMove );
			document.addEventListener( 'touchstart', onDocumentTouchStart );
			document.addEventListener( 'touchend', onDocumentTouchEnd );
			document.addEventListener( 'touchmove', onDocumentTouchMove );

			dispatch( events.start, arguments );

			request = requestAnimationFrame( animate );
			prevTime = performance.now();
		};

		this.stop = function () {

			document.removeEventListener( 'keydown', onDocumentKeyDown );
			document.removeEventListener( 'keyup', onDocumentKeyUp );
			document.removeEventListener( 'mousedown', onDocumentMouseDown );
			document.removeEventListener( 'mouseup', onDocumentMouseUp );
			document.removeEventListener( 'mousemove', onDocumentMouseMove );
			document.removeEventListener( 'touchstart', onDocumentTouchStart );
			document.removeEventListener( 'touchend', onDocumentTouchEnd );
			document.removeEventListener( 'touchmove', onDocumentTouchMove );

			dispatch( events.stop, arguments );

			cancelAnimationFrame( request );
		};

		//

		var onDocumentKeyDown = function ( event ) {

			dispatch( events.keydown, event );

		};

		var onDocumentKeyUp = function ( event ) {

			dispatch( events.keyup, event );

		};

		var onDocumentMouseDown = function ( event ) {

			dispatch( events.mousedown, event );

		};

		var onDocumentMouseUp = function ( event ) {

			dispatch( events.mouseup, event );

		};

		var onDocumentMouseMove = function ( event ) {

			dispatch( events.mousemove, event );

		};

		var onDocumentTouchStart = function ( event ) {

			dispatch( events.touchstart, event );

		};

		var onDocumentTouchEnd = function ( event ) {

			dispatch( events.touchend, event );

		};

		var onDocumentTouchMove = function ( event ) {

			dispatch( events.touchmove, event );

		};

	}

};
<commit_msg>Player: Add fallback for 'performance.now()'.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var APP = {

	Player: function () {

		var scope = this;

		var loader = new THREE.ObjectLoader();
		var camera, scene, renderer;

		var vr, controls, effect;

		var events = {};

		this.dom = undefined;

		this.width = 500;
		this.height = 500;

		this.load = function ( json ) {

			vr = json.project.vr;

			renderer = new THREE.WebGLRenderer( { antialias: true } );
			renderer.setClearColor( 0x000000 );
			renderer.setPixelRatio( window.devicePixelRatio );
			this.dom = renderer.domElement;

			this.setScene( loader.parse( json.scene ) );
			this.setCamera( loader.parse( json.camera ) );

			events = {
				init: [],
				start: [],
				stop: [],
				keydown: [],
				keyup: [],
				mousedown: [],
				mouseup: [],
				mousemove: [],
				touchstart: [],
				touchend: [],
				touchmove: [],
				update: []
			};

			var scriptWrapParams = 'player,renderer,scene';
			var scriptWrapResultObj = {};
			for ( var eventKey in events ) {
				scriptWrapParams += ',' + eventKey;
				scriptWrapResultObj[ eventKey ] = eventKey;
			}
			var scriptWrapResult =
					JSON.stringify( scriptWrapResultObj ).replace( /\"/g, '' );

			for ( var uuid in json.scripts ) {

				var object = scene.getObjectByProperty( 'uuid', uuid, true );

				var scripts = json.scripts[ uuid ];

				for ( var i = 0; i < scripts.length; i ++ ) {

					var script = scripts[ i ];

					var functions = ( new Function( scriptWrapParams,
							script.source + '\nreturn ' + scriptWrapResult+ ';' ).bind( object ) )( this, renderer, scene );

					for ( var name in functions ) {

						if ( functions[ name ] === undefined ) continue;

						if ( events[ name ] === undefined ) {

							console.warn( 'APP.Player: event type not supported (', name, ')' );
							continue;

						}

						events[ name ].push( functions[ name ].bind( object ) );

					}

				}

			}

			dispatch( events.init, arguments );

		};

		this.setCamera = function ( value ) {

			camera = value;
			camera.aspect = this.width / this.height;
			camera.updateProjectionMatrix();

			if ( vr === true ) {

				if ( camera.parent === null ) {

					// camera needs to be in the scene so camera2 matrix updates

					scene.add( camera );

				}

				var camera2 = camera.clone();
				camera.add( camera2 );

				camera = camera2;

				controls = new THREE.VRControls( camera );
				effect = new THREE.VREffect( renderer );

				document.addEventListener( 'keyup', function ( event ) {

					switch ( event.keyCode ) {
						case 90:
							controls.zeroSensor();
							break;
					}

				} );

				this.dom.addEventListener( 'dblclick', function () {

					effect.setFullScreen( true );

				} );

			}

		};

		this.setScene = function ( value ) {

			scene = value;

		},

		this.setSize = function ( width, height ) {

			if ( renderer._fullScreen ) return;

			this.width = width;
			this.height = height;

			camera.aspect = this.width / this.height;
			camera.updateProjectionMatrix();

			renderer.setSize( width, height );

		};

		var dispatch = function ( array, event ) {

			for ( var i = 0, l = array.length; i < l; i ++ ) {

				try {

					array[ i ]( event );

				} catch (e) {

					console.error( ( e.message || e ), ( e.stack || "" ) );

				}

			}

		};

		var prevTime, request;

		var animate = function ( time ) {

			request = requestAnimationFrame( animate );

			dispatch( events.update, { time: time, delta: time - prevTime } );

			if ( vr === true ) {

				controls.update();
				effect.render( scene, camera );

			} else {

				renderer.render( scene, camera );

			}

			prevTime = time;

		};

		this.play = function () {

			document.addEventListener( 'keydown', onDocumentKeyDown );
			document.addEventListener( 'keyup', onDocumentKeyUp );
			document.addEventListener( 'mousedown', onDocumentMouseDown );
			document.addEventListener( 'mouseup', onDocumentMouseUp );
			document.addEventListener( 'mousemove', onDocumentMouseMove );
			document.addEventListener( 'touchstart', onDocumentTouchStart );
			document.addEventListener( 'touchend', onDocumentTouchEnd );
			document.addEventListener( 'touchmove', onDocumentTouchMove );

			dispatch( events.start, arguments );

			request = requestAnimationFrame( animate );
			prevTime = ( window.performance || Date ).now();
		};

		this.stop = function () {

			document.removeEventListener( 'keydown', onDocumentKeyDown );
			document.removeEventListener( 'keyup', onDocumentKeyUp );
			document.removeEventListener( 'mousedown', onDocumentMouseDown );
			document.removeEventListener( 'mouseup', onDocumentMouseUp );
			document.removeEventListener( 'mousemove', onDocumentMouseMove );
			document.removeEventListener( 'touchstart', onDocumentTouchStart );
			document.removeEventListener( 'touchend', onDocumentTouchEnd );
			document.removeEventListener( 'touchmove', onDocumentTouchMove );

			dispatch( events.stop, arguments );

			cancelAnimationFrame( request );
		};

		//

		var onDocumentKeyDown = function ( event ) {

			dispatch( events.keydown, event );

		};

		var onDocumentKeyUp = function ( event ) {

			dispatch( events.keyup, event );

		};

		var onDocumentMouseDown = function ( event ) {

			dispatch( events.mousedown, event );

		};

		var onDocumentMouseUp = function ( event ) {

			dispatch( events.mouseup, event );

		};

		var onDocumentMouseMove = function ( event ) {

			dispatch( events.mousemove, event );

		};

		var onDocumentTouchStart = function ( event ) {

			dispatch( events.touchstart, event );

		};

		var onDocumentTouchEnd = function ( event ) {

			dispatch( events.touchend, event );

		};

		var onDocumentTouchMove = function ( event ) {

			dispatch( events.touchmove, event );

		};

	}

};
<|endoftext|>


<commit_before>var Twit = require('twit');
var config = require(__dirname + '/config.js');
var scraperjs = require('scraperjs');

var T = new Twit({
  consumer_key:        config.keys.consumer_key,
  consumer_secret:     config.keys.consumer_secret,
  access_token:        config.keys.access_token,
  access_token_secret: config.keys.access_token_secret,
  timeout_ms:          60*1000,  // optional HTTP request timeout to apply to all requests.
});

var options = {exclude_replies:true, include_rts:false, count: 1 };

function getTweet(who) {
  who = who || 'tinycarebot';
  return config.apiKeys ? apiTweet(who) : scrapeTweet(who);
}

function apiTweet(who) {
  options.screen_name = who;
  return new Promise(function (resolve, reject) {
    T.get('statuses/user_timeline', options, function(err, data) {
      if (err) {
        reject('This didn\'t work. Maybe you didn\'t set up the twitter API keys?');
      } else {
        resolve({text:data[0].text, bot: data[0].user.screen_name});
      }
    });
  });
}

function scrapeTweet(who) {
  return new Promise(function (resolve, reject) {
    scraperjs.StaticScraper.create('https://twitter.com/' + who)
        .scrape(function($) {
            return $(".js-tweet-text.tweet-text").map(function() {
                return $(this).text();
            }).get();
        })
        .then(function(tweets) {
          var tweetNumber = Math.floor(Math.random() * tweets.length);
          resolve({text:tweets[tweetNumber], bot: who});
        },function(error) {
          reject('Can\'t scrape tweets. Maybe the user is private or doesn\'t exist?');
        });
  });
}

module.exports.getTweet = getTweet;
<commit_msg>Prevent app from crashing when there is no ingternet connection (#127)<commit_after>var Twit = require('twit');
var config = require(__dirname + '/config.js');
var scraperjs = require('scraperjs');

var T = new Twit({
  consumer_key:        config.keys.consumer_key,
  consumer_secret:     config.keys.consumer_secret,
  access_token:        config.keys.access_token,
  access_token_secret: config.keys.access_token_secret,
  timeout_ms:          60*1000,  // optional HTTP request timeout to apply to all requests.
});

var options = {exclude_replies:true, include_rts:false, count: 1 };

function getTweet(who) {
  who = who || 'tinycarebot';
  return config.apiKeys ? apiTweet(who) : scrapeTweet(who);
}

function apiTweet(who) {
  options.screen_name = who;
  return new Promise(function (resolve, reject) {
    T.get('statuses/user_timeline', options, function(err, data) {
      if (err) {
        reject('This didn\'t work. Maybe you didn\'t set up the twitter API keys?');
      } else {
        resolve({text:data[0].text, bot: data[0].user.screen_name});
      }
    });
  });
}

function scrapeTweet(who) {
  return new Promise(function (resolve, reject) {
    scraperjs.StaticScraper.create('https://twitter.com/' + who)
        .scrape(function($) {
            return $(".js-tweet-text.tweet-text").map(function() {
                return $(this).text();
            }).get();
        })
        .then(function(tweets) {
          var tweetNumber = Math.floor(Math.random() * tweets.length);
          resolve({text:tweets[tweetNumber], bot: who});
        })
        .catch(function(error) {
          reject('Can\'t scrape tweets. Maybe the user is private or doesn\'t exist?');
        });
  });
}

module.exports.getTweet = getTweet;
<|endoftext|>


<commit_before>// twitterlib.js (c) 2009 Remy Sharp
// Licensed under the terms of the MIT license.
(function (twitter, container) {
  var ify = function() {
    return {
      link: function(t) {
        return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
          return '' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '';
        });
      },
      at: function(t) {
        return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15}(\/[a-zA-Z0-9-_]+)*)/g, function(m, m1, m2) {
          return m1 + '@' + m2 + '';
        });
      },
      hash: function(t) {
        return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
          return m1 + '#' + m2 + '';
        });
      },
      clean: function(tweet) {
        return this.hash(this.at(this.link(tweet)));
      }
    };
  }();

  var time = function () {
    var monthDict = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return {
      time: function (date) {
        var hour = date.getHours(),
            min = date.getMinutes() + "",
            ampm = 'AM';

        if (hour == 0) {
          hour = 12;
        } else if (hour == 12) {
          ampm = 'PM';
        } else if (hour > 12) {
          hour -= 12;
          ampm = 'PM';
        }

        if (min.length == 1) {
          min = '0' + min;
        }

        return hour + ':' + min + ' ' + ampm;
      },
      date: function (date) {
        var ds = date.toDateString().split(/ /),
            mon = monthDict[date.getMonth()],
            day = date.getDate()+'',
            dayi = ~~(day),
            year = date.getFullYear(),
            thisyear = (new Date()).getFullYear(),
            th = 'th';

        // anti-'th' - but don't do the 11th, 12th or 13th
        if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
          th = 'st';
        } else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
          th = 'nd';
        } else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
          th = 'rd';
        }

        if (day.substr(0, 1) == '0') {
          day = day.substr(1);
        }

        return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '');
      },
      relative: function (time_value) {
        var values = time_value.split(" "),
            parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]),
            date = new Date(parsed_date),
            relative_to = (arguments.length > 1) ? arguments[1] : new Date(),
            delta = ~~((relative_to.getTime() - parsed_date) / 1000),
            r = '';

        delta = delta + (relative_to.getTimezoneOffset() * 60);

        if (delta < 5) {
          r = 'less than 5 seconds ago';
        } else if (delta < 30) {
          r = 'half a minute ago';
        } else if (delta < 60) {
          r = 'less than a minute ago';
        } else if (delta < 120) {
          r = '1 minute ago';
        } else if (delta < (45*60)) {
          r = (~~(delta / 60)).toString() + ' minutes ago';
        } else if (delta < (2*90*60)) { // 2* because sometimes read 1 hours ago
          r = 'about 1 hour ago';
        } else if (delta < (24*60*60)) {
          r = 'about ' + (~~(delta / 3600)).toString() + ' hours ago';
        } else {
          if (delta < (48*60*60)) {
            r = this.time(date) + ' yesterday';
          } else {
            r = this.time(date) + ' ' + this.date(date);
          }
        }

        return r;
      }
    };
  }();

  var filter = (function () {
    return {
     match: function (tweet, search, includeHighlighted) {
       var i = 0, s = '', text = tweet.text.toLowerCase();

       if (typeof search == "string") {
         search = this.format(search);
       }

       // loop ignore first
       if (search['not'].length) {
         for (i = 0; i < search['not'].length; i++) {
           if (text.indexOf(search['not'][i]) !== -1) {
             return false;
           }
         }

         if (!search['and'].length && !search['or'].length) {
           return true;
         }
       }

       if (search['and'].length) {
         for (i = 0; i < search['and'].length; i++) {
           s = search['and'][i];

           if (s.substr(0, 3) === 'to:') {
             if (!RegExp('^@' + s.substr(3)).test(text)) {
               return false;
             }
           } else if (s.substr(0, 5) == 'from:') {
             if (tweet.user.screen_name !== s.substr(5)) {
               return false;
             }
           } else if (text.indexOf(s) === -1) {
             return false;
           }
         }
       }

       if (search['or'].length) {
         for (i = 0; i < search['or'].length; i++) {
           s = search['or'][i];

           if (s.substr(0, 3) === 'to:') {
             if (RegExp('^@' + s.substr(3)).test(text)) {
               return true;
             }
           } else if (s.substr(0, 5) == 'from:') {
             if (tweet.user.screen_name === s.substr(5)) {
               return true;
             }
           } else if (text.indexOf(search['or'][i]) !== -1) {
             return true;
           }
         }
       } else if (search['and'].length) {
         return true;
       }

       return false;
     },

     format: function (search, caseSensitive) {
       // search can match search.twitter.com format
       var blocks = [], ors = [], ands = [], i = 0, negative = [], since = '', until = '';

       search.replace(/(["'](.*?)["']|\S+\b)/g, function (m) {
         m = m.replace(/^["']+|["']+$/g, '');
         blocks.push(m);
       });

       for (i = 0; i < blocks.length; i++) {
         if (blocks[i] == 'OR' && blocks[i+1]) {
           ors.push(blocks[i-1].toLowerCase());
           ors.push(blocks[i+1].toLowerCase());
           i++;
           ands.pop(); // remove the and test from the last loop
         } else if (blocks[i].substr(0, 1) == '-') {
           negative.push(blocks[i].substr(1).toLowerCase());
         } else {
           ands.push(blocks[i].toLowerCase());
         }
       }

       return {
         'or' : ors,
         'and' : ands,
         'not' : negative
       };
     },

     // tweets typeof Array
     matchTweets: function (tweets, search, includeHighlighted) {
       var updated = [], tmp, i = 0;

       if (typeof search == 'string') {
         search = this.format(search);
       }

       for (i = 0; i < tweets.length; i++) {
         if (this.match(tweets[i], search, includeHighlighted)) {
           updated.push(tweets[i]);
         }
       }

       return updated;
     }
   };
  })();

  var guid = +new Date,
      head = document.getElementsByTagName('head')[0],
      doc = document,
      last = {}, // memorisation object for the next method
      URLS = {
        search: 'http://search.twitter.com/search.json?q=%search%&page=%page|1%&rpp=%limit|100%',
        timeline: 'http://twitter.com/statuses/user_timeline/%user%.json?count=%limit|200%&page=%page|1%',
        listTimeline: 'http://api.twitter.com/1/%user%/lists/%list%/statuses.json?page=%page|1%&per_page=%limit|200%',
        favs: 'http://twitter.com/favorites/%user%.json?page=%page|1%'
      },
      undefined;

  function load(url, options, callback) {
    var script = doc.createElement('script'), match = null;
    if (options == undefined) options = {};
    guid++;

    window[twitter + guid] = (function (guid, options) { // args are now private and static
      return function (tweets) {
        // remove original script include
        var i = 0;
        head.removeChild(doc.getElementById(twitter + guid));

        if (tweets.results) {
          tweets = tweets.results;
          i = tweets.length;
          // fix the user prop to match "normal" API calls
          while (i--) {
            tweets[i].user = { id: tweets[i].from_user_id, screen_name: tweets[i].from_user_id };
          }
        }

        if (options.filter) {
          tweets = filter.matchTweets(tweets, options.filter);
        }
        callback.call(container[twitter], tweets, options);
      };
    })(guid, options);

    match = url.match(/callback=(.*?)/);
    if (match != null && match.length > 1) {
      window[match[1]] = window[twitter + guid];
    } else {
      url += '&callback=' + twitter + guid;
    }

    script.src = url;
    script.id = twitter + guid;
    head.appendChild(script);
  }

  function getUrl(type, options) {
    return URLS[type].replace(/%(.*?)(\|.*?)?%/g, function (a, key, def) {
      return options[key] === undefined ? def.substr(1) : options[key];
    });
  }

  function normaliseArgs(options, callback) {
    if (typeof options == 'function') {
      callback = options;
      options = {};
    }
    if (options === undefined) options = {};
    options.page = options.page || 1;
    options.callback = callback;
    // don't bother returning the options since they're being modified
    return options;
  }

  function setLast(method, arg, options) {
    last = {
      method: method,
      arg: arg,
      options: options,
      callback: options.callback,
      page: options.page || 1
    };
  }

  container[twitter] = {
    // search is an exception case
    search: function (q, options, callback) {
      options = normaliseArgs(options, callback);

      if (options.filter) {
        // remove filter as it conflicts with content
        delete options.filter;
      }

      options.search = encodeURIComponent(q);

      setLast('search', q, options);
      if (options.callback) load(getUrl('search', options), options, options.callback);
      return this;
    },
    status: function (user, options, callback) { // alias function
      options = normaliseArgs(options, callback);
      options.limit = 1;
      setLast('status', user, options); // setting after limit = 1 to keep this intact
      return this.timeline(user, options, options.callback);
    },
    timeline: function (user, options, callback) {
      options = normaliseArgs(options, callback);
      setLast('timeline', user, options);
      options.user = user;
      if (options.callback) load(getUrl('timeline', options), options, options.callback);
      return this;
    },
    list: function (list, options, callback) {
      var parts = list.split('/');
      options = normaliseArgs(options, callback);
      setLast('list', list, options);
      options.user = parts[0];
      options.list = parts[1];
      if (callback) load(getUrl('listTimeline', options), options, options.callback);
      return this;
    },
    favs: function (user, options, callback) {
      options = normaliseArgs(options, callback);
      setLast('favs', user, options);
      options.user = user;
      if (callback) load(getUrl('favs', options), options, options.callback);
      return this;
    },
    next: function () {
      if (last.method) {
        last.page++;
        last.options.page = last.page;
        this[last.method](last.arg, last.options, last.callback);
      } // else we won't do anything
      return this;
    },

    // appending on pre-existing utilities
    time: time,
    ify: ify,
    filter: filter,
    debug: function (urls) {
      for (var url in urls) {
        URLS[url] = urls[url];
      }
      return this;
    }
  };
})('twitterlib', this);<commit_msg>Tweaking debug callback parser<commit_after>// twitterlib.js (c) 2009 Remy Sharp
// Licensed under the terms of the MIT license.
(function (twitter, container) {
  var ify = function() {
    return {
      link: function(t) {
        return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
          return '' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '';
        });
      },
      at: function(t) {
        return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15}(\/[a-zA-Z0-9-_]+)*)/g, function(m, m1, m2) {
          return m1 + '@' + m2 + '';
        });
      },
      hash: function(t) {
        return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
          return m1 + '#' + m2 + '';
        });
      },
      clean: function(tweet) {
        return this.hash(this.at(this.link(tweet)));
      }
    };
  }();

  var time = function () {
    var monthDict = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return {
      time: function (date) {
        var hour = date.getHours(),
            min = date.getMinutes() + "",
            ampm = 'AM';

        if (hour == 0) {
          hour = 12;
        } else if (hour == 12) {
          ampm = 'PM';
        } else if (hour > 12) {
          hour -= 12;
          ampm = 'PM';
        }

        if (min.length == 1) {
          min = '0' + min;
        }

        return hour + ':' + min + ' ' + ampm;
      },
      date: function (date) {
        var ds = date.toDateString().split(/ /),
            mon = monthDict[date.getMonth()],
            day = date.getDate()+'',
            dayi = ~~(day),
            year = date.getFullYear(),
            thisyear = (new Date()).getFullYear(),
            th = 'th';

        // anti-'th' - but don't do the 11th, 12th or 13th
        if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
          th = 'st';
        } else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
          th = 'nd';
        } else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
          th = 'rd';
        }

        if (day.substr(0, 1) == '0') {
          day = day.substr(1);
        }

        return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '');
      },
      relative: function (time_value) {
        var values = time_value.split(" "),
            parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]),
            date = new Date(parsed_date),
            relative_to = (arguments.length > 1) ? arguments[1] : new Date(),
            delta = ~~((relative_to.getTime() - parsed_date) / 1000),
            r = '';

        delta = delta + (relative_to.getTimezoneOffset() * 60);

        if (delta < 5) {
          r = 'less than 5 seconds ago';
        } else if (delta < 30) {
          r = 'half a minute ago';
        } else if (delta < 60) {
          r = 'less than a minute ago';
        } else if (delta < 120) {
          r = '1 minute ago';
        } else if (delta < (45*60)) {
          r = (~~(delta / 60)).toString() + ' minutes ago';
        } else if (delta < (2*90*60)) { // 2* because sometimes read 1 hours ago
          r = 'about 1 hour ago';
        } else if (delta < (24*60*60)) {
          r = 'about ' + (~~(delta / 3600)).toString() + ' hours ago';
        } else {
          if (delta < (48*60*60)) {
            r = this.time(date) + ' yesterday';
          } else {
            r = this.time(date) + ' ' + this.date(date);
          }
        }

        return r;
      }
    };
  }();

  var filter = (function () {
    return {
     match: function (tweet, search, includeHighlighted) {
       var i = 0, s = '', text = tweet.text.toLowerCase();

       if (typeof search == "string") {
         search = this.format(search);
       }

       // loop ignore first
       if (search['not'].length) {
         for (i = 0; i < search['not'].length; i++) {
           if (text.indexOf(search['not'][i]) !== -1) {
             return false;
           }
         }

         if (!search['and'].length && !search['or'].length) {
           return true;
         }
       }

       if (search['and'].length) {
         for (i = 0; i < search['and'].length; i++) {
           s = search['and'][i];

           if (s.substr(0, 3) === 'to:') {
             if (!RegExp('^@' + s.substr(3)).test(text)) {
               return false;
             }
           } else if (s.substr(0, 5) == 'from:') {
             if (tweet.user.screen_name !== s.substr(5)) {
               return false;
             }
           } else if (text.indexOf(s) === -1) {
             return false;
           }
         }
       }

       if (search['or'].length) {
         for (i = 0; i < search['or'].length; i++) {
           s = search['or'][i];

           if (s.substr(0, 3) === 'to:') {
             if (RegExp('^@' + s.substr(3)).test(text)) {
               return true;
             }
           } else if (s.substr(0, 5) == 'from:') {
             if (tweet.user.screen_name === s.substr(5)) {
               return true;
             }
           } else if (text.indexOf(search['or'][i]) !== -1) {
             return true;
           }
         }
       } else if (search['and'].length) {
         return true;
       }

       return false;
     },

     format: function (search, caseSensitive) {
       // search can match search.twitter.com format
       var blocks = [], ors = [], ands = [], i = 0, negative = [], since = '', until = '';

       search.replace(/(["'](.*?)["']|\S+\b)/g, function (m) {
         m = m.replace(/^["']+|["']+$/g, '');
         blocks.push(m);
       });

       for (i = 0; i < blocks.length; i++) {
         if (blocks[i] == 'OR' && blocks[i+1]) {
           ors.push(blocks[i-1].toLowerCase());
           ors.push(blocks[i+1].toLowerCase());
           i++;
           ands.pop(); // remove the and test from the last loop
         } else if (blocks[i].substr(0, 1) == '-') {
           negative.push(blocks[i].substr(1).toLowerCase());
         } else {
           ands.push(blocks[i].toLowerCase());
         }
       }

       return {
         'or' : ors,
         'and' : ands,
         'not' : negative
       };
     },

     // tweets typeof Array
     matchTweets: function (tweets, search, includeHighlighted) {
       var updated = [], tmp, i = 0;

       if (typeof search == 'string') {
         search = this.format(search);
       }

       for (i = 0; i < tweets.length; i++) {
         if (this.match(tweets[i], search, includeHighlighted)) {
           updated.push(tweets[i]);
         }
       }

       return updated;
     }
   };
  })();

  var guid = +new Date,
      head = document.getElementsByTagName('head')[0],
      doc = document,
      last = {}, // memorisation object for the next method
      URLS = {
        search: 'http://search.twitter.com/search.json?q=%search%&page=%page|1%&rpp=%limit|100%',
        timeline: 'http://twitter.com/statuses/user_timeline/%user%.json?count=%limit|200%&page=%page|1%',
        listTimeline: 'http://api.twitter.com/1/%user%/lists/%list%/statuses.json?page=%page|1%&per_page=%limit|200%',
        favs: 'http://twitter.com/favorites/%user%.json?page=%page|1%'
      },
      undefined;

  function load(url, options, callback) {
    var script = doc.createElement('script'), match = null;
    if (options == undefined) options = {};
    guid++;

    window[twitter + guid] = (function (guid, options) { // args are now private and static
      return function (tweets) {
        // remove original script include
        var i = 0;
        head.removeChild(doc.getElementById(twitter + guid));

        if (tweets.results) {
          tweets = tweets.results;
          i = tweets.length;
          // fix the user prop to match "normal" API calls
          while (i--) {
            tweets[i].user = { id: tweets[i].from_user_id, screen_name: tweets[i].from_user_id };
          }
        }

        if (options.filter) {
          tweets = filter.matchTweets(tweets, options.filter);
        }
        callback.call(container[twitter], tweets, options);
      };
    })(guid, options);

    match = url.match(/callback=(.*)/);
    if (match != null && match.length > 1) {
      window[match[1]] = window[twitter + guid];
    } else {
      url += '&callback=' + twitter + guid;
    }

    script.src = url;
    script.id = twitter + guid;
    head.appendChild(script);
  }

  function getUrl(type, options) {
    return URLS[type].replace(/%(.*?)(\|.*?)?%/g, function (a, key, def) {
      return options[key] === undefined ? def.substr(1) : options[key];
    });
  }

  function normaliseArgs(options, callback) {
    if (typeof options == 'function') {
      callback = options;
      options = {};
    }
    if (options === undefined) options = {};
    options.page = options.page || 1;
    options.callback = callback;
    // don't bother returning the options since they're being modified
    return options;
  }

  function setLast(method, arg, options) {
    last = {
      method: method,
      arg: arg,
      options: options,
      callback: options.callback,
      page: options.page || 1
    };
  }

  container[twitter] = {
    // search is an exception case
    search: function (q, options, callback) {
      options = normaliseArgs(options, callback);

      if (options.filter) {
        // remove filter as it conflicts with content
        delete options.filter;
      }

      options.search = encodeURIComponent(q);

      setLast('search', q, options);
      if (options.callback) load(getUrl('search', options), options, options.callback);
      return this;
    },
    status: function (user, options, callback) { // alias function
      options = normaliseArgs(options, callback);
      options.limit = 1;
      setLast('status', user, options); // setting after limit = 1 to keep this intact
      return this.timeline(user, options, options.callback);
    },
    timeline: function (user, options, callback) {
      options = normaliseArgs(options, callback);
      setLast('timeline', user, options);
      options.user = user;
      if (options.callback) load(getUrl('timeline', options), options, options.callback);
      return this;
    },
    list: function (list, options, callback) {
      var parts = list.split('/');
      options = normaliseArgs(options, callback);
      setLast('list', list, options);
      options.user = parts[0];
      options.list = parts[1];
      if (callback) load(getUrl('listTimeline', options), options, options.callback);
      return this;
    },
    favs: function (user, options, callback) {
      options = normaliseArgs(options, callback);
      setLast('favs', user, options);
      options.user = user;
      if (callback) load(getUrl('favs', options), options, options.callback);
      return this;
    },
    next: function () {
      if (last.method) {
        last.page++;
        last.options.page = last.page;
        this[last.method](last.arg, last.options, last.callback);
      } // else we won't do anything
      return this;
    },

    // appending on pre-existing utilities
    time: time,
    ify: ify,
    filter: filter,
    debug: function (urls) {
      for (var url in urls) {
        URLS[url] = urls[url];
      }
      return this;
    }
  };
})('twitterlib', this);<|endoftext|>


<commit_before>/*txtCell
* txtCell_+1.js
*
*    Copyright (c) 2017 Yuji SODE <yuji.sode@gmail.com>
*
*    This software is released under the MIT License.
*    See LICENSE or http://opensource.org/licenses/mit-license.php
*/
//============================================================================
//this is Web Worker interface for Cellular Automaton.
//overflow simulation with +1
var slf=this;
//this function converts a given text into an array separated by given text width
//txt and w are given text and text width
var txt2Arr=function(txt,w){
  var a=[],i=0,n=txt.length,j=0;
  while(i<n){
    a[j]=(a[j]!==undefined)?a[j]:'';
    a[j]+=txt[i],i+=1;
    j=((i%w)!=0)?j:j+1;
  }
  return a;
};
//=== message event ===
slf.addEventListener('message',function(e){
  var d=e.data.split(/@/),P0,P=[],N=0,M=0,I=0,J=0;
  //d[0]:width,d[1]:data, and d[2]:map data
  P0=txt2Arr(d[1],d[0]);
  N=P0.length;
  while(I<N){
    P[I]='',M=P0[I].length,J=0;
    while(J<M){
      P[I]+=+P0[I][J]+1,J+=1;
    }
    I+=1;
  }
  slf.postMessage(P.join(''));
  d=P0=P=N=M=I=J=null
},true);
<commit_msg>Delete txtCell_+1.js<commit_after><|endoftext|>


<commit_before>/*! Simple CSS JS loader asynchronously for all browsers by cara-tm.com, MIT License */
var LoadCSSJS = function ( e, t, o ) {

	"use strict";

	var f="", s;

	if( f.indexOf("["+e+"]") == -1 ) {

		f += "["+e+"]";

		switch (t) {

			case "css" :
				s = document.createElement( "link" );
				s.rel = ( o.rel || "stylesheet" );
				s.href = e;
				// Temporary invalid media query to load it async
				s.media = "only foo";
				setTimeout( function(){ s.media = ( o.media || "all" ); } );
			break;

			case "js" :
				s = document.createElement( "script" );
				if (o.defer)
					s.defer = "defer";
				else
					s.async = "async";
				s.src = e;
			break;

		}

	}

	if ( "undefined" != typeof s ) {

		var a = document.getElementsByTagName( "script" )[0];
		a.parentNode.insertBefore(s, a);

	} else {

		alert( "File: \""+e+"\" already loaded (keep only one)!" );
	}

};
<commit_msg>Update LoadCSSJS.js<commit_after>/*! Simple CSS JS loader asynchronously for all browsers by cara-tm.com, MIT License */
var LoadCSSJS = function ( e, t, o ) {

	"use strict";

	var f="", s;

	if( f.indexOf("["+e+"]") == -1 ) {

		f += "["+e+"]";

		switch (t) {

			case "css" :
				s = document.createElement( "link" );
				s.rel = ( o.rel || "stylesheet" );
				s.href = e;
				// Temporary invalid media query to load it async
				s.media = "only foo";
				setTimeout( function(){ s.media = ( o.media || "all" ); } );
			break;

			case "js" :
				s = document.createElement( "script" );
				if (o.defer)
					s.defer = "defer";
				else
					s.async = "async";
				s.src = e;
			break;

		}

	}

	if ( "undefined" != typeof s ) {

		var a = document.getElementsByTagName( "script" )[0];
		window.setTimeout(function() {
				t == "css" ?
					document.getElementsByTagName("head")[0].appendChild(s) :
					a.parentNode.insertBefore(s, a);
			}, 35);
			window.clearTimeout(a);

	} else {

		alert( "File: \""+e+"\" already loaded (keep only one)!" );
	}

};
<|endoftext|>


<commit_before>'use strict'

class Type {
  static get SOURCE_DEFAULT () {
    return 'default'
  }

  static get SOURCE_FLAG () {
    return 'flag'
  }

  static get SOURCE_POSITIONAL () {
    return 'positional'
  }

  constructor (opts) {
    this._aliases = []
    this.configure(opts, true)
    // prepare for parsing
    this.reset()
  }

  configure (opts, override) {
    opts = opts || {}
    if (typeof override === 'undefined') override = true
    // configurable for parsing
    if (override || !this._aliases.length) this._aliases = opts.aliases ? (this._aliases || []).concat(opts.aliases) : this._aliases
    if (override || typeof this._defaultVal === 'undefined') this._defaultVal = 'defaultValue' in opts ? opts.defaultValue : this._defaultVal
    if (override || typeof this._required === 'undefined') this._required = 'required' in opts ? opts.required : this._required
    // configurable for help text
    if (override || !this._flags) this._flags = opts.flags || this._flags
    if (override || !this._desc) this._desc = opts.description || opts.desc || this._desc
    if (override || typeof this._hints === 'undefined') this._hints = 'hints' in opts ? opts.hints : this._hints
    if (override || !this._group) this._group = opts.group || this._group
    if (override || typeof this._hidden === 'undefined') this._hidden = 'hidden' in opts ? opts.hidden : this._hidden
    return this
  }

  withParent (apiName) {
    this._parent = apiName
    return this
  }

  get parent () {
    return this._parent || 'node'
  }

  get datatype () {
    // subtypes should override this so as not to rely on this._value
    // because it's used for help text hints, when value is not set
    return Array.isArray(this._value) ? 'array' : typeof this._value
  }

  // == before parsing ==
  alias (a) {
    if (a) this._aliases = this._aliases.concat(a)
    return this
  }

  get aliases () {
    return this._aliases
  }

  defaultValue (dv) {
    this._defaultVal = dv
    return this
  }

  get defaultVal () {
    return this._defaultVal
  }

  required (r) {
    this._required = r
    return this
  }

  get isRequired () {
    return !!this._required
  }

  flags (f) {
    this._flags = f
    return this
  }

  get helpFlags () {
    return this._flags
  }

  description (d) {
    this._desc = d
    return this
  }

  desc (d) {
    return this.description(d)
  }

  get helpDesc () {
    // if this isn't a string, it can mess up buffer.js logic
    return typeof this._desc === 'string' ? this._desc : ''
  }

  hints (h) {
    this._hints = h
    return this
  }

  get helpHints () {
    if (typeof this._hints !== 'undefined') return this._hints
    let hints = []
    this.buildHelpHints(hints)
    return hints.length ? '[' + hints.join('] [') + ']' : ''
  }

  buildHelpHints (hintsArray) {
    // datatype
    if (this.datatype) hintsArray.push(this.datatype)
    // default value
    let dv = this._defaultVal
    if (dv && (!Array.isArray(dv) || dv.length)) hintsArray.push(`default: ${dv}`)
  }

  group (g) {
    this._group = g
    return this
  }

  get helpGroup () {
    return this._group || 'Options:'
  }

  hidden (h) {
    this._hidden = h
    return this
  }

  get isHidden () {
    return !!this._hidden
  }

  validateConfig (utils) {
    // derive flags from aliases
    if (typeof this._flags !== 'string' && this._aliases.length) {
      this._flags = utils.aliasesToFlags(this._aliases)
    }
    // nornalize aliases or derive from flags
    if (this._aliases.length) {
      this._aliases = utils.normalizeAliases(this._aliases)
    } else if (typeof this._flags === 'string' && this._flags.length) {
      this._aliases = utils.flagsToAliases(this._flags)
    }
    // console.log(`aliases=${this.aliases}, flags=${this.helpFlags}`)
    // validate aliases
    if (!this._aliases.length) {
      throw new Error(`${this.constructor.name} requires aliases or flags.`)
    }
  }

  // + parse <-- async?
  // - interactivePrompt ?
  // + rawGiven
  // + keys or aliases
  // + value
  // + positions (key + values?)
  // - required
  // + helpGroup
  // + helpKeys: all flagged aliases
  // x helpPlaceholder: all value aliases
  // + helpDesc
  // + helpHints
  // typeName ?

  // resolveSlow () {
  //   let self = this
  //   let timeout = Math.floor(Math.random() * 500)
  //   console.log('resolving %s in %d ms', self.constructor.name, timeout)
  //   return new Promise((resolve, reject) => {
  //     setTimeout(() => {
  //       console.log('resolve', self.constructor.name)
  //       resolve(self)
  //     }, timeout)
  //   })
  // }

  resolve () {
    // console.log('resolve', this.constructor.name)
    return Promise.resolve(this)
    // return this.resolveSlow()
  }

  // async parsing
  parse (context) {
    return this._internalParse(context, true)
  }

  _internalParse (context, validate) {
    // console.log('parse', this.constructor.name, this.helpFlags)
    let lastKeyMatchesAlias = false
    let anyKeyMatchedAlias = false
    let previousUsedValue
    // iterate over each slurped arg and determine if its key-value pairs are relevant to this type/option
    context.slurped.forEach(arg => {
      // if the last key seen applies to this type, see if a keyless value applies as the value
      // e.g. --key value1 value2 => (1) k=key v=true, (2) k='' v=value1, (3) k='' v=value2
      //      does value1 apply to key? how about value2?
      if (lastKeyMatchesAlias && arg.parsed.length === 1 && !arg.parsed[0].key && this.isApplicable(arg.parsed[0].value, previousUsedValue, arg)) {
        previousUsedValue = arg.parsed[0].value
        this.setValue(previousUsedValue)
        this.applySource(Type.SOURCE_FLAG, arg.index, arg.raw)
        arg.parsed[0].claimed = true
        return
      }

      arg.parsed.forEach((kv, kvIndex) => {
        if (!kv.key) return undefined
        let matchedAlias = this.aliases.find(alias => alias === kv.key)
        lastKeyMatchesAlias = !!matchedAlias
        if (matchedAlias) {
          anyKeyMatchedAlias = true
          this.observeAlias(matchedAlias)
          previousUsedValue = kv.value
          this.setValue(previousUsedValue) // TODO pass isExplicit arg ? or first check if isValid(value) ?
          this.applySource(Type.SOURCE_FLAG, arg.index, arg.raw)
          kv.claimed = true
        }
      })
    })

    if (!anyKeyMatchedAlias) {
      this.setValue(this.defaultVal)
      this._source = Type.SOURCE_DEFAULT
    }

    return validate ? this.validateParsed(context) : this.resolve()
  }

  // async validation called from parse
  validateParsed (context) {
    // TODO do validation here, add any errors to context
    if (this.isRequired && this.source === Type.SOURCE_DEFAULT) context.cliMessage('Missing required argument:', this.aliases)
    return this.resolve()
  }

  // async hook to execute after all parsing
  postParse (context) {
    // console.log('postParse', this.constructor.name)
    return this.resolve()
  }

  applySource (source, position, raw) {
    this._source = source
    this._addPosition(position)
    this._addRaw(raw)
  }

  isApplicable (currentValue, previousValue, slurpedArg) {
    // assumes (1) this type should hold a single value
    // and (2) a non-string previous value was not explicit
    // e.g. previous was not --key=value
    return typeof previousValue !== 'string'
  }

  observeAlias (alias) {}

  setValue (value) {
    this._value = value
  }

  // == after parsing ==
  get value () {
    return this._value
  }

  get source () {
    return this._source
  }

  _addPosition (p) {
    this._position = (this._position || []).concat(p)
  }

  get position () {
    return this._position
  }

  _addRaw (r) {
    this._raw = (this._raw || []).concat(r)
  }

  get raw () {
    return this._raw
  }

  reset () {
    this._value = this._defaultVal
    this._source = Type.SOURCE_DEFAULT
    // source precedence, most to least direct (for future reference):
    // 1. prompt (interactive mode only)
    // 2. arg
    // 3. stdin
    // 4. env
    // 5. configfile
    // 6. default
    this._position = []
    this._raw = []
  }

  toObject () {
    return {
      // populated via config
      aliases: this.aliases,
      datatype: this.datatype,
      defaultVal: this.defaultVal,
      isRequired: this.isRequired,
      helpFlags: this.helpFlags,
      helpDesc: this.helpDesc,
      helpHints: this.helpHints,
      helpGroup: this.helpGroup,
      isHidden: this.isHidden,
      // populated via parse
      value: this.value,
      source: this.source,
      position: this.position,
      raw: this.raw
    }
  }

  toResult () {
    // console.log('toResult', this.constructor.name, this.helpFlags)
    return {
      // populated via config
      parent: this.parent,
      aliases: this.aliases,
      datatype: this.datatype,
      // defaultVal: this.defaultVal,
      // helpFlags: this.helpFlags,
      // helpDesc: this.helpDesc,
      // helpHints: this.helpHints,
      // helpGroup: this.helpGroup,
      // populated via parse
      value: this.value,
      source: this.source,
      position: this.position,
      raw: this.raw
    }
  }
}

module.exports = Type
<commit_msg>indicate required in default help hints<commit_after>'use strict'

class Type {
  static get SOURCE_DEFAULT () {
    return 'default'
  }

  static get SOURCE_FLAG () {
    return 'flag'
  }

  static get SOURCE_POSITIONAL () {
    return 'positional'
  }

  constructor (opts) {
    this._aliases = []
    this.configure(opts, true)
    // prepare for parsing
    this.reset()
  }

  configure (opts, override) {
    opts = opts || {}
    if (typeof override === 'undefined') override = true
    // configurable for parsing
    if (override || !this._aliases.length) this._aliases = opts.aliases ? (this._aliases || []).concat(opts.aliases) : this._aliases
    if (override || typeof this._defaultVal === 'undefined') this._defaultVal = 'defaultValue' in opts ? opts.defaultValue : this._defaultVal
    if (override || typeof this._required === 'undefined') this._required = 'required' in opts ? opts.required : this._required
    // configurable for help text
    if (override || !this._flags) this._flags = opts.flags || this._flags
    if (override || !this._desc) this._desc = opts.description || opts.desc || this._desc
    if (override || typeof this._hints === 'undefined') this._hints = 'hints' in opts ? opts.hints : this._hints
    if (override || !this._group) this._group = opts.group || this._group
    if (override || typeof this._hidden === 'undefined') this._hidden = 'hidden' in opts ? opts.hidden : this._hidden
    return this
  }

  withParent (apiName) {
    this._parent = apiName
    return this
  }

  get parent () {
    return this._parent || 'node'
  }

  get datatype () {
    // subtypes should override this so as not to rely on this._value
    // because it's used for help text hints, when value is not set
    return Array.isArray(this._value) ? 'array' : typeof this._value
  }

  // == before parsing ==
  alias (a) {
    if (a) this._aliases = this._aliases.concat(a)
    return this
  }

  get aliases () {
    return this._aliases
  }

  defaultValue (dv) {
    this._defaultVal = dv
    return this
  }

  get defaultVal () {
    return this._defaultVal
  }

  required (r) {
    this._required = r
    return this
  }

  get isRequired () {
    return !!this._required
  }

  flags (f) {
    this._flags = f
    return this
  }

  get helpFlags () {
    return this._flags
  }

  description (d) {
    this._desc = d
    return this
  }

  desc (d) {
    return this.description(d)
  }

  get helpDesc () {
    // if this isn't a string, it can mess up buffer.js logic
    return typeof this._desc === 'string' ? this._desc : ''
  }

  hints (h) {
    this._hints = h
    return this
  }

  get helpHints () {
    if (typeof this._hints !== 'undefined') return this._hints
    let hints = []
    this.buildHelpHints(hints)
    return hints.length ? '[' + hints.join('] [') + ']' : ''
  }

  buildHelpHints (hintsArray) {
    // required
    if (this.isRequired) hintsArray.push('required')
    // datatype
    if (this.datatype) hintsArray.push(this.datatype)
    // default value
    let dv = this._defaultVal
    if (dv && (!Array.isArray(dv) || dv.length)) hintsArray.push(`default: ${dv}`)
  }

  group (g) {
    this._group = g
    return this
  }

  get helpGroup () {
    return this._group || 'Options:'
  }

  hidden (h) {
    this._hidden = h
    return this
  }

  get isHidden () {
    return !!this._hidden
  }

  validateConfig (utils) {
    // derive flags from aliases
    if (typeof this._flags !== 'string' && this._aliases.length) {
      this._flags = utils.aliasesToFlags(this._aliases)
    }
    // nornalize aliases or derive from flags
    if (this._aliases.length) {
      this._aliases = utils.normalizeAliases(this._aliases)
    } else if (typeof this._flags === 'string' && this._flags.length) {
      this._aliases = utils.flagsToAliases(this._flags)
    }
    // console.log(`aliases=${this.aliases}, flags=${this.helpFlags}`)
    // validate aliases
    if (!this._aliases.length) {
      throw new Error(`${this.constructor.name} requires aliases or flags.`)
    }
  }

  // + parse <-- async?
  // - interactivePrompt ?
  // + rawGiven
  // + keys or aliases
  // + value
  // + positions (key + values?)
  // - required
  // + helpGroup
  // + helpKeys: all flagged aliases
  // x helpPlaceholder: all value aliases
  // + helpDesc
  // + helpHints
  // typeName ?

  // resolveSlow () {
  //   let self = this
  //   let timeout = Math.floor(Math.random() * 500)
  //   console.log('resolving %s in %d ms', self.constructor.name, timeout)
  //   return new Promise((resolve, reject) => {
  //     setTimeout(() => {
  //       console.log('resolve', self.constructor.name)
  //       resolve(self)
  //     }, timeout)
  //   })
  // }

  resolve () {
    // console.log('resolve', this.constructor.name)
    return Promise.resolve(this)
    // return this.resolveSlow()
  }

  // async parsing
  parse (context) {
    return this._internalParse(context, true)
  }

  _internalParse (context, validate) {
    // console.log('parse', this.constructor.name, this.helpFlags)
    let lastKeyMatchesAlias = false
    let anyKeyMatchedAlias = false
    let previousUsedValue
    // iterate over each slurped arg and determine if its key-value pairs are relevant to this type/option
    context.slurped.forEach(arg => {
      // if the last key seen applies to this type, see if a keyless value applies as the value
      // e.g. --key value1 value2 => (1) k=key v=true, (2) k='' v=value1, (3) k='' v=value2
      //      does value1 apply to key? how about value2?
      if (lastKeyMatchesAlias && arg.parsed.length === 1 && !arg.parsed[0].key && this.isApplicable(arg.parsed[0].value, previousUsedValue, arg)) {
        previousUsedValue = arg.parsed[0].value
        this.setValue(previousUsedValue)
        this.applySource(Type.SOURCE_FLAG, arg.index, arg.raw)
        arg.parsed[0].claimed = true
        return
      }

      arg.parsed.forEach((kv, kvIndex) => {
        if (!kv.key) return undefined
        let matchedAlias = this.aliases.find(alias => alias === kv.key)
        lastKeyMatchesAlias = !!matchedAlias
        if (matchedAlias) {
          anyKeyMatchedAlias = true
          this.observeAlias(matchedAlias)
          previousUsedValue = kv.value
          this.setValue(previousUsedValue) // TODO pass isExplicit arg ? or first check if isValid(value) ?
          this.applySource(Type.SOURCE_FLAG, arg.index, arg.raw)
          kv.claimed = true
        }
      })
    })

    if (!anyKeyMatchedAlias) {
      this.setValue(this.defaultVal)
      this._source = Type.SOURCE_DEFAULT
    }

    return validate ? this.validateParsed(context) : this.resolve()
  }

  // async validation called from parse
  validateParsed (context) {
    // TODO do validation here, add any errors to context
    if (this.isRequired && this.source === Type.SOURCE_DEFAULT) context.cliMessage('Missing required argument:', this.aliases)
    return this.resolve()
  }

  // async hook to execute after all parsing
  postParse (context) {
    // console.log('postParse', this.constructor.name)
    return this.resolve()
  }

  applySource (source, position, raw) {
    this._source = source
    this._addPosition(position)
    this._addRaw(raw)
  }

  isApplicable (currentValue, previousValue, slurpedArg) {
    // assumes (1) this type should hold a single value
    // and (2) a non-string previous value was not explicit
    // e.g. previous was not --key=value
    return typeof previousValue !== 'string'
  }

  observeAlias (alias) {}

  setValue (value) {
    this._value = value
  }

  // == after parsing ==
  get value () {
    return this._value
  }

  get source () {
    return this._source
  }

  _addPosition (p) {
    this._position = (this._position || []).concat(p)
  }

  get position () {
    return this._position
  }

  _addRaw (r) {
    this._raw = (this._raw || []).concat(r)
  }

  get raw () {
    return this._raw
  }

  reset () {
    this._value = this._defaultVal
    this._source = Type.SOURCE_DEFAULT
    // source precedence, most to least direct (for future reference):
    // 1. prompt (interactive mode only)
    // 2. arg
    // 3. stdin
    // 4. env
    // 5. configfile
    // 6. default
    this._position = []
    this._raw = []
  }

  toObject () {
    return {
      // populated via config
      aliases: this.aliases,
      datatype: this.datatype,
      defaultVal: this.defaultVal,
      isRequired: this.isRequired,
      helpFlags: this.helpFlags,
      helpDesc: this.helpDesc,
      helpHints: this.helpHints,
      helpGroup: this.helpGroup,
      isHidden: this.isHidden,
      // populated via parse
      value: this.value,
      source: this.source,
      position: this.position,
      raw: this.raw
    }
  }

  toResult () {
    // console.log('toResult', this.constructor.name, this.helpFlags)
    return {
      // populated via config
      parent: this.parent,
      aliases: this.aliases,
      datatype: this.datatype,
      // defaultVal: this.defaultVal,
      // helpFlags: this.helpFlags,
      // helpDesc: this.helpDesc,
      // helpHints: this.helpHints,
      // helpGroup: this.helpGroup,
      // populated via parse
      value: this.value,
      source: this.source,
      position: this.position,
      raw: this.raw
    }
  }
}

module.exports = Type
<|endoftext|>


<commit_before><commit_msg>Update tmp/bower_components/ace-builds/src-noconflict/mode-glsl.js<commit_after><|endoftext|>


<commit_before><commit_msg>Fix context-level aggregate loading attributes on the client-side<commit_after><|endoftext|>


<commit_before><commit_msg>Resorted imports.<commit_after><|endoftext|>


<commit_before><commit_msg>Only auto select single item on enter key<commit_after><|endoftext|>


<commit_before>var css = require('dom-css')

module.exports = function (container) {
  var width = container.clientWidth
  var height = container.clientHeight
  var ismobile = width < height

  var label = document.createElement('div')
  container.appendChild(label)
  css(label, {
    top: height * 0.35,
    margin: '0px auto',
    left: 0, right: 0,
    width: ismobile ? width : width * 0.6,
    textAlign: 'center',
    position: 'absolute',
    pointerEvents: 'none'
  })

  var message = document.createElement('div')
  label.appendChild(message)
  css(message, {
    color: 'rgb(150,150,150)',
    fontFamily: 'Hack',
    fontSize: Math.sqrt(width * 5),
    opacity: 0
  })

  function show (text) {
    css(message, {opacity: 1})
    message.innerHTML = text
  }

  function hide () {
    css(message, {opacity: 0})
  }

  return {
    show: show,
    hide: hide
  }
}
<commit_msg>put message in hexagon<commit_after>var css = require('dom-css')
var _ = require('lodash')

module.exports = function (container) {
  var width = container.clientWidth
  var height = container.clientHeight
  var ismobile = width < height

  var size = ismobile ? width * 0.9 : 0.65 * height

  var points1 = _.range(7).map(function (i) {
    var dx = (size / Math.sqrt(3)) * Math.cos(i * 2 * Math.PI / 6 + Math.PI / 6) + 1.1 * size / 2
    var dy = (size / Math.sqrt(3)) * Math.sin(i * 2 * Math.PI / 6 + Math.PI / 6) + 1.1 * size / Math.sqrt(3)
    return [dx, dy]
  })

  var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
  svg.setAttribute('width', size * 1.1)
  svg.setAttribute('height', size * (2 / Math.sqrt(3)) * 1.1)
  css(svg, {
    pointerEvents: 'none',
    position: 'absolute',
    left: 0, right: 0,
    margin: '0px auto',
    marginTop: ismobile
      ? (height - size) * 0.6 - 0.05 * size * (2 / Math.sqrt(3))
      : (height - size) * 0.5 - 0.05 * size * (2 / Math.sqrt(3)),
    display: 'block'
  })
  container.appendChild(svg)

  var background = document.createElementNS('http://www.w3.org/2000/svg', 'polygon')
  background.setAttribute('points', points1.join(' '))
  css(background, {
    fill: 'rgb(45,45,45)',
    stroke: 'none',
    zIndex: 2000
  })
  svg.appendChild(background)

  var label = document.createElement('div')
  container.appendChild(label)
  css(label, {
    top: ismobile
      ? (height - size) * 0.6 - 0.05 * size * (2 / Math.sqrt(3)) + height * 0.2
      : (height - size) * 0.5 - 0.05 * size * (2 / Math.sqrt(3)) + height * 0.25,
    margin: '0px auto',
    left: 0, right: 0,
    width: ismobile ? width : width * 0.6,
    textAlign: 'center',
    position: 'absolute',
    pointerEvents: 'none'
  })

  var message = document.createElement('div')
  label.appendChild(message)
  css(message, {
    color: 'rgb(220,220,220)',
    fontFamily: 'Hack',
    fontSize: Math.sqrt(width * 5),
    opacity: 0
  })

  function show (text) {
    css(message, {opacity: 1})
    css(background, {opacity: 1})
    message.innerHTML = text
  }

  function hide () {
    css(message, {opacity: 0})
    css(background, {opacity: 0})
  }

  return {
    show: show,
    hide: hide
  }
}
<|endoftext|>


<commit_before>Module['preInit'] = Module['preInit'] || [];
Module['preInit'].push(function () {
  if (ENVIRONMENT_IS_NODE) {
    Module['stdout'] = function(x) { process.stdout.write(String.fromCharCode(x & 255), 'binary'); };
    Module['stdin'] = function stdin_reader () {
      if (!stdin_reader.input || stdin_reader.input.length == 0) {
        var fs = require('fs');
        var result = null;
        var BUFSIZE = 256;
        var buf = new Buffer(BUFSIZE, 'binary');
        var fd = process.stdin.fd;

        var bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null);

        if (bytesRead > 0) {
          result = buf.slice(0, bytesRead);
        } else {
          result = null;
        }

        stdin_reader.input = result;
      }

      if (stdin_reader.input && stdin_reader.input.length > 0) {
        var result = stdin_reader.input[0];
        stdin_reader.input = stdin_reader.input.slice(1);
        return result;
      } else {
        return null;
      }
    };
  }
});

<commit_msg>Retry EAGAIN in node.js<commit_after>Module['preInit'] = Module['preInit'] || [];
Module['preInit'].push(function () {
  if (ENVIRONMENT_IS_NODE) {
    Module['stdout'] = function(x) { process.stdout.write(String.fromCharCode(x & 255), 'binary'); };
    Module['stdin'] = function stdin_reader () {
      if (!stdin_reader.input || stdin_reader.input.length == 0) {
        var fs = require('fs');
        var result = null;
        var BUFSIZE = 256;
        var buf = new Buffer(BUFSIZE, 'binary');
        var fd = process.stdin.fd;

        var again = false;
        var bytesRead = 0;
        do {
          try {
            bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null);
            again = false;
          } catch (e) {
            again = -e.errno == ERRNO_CODES.EAGAIN;
          }
        } while (again);

        if (bytesRead > 0) {
          result = buf.slice(0, bytesRead);
        } else {
          result = null;
        }

        stdin_reader.input = result;
      }

      if (stdin_reader.input && stdin_reader.input.length > 0) {
        var result = stdin_reader.input[0];
        stdin_reader.input = stdin_reader.input.slice(1);
        return result;
      } else {
        return null;
      }
    };
  }
});

<|endoftext|>


<commit_before>Ext.define('Mba.ux.incubator.util.Toast', {
    extend: 'Ext.Toast',
    config: {
        cls: 'error-message'
    },

    show: function(message) {
        var config = { timeout: 8000, message: message};
        this.callParent([config]);
    }
});

<commit_msg>Update Toast.js<commit_after>Ext.define('Mba.ux.incubator.util.Toast', {
    extend: 'Ext.Toast',
    singleton: true,
    alternateClassName: 'MbaToast',
    config: {
        cls: 'error-message'
    },

    show: function(message) {
        var config = { timeout: 2000, message: message};
        this.callParent([config]);
    }
});
<|endoftext|>


<commit_before>'use strict';
import $ from 'jquery';

function noop() {}

const styles = `

`;

const defaultOptions = {
    tiles: [],
    onTileClick: noop,
    onTileShiftClick: noop,
    shouldRender: () => true,
    ribbon: () => '',
    isLink: () => true,
    isActive: () => true,
    backgroundColor: tile => tile.backgroundColor,
    color: tile => tile.color,
    header: tile => tile.header,
    footer: tile => tile.footer,
    title: tile => tile.title,
    icon: tile => tile.icon
};

module.exports = function(div, options) {
    let lineCount = 0;
    options = Object.assign({}, defaultOptions, options);
    const {tiles} = options;
    const $div = $('#' + div);
    $div.empty();
    $div.append(styles);
    const $main = $(`<div>`);
    $div.append($main);
    if (!tiles)  return $div.append('No tiles');
    $main.addClass('on-tabs-tiles');
    $main.append(tiles.map(getTile));

    $main.on('click', function (event) {
        let $el;
        if($(event.target).hasClass('cell')) {
            $el = $(event.target);
        } else {
            $el = $(event.target).parents('.cell').first();
        }
        let idx = $el.attr('data-idx');
        const tile = tiles[idx];
        if(tile && options.isActive(tile)) {
            options.onTileClick(event, tile, $el);
        }
    });

    function getTile(tile, idx) {
        tile.line = lineCount;
        if(Object.keys(tile).length === 1) {
            lineCount++;
            return '

';
        }
        if (!shouldRenderTile(tile)) return '';
        const ribbon = options.ribbon(tile);
        const active = options.isActive(tile);
        const header = options.header(tile);
        const footer = options.footer(tile);
        const title = options.title(tile);
        const icon = options.icon(tile);

        let iconType = /(fa|ci-icon)-/.exec(tile.icon);
        if (iconType) iconType = iconType[1];
        const $el = $(`

${header || ''}

                        ${icon ? `<div class="${iconType} ${icon}"><div class="bottomRight">${title || ''}</div></div>` : `<div class="center">${title || ''}</div>`}

${footer || ''}

                    ${active ? '' : '

'}
                    ${ribbon ? `<div class="ribbon-wrapper"><div class="ribbon beta">${ribbon}</div></div>` : ''}

        `);

        $el.css({
            color: options.color(tile),
            backgroundColor: options.backgroundColor(tile),
            cursor: active && options.isLink(tile) ? 'pointer' : 'inherit',
        });

        $el.attr({
            'data-idx': idx
        });
        return $el;
    }

    function shouldRenderTile(tile) {
        return options.shouldRender(tile);
    }
};
<commit_msg>tile: fix icon bug<commit_after>'use strict';
import $ from 'jquery';

function noop() {}

const styles = `

`;

const defaultOptions = {
    tiles: [],
    onTileClick: noop,
    shouldRender: () => true,
    ribbon: () => '',
    isLink: () => true,
    isActive: () => true,
    backgroundColor: tile => tile.backgroundColor,
    color: tile => tile.color,
    header: tile => tile.header,
    footer: tile => tile.footer,
    title: tile => tile.title,
    icon: tile => tile.icon
};

module.exports = function(div, options) {
    let lineCount = 0;
    options = Object.assign({}, defaultOptions, options);
    const {tiles} = options;
    const $div = $('#' + div);
    $div.empty();
    $div.append(styles);
    const $main = $(`<div>`);
    $div.append($main);
    if (!tiles)  return $div.append('No tiles');
    $main.addClass('on-tabs-tiles');
    $main.append(tiles.map(getTile));

    $main.on('click', function (event) {
        let $el;
        if($(event.target).hasClass('cell')) {
            $el = $(event.target);
        } else {
            $el = $(event.target).parents('.cell').first();
        }
        let idx = $el.attr('data-idx');
        const tile = tiles[idx];
        if(tile && options.isActive(tile)) {
            options.onTileClick(event, tile, $el);
        }
    });

    function getTile(tile, idx) {
        tile.line = lineCount;
        if(Object.keys(tile).length === 1) {
            lineCount++;
            return '

';
        }
        if (!shouldRenderTile(tile)) return '';
        const ribbon = options.ribbon(tile);
        const active = options.isActive(tile);
        const header = options.header(tile);
        const footer = options.footer(tile);
        const title = options.title(tile);
        const icon = options.icon(tile);

        let iconType = /(fa|ci-icon)-/.exec(icon);
        if (iconType) iconType = iconType[1];
        const $el = $(`

${header || ''}

                        ${icon ? `<div class="${iconType} ${icon}"><div class="bottomRight">${title || ''}</div></div>` : `<div class="center">${title || ''}</div>`}

${footer || ''}

                    ${active ? '' : '

'}
                    ${ribbon ? `<div class="ribbon-wrapper"><div class="ribbon beta">${ribbon}</div></div>` : ''}

        `);

        $el.css({
            color: options.color(tile),
            backgroundColor: options.backgroundColor(tile),
            cursor: active && options.isLink(tile) ? 'pointer' : 'inherit',
        });

        $el.attr({
            'data-idx': idx
        });
        return $el;
    }

    function shouldRenderTile(tile) {
        return options.shouldRender(tile);
    }
};
<|endoftext|>


<commit_before>/**
 * Created by ssw on 2014-06-17.
 */
(function(){
    var W = window, DOC = document;
//    if( W.log ) return W.log( "Dk : log가 이미 존재합니다." );
    var log, logArr = [], jcJoin = Array.prototype.join, e0, e1, es0, es1, toggle, x = 710, y = 10, w = 800;

    e0 = DOC.createElement( "div" ), es0 = e0.style,
        es0.cssText = "left : " + x + "px; top : " + ( y + 22 ) + "px; width : " + w + "px; height : 90%; position : fixed; display : block; overflow : auto; padding : 10px; background-color : #000; font : 12px/18px 돋움, sans-serif; color : #FFF; opacity : 0.8; z-index : 10000000;",
        e1 = DOC.createElement( "div" ), es1 = e1.style,
        es1.cssText = "left : " + x + "px; top : " + y + "px; width : " + ( w + 10 ) + "px; height : 20px; position : fixed;display : block; padding-left : 10px; background-color : #000; font : 12px/18px 돋움, sans-serif; color : #FFF; opacity : 0.8; z-index : 10000000;",

        W.log = log = (function(){
            if( ( W[ "console" ] ) )
                return function( $log ){
                    //logArr.splice( 0, 0, $log, console.log( $log ) ), toggle ? e0.innerHTML = logArr[ 0 ] + "
" + e0.innerHTML : null;
                    e0.innerHTML = $log
                }
            else
                return function( $log ){
                    logArr.splice( 0, 0, $log ), toggle ? e0.innerHTML = logArr[ 0 ] + "
" + e0.innerHTML : null;
                }
        })(),

        log.show = function(){
            var body = DOC.body;
            e0.innerHTML = jcJoin.call( logArr, "
" ), body.appendChild( e0 ), body.appendChild( e1 ), toggle = true;
        },

        log.hide = function(){
            var body = DOC.body;
            body.removeChild( e0 ), body.removeChild( e1 ), toggle = false;
        },

        log.position = function( $left, $top, $width ){
            if( $left !== undefined ) es0.left = $left + "px", es1.left = $left + "px";
            if( $top !== undefined ) es0.top = $top + 22 + "px", es1.top = $top + "px";
            if( $width !== undefined ) es0.width = $width + "px", es1.width = $width + 10 + "px";
        },

		log.show()
})()<commit_msg>dkLog<commit_after>/**
 * Created by ssw on 2014-06-17.
 */
(function(){
    var W = window, DOC = document;
//    if( W.log ) return W.log( "Dk : log가 이미 존재합니다." );
    var log, logArr = [], jcJoin = Array.prototype.join, e0, e1, es0, es1, toggle, x = 710, y = 10, w = 800;

    e0 = DOC.createElement( "div" ), es0 = e0.style,
        es0.cssText = "left : " + x + "px; top : " + ( y + 22 ) + "px; width : " + w + "px; height : 90%; position : fixed; display : block; overflow : auto; padding : 10px; background-color : #000; font : 12px/18px 돋움, sans-serif; color : #FFF; opacity : 0.8; z-index : 10000000;",
        e1 = DOC.createElement( "div" ), es1 = e1.style,
        es1.cssText = "left : " + x + "px; top : " + y + "px; width : " + ( w + 10 ) + "px; height : 20px; position : fixed;display : block; padding-left : 10px; background-color : #000; font : 12px/18px 돋움, sans-serif; color : #FFF; opacity : 0.8; z-index : 10000000;",

        W.log = log = (function(){
            if( ( W[ "console" ] ) )
                return function( $log ){
                    logArr.splice( 0, 0, $log, console.log( $log ) ), toggle ? e0.innerHTML = logArr[ 0 ] + "
" + e0.innerHTML : null;
                    //e0.innerHTML = $log
                }
            else
                return function( $log ){
                    logArr.splice( 0, 0, $log ), toggle ? e0.innerHTML = logArr[ 0 ] + "
" + e0.innerHTML : null;
                }
        })(),

        log.show = function(){
            var body = DOC.body;
            e0.innerHTML = jcJoin.call( logArr, "
" ), body.appendChild( e0 ), body.appendChild( e1 ), toggle = true;
        },

        log.hide = function(){
            var body = DOC.body;
            body.removeChild( e0 ), body.removeChild( e1 ), toggle = false;
        },

        log.position = function( $left, $top, $width ){
            if( $left !== undefined ) es0.left = $left + "px", es1.left = $left + "px";
            if( $top !== undefined ) es0.top = $top + 22 + "px", es1.top = $top + "px";
            if( $width !== undefined ) es0.width = $width + "px", es1.width = $width + 10 + "px";
        },

		log.show()
})()<|endoftext|>


<commit_before>(function () {
  // Set up local filename, dirname, and `module.filename`
  // DEV: `__filename` would be a path to Electron since we are loading an HTTP URL
  //   /home/todd/github/karma-electron/node_modules/electron/dist/resources/electron.asar/renderer/init.js
  //   This overrides to user's expectations of Karma's `file://` filepaths
  // DEV: Ignore JSHint so we can override `__filename` in our closure
  // DEV: We use `window.require` sniffing to prevent emulating a Node.js environment in a non-Node.js one
  var __filename, __dirname;
  if (window.require) {
    __filename = window.location.path !== '/debug.html' ? '{{!karmaContextFile}}' : '{{!karmaDebugFile}}';
    __dirname = window.require('path').dirname(__filename);
    if (module) {
      module.filename = __filename;
    }
  }

  // Save original require/require.resolve
  if (window.require) {
    var __require = window.require;
    var __requireResolve = __require.resolve;

    // Add our base directory as the path to find node modules from
    if (!window.__karmaBasePathAddedToModule) {
      module.paths = module.paths.concat(__require('module')._nodeModulePaths('{{!karmaBasePath}}'));
      window.__karmaBasePathAddedToModule = true;
    }

    // Define our patched require/require.resolve
    var __requireFilepath = function (filepath) {
      // If the filepath is relative, prepend the filename
      // e.g. `./submodule` -> `/home/todd/.../integration-test/./submodule`
      if (filepath && filepath[0] === '.') {
        filepath = __dirname + '{{!sep}}' + filepath;
      }

      // Return our filepath
      return filepath;
    };
    // Define our require/resolve.resolve
    window.require = function (filepath) {
      return __require(__requireFilepath(filepath));
    };
    window.require.resolve = function (filepath) {
      return __requireResolve(__requireFilepath(filepath));
    };
  // jscs:disable
  // DEV: Due to the Mustache content, we have to add a `jscs:disable` early
  }

  // Inject our content
  // jshint ignore:start
  {{!content}}
  // jshint ignore:end
  // jscs:enable
}());
<commit_msg>Added missing module detection<commit_after>(function () {
  // Set up local filename, dirname, and `module.filename`
  // DEV: `__filename` would be a path to Electron since we are loading an HTTP URL
  //   /home/todd/github/karma-electron/node_modules/electron/dist/resources/electron.asar/renderer/init.js
  //   This overrides to user's expectations of Karma's `file://` filepaths
  // DEV: Ignore JSHint so we can override `__filename` in our closure
  // DEV: We use `window.require` sniffing to prevent emulating a Node.js environment in a non-Node.js one
  var __filename, __dirname;
  if (window.require) {
    __filename = window.location.path !== '/debug.html' ? '{{!karmaContextFile}}' : '{{!karmaDebugFile}}';
    __dirname = window.require('path').dirname(__filename);
    if (window.module) {
      module.filename = __filename;
    }
  }

  // Save original require/require.resolve
  if (window.require) {
    var __require = window.require;
    var __requireResolve = __require.resolve;

    // Add our base directory as the path to find node modules from
    if (!window.__karmaBasePathAddedToModule) {
      module.paths = module.paths.concat(__require('module')._nodeModulePaths('{{!karmaBasePath}}'));
      window.__karmaBasePathAddedToModule = true;
    }

    // Define our patched require/require.resolve
    var __requireFilepath = function (filepath) {
      // If the filepath is relative, prepend the filename
      // e.g. `./submodule` -> `/home/todd/.../integration-test/./submodule`
      if (filepath && filepath[0] === '.') {
        filepath = __dirname + '{{!sep}}' + filepath;
      }

      // Return our filepath
      return filepath;
    };
    // Define our require/resolve.resolve
    window.require = function (filepath) {
      return __require(__requireFilepath(filepath));
    };
    window.require.resolve = function (filepath) {
      return __requireResolve(__requireFilepath(filepath));
    };
  // jscs:disable
  // DEV: Due to the Mustache content, we have to add a `jscs:disable` early
  }

  // Inject our content
  // jshint ignore:start
  {{!content}}
  // jshint ignore:end
  // jscs:enable
}());
<|endoftext|>


<commit_before>var http = require('http'),
      fs = require('fs'),
    path = require('path'),
    util = require('util');

function serveStaticFile(res, path, contentType, responseCode) {
  if(!responseCode) responseCode = 200;
  var read_path = __dirname + '/' + path;
  util.log("Read path:" + read_path);
  fs.readFile(read_path,
    function(err,data) {
      if(err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('500 - Internal Error:' + err.message);
      } else {
        res.writeHead(responseCode,
          { 'Content-Type': contentType });
        res.end(data);
      }
    }
  );
}

function loadData(res,load_path) {
  pth = buildSafePath(res,load_path);
  if(!pth)
    return;
  fs.readFile(pth,
    function(err,data) {
      if(err) {
        response = '500 - Internal Error:' + err.message;
      } else {
        var isDirectory = false;
        try {
          isDirectory = fs.lstatSync(pth).isDirectory();
        } catch(e) {
          response = '500 - Error:'+e;
          respondPost(res,response);
          return;
        }
        if(isDirectory) {
          var darray = [];
          for(var i in data) {
            var p = path.join(pth, data[i]);
            //console.log(p);
            var t = "file";
            if(fs.lstatSync(p).isDirectory())
              t = "dir";
            var ft = {type:t,name:data[i]};
            darray.push(ft);
          }
          rtnval = {type:'dir', path: path_ext, dir:darray};
          response = JSON.stringify(rtnval);
        } else {
          //console.log("Response:" + response);
          console.log("File is of length:" + data.length);
          console.log("Type:" + (typeof data));
          rtnval = {type:'file',data:data.toString()};
          response = JSON.stringify(rtnval);
        }
        console.log("Response:" + response);
        respondPost(res,response);
      }
    }
  );
}

function buildSafePath(res,rel_path) {
  var path_ext = decodeURI(rel_path);
  console.log("Path Extension:"+path_ext);
  if(path_ext.indexOf("..") >= 0) {  //we don't want anyone hacking into a parent directory
    response = '500 - Error: Attempting to access parent directories';
    respondPost(res,response);
    return null;
  }
  return path.join(__dirname, path_ext);
}

function saveData(res,save_path,data,overwrite) {
  pth = buildSafePath(res,save_path);
  if(!path)
    return;
  console.log("Path:"+pth);
  isDirectory = false;
  try {
    if(fs.lstatSync(pth).isDirectory()) {
      response = '500 - Error: Attempting to write to directory';
      respondPost(res,response);
      return;
    } else if(!overwrite) {
      rtnval = {type:'ack',msg:'fileExists'};
      respondPost(res,rtnval);
      return;
    }
  } catch(e) {
    // file does not exist yet - could have also used if (fs.existsSync(path))
  }
  try {
    console.log("Attempting to write " + data.length + "bytes to path:"+pth);
    fs.writeFile(pth,data,
      function(err) {
        if(err) {
          response = '500 - Internal Error:' + err.message;
        } else {
          console.log("File written");
          rtnval = {type:'ack',msg:'data saved'};
          response = JSON.stringify(rtnval);
        }
        respondPost(res,response);
      }
    );
  } catch(err) {
    respondPost(res,'500 - Internal Error:' + err.message);
  }
}

function respondPost(res,resval) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(resval);
}

http.createServer(function(req,res){
  util.log("Request method:" + req.method);
  if (req.method == 'GET') {
    // normalize url by removing querystring, optional
    // trailing slash, and making lowercase
    var url_path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
    util.log("Request:" + url_path);
    util.log("Request length:" + url_path.length);
    util.log("Res:" + res);
    var content_type = 'text/html';
    var ext = path.extname(url_path);
    if( ext == ".js")
      content_type = 'text/javascript';
    else if(ext == "png")
        content_type = 'image/png';
    else if(ext == "jpg")
        content_type = 'image/jpg';
    if(url_path === '')
      url_path = '/home.html';
    serveStaticFile(res, url_path, content_type);
    //    serveStaticFile(res, '/public/404.html', 'text/html', 404);
  } else if (req.method == 'POST') {
    var post_data = '';
    req.on('data', function (data) {
      post_data += data;
    });
    req.on('end', function() {
      // every end path must end with a respondPost(res,string)
      console.log('RECEIVED THIS DATA:\n'+ post_data);
      var response = '';
      var post_obj;
      try {
        post_obj = JSON.parse(post_data);
      } catch(err) {
        respondPost(res,'500 - Error: JSON Parse Error:' + err.message);
        return;
      }
      var rtnval;
      switch(post_obj.command) {
        case 'save':
          saveData(res,post_obj.path,post_obj.data);
          break;
        case 'list':  // the same as load only using a path to a directory
        case 'load':
          loadData(res,post_obj.path);
          break;
        default:
          rtnval = {type:'ack',msg:'unknown command'};
          respondPost(res,JSON.stringify(rtnval));
      }
    });
  }

}).listen(3000);

console.log('Server started on localhost:3000; press Ctrl-C to terminate....');
<commit_msg>Forgot to commit from copy(47) - only added log<commit_after>var http = require('http'),
      fs = require('fs'),
    path = require('path'),
    util = require('util');

function serveStaticFile(res, path, contentType, responseCode) {
  if(!responseCode) responseCode = 200;
  var read_path = __dirname + '/' + path;
  util.log("Read path:" + read_path);
  fs.readFile(read_path,
    function(err,data) {
      if(err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('500 - Internal Error:' + err.message);
      } else {
        res.writeHead(responseCode,
          { 'Content-Type': contentType });
        res.end(data);
      }
    }
  );
}

function loadData(res,load_path) {
  pth = buildSafePath(res,load_path);
  if(!pth)
    return;
  fs.readFile(pth,
    function(err,data) {
      if(err) {
        response = '500 - Internal Error:' + err.message;
      } else {
        var isDirectory = false;
        try {
          isDirectory = fs.lstatSync(pth).isDirectory();
        } catch(e) {
          response = '500 - Error:'+e;
          respondPost(res,response);
          return;
        }
        if(isDirectory) {
          var darray = [];
          for(var i in data) {
            var p = path.join(pth, data[i]);
            //console.log(p);
            var t = "file";
            if(fs.lstatSync(p).isDirectory())
              t = "dir";
            var ft = {type:t,name:data[i]};
            darray.push(ft);
          }
          rtnval = {type:'dir', path: path_ext, dir:darray};
          response = JSON.stringify(rtnval);
        } else {
          //console.log("Response:" + response);
          console.log("File is of length:" + data.length);
          console.log("Type:" + (typeof data));
          rtnval = {type:'file',data:data.toString()};
          response = JSON.stringify(rtnval);
        }
        console.log("Response:" + response);
        respondPost(res,response);
      }
    }
  );
}

function buildSafePath(res,rel_path) {
  var path_ext = decodeURI(rel_path);
  console.log("Path Extension:"+path_ext);
  if(path_ext.indexOf("..") >= 0) {  //we don't want anyone hacking into a parent directory
    response = '500 - Error: Attempting to access parent directories';
    respondPost(res,response);
    return null;
  }
  return path.join(__dirname, path_ext);
}

function saveData(res,save_path,data,overwrite) {
  pth = buildSafePath(res,save_path);
  if(!path)
    return;
  console.log("Path:"+pth);
  isDirectory = false;
  try {
    if(fs.lstatSync(pth).isDirectory()) {
      response = '500 - Error: Attempting to write to directory';
      respondPost(res,response);
      return;
    } else if(!overwrite) {
      rtnval = {type:'ack',msg:'fileExists'};
      respondPost(res,rtnval);
      return;
    }
  } catch(e) {
    // file does not exist yet - could have also used if (fs.existsSync(path))
  }
  try {
    console.log("Attempting to write " + data.length + "bytes to path:"+pth);
    fs.writeFile(pth,data,
      function(err) {
        if(err) {
          response = '500 - Internal Error:' + err.message;
        } else {
          console.log("File written");
          rtnval = {type:'ack',msg:'data saved'};
          response = JSON.stringify(rtnval);
        }
        respondPost(res,response);
      }
    );
  } catch(err) {
    respondPost(res,'500 - Internal Error:' + err.message);
  }
}

function respondPost(res,resval) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(resval);
}

http.createServer(function(req,res){
  util.log("Request method:" + req.method);
  if (req.method == 'GET') {
    // normalize url by removing querystring, optional
    // trailing slash, and making lowercase
    util.log("Request:" + req.url);
    var url_path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
    util.log("Request:" + url_path);
    util.log("Request length:" + url_path.length);
    util.log("Res:" + res);
    var content_type = 'text/html';
    var ext = path.extname(url_path);
    if( ext == ".js")
      content_type = 'text/javascript';
    else if(ext == "png")
        content_type = 'image/png';
    else if(ext == "jpg")
        content_type = 'image/jpg';
    if(url_path === '')
      url_path = '/home.html';
    serveStaticFile(res, url_path, content_type);
    //    serveStaticFile(res, '/public/404.html', 'text/html', 404);
  } else if (req.method == 'POST') {
    var post_data = '';
    req.on('data', function (data) {
      post_data += data;
    });
    req.on('end', function() {
      // every end path must end with a respondPost(res,string)
      console.log('RECEIVED THIS DATA:\n'+ post_data);
      var response = '';
      var post_obj;
      try {
        post_obj = JSON.parse(post_data);
      } catch(err) {
        respondPost(res,'500 - Error: JSON Parse Error:' + err.message);
        return;
      }
      var rtnval;
      switch(post_obj.command) {
        case 'save':
          saveData(res,post_obj.path,post_obj.data);
          break;
        case 'list':  // the same as load only using a path to a directory
        case 'load':
          loadData(res,post_obj.path);
          break;
        default:
          rtnval = {type:'ack',msg:'unknown command'};
          respondPost(res,JSON.stringify(rtnval));
      }
    });
  }

}).listen(3000);

console.log('Server started on localhost:3000; press Ctrl-C to terminate....');
<|endoftext|>


<commit_before>export default {
	name: 'HomePage',
};
<commit_msg>prepush test<commit_after>export default {
	name: 'HomePage'

};
<|endoftext|>