<commit_before>import electron from 'electron';
import multihashes from 'multihashes';
import { View } from 'backbone';
import loadTemplate from '../utils/loadTemplate';
import app from '../app';
import $ from 'jquery';
import SettingsModal from './modals/settings/Settings';

const remote = electron.remote;

export default class extends View {
  constructor(options) {
    super({
      className: 'pageNav',
      events: {
        'click .js-navBack': 'navBackClick',
        'click .js-navFwd': 'navFwdClick',
        'click .js-navClose': 'navCloseClick',
        'click .js-navMin': 'navMinClick',
        'click .js-navMax': 'navMaxClick',
        'keyup .js-addressBar': 'onKeyupAddressBar',
        'click .js-navListBtn': 'navListBtnClick',
        'click .js-navSettings': 'navSettingsClick',
      },
      ...options,
    });

    $(document).on('click', this.onDocClick.bind(this));

    this.listenTo(app.localSettings, 'change:mac_style_win_controls',
      this.onWinControlsStyleChange);
    this.setWinControlsStyle(app.localSettings.get('mac_style_win_controls') ? 'mac' : 'win');
  }

  navBackClick() {
    window.history.back();
  }

  navFwdClick() {
    window.history.forward();
  }

  setWinControlsStyle(style) {
    if (style !== 'mac' && style !== 'win') {
      throw new Error('Style must be \'mac\' or \'win\'.');
    }

    this.$el.removeClass('winStyleWindowControls macStyleWindowControls');
    this.$el.addClass(style === 'mac' ? 'macStyleWindowControls' : 'winStyleWindowControls');
  }

  onWinControlsStyleChange(model, useMacStyle) {
    this.setWinControlsStyle(useMacStyle ? 'mac' : 'win');
  }

  navCloseClick() {
    if (remote.process.platform !== 'darwin') {
      remote.getCurrentWindow().close();
    } else {
      remote.getCurrentWindow().hide();
    }
  }

  navMinClick() {
    remote.getCurrentWindow().minimize();
  }

  navMaxClick() {
    if (remote.getCurrentWindow().isMaximized()) {
      remote.getCurrentWindow().unmaximize();
      // this.$('.js-navMax').attr('data-tooltip', window.polyglot.t('Maximize'));
    } else {
      remote.getCurrentWindow().maximize();
      // this.$('.js-navMax').attr('data-tooltip', window.polyglot.t('Restore'));
    }
  }

  navListBtnClick() {
    const $popMenu = this.$navList;
    this.togglePopMenu($popMenu);
  }

  togglePopMenu($popMenu) {
    if ($popMenu) {
      this.$popMenus.not($popMenu).removeClass('open');
      $popMenu.toggleClass('open');
    } else {
      this.$popMenus.removeClass('open');
    }
  }

  onDocClick(e) {
    if (!$(e.target).closest('.js-navListBtn, .js-navNotifBtn, .js-navPopMenu').length) {
      this.togglePopMenu();
    }
  }

  onKeyupAddressBar(e) {
    if (e.which === 13) {
      let text = this.$addressBar.val();
      let isGuid = true;

      if (text.startsWith('ob://')) text = text.slice(5);

      const firstTerm = text.split(' ')[0];

      try {
        multihashes.validate(multihashes.fromB58String(firstTerm));
      } catch (exc) {
        isGuid = false;
      }

      // temporary way to check for GUIDs, since our dummy guids from
      // start.js aren't valid v2 guids, but are registered with the
      // one-name api.
      if (firstTerm.startsWith('Qm')) isGuid = true;
      // end - temporary guid check

      if (isGuid) {
        app.router.navigate(firstTerm, { trigger: true });
      } else if (firstTerm.charAt(0) === '@' && firstTerm.length > 1) {
        // a handle
        app.router.navigate(firstTerm, { trigger: true });
      } else {
        // tag(s)
        const tags = text.trim()
          .replace(',', ' ')
          .replace(/\s+/g, ' ') // collapse multiple spaces into single spaces
          .split(' ')
          .map((frag) => (frag.charAt(0) === '#' ? frag.slice(1) : frag));

        alert(`boom - Searching for tags: ${tags.join(', ')}`);
      }
    }
  }

  setAddressBar(text = '') {
    if (this.$addressBar) {
      this.$addressBar.val(text);
    }
  }

  navSettingsClick() {
    new SettingsModal().render().open();
    this.togglePopMenu();
  }

  render() {
    loadTemplate('pageNav.html', (t) => {
      this.$el.html(t());
    });

    this.$addressBar = this.$('.js-addressBar');
    this.$navList = this.$('.js-navList');
    this.$popMenus = this.$('.js-navPopMenu');

    return this;
  }

  remove() {
    $(document).off('click', this.onDocClick);
  }
}
<commit_msg>Fix capitalization of Settings folder<commit_after>import electron from 'electron';
import multihashes from 'multihashes';
import { View } from 'backbone';
import loadTemplate from '../utils/loadTemplate';
import app from '../app';
import $ from 'jquery';
import SettingsModal from './modals/Settings/Settings';

const remote = electron.remote;

export default class extends View {
  constructor(options) {
    super({
      className: 'pageNav',
      events: {
        'click .js-navBack': 'navBackClick',
        'click .js-navFwd': 'navFwdClick',
        'click .js-navClose': 'navCloseClick',
        'click .js-navMin': 'navMinClick',
        'click .js-navMax': 'navMaxClick',
        'keyup .js-addressBar': 'onKeyupAddressBar',
        'click .js-navListBtn': 'navListBtnClick',
        'click .js-navSettings': 'navSettingsClick',
      },
      ...options,
    });

    $(document).on('click', this.onDocClick.bind(this));

    this.listenTo(app.localSettings, 'change:mac_style_win_controls',
      this.onWinControlsStyleChange);
    this.setWinControlsStyle(app.localSettings.get('mac_style_win_controls') ? 'mac' : 'win');
  }

  navBackClick() {
    window.history.back();
  }

  navFwdClick() {
    window.history.forward();
  }

  setWinControlsStyle(style) {
    if (style !== 'mac' && style !== 'win') {
      throw new Error('Style must be \'mac\' or \'win\'.');
    }

    this.$el.removeClass('winStyleWindowControls macStyleWindowControls');
    this.$el.addClass(style === 'mac' ? 'macStyleWindowControls' : 'winStyleWindowControls');
  }

  onWinControlsStyleChange(model, useMacStyle) {
    this.setWinControlsStyle(useMacStyle ? 'mac' : 'win');
  }

  navCloseClick() {
    if (remote.process.platform !== 'darwin') {
      remote.getCurrentWindow().close();
    } else {
      remote.getCurrentWindow().hide();
    }
  }

  navMinClick() {
    remote.getCurrentWindow().minimize();
  }

  navMaxClick() {
    if (remote.getCurrentWindow().isMaximized()) {
      remote.getCurrentWindow().unmaximize();
      // this.$('.js-navMax').attr('data-tooltip', window.polyglot.t('Maximize'));
    } else {
      remote.getCurrentWindow().maximize();
      // this.$('.js-navMax').attr('data-tooltip', window.polyglot.t('Restore'));
    }
  }

  navListBtnClick() {
    const $popMenu = this.$navList;
    this.togglePopMenu($popMenu);
  }

  togglePopMenu($popMenu) {
    if ($popMenu) {
      this.$popMenus.not($popMenu).removeClass('open');
      $popMenu.toggleClass('open');
    } else {
      this.$popMenus.removeClass('open');
    }
  }

  onDocClick(e) {
    if (!$(e.target).closest('.js-navListBtn, .js-navNotifBtn, .js-navPopMenu').length) {
      this.togglePopMenu();
    }
  }

  onKeyupAddressBar(e) {
    if (e.which === 13) {
      let text = this.$addressBar.val();
      let isGuid = true;

      if (text.startsWith('ob://')) text = text.slice(5);

      const firstTerm = text.split(' ')[0];

      try {
        multihashes.validate(multihashes.fromB58String(firstTerm));
      } catch (exc) {
        isGuid = false;
      }

      // temporary way to check for GUIDs, since our dummy guids from
      // start.js aren't valid v2 guids, but are registered with the
      // one-name api.
      if (firstTerm.startsWith('Qm')) isGuid = true;
      // end - temporary guid check

      if (isGuid) {
        app.router.navigate(firstTerm, { trigger: true });
      } else if (firstTerm.charAt(0) === '@' && firstTerm.length > 1) {
        // a handle
        app.router.navigate(firstTerm, { trigger: true });
      } else {
        // tag(s)
        const tags = text.trim()
          .replace(',', ' ')
          .replace(/\s+/g, ' ') // collapse multiple spaces into single spaces
          .split(' ')
          .map((frag) => (frag.charAt(0) === '#' ? frag.slice(1) : frag));

        alert(`boom - Searching for tags: ${tags.join(', ')}`);
      }
    }
  }

  setAddressBar(text = '') {
    if (this.$addressBar) {
      this.$addressBar.val(text);
    }
  }

  navSettingsClick() {
    new SettingsModal().render().open();
    this.togglePopMenu();
  }

  render() {
    loadTemplate('pageNav.html', (t) => {
      this.$el.html(t());
    });

    this.$addressBar = this.$('.js-addressBar');
    this.$navList = this.$('.js-navList');
    this.$popMenus = this.$('.js-navPopMenu');

    return this;
  }

  remove() {
    $(document).off('click', this.onDocClick);
  }
}
<|endoftext|>


<commit_before>var app = app || {};

app.LibraryView = Backbone.View.extend({

    initialize: function(options) {
        this.collection.on('add reset remove', function() {
            this.render(this.collection);
        }, this);

        this.itemView = options.itemView;
        this.filter = options.filter || false;
        if (this.filter) {
            this.search(this.filter)
        } else {
            this.render();
        }
    },

    render: function(collection, isFiltered) {
        var numActiveItems = 0,
            totalItems = 0,
            numItemsDisplayed = 0;
            this.el_html = [];

        collection = collection || this.collection;
        if (isFiltered && collection.length == this.collection.length) {
            return this;
        }
        this.$el.html('');

        if (!isFiltered) {
            if (collection.length > 0) {
                collection.each(function(item) {
                    this.renderItem(item);
                }, this);
                this.$el.html(this.el_html);
            } else {
                this.$el.html($('#noItemsTemplate').html());
            }
        } else {
            //get the total number of active items
            numActiveItems = this.collection.where({
                active: true
            }).length;
            totalItems = numActiveItems;
            numItemsDisplayed = collection.toArray().length;

            collection.each(function(item) {
                this.renderItem(item);
            }, this);
            this.$el.html(this.el_html);
            if (numItemsDisplayed < totalItems) {
                this.$el.prepend('
Displaying ' + numItemsDisplayed + ' out of ' + totalItems + '
');
            }
        }

        return this;
    },

    renderItem: function(item) {
        var itemView = new this.itemView({
            model: item
        });
        this.el_html.push(itemView.render().el);
    },

    search: function(options) {
        var collection = (options && options.collection ? options.collection : this.collection),
        	results = [], key, val;

        if (!options || options.val == '' || options.key == '') {
            this.render(this.collection, false);
        } else {
        	key = options.key;
        	val = options.val;
        	results = this.collection.filter(function(item){
        		return (item.get(query[key]).indexOf(val) > -1);
        	});
        	this.render(new Backbone.Collection(results), true);
           // this.render(collection.search(options), true);
        }
    }
});
<commit_msg>syntax fix<commit_after>var app = app || {};

app.LibraryView = Backbone.View.extend({

    initialize: function(options) {
        this.collection.on('add reset remove', function() {
            this.render(this.collection);
        }, this);

        this.itemView = options.itemView;
        this.filter = options.filter || false;
        if (this.filter) {
            this.search(this.filter)
        } else {
            this.render();
        }
    },

    render: function(collection, isFiltered) {
        var numActiveItems = 0,
            totalItems = 0,
            numItemsDisplayed = 0;
            this.el_html = [];

        collection = collection || this.collection;
        if (isFiltered && collection.length == this.collection.length) {
            return this;
        }
        this.$el.html('');

        if (!isFiltered) {
            if (collection.length > 0) {
                collection.each(function(item) {
                    this.renderItem(item);
                }, this);
                this.$el.html(this.el_html);
            } else {
                this.$el.html($('#noItemsTemplate').html());
            }
        } else {
            //get the total number of active items
            numActiveItems = this.collection.where({
                active: true
            }).length;
            totalItems = numActiveItems;
            numItemsDisplayed = collection.toArray().length;

            collection.each(function(item) {
                this.renderItem(item);
            }, this);
            this.$el.html(this.el_html);
            if (numItemsDisplayed < totalItems) {
                this.$el.prepend('
Displaying ' + numItemsDisplayed + ' out of ' + totalItems + '
');
            }
        }

        return this;
    },

    renderItem: function(item) {
        var itemView = new this.itemView({
            model: item
        });
        this.el_html.push(itemView.render().el);
    },

    search: function(options) {
        var collection = (options && options.collection ? options.collection : this.collection),
        	results = [], key, val;

        if (!options || options.val == '' || options.key == '') {
            this.render(this.collection, false);
        } else {
        	key = options.key;
        	val = options.val;
        	results = this.collection.filter(function(item){
        		return (item.get(key).indexOf(val) > -1);
        	});
        	this.render(new Backbone.Collection(results), true);
           // this.render(collection.search(options), true);
        }
    }
});
<|endoftext|>


<commit_before>var SerialPort = require("serialport");
var readline = require("readline");
var fs = require('fs');

var deviceName = "";
var baudRate = 9600;
var madeFile = false;
var filePath = "data/log.txt"
var logData = false;
var timeStamp = true;

var port;

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: '> '
});

if (!fs.existsSync("data")){
    fs.mkdirSync("data");
}

listPorts();

  rl.on('line', function(line, lineCount, byteCount) {
    if(line == "exit"){
        console.log('Closing...');
        process.exit(0);
    }

    if(line.startsWith("setPort ")){
        console.log("Set port!");
        var command = line.split(" ");
        deviceName = "/dev/" + command[1];
    }

    if(line.startsWith("setRate ")){
        console.log("Set baudrate!");
        var command = line.split(" ");
        baudRate = parseInt(command[1]);
    }

    if(line.startsWith("setFile ")){
        console.log("Set filename!");
        var command = line.split(" ");
        filePath = "data/" + command[1];
    }

    if (line == "toggleLog"){
        if(logData == false){
            logData = true;
            console.log("Now logging data to: " + filePath);
        }
        else
        {
            logData = false;
            console.log("Data logging is disabled");
        }
    }

    if (line == "toggleTimestamp"){
        if(timeStamp == false){
            timeStamp = true;
            console.log("Now adding a timestamp to every entry");
        }
        else
        {
            timeStamp = false;
            console.log("Entries will be logged without timestamp");
        }
    }

    if (line == "list"){
        listPorts();
    }

    if (line == "start"){
        port = new SerialPort(deviceName, {
        parser: SerialPort.parsers.readline('\n'),
        baudrate:baudRate
        });

        port.on('data', function (data) {
         console.log(': ' + data);
         logToFile(data);
        });
    }

    if (line == "stop"){
        port.close();
        console.log('stopping readout.');
    }

    rl.prompt();
  })
  .on('error', function(e) {
    // something went wrong
  })
  .on('close', () => {
  console.log('Closing...');
  process.exit(0);
});

function logToFile(v){
    if(logData == true && timeStamp == false)
    {
        if(madeFile = false)
        {
            fs.writeFile(filePath, v , function (err) {
            if (err) return console.log(err);
                madeFile = true;
            });
        }
        else
        {
            fs.appendFile(filePath, v , function (err) {
            if (err) return console.log(err);
            });
        }
    }

    if(logData == true && timeStamp == true)
    {
        if(madeFile = false)
        {
            fs.writeFile(filePath, getDateTime() + "," + v , function (err) {
            if (err) return console.log(err);
                madeFile = true;
            });
        }
        else
        {
            fs.appendFile(filePath, getDateTime() + "," + v , function (err) {
            if (err) return console.log(err);
            });
        }
    }
}

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}

function listPorts() {
        SerialPort.list(function (err, ports) {
        console.log("current ports on system.");
        console.log("--------------------------");
    ports.forEach(function(port) {
        console.log(port.comName);
        console.log(port.pnpId);
        console.log(port.manufacturer);
        console.log("--------------------------");
    });
    rl.prompt();
    });
}<commit_msg>added autocomplete support<commit_after>var SerialPort = require("serialport");
var readline = require("readline");
var fs = require('fs');

var deviceName = "";
var baudRate = 9600;
var madeFile = false;
var filePath = "data/log.txt"
var logData = false;
var timeStamp = true;

var port;

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: '> ',
  completer: tabComp
});

if (!fs.existsSync("data")){
    fs.mkdirSync("data");
}

listPorts();

  rl.on('line', function(line, lineCount, byteCount) {
    if(line == "exit"){
        console.log('Closing...');
        process.exit(0);
    }

    if(line.startsWith("setPort ")){
        console.log("Set port!");
        var command = line.split(" ");
        deviceName = "/dev/" + command[1];
    }

    if(line.startsWith("setRate ")){
        console.log("Set baudrate!");
        var command = line.split(" ");
        baudRate = parseInt(command[1]);
    }

    if(line.startsWith("setFile ")){
        console.log("Set filename!");
        var command = line.split(" ");
        filePath = "data/" + command[1];
    }

    if (line == "toggleLog"){
        if(logData == false){
            logData = true;
            console.log("Now logging data to: " + filePath);
        }
        else
        {
            logData = false;
            console.log("Data logging is disabled");
        }
    }

    if (line == "toggleTimestamp"){
        if(timeStamp == false){
            timeStamp = true;
            console.log("Now adding a timestamp to every entry");
        }
        else
        {
            timeStamp = false;
            console.log("Entries will be logged without timestamp");
        }
    }

    if (line == "list"){
        listPorts();
    }

    if (line == "start"){
        port = new SerialPort(deviceName, {
        parser: SerialPort.parsers.readline('\n'),
        baudrate:baudRate
        });

        port.on('data', function (data) {
         console.log(': ' + data);
         logToFile(data);
        });
    }

    if (line == "stop"){
        port.close();
        console.log('stopping readout.');
    }

    rl.prompt();
  })
  .on('error', function(e) {
    // something went wrong
  })
  .on('close', () => {
  console.log('Closing...');
  process.exit(0);
});

function logToFile(v){
    if(logData == true && timeStamp == false)
    {
        if(madeFile = false)
        {
            fs.writeFile(filePath, v , function (err) {
            if (err) return console.log(err);
                madeFile = true;
            });
        }
        else
        {
            fs.appendFile(filePath, v , function (err) {
            if (err) return console.log(err);
            });
        }
    }

    if(logData == true && timeStamp == true)
    {
        if(madeFile = false)
        {
            fs.writeFile(filePath, getDateTime() + "," + v , function (err) {
            if (err) return console.log(err);
                madeFile = true;
            });
        }
        else
        {
            fs.appendFile(filePath, getDateTime() + "," + v , function (err) {
            if (err) return console.log(err);
            });
        }
    }
}

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}

function listPorts() {
        SerialPort.list(function (err, ports) {
        console.log("current ports on system.");
        console.log("--------------------------");
    ports.forEach(function(port) {
        console.log(port.comName);
        console.log(port.pnpId);
        console.log(port.manufacturer);
        console.log("--------------------------");
    });
    rl.prompt();
    });
}

function tabComp(line) {
  var completions = 'start stop setFile setPort setRate toggleLog toggleTimestamp exit list'.split(' ');
  var hits = completions.filter((c) => { return c.indexOf(line) == 0 });
  // show all completions if none found
  return [hits.length ? hits : completions, line];
}<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Responsive presentation and behavior for HTML data panels
//>>label: Panel
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.panel.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "./page", "./page.sections" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.panel", $.mobile.widget, {
	options: {
		classes: {
			panel: "ui-panel",
			contentWrap: "ui-panel-content-wrap"
		},
		theme: null,
		position: "left",
		dismissible: true,
		display: "reveal",
		initSelector: ":jqmData(role='panel')"
	},
	_handleLink: function( roleType , callback ){
		var elId = this.element.attr( "id" ),
			self = this;
		$( document ).on( "click" , "a", function( e ) {
			var $link = $( this ),
				id = $link.attr( "href" ).split( "#" )[1];
			if( elId === id ){
				e.preventDefault();
				callback.call( self , $link , id );
				return false;
			}
		});
	},
	_blockPage: function( options ){
		var deferred = $.Deferred();
		var $div = $( "
" ),
			$panel = this,
			slideDir = options.position === "left" ? "right" : "left",
			clickable = options.dismissible && options.display !== "push",
			klass = clickable ? "ui-panel-dismiss" : "ui-panel-no-dismiss";
		setTimeout(function(){
			if( $panel.element.hasClass( "ui-responsive" ) ){
				$div.addClass( "ui-responsive" );
			}
			$div.addClass( "ui-panel-dismiss-overlay" )
				.css( "height" , $.mobile.activePage.height() )
				.css( slideDir , 0 )
				.attr( "id" , "page-block" )
				.addClass( klass )
				.appendTo( $.mobile.activePage );
			if( clickable ){
				$div.bind( "vclick" , function(){
					$panel.close();
				});
			}
			deferred.resolve( options );
		}, 0); // TODO get rid of setTimeout 0 hacks
		return deferred.promise();
	},
	_create: function() {
		var o = this.options,
			klass = o.classes.panel,
			$el = this.element,
			$closeLink = $el.find( "[data-rel=close]" ),
			$page = $el.closest( ":jqmData(role='page')" );

		$el.addClass( klass );
		if( $( "." + o.classes.contentWrap ).length === 0 ){
			$( ".ui-header, .ui-content, .ui-footer" ).wrapAll( '
' );
		}
		if( o.theme ){
			$el.addClass( "ui-body-" + o.theme );
		}

		$page.addClass( $.support.cssTransform3d ? "ui-panel-transforms" : "ui-panel-positioning" );

		this._handleLink( "panel" , function( $link , id ){
			var options = $.extend( {} , this.options ),
				op = {
					position: $link.jqmData( "position" ),
					dismissible: $link.jqmData( "dismissible" ),
					display: $link.jqmData( "display" )
				};
			for( var i in op ){
				if( op.hasOwnProperty( i ) && typeof op[ i ] !== "undefined" ){
					options[ i ] = op[ i ];
				}
			}
			$( "#" + id ).panel( "toggle" , {
				position: options.position,//left right
				dismissible: options.dismissible,//true or false
				display: options.display,// overlay or push
				link: $link
			});
		});
		$closeLink.on( "vclick" , function( e ){
			e.preventDefault();
			$el.panel( "close" );
			return false;
		});
		this._trigger( "create" );
	},
	_position: function( options ){
		var deferred = $.Deferred();
		var o = options,
			klass = o.classes.panel,
			$el = this.element;
		setTimeout(function(){
			$el.addClass( "hidden" )
				.addClass( klass + "-position-" + o.position )
				.addClass( klass + "-dismissible-" + o.dismissible )
				.addClass( klass + "-display-" + o.display )
				.jqmData( "position" , o.position )
				.jqmData( "display" , o.display )
				.jqmData( "dismissible" , o.dismissible )
				.removeClass( "hidden" );
				deferred.resolve( options );
		}, 0); // TODO get rid of setTimeout 0 hacks
		return deferred.promise();
	},
	_openPanel: function( options ){
		var deferred = $.Deferred();
		var o = options,
			$el = this.element,
			klass = o.classes.panel,
			$contentsWrap = $( "." + o.classes.contentWrap ),
			self = this,
			_triggerAndResolve = function(){
				self._trigger( "open" , "open" , { link: o.link } );
				deferred.resolve( options );
			};
		if( o.display === "reveal" ){
			$contentsWrap.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _triggerAndResolve );
		} else {
			$el.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _triggerAndResolve );
		}
		setTimeout(function(){
			$el.addClass( klass + "-active" );
			if( o.display === "reveal" || o.display === "push" ){
				$contentsWrap.addClass( "panel-shift-" + o.position );
			}
			if( o.display === "push" ){
				$contentsWrap.addClass( "panel-push" );
			}
			$( ".ui-page-active" ).addClass( "ui-panel-body-scroll-block" );
		}, 0);//TODO setTimout hacks
		return deferred.promise();
	},
	_destroy: function(){},
	open: function( options , toggle ){
		var self = this;
		var deferred = $.Deferred();
		var o = $.extend( {} , this.options ),
			klass = o.classes.panel,
			$el = this.element,
			$contentsWrap = $( "." + o.classes.contentWrap );
		for( var i in options ){
			if( options.hasOwnProperty( i ) ){
				o[ i ] = options[ i ];
			}
		}
		if( $el.hasClass( "ui-responsive" ) ){
			$contentsWrap.addClass( "ui-responsive" );
		}
		this._position( o )
		.then( function( o ){
			return self._openPanel( o );
		})
		.then( function( o ){
			return self._blockPage( o );
		})
		.then( function( o ){
			deferred.resolve( o );
		});
		return deferred.promise();
	},
	close: function( options , toggle ){
		var deferred = $.Deferred();
		var o = $.extend( {} , this.options ),
			klass = o.classes.panel,
			$el = this.element,
			position = $el.jqmData( "position" ),
			display = $el.jqmData( "display" ),
			dismissible = $el.jqmData( "dismissible" ),
			$contentsWrap = $( "." + o.classes.contentWrap );
			_closePanel = function(){
				$el.removeClass( klass + "-position-" + position )
					.removeClass( klass + "-display-" + display )
					.removeClass( klass + "-dismissible-" + dismissible );
				$contentsWrap.removeClass( "ui-responsive" );
				$el.data( "mobile-panel" )._trigger( "close" , "close" , { link: o.link } );
				deferred.resolve( o , toggle );
			};
		for( var i in options ){
			if( options.hasOwnProperty( i ) ){
				o[ i ] = options[ i ];
			}
		}
		if( toggle ){
			$el.addClass( "ui-panel-toggle" );
		}
		if( display === "reveal" ){
			$contentsWrap.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _closePanel );
		} else {
			$el.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _closePanel );
		}

		$el.removeClass( klass + "-active" );
		$( "#page-block" ).remove();
		$( "." + o.classes.contentWrap ).removeClass( "panel-shift-" + position )
			.removeClass( "panel-push" );
		$( ".ui-page-active" ).removeClass( "ui-panel-body-scroll-block" );
		return deferred.promise();
	},
	toggle: function( options ){
		var $el = this.element,
			active = $( ".ui-panel-active" ).data( "mobile-panel" ),
			self = this;
		if( active &&
				( active.element.jqmData( "position") === options.position ) &&
				( active.element.attr( "id" ) === $el.attr( "id" ) ) &&
				( active.element.jqmData( "display" ) === options.display ) ){
			return active.close( options );
		} else if ( active ){
			active.close( options , true ).
			then( function( options , toggle ){
				self.open( options , toggle );
			});
		} else {
			return this.open( options );
		}
	},
	refresh: function(){
	}
});

$( document ).bind( "panelopen panelclose" , function( e , data ){
	var $link = data.link, $parent;
	if( $link ){
		$parent = $link.parent().parent();
		if ($parent.hasClass("ui-li")) {
			$link = $parent.parent();
		}
		$link.removeClass( $.mobile.activeBtnClass );
	}
});

$( document ).bind( "pagehide" , function( e , data ){
	$( ".ui-panel-active" ).panel( "close" );
});

$(document).keyup(function(e) {
	if( e.keyCode === 27 ){
		$( ".ui-panel-active" ).panel( "close" );
	}
});

//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
	$.mobile.panel.prototype.enhanceWithin( e.target );
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");

<commit_msg>Don't create the dismissing div if it isnt' called for<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Responsive presentation and behavior for HTML data panels
//>>label: Panel
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.panel.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "./page", "./page.sections" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

$.widget( "mobile.panel", $.mobile.widget, {
	options: {
		classes: {
			panel: "ui-panel",
			contentWrap: "ui-panel-content-wrap"
		},
		theme: null,
		position: "left",
		dismissible: true,
		display: "reveal",
		initSelector: ":jqmData(role='panel')"
	},
	_handleLink: function( roleType , callback ){
		var elId = this.element.attr( "id" ),
			self = this;
		$( document ).on( "click" , "a", function( e ) {
			var $link = $( this ),
				id = $link.attr( "href" ).split( "#" )[1];
			if( elId === id ){
				e.preventDefault();
				callback.call( self , $link , id );
				return false;
			}
		});
	},
	_blockPage: function( options ){
		var deferred = $.Deferred();
		var $div = $( "
" ),
			$panel = this,
			slideDir = options.position === "left" ? "right" : "left",
			clickable = options.dismissible && options.display !== "push",
			klass = clickable ? "ui-panel-dismiss" : "ui-panel-no-dismiss";
		setTimeout(function(){
			if( clickable ){
				if( $panel.element.hasClass( "ui-responsive" ) ){
					$div.addClass( "ui-responsive" );
				}
				$div.addClass( "ui-panel-dismiss-overlay" )
					.css( "height" , $.mobile.activePage.height() )
					.css( slideDir , 0 )
					.attr( "id" , "page-block" )
					.addClass( klass )
					.appendTo( $.mobile.activePage );
				$div.bind( "vclick" , function(){
					$panel.close();
				});
			}
			deferred.resolve( options );
		}, 0); // TODO get rid of setTimeout 0 hacks
		return deferred.promise();
	},
	_create: function() {
		var o = this.options,
			klass = o.classes.panel,
			$el = this.element,
			$closeLink = $el.find( "[data-rel=close]" ),
			$page = $el.closest( ":jqmData(role='page')" );

		$el.addClass( klass );
		if( $( "." + o.classes.contentWrap ).length === 0 ){
			$( ".ui-header, .ui-content, .ui-footer" ).wrapAll( '
' );
		}
		if( o.theme ){
			$el.addClass( "ui-body-" + o.theme );
		}

		$page.addClass( $.support.cssTransform3d ? "ui-panel-transforms" : "ui-panel-positioning" );

		this._handleLink( "panel" , function( $link , id ){
			var options = $.extend( {} , this.options ),
				op = {
					position: $link.jqmData( "position" ),
					dismissible: $link.jqmData( "dismissible" ),
					display: $link.jqmData( "display" )
				};
			for( var i in op ){
				if( op.hasOwnProperty( i ) && typeof op[ i ] !== "undefined" ){
					options[ i ] = op[ i ];
				}
			}
			$( "#" + id ).panel( "toggle" , {
				position: options.position,//left right
				dismissible: options.dismissible,//true or false
				display: options.display,// overlay or push
				link: $link
			});
		});
		$closeLink.on( "vclick" , function( e ){
			e.preventDefault();
			$el.panel( "close" );
			return false;
		});
		this._trigger( "create" );
	},
	_position: function( options ){
		var deferred = $.Deferred();
		var o = options,
			klass = o.classes.panel,
			$el = this.element;
		setTimeout(function(){
			$el.addClass( "hidden" )
				.addClass( klass + "-position-" + o.position )
				.addClass( klass + "-dismissible-" + o.dismissible )
				.addClass( klass + "-display-" + o.display )
				.jqmData( "position" , o.position )
				.jqmData( "display" , o.display )
				.jqmData( "dismissible" , o.dismissible )
				.removeClass( "hidden" );
				deferred.resolve( options );
		}, 0); // TODO get rid of setTimeout 0 hacks
		return deferred.promise();
	},
	_openPanel: function( options ){
		var deferred = $.Deferred();
		var o = options,
			$el = this.element,
			klass = o.classes.panel,
			$contentsWrap = $( "." + o.classes.contentWrap ),
			self = this,
			_triggerAndResolve = function(){
				self._trigger( "open" , "open" , { link: o.link } );
				deferred.resolve( options );
			};
		if( o.display === "reveal" ){
			$contentsWrap.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _triggerAndResolve );
		} else {
			$el.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _triggerAndResolve );
		}
		setTimeout(function(){
			$el.addClass( klass + "-active" );
			if( o.display === "reveal" || o.display === "push" ){
				$contentsWrap.addClass( "panel-shift-" + o.position );
			}
			if( o.display === "push" ){
				$contentsWrap.addClass( "panel-push" );
			}
			$( ".ui-page-active" ).addClass( "ui-panel-body-scroll-block" );
		}, 0);//TODO setTimout hacks
		return deferred.promise();
	},
	_destroy: function(){},
	open: function( options , toggle ){
		var self = this;
		var deferred = $.Deferred();
		var o = $.extend( {} , this.options ),
			klass = o.classes.panel,
			$el = this.element,
			$contentsWrap = $( "." + o.classes.contentWrap );
		for( var i in options ){
			if( options.hasOwnProperty( i ) ){
				o[ i ] = options[ i ];
			}
		}
		if( $el.hasClass( "ui-responsive" ) ){
			$contentsWrap.addClass( "ui-responsive" );
		}
		this._position( o )
		.then( function( o ){
			return self._openPanel( o );
		})
		.then( function( o ){
			return self._blockPage( o );
		})
		.then( function( o ){
			deferred.resolve( o );
		});
		return deferred.promise();
	},
	close: function( options , toggle ){
		var deferred = $.Deferred();
		var o = $.extend( {} , this.options ),
			klass = o.classes.panel,
			$el = this.element,
			position = $el.jqmData( "position" ),
			display = $el.jqmData( "display" ),
			dismissible = $el.jqmData( "dismissible" ),
			$contentsWrap = $( "." + o.classes.contentWrap );
			_closePanel = function(){
				$el.removeClass( klass + "-position-" + position )
					.removeClass( klass + "-display-" + display )
					.removeClass( klass + "-dismissible-" + dismissible );
				$contentsWrap.removeClass( "ui-responsive" );
				$el.data( "mobile-panel" )._trigger( "close" , "close" , { link: o.link } );
				deferred.resolve( o , toggle );
			};
		for( var i in options ){
			if( options.hasOwnProperty( i ) ){
				o[ i ] = options[ i ];
			}
		}
		if( toggle ){
			$el.addClass( "ui-panel-toggle" );
		}
		if( display === "reveal" ){
			$contentsWrap.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _closePanel );
		} else {
			$el.one( "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd" , _closePanel );
		}

		$el.removeClass( klass + "-active" );
		$( "#page-block" ).remove();
		$( "." + o.classes.contentWrap ).removeClass( "panel-shift-" + position )
			.removeClass( "panel-push" );
		$( ".ui-page-active" ).removeClass( "ui-panel-body-scroll-block" );
		return deferred.promise();
	},
	toggle: function( options ){
		var $el = this.element,
			active = $( ".ui-panel-active" ).data( "mobile-panel" ),
			self = this;
		if( active &&
				( active.element.jqmData( "position") === options.position ) &&
				( active.element.attr( "id" ) === $el.attr( "id" ) ) &&
				( active.element.jqmData( "display" ) === options.display ) ){
			return active.close( options );
		} else if ( active ){
			active.close( options , true ).
			then( function( options , toggle ){
				self.open( options , toggle );
			});
		} else {
			return this.open( options );
		}
	},
	refresh: function(){
	}
});

$( document ).bind( "panelopen panelclose" , function( e , data ){
	var $link = data.link, $parent;
	if( $link ){
		$parent = $link.parent().parent();
		if ($parent.hasClass("ui-li")) {
			$link = $parent.parent();
		}
		$link.removeClass( $.mobile.activeBtnClass );
	}
});

$( document ).bind( "pagehide" , function( e , data ){
	$( ".ui-panel-active" ).panel( "close" );
});

$(document).keyup(function(e) {
	if( e.keyCode === 27 ){
		$( ".ui-panel-active" ).panel( "close" );
	}
});

//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
	$.mobile.panel.prototype.enhanceWithin( e.target );
});

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");

<|endoftext|>


<commit_before>const express = require('express');
const bodyParser = require('body-parser');
const webpush = require('web-push');
const gcloud = require('google-cloud');
const model = require('../model');
const path = require ('path');

// Project variables
const project_id = 'web-push-rocks';
const app = express();
const pubsub = gcloud.pubsub({
  projectId: project_id
});
const subscribeTopicId = `projects/${project_id}/topics/subscribe`;
const sendTopicId = `projects/${project_id}/topics/send`;
const jsonParser = bodyParser.json();

let subscribeTopic;
let sendTopic;
let sendRawTopic;
let instanceVAPIDKey;

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.render('index', {
    publicKey: instanceVAPIDKey.publicKey,
    messages: [{}]
  });
});

app.post('/subscribe', jsonParser, (req, res) => {
  const subscription = req.body;
  console.log(subscription);

  subscription.privateKey = instanceVAPIDKey.privateKey;

  subscribeTopic.publish({
    subscription: subscription
  });
  res.send('ok');
});

app.post('/send', jsonParser, (req, res) => {
  const message = req.body;
  const id = req.query.id;

  console.log(message)

  sendTopic.publish({
    id: id,
    message: message
  });

  res.send('ok');
});

app.post('/send-raw', jsonParser, (req, res) => {
  const message = req.body;
  const id = req.query.id;
  const processor = req.query.processor;

  // Topic must exist
  const rawTopic = pubsub.topic(`projects/${project_id}/topics/send-${processor}`);
  rawTopic.publish({
      id: id,
      processor: processor,
      message: message
    })
    .then(() => res.send('ok'))
    .catch(() => res.send('error'))
});

app.listen(3000, () => {
  app.set('views', path.join(__dirname , 'views'));
  app.set('view engine', 'ejs');

  const vapidKeys = webpush.generateVAPIDKeys();

  // Before the server starts, let's get VAPID persisted
  instanceVAPIDKey = new model.ApplicationKey(vapidKeys.publicKey, vapidKeys.privateKey);
  instanceVAPIDKey.put();

  // Create the topic
  pubsub.createTopic(subscribeTopicId)
        .then(data => subscribeTopic = data[0])
        .catch(data => subscribeTopic = pubsub.topic(subscribeTopicId));

  // Create the topic that will be used to send the broadcasts.
  pubsub.createTopic(sendTopicId)
        .then(data => sendTopic = data[0])
        .catch(data => sendTopic = pubsub.topic(sendTopicId));

  console.log('Front-end is listenting on port 3000');
});<commit_msg>body parsing.<commit_after>const express = require('express');
const bodyParser = require('body-parser');
const webpush = require('web-push');
const gcloud = require('google-cloud');
const model = require('../model');
const path = require ('path');

// Project variables
const project_id = 'web-push-rocks';
const app = express();
const pubsub = gcloud.pubsub({
  projectId: project_id
});
const subscribeTopicId = `projects/${project_id}/topics/subscribe`;
const sendTopicId = `projects/${project_id}/topics/send`;
const jsonParser = bodyParser.json();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

let subscribeTopic;
let sendTopic;
let sendRawTopic;
let instanceVAPIDKey;

app.use(express.static('public'));

app.get('/', (req, res) => {
  res.render('index', {
    publicKey: instanceVAPIDKey.publicKey,
    messages: [{}]
  });
});

app.post('/subscribe', jsonParser, (req, res) => {
  const subscription = req.body;
  console.log(subscription);

  subscription.privateKey = instanceVAPIDKey.privateKey;

  subscribeTopic.publish({
    subscription: subscription
  });
  res.send('ok');
});

app.post('/send', jsonParser, (req, res) => {
  const message = req.body;
  const id = req.query.id;

  console.log(message)

  sendTopic.publish({
    id: id,
    message: message
  });

  res.send('ok');
});

app.post('/send-raw', (req, res) => {
  const message = req.body;
  const id = req.query.id;
  const processor = req.query.processor;

  // Topic must exist
  const rawTopic = pubsub.topic(`projects/${project_id}/topics/send-${processor}`);
  rawTopic.publish({
      id: id,
      processor: processor,
      message: message
    })
    .then(() => res.send('ok'))
    .catch(() => res.send('error'))
});

app.listen(3000, () => {
  app.set('views', path.join(__dirname , 'views'));
  app.set('view engine', 'ejs');

  const vapidKeys = webpush.generateVAPIDKeys();

  // Before the server starts, let's get VAPID persisted
  instanceVAPIDKey = new model.ApplicationKey(vapidKeys.publicKey, vapidKeys.privateKey);
  instanceVAPIDKey.put();

  // Create the topic
  pubsub.createTopic(subscribeTopicId)
        .then(data => subscribeTopic = data[0])
        .catch(data => subscribeTopic = pubsub.topic(subscribeTopicId));

  // Create the topic that will be used to send the broadcasts.
  pubsub.createTopic(sendTopicId)
        .then(data => sendTopic = data[0])
        .catch(data => sendTopic = pubsub.topic(sendTopicId));

  console.log('Front-end is listenting on port 3000');
});<|endoftext|>


<commit_before>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2010 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('mirosubs.widget.SubtitleController');

/**
 * @constructor
 */
mirosubs.widget.SubtitleController = function(
    videoID, videoURL, playController, videoTab, dropDown)
{
    this.videoID_ = videoID;
    this.videoURL_ = videoURL;
    this.videoTab_ = videoTab;
    this.dropDown_ = dropDown;
    this.playController_ = playController;
    this.playController_.setSubtitleController(this);
    this.handler_ = new goog.events.EventHandler(this);
    this.dialogOpener_ = new mirosubs.widget.SubtitleDialogOpener(
        videoID, videoURL, this.playController_.getVideoSource(),
        function(loading) {
            if (loading)
                videoTab.showLoading();
            else
                videoTab.stopLoading();
        },
        goog.bind(playController.stopForDialog, playController));
    this.handler_.listenOnce(
        this.dialogOpener_,
        goog.ui.Dialog.EventType.AFTER_HIDE,
        this.subtitleDialogClosed_);
    var s = mirosubs.widget.DropDown.Selection;
    this.handler_.
        listen(
            dropDown,
            s.ADD_LANGUAGE,
            this.openNewLanguageDialog).
        listen(
            dropDown,
            s.IMPROVE_SUBTITLES,
            this.openSubtitleDialog).
        listen(
            videoTab.getAnchorElem(), 'click',
            this.videoAnchorClicked_
        );
};

mirosubs.widget.SubtitleController.prototype.videoAnchorClicked_ =
    function(e)
{
    mirosubs.Tracker.getInstance().track('videoTabClicked');
    if (!this.dropDown_.hasSubtitles())
        this.openSubtitleDialog();
    else
        this.dropDown_.toggleShow();
    e.preventDefault();
};

/**
 * Corresponds to "Add new subs" or "Improve these subs" in menu.
 * @param type {string} opt_intitial_lang= When on Improve these subs,
 *  we should now which lang to default to on the started dialog
 */
mirosubs.widget.SubtitleController.prototype.openSubtitleDialog =
    function(e)
{
    var state  = this.playController_.getSubtitleState();
    this.openNewLanguageDialog(state);
};

mirosubs.widget.SubtitleController.prototype.openNewLanguageDialog =
    function(opt_langState)
{
    this.dialogOpener_.showStartDialog(
        this.playController_.getVideoSource().getVideoURL(), opt_langState);
};

mirosubs.widget.SubtitleController.prototype.subtitleDialogClosed_ = function(e) {
    var dropDownContents = e.target.getDropDownContents();
    this.playController_.dialogClosed();
    this.videoTab_.showContent(
        this.dropDown_.hasSubtitles(),
        this.playController_.getSubtitleState());
    this.dropDown_.setCurrentSubtitleState(
        this.playController_.getSubtitleState());
    if (dropDownContents != null) {
        this.dropDown_.updateContents(dropDownContents);
    }
};
<commit_msg>"Improve this subtitles" will now start to edit the selected subtitles, instead of showing the new lang dialog, fixes https://www.pivotaltracker.com/story/show/12519451<commit_after>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2010 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('mirosubs.widget.SubtitleController');

/**
 * @constructor
 */
mirosubs.widget.SubtitleController = function(
    videoID, videoURL, playController, videoTab, dropDown)
{
    this.videoID_ = videoID;
    this.videoURL_ = videoURL;
    this.videoTab_ = videoTab;
    this.dropDown_ = dropDown;
    this.playController_ = playController;
    this.playController_.setSubtitleController(this);
    this.handler_ = new goog.events.EventHandler(this);
    this.dialogOpener_ = new mirosubs.widget.SubtitleDialogOpener(
        videoID, videoURL, this.playController_.getVideoSource(),
        function(loading) {
            if (loading)
                videoTab.showLoading();
            else
                videoTab.stopLoading();
        },
        goog.bind(playController.stopForDialog, playController));
    this.handler_.listenOnce(
        this.dialogOpener_,
        goog.ui.Dialog.EventType.AFTER_HIDE,
        this.subtitleDialogClosed_);
    var s = mirosubs.widget.DropDown.Selection;
    this.handler_.
        listen(
            dropDown,
            s.ADD_LANGUAGE,
            this.openNewLanguageDialog).
        listen(
            dropDown,
            s.IMPROVE_SUBTITLES,
            this.openSubtitleDialog).
        listen(
            videoTab.getAnchorElem(), 'click',
            this.videoAnchorClicked_
        );
};

mirosubs.widget.SubtitleController.prototype.videoAnchorClicked_ =
    function(e)
{
    mirosubs.Tracker.getInstance().track('videoTabClicked');
    if (!this.dropDown_.hasSubtitles())
        this.openSubtitleDialog();
    else
        this.dropDown_.toggleShow();
    e.preventDefault();
};

/**
 * Corresponds to  "Improve these subs" in menu.
 */
mirosubs.widget.SubtitleController.prototype.openSubtitleDialog =
    function()
{
    var state  = this.playController_.getSubtitleState();
    this.dialogOpener_.openDialogOrRedirect_(
        state.LANGUAGE,
        null,
        state.LANGUAGE_PK
    );

};

mirosubs.widget.SubtitleController.prototype.openNewLanguageDialog =
    function(opt_langState)
{
    this.dialogOpener_.showStartDialog(
        this.playController_.getVideoSource().getVideoURL(), opt_langState);
};

mirosubs.widget.SubtitleController.prototype.subtitleDialogClosed_ = function(e) {
    var dropDownContents = e.target.getDropDownContents();
    this.playController_.dialogClosed();
    this.videoTab_.showContent(
        this.dropDown_.hasSubtitles(),
        this.playController_.getSubtitleState());
    this.dropDown_.setCurrentSubtitleState(
        this.playController_.getSubtitleState());
    if (dropDownContents != null) {
        this.dropDown_.updateContents(dropDownContents);
    }
};
<|endoftext|>


<commit_before>(function(window) {

  var TRANSITION_EVENT = 'transitionend';
  var TRANSITION_PROPERTY = 'transition-property';

  var transitionable = (function() {
    var b = document.body || document.documentElement,
        s = b.style,
        p = 'transition',
        v = ['Moz', 'webkit', 'Webkit', 'Khtml', 'O', 'ms'];

    if (typeof s[p] === 'string') {
      var computed = window.getComputedStyle(b);
      if (typeof b[TRANSITION_PROPERTY] !== 'string') {
        for (var i = 0; i < v.length; i++) {
          if (typeof computed[v[i] + 'TransitionProperty'] === 'string') {
            TRANSITION_PROPERTY = v[i] + 'TransitionProperty';
          }
        }
      }
      return true;
    }

    p = p.charAt(0).toUpperCase() + p.substr(1);

    for (var i = 0; i < v.length; i++) {
      if (typeof s[v[i] + p] === 'string') {
        TRANSITION_EVENT = v[i] + p + 'End';
        TRANSITION_PROPERTY = v[i] + 'TransitionProperty';
        return true;
      }
    }

    return false;
  }());

  function findTransitionProperties(el) {
    var out = [],
        prop = window.getComputedStyle(el)[TRANSITION_PROPERTY];
    if (prop) {
      var props = prop.split(',');
      for (var i = 0; i < props.length; i++) {
        var p = props[i].replace(/\s+/, '');
        if (p !== 'all') {
          out.push(p);
        }
      }
    }
    return out;
  }

  function addClass(el, cls) {
    if (el.classList) {
      el.classList.add(cls);
    } else {
      el.className = classesFrom(el).concat(cls).join(' ');
    }
  }

  function removeClass(el, cls) {
    if (el.classList) {
      el.classList.remove(cls);
    } else {
      el.className = cleanArray(classesFrom(el), function(item) {
        return item !== cls;
      }).join(' ');
    }
  }

  function classesFrom(el) {
    if (el.classList) {
      return Array.prototype.slice.call(el.classList);
    } else {
      return el.className.split(/\s+/);
    }
  }

  function cleanArray(arr, fn) {
    var newarr = [];
    for (var i = 0; i < arr.length; i++) {
      if (fn.call(arr[i], arr[i]) === true) {
        newarr.push(arr[i]);
      }
    }
    return newarr;
  }

  function removeNegationClasses(arr) {
    return cleanArray(arr, function(item) {
      return item.indexOf('-') === -1;
    });
  }

  function isInArray(arr1, arr2) {
    for (var i = 0; i < arr1.length; i++) {
      if (arr2.indexOf(arr1[i]) === -1) {
        return false;
      }
    }
    return true;
  }

  function parentAt(el, level) {
    for (var i = 0; i < level; i++) {
      if (!el.parentNode || el === document.body) {
        break;
      }
      el = el.parentNode;
    }
    return el;
  }

  function hasCommonParent(el, level, common) {
    return (parentAt(el, level) === common);
  }

  function findCommonParent(els) {
    var lastParent,
        level = 1;
    for (var i = 0; i < els.length; i++) {
      if (!lastParent) {
        lastParent = parentAt(els[i], level);
        continue;
      }
      if (lastParent && !hasCommonParent(els[i], level, lastParent)) {
        lastParent = null;
        level++;
        i = 0;
      }
    }
    return lastParent || document.body;
  }

  function EventContainer(opts) {
    this.nextRun = opts.nextRun;
    this.waitForContinue = false;
  }

  EventContainer.prototype.resume = function() {
    this.waitForContinue = false;
    return this.nextRun();
  };

  EventContainer.prototype.wait = function() {
    this.waitForContinue = true;
  };

  function Root(els) {
    this.processElements(els);
    this.classes = [];
    this.callbacks = [];
    this.timings = [];
    return this;
  }

  Root.prototype.processElements = function(els) {
    if (typeof els === 'string') {
      var found = document.querySelectorAll(els);
      if (found.length === 0) {
        this.els = [];
        if ((typeof this.deferredEls === 'undefined')) {
          this.deferredEls = els;
        } else {
          this.deferredEls = null;
        }
      } else {
        this.els = Array.prototype.slice.call(found);
      }
    } else {
      this.els = Array.prototype.slice.call(els);
    }
    this.parent = findCommonParent(this.els);
  };

  Root.prototype.alter = function() {
    var args = Array.prototype.slice.call(arguments);
    this.classes.push(cleanArray(args, function(item) {
      return typeof item === 'string';
    }));
    return this;
  };

  Root.prototype.thenEach = function(fn) {
    return this;
  };

  Root.prototype.then = function(fn) {
    var args = Array.prototype.slice.call(arguments);
    this.callbacks.push(cleanArray(args, function(item) {
      return typeof item === 'function';
    }));
    return this;
  };

  Root.prototype.stagger = function(ms, buff) {
    if (!transitionable) {
      ms = buff = 0;
    } else {
      ms = ms || 0;
      buff = buff || 0;
    }
    this.timings.push([ms, buff]);
    return this;
  };

  Root.prototype.run = function(current) {

    if (this.deferredEls) {
      this.processElements(this.deferredEls);
    }

    current = current || 0;

    var total = this.classes.length,
        parent = this.parent,
        callbacks = this.callbacks[current] || [],
        classes = this.classes[current] || [],
        timing = this.timings[current] || [0, 0],
        els = this.els,
        len = this.els.length,
        self = this;

    var nextRun = function() {
      if (current + 1 < total) {
        self.run(current + 1);
      } else {
        flushCallbacks(current + 1);
      }
    };

    var eventContainer = new EventContainer({
      nextRun: nextRun
    });

    var flushCallbacks = function(start) {
      for (var i = start; i < self.callbacks.length; i++) {
        for (var j = 0; j < self.callbacks[i].length; j++) {
          self.callbacks[i][j](eventContainer, els);
        }
      }
    };

    var runCallbacks = function() {
      for (var i = 0; i < callbacks.length; i++) {
        callbacks[i](eventContainer, els);
      }
      if (!eventContainer.waitForContinue) {
        nextRun();
      }
    };

    var hasFulfilledAllTransitions = function(e) {
      if (!e.target.fulfilledTransitions) {
        e.target.fulfilledTransitions = [];
        e.target.transitionsToFulfill = findTransitionProperties(e.target);
      }
      if (e.target.fulfilledTransitions.indexOf(e.propertyName) === -1) {
        e.target.fulfilledTransitions.push(e.propertyName);
      }
      if (e.target.transitionsToFulfill.length === 0 ||
          (e.target.fulfilledTransitions.length >= e.target.transitionsToFulfill.length)) {
        e.target.fulfilledTransitions = [];
        return true;
      } else {
        return false;
      }
    };

    var transitionCallback = function(e) {
      if (els.indexOf(e.target) !== -1 &&
          isInArray(removeNegationClasses(classes), classesFrom(e.target)) &&
          hasFulfilledAllTransitions(e)) {
        len--;
        if (len <= 0) {
          parent.removeEventListener(TRANSITION_EVENT, transitionCallback);
          runCallbacks();
        }
      }
    };

    var alterClasses = function() {
      for (var i = 0; i < els.length; i++) {
        window.setTimeout(function(el) {
          return function() {
            for (var j = 0; j < classes.length; j++) {
              if (classes[j].indexOf('-') === 0) {
                removeClass(el, classes[j].slice(1));
              } else {
                addClass(el, classes[j]);
              }
            }
          };
        }(els[i]), (i * timing[0]) + timing[1]);
      }
    };

    if (transitionable) {
      parent.addEventListener(TRANSITION_EVENT, transitionCallback);
      window.setTimeout(alterClasses, 15);
    } else {
      alterClasses();
      runCallbacks();
    }

    return null;

  };

  function Preloader() {
    var args = Array.prototype.slice.call(arguments);
    this.src = cleanArray(args, function(item) {
      return typeof item === 'string';
    });
    this.callbacks = [];
    this.individualCallbacks = [];
  }

  Preloader.prototype.then = function(fn) {
    fn = fn || function() {};
    this.callbacks.push(fn);
  };

  Preloader.prototype.thenEach = function(fn) {
    fn = fn || function() {};
    this.individualCallbacks.push(fn);
  };

  Preloader.prototype.run = function() {
    var src = this.src,
        total = src.length,
        self = this;

    var handleImageLoad = function() {
      runIndividualCallbacks(this.originalSrc, this);
      total--;
      if (total <= 0) {
        runCallbacks();
      }
    };

    var runIndividualCallbacks = function(src, img) {
      for (var i = 0; i < self.individualCallbacks.length; i++) {
        self.individualCallbacks[i](src, img);
      }
    };

    var runCallbacks = function() {
      for (var i = 0; i < self.callbacks.length; i++) {
        self.callbacks[i](src);
      }
    };

    var loadImage = function(src) {
      var img = new window.Image();
      img.onload = handleImageLoad;
      img.onerror = handleImageLoad;
      img.originalSrc = src;
      img.src = src;
    };

    if (src.length) {
      for (var i = 0; i < src.length; i++) {
        loadImage(src[i]);
      }
    } else {
      runCallbacks();
    }

  };

  function RootWrapper(els) {
    this.chain = [];
    if (els) {
      this.on(els);
    }
    return this;
  };

  RootWrapper.prototype.preload = function(src) {
    this.chain.push(new Preloader(src));
    return this;
  };

  RootWrapper.prototype.on = function(els) {
    this.chain.push(new Root(els));
    return this;
  };
  RootWrapper.prototype.thenOn = RootWrapper.prototype.on;

  RootWrapper.prototype.currentRoot = function() {
    return this.chain[this.chain.length - 1];
  };

  RootWrapper.prototype.alter = function() {
    this.currentRoot().alter.apply(this.currentRoot(),
      Array.prototype.slice.call(arguments)
    );
    return this;
  };

  RootWrapper.prototype.stagger = function() {
    this.currentRoot().stagger.apply(this.currentRoot(),
      Array.prototype.slice.call(arguments)
    );
    return this;
  };

  RootWrapper.prototype.then = function() {
    this.currentRoot().then.apply(this.currentRoot(),
      Array.prototype.slice.call(arguments)
    );
    return this;
  };

  RootWrapper.prototype.thenEach = function() {
    this.currentRoot().thenEach.apply(this.currentRoot(),
      Array.prototype.slice.call(arguments)
    );
    return this;
  };

  RootWrapper.prototype.run = function(current) {
    current = current || 0;

    var total = this.chain.length,
        self = this;

    var nextRun = function() {
      if (current + 1 < total) {
        self.run(current + 1);
      }
    };

    this.chain[current].then(nextRun);
    this.chain[current].run();
  };

  window.converge = {
    preload: function(src) {
      var wrapper = new RootWrapper();
      return wrapper.preload(src);
    },
    on: function(els) {
      return new RootWrapper(els);
    }
  };

}(window));
<commit_msg>remove old source<commit_after><|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import storeCreator from './store/configureStore';
import { Router, Route } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory'

// Route components.
import App from './App/App'; // Main application.
import Category from './Category/Container';
import Categories from './Categories/Container';
import Activation from './Activation/Container';
import User from  './User/Container';
import Stories from './Stories/Container';
import Story from './Story/Container';
import StoryComposer from './StoryComposer/Container';
import Login from './Login/ConnectedLogin';
import Authentication from './Authentication/Container';
import Register from './Register/Container';
import Home from './App/Home'; // Home
import NotFound from './Errors/NotFound'; // 404
import loadConfig from './App/Actions';
import injectTapEventPlugin from 'react-tap-event-plugin';

// Required by material-ui.
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

const store = storeCreator();
const browserHistory = createBrowserHistory();

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

// Load configuration.
store.dispatch(loadConfig());

function requireAuth(nextState, replace) {
  const state = store.getState();
  const loggedIn = state.session.loggedIn;

  if (!loggedIn) {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

function requireAuthExtra(nextState, replace){

  const state = store.getState();
  const loggedIn = state.session.loggedIn;
  const role = state.session.user.role;

  if (!loggedIn || role != "author") {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }

}

function redirectFromLogin(nextState, replace) {

  const state = store.getState();
  const loggedIn = state.session.loggedIn;

  if (loggedIn) {
    replace({
      pathname: '/',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

class Root extends React.Component {

 render() {

   return (
     <Provider store={store}>
       <Router history={browserHistory} >
	    <MuiThemeProvider>

		   <Route path="/" component={App}/>
		   <Route exact path="/" component={Home}/>
		   <Route exact path="/login" component={Login} onEnter={redirectFromLogin} />
		   <Route exact path="/auth" component={Authentication} />
		   <Route exact path="/register" component={Register} />
           <Route exact path="/users/:userId/:userName" component={User}/>
           <Route exact path="/stories" component={Stories} />
           <Route exact path="/stories/new" component={StoryComposer} onEnter={requireAuthExtra} />
           <Route exact path="/stories/:storyId/:storyName" component={Story} />
           <Route exact path="/categories" component={Categories} />
           <Route exact path="/categories/:categoryId/:categoryName" component={Category} />
           <Route exact path="/activation/:code" component={Activation} />

		</MuiThemeProvider>
       </Router>
      </Provider>
    );
  }
}

//<Route exact path="*" component={NotFound} />
ReactDOM.render(<Root />, document.getElementById('root'));
<commit_msg>Make private routes work again.<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import storeCreator from './store/configureStore';
import { Router, Route } from 'react-router';
import {  Redirect } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory'

// Route components.
import App from './App/App'; // Main application.
import Category from './Category/Container';
import Categories from './Categories/Container';
import Activation from './Activation/Container';
import User from  './User/Container';
import Stories from './Stories/Container';
import Story from './Story/Container';
import StoryComposer from './StoryComposer/Container';
import Login from './Login/ConnectedLogin';
import Authentication from './Authentication/Container';
import Register from './Register/Container';
import Home from './App/Home'; // Home
import NotFound from './Errors/NotFound'; // 404
import loadConfig from './App/Actions';
import injectTapEventPlugin from 'react-tap-event-plugin';

// Required by material-ui.
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

const store = storeCreator();
const browserHistory = createBrowserHistory();

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

// Load configuration.
store.dispatch(loadConfig());

function requireAuth(nextState, replace) {
  const state = store.getState();
  const loggedIn = state.session.loggedIn;

  if (!loggedIn) {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

function requireAuthExtra(nextState, replace){

  const state = store.getState();
  const loggedIn = state.session.loggedIn;
  const role = state.session.user.role;

  if (!loggedIn || role != "author") {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }

}

function redirectFromLogin(nextState, replace) {

  const state = store.getState();
  const loggedIn = state.session.loggedIn;

  if (loggedIn) {
    replace({
      pathname: '/',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

const PrivateRoute = ({ component: Component, ...rest, state }) => (
  <Route {...rest} render={props => (state.session.loggedIn ? (<Component {...props}/>) :
  (<Redirect to={{pathname: '/login', state: { from: props.location }}} />) )}
  />
);

class Root extends React.Component {

 render() {

   return (
     <Provider store={store}>
       <Router history={browserHistory} >
	    <MuiThemeProvider>

		   <Route path="/" component={App}/>
		   <Route exact path="/" component={Home}/>
		   <Route exact path="/login" component={Login} onEnter={redirectFromLogin} />
		   <Route exact path="/auth" component={Authentication} />
		   <Route exact path="/register" component={Register} />
           <Route exact path="/users/:userId/:userName" component={User}/>
           <Route exact path="/stories" component={Stories} />
           <PrivateRoute exact path="/stories/new" component={StoryComposer} state={store.getState()} />
           <Route exact path="/stories/:storyId/:storyName" component={Story} />
           <Route exact path="/categories" component={Categories} />
           <Route exact path="/categories/:categoryId/:categoryName" component={Category} />
           <Route exact path="/activation/:code" component={Activation} />

		</MuiThemeProvider>
       </Router>
      </Provider>
    );
  }
}

//<Route exact path="*" component={NotFound} />
ReactDOM.render(<Root />, document.getElementById('root'));
<|endoftext|>


<commit_before>// -------------------------------------------------
// ------------------- SYSTEM ----------------------
// -------------------------------------------------

function System() {

    DebugMessage("Init Terminal");
    this.term = new Terminal();

    DebugMessage("Init RAM");
    this.ram = new RAM(0x2000000);

    DebugMessage("Init CPU");
    this.cpu = new CPU(this.ram);

    DebugMessage("Init Devices");
    this.uartdev = new UARTDev(this.term, this.cpu);
    this.ethdev = new EthDev();
    this.fbdev = new FBDev(this.ram);
    this.atadev = new ATADev(this.cpu);

    DebugMessage("Add Devices");
    this.ram.AddDevice(this.atadev, 0x9e000000, 0x1000);
    this.ram.AddDevice(this.uartdev, 0x90000000, 0x7);
    this.ram.AddDevice(this.ethdev, 0x92000000, 0x1000);
    this.ram.AddDevice(this.fbdev, 0x91000000, 0x1000);

    this.ips = 0; // inctruction per second counter
    sys = this; // one global variable used by the abort() function
}

System.prototype.PrintState = function() {
    DebugMessage("Current state of the machine")
    //DebugMessage("clock: " + hex8(cpu.clock));
    DebugMessage("PC: " + hex8(this.cpu.pc));
    DebugMessage("next PC: " + hex8(this.cpu.nextpc));
    //DebugMessage("ins: " + hex8(cpu.ins));
    //DebugMessage("main opcode: " + hex8(cpu.ins>>>26));
    //DebugMessage("sf... opcode: " + hex8((cpu.ins>>>21)&0x1F));
    //DebugMessage("op38. opcode: " + hex8((cpu.ins>>>0)&0x3CF));

    for (var i = 0; i < 32; i += 4) {
        DebugMessage("   r" + (i + 0) + ": " +
            hex8(this.cpu.r[i + 0]) + "   r" + (i + 1) + ": " +
            hex8(this.cpu.r[i + 1]) + "   r" + (i + 2) + ": " +
            hex8(this.cpu.r[i + 2]) + "   r" + (i + 3) + ": " +
            hex8(this.cpu.r[i + 3]));
    }

    if (this.cpu.delayedins) {
        DebugMessage("delayed instruction");
    }
    if (this.cpu.SR_SM) {
        DebugMessage("Supervisor mode");
    }
    else {
        DebugMessage("User mode");
    }
    if (this.cpu.SR_TEE) {
        DebugMessage("tick timer exception enabled");
    }
    if (this.cpu.SR_IEE) {
        DebugMessage("interrupt exception enabled");
    }
    if (this.cpu.SR_DME) {
        DebugMessage("data mmu enabled");
    }
    if (this.cpu.SR_IME) {
        DebugMessage("instruction mmu enabled");
    }
    if (this.cpu.SR_LEE) {
        DebugMessage("little endian enabled");
    }
    if (this.cpu.SR_CID) {
        DebugMessage("context id enabled");
    }
    if (this.cpu.SR_F) {
        DebugMessage("flag set");
    }
    if (this.cpu.SR_CY) {
        DebugMessage("carry set");
    }
    if (this.cpu.SR_OV) {
        DebugMessage("overflow set");
    }
}

System.prototype.LoadImageAndStart = function(filename) {
    DebugMessage("Loading Image " + filename);
    var str = "Loading Image from Web Server (5 MB). Please wait ..."
    for (var i = 0; i < str.length; i++) {
        this.term.PutChar(str.charCodeAt(i));
    }
    LoadBinaryResource(filename, this.ImageFinished.bind(this));
}

System.prototype.ImageFinished = function(buffer) {
    var buffer8 = new Uint8Array(buffer);
    DebugMessage("Image loaded: " + buffer8.length + " bytes");
    for (var i = 0; i < buffer8.length; i++) this.ram.uint8mem[i] = buffer8[i];
    for (var i = 0; i < buffer8.length >>> 2; i++) this.ram.int32mem[i] = Swap32(this.ram.int32mem[i]); // big endian to little endian
    this.cpu.AnalyzeImage();
    DebugMessage("Starting emulation");
    SendToMaster("execute", 0);
    this.MainLoop();
}

System.prototype.MainLoop = function() {
    this.cpu.Step(0x10000);
    this.ips += 0x10000;
    // go to idle state that onmessage is executed
}
<commit_msg>Double Mainloop count to reduce number of message passings<commit_after>// -------------------------------------------------
// ------------------- SYSTEM ----------------------
// -------------------------------------------------

function System() {

    DebugMessage("Init Terminal");
    this.term = new Terminal();

    DebugMessage("Init RAM");
    this.ram = new RAM(0x2000000);

    DebugMessage("Init CPU");
    this.cpu = new CPU(this.ram);

    DebugMessage("Init Devices");
    this.uartdev = new UARTDev(this.term, this.cpu);
    this.ethdev = new EthDev();
    this.fbdev = new FBDev(this.ram);
    this.atadev = new ATADev(this.cpu);

    DebugMessage("Add Devices");
    this.ram.AddDevice(this.atadev, 0x9e000000, 0x1000);
    this.ram.AddDevice(this.uartdev, 0x90000000, 0x7);
    this.ram.AddDevice(this.ethdev, 0x92000000, 0x1000);
    this.ram.AddDevice(this.fbdev, 0x91000000, 0x1000);

    this.ips = 0; // inctruction per second counter
    sys = this; // one global variable used by the abort() function
}

System.prototype.PrintState = function() {
    DebugMessage("Current state of the machine")
    //DebugMessage("clock: " + hex8(cpu.clock));
    DebugMessage("PC: " + hex8(this.cpu.pc));
    DebugMessage("next PC: " + hex8(this.cpu.nextpc));
    //DebugMessage("ins: " + hex8(cpu.ins));
    //DebugMessage("main opcode: " + hex8(cpu.ins>>>26));
    //DebugMessage("sf... opcode: " + hex8((cpu.ins>>>21)&0x1F));
    //DebugMessage("op38. opcode: " + hex8((cpu.ins>>>0)&0x3CF));

    for (var i = 0; i < 32; i += 4) {
        DebugMessage("   r" + (i + 0) + ": " +
            hex8(this.cpu.r[i + 0]) + "   r" + (i + 1) + ": " +
            hex8(this.cpu.r[i + 1]) + "   r" + (i + 2) + ": " +
            hex8(this.cpu.r[i + 2]) + "   r" + (i + 3) + ": " +
            hex8(this.cpu.r[i + 3]));
    }

    if (this.cpu.delayedins) {
        DebugMessage("delayed instruction");
    }
    if (this.cpu.SR_SM) {
        DebugMessage("Supervisor mode");
    }
    else {
        DebugMessage("User mode");
    }
    if (this.cpu.SR_TEE) {
        DebugMessage("tick timer exception enabled");
    }
    if (this.cpu.SR_IEE) {
        DebugMessage("interrupt exception enabled");
    }
    if (this.cpu.SR_DME) {
        DebugMessage("data mmu enabled");
    }
    if (this.cpu.SR_IME) {
        DebugMessage("instruction mmu enabled");
    }
    if (this.cpu.SR_LEE) {
        DebugMessage("little endian enabled");
    }
    if (this.cpu.SR_CID) {
        DebugMessage("context id enabled");
    }
    if (this.cpu.SR_F) {
        DebugMessage("flag set");
    }
    if (this.cpu.SR_CY) {
        DebugMessage("carry set");
    }
    if (this.cpu.SR_OV) {
        DebugMessage("overflow set");
    }
}

System.prototype.LoadImageAndStart = function(filename) {
    DebugMessage("Loading Image " + filename);
    var str = "Loading Image from Web Server (5 MB). Please wait ..."
    for (var i = 0; i < str.length; i++) {
        this.term.PutChar(str.charCodeAt(i));
    }
    LoadBinaryResource(filename, this.ImageFinished.bind(this));
}

System.prototype.ImageFinished = function(buffer) {
    var buffer8 = new Uint8Array(buffer);
    DebugMessage("Image loaded: " + buffer8.length + " bytes");
    for (var i = 0; i < buffer8.length; i++) this.ram.uint8mem[i] = buffer8[i];
    for (var i = 0; i < buffer8.length >>> 2; i++) this.ram.int32mem[i] = Swap32(this.ram.int32mem[i]); // big endian to little endian
    this.cpu.AnalyzeImage();
    DebugMessage("Starting emulation");
    SendToMaster("execute", 0);
    this.MainLoop();
}

System.prototype.MainLoop = function() {
    this.cpu.Step(0x20000);
    this.ips += 0x20000;
    // go to idle state that onmessage is executed
}
<|endoftext|>


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

( function ( THREE ) {

	THREE.Raycaster = function ( origin, direction, near, far ) {

		this.ray = new THREE.Ray( origin, direction );

		// normalized ray.direction required for accurate distance calculations
		if ( this.ray.direction.lengthSq() > 0 ) {

			this.ray.direction.normalize();

		}

		this.near = near || 0;
		this.far = far || Infinity;

	};

	var sphere = new THREE.Sphere();
	var localRay = new THREE.Ray();
	var facePlane = new THREE.Plane();
	var intersectPoint = new THREE.Vector3();
	var matrixPosition = new THREE.Vector3();

	var inverseMatrix = new THREE.Matrix4();

	var descSort = function ( a, b ) {

		return a.distance - b.distance;

	};

	var intersectObject = function ( object, raycaster, intersects ) {

		if ( object instanceof THREE.Particle ) {

			matrixPosition.getPositionFromMatrix( object.matrixWorld );
			var distance = raycaster.ray.distanceToPoint( matrixPosition );

			if ( distance > object.scale.x ) {

				return intersects;

			}

			intersects.push( {

				distance: distance,
				point: object.position,
				face: null,
				object: object

			} );

		} else if ( object instanceof THREE.LOD ) {

			matrixPosition.getPositionFromMatrix( object.matrixWorld );
			var distance = raycaster.ray.origin.distanceTo( matrixPosition );

			intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );

		} else if ( object instanceof THREE.Mesh ) {

			var geometry = object.geometry;

			// Checking boundingSphere distance to ray
			matrixPosition.getPositionFromMatrix( object.matrixWorld );

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			var vertices = geometry.vertices;

			if ( geometry instanceof THREE.BufferGeometry ) {

				var material = object.material;

				if ( material === undefined ) return intersects;
				if ( geometry.dynamic === false ) return intersects;

				var a, b, c;
				var precision = raycaster.precision;

				inverseMatrix.getInverse( object.matrixWorld );

				localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

				var fl;
				var indexed = false;

				if ( geometry.attributes.index ) {

					indexed = true;
					fl = geometry.attributes.index.numItems / 3;

				} else {

					fl = geometry.attributes.position.numItems / 9;

				}

				var vA = new THREE.Vector3();
				var vB = new THREE.Vector3();
				var vC = new THREE.Vector3();

				var offsets = geometry.offsets;
				var indices = geometry.attributes.index.array;
				var positions = geometry.attributes.position.array;
				var offLength = geometry.offsets.length;

				for ( var oi = 0; oi < offLength; ++oi ) {

					var start = offsets[ oi ].start;
					var count = offsets[ oi ].count;
					var index = offsets[ oi ].index;

					for ( var i = start, il = start + count; i < il; i += 3 ) {

						if ( indexed ) {

							a = index + indices[ i ];
							b = index + indices[ i + 1 ];
							c = index + indices[ i + 2 ];

						} else {

							a = index;
							b = index + 1;
							c = index + 2;

						}

						vA.set(
							positions[ a * 3 ],
							positions[ a * 3 + 1 ],
							positions[ a * 3 + 2 ]
						);
						vB.set(
							positions[ b * 3 ],
							positions[ b * 3 + 1 ],
							positions[ b * 3 + 2 ]
						);
						vC.set(
							positions[ c * 3 ],
							positions[ c * 3 + 1 ],
							positions[ c * 3 + 2 ]
						);

						var interPoint = THREE.Triangle.intersectionRay( localRay, vA, vB, vC, material.side !== THREE.DoubleSide );

						if ( !interPoint ) continue;

						interPoint.applyMatrix4( object.matrixWorld );
						var distance = raycaster.ray.origin.distanceTo( interPoint );

						// bail if the ray is too close to the plane
						if ( distance < precision ) continue;

						if ( distance < raycaster.near || distance > raycaster.far ) continue;

						intersects.push( {

							// this works because the original ray was normalized,
							// and the transformed localRay wasn't
							distance: distance,
							point: interPoint,
							face: null,
							faceIndex: null,
							object: object

						} );

					}
				}

			} else if ( geometry instanceof THREE.Geometry ) {

				var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
				var objectMaterials = isFaceMaterial === true ? object.material.materials : null;

				var a, b, c, d;
				var precision = raycaster.precision;

				inverseMatrix.getInverse( object.matrixWorld );

				localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

				for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {

					var face = geometry.faces[ f ];

					var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;

					if ( material === undefined ) continue;

					var interPoint;

					if ( face instanceof THREE.Face3 ) {

						a = vertices[ face.a ];
						b = vertices[ face.b ];
						c = vertices[ face.c ];
						interPoint = THREE.Triangle.intersectionRay( localRay, a, b, c, material.side !== THREE.DoubleSide );

						if ( !interPoint ) {

							continue;

						}

					} else if ( face instanceof THREE.Face4 ) {

						a = vertices[ face.a ];
						b = vertices[ face.b ];
						c = vertices[ face.c ];
						d = vertices[ face.d ];
						interPoint = THREE.Triangle.intersectionRay( localRay, a, b, d, material.side !== THREE.DoubleSide );

						if( !interPoint ) {

						 interPoint = THREE.Triangle.intersectionRay( localRay, b, c, d, material.side !== THREE.DoubleSide  );

						 if( !interPoint ) continue;

						}

					} else {

						// This is added because if we call out of this if/else group when
						// none of the cases match it will add a point to the intersection
						// list erroneously.
						throw Error( "face type not supported" );

					}

					interPoint.applyMatrix4( object.matrixWorld );
					var distance = raycaster.ray.origin.distanceTo( interPoint );

					// bail if the ray is too close to the plane
					if ( distance < precision ) continue;

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						point: interPoint,
						face: face,
						faceIndex: f,
						object: object

					} );

				}

			}

		} else if ( object instanceof THREE.Line ) {

			var precision = raycaster.linePrecision;
			var precisionSq = precision * precision;

			var geometry = object.geometry;

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			// Checking boundingSphere distance to ray
			matrixPosition.getPositionFromMatrix(object.matrixWorld);
			sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			inverseMatrix.getInverse( object.matrixWorld );
			localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
			localRay.direction.normalize(); // for scale matrix

			var vertices = geometry.vertices;
			var nbVertices = vertices.length;
			var interSegment = new THREE.Vector3();
			var interRay = new THREE.Vector3();
			var step = object.type === THREE.LineStrip ? 1 : 2;

			for ( var i = 0; i < nbVertices - 1; i = i + step ) {

				var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

				if ( distSq <= precisionSq ) {

					var distance = localRay.origin.distanceTo( interRay );

					if ( raycaster.near <= distance && distance <= raycaster.far ) {

						intersects.push( {

							distance: distance,
							// What do we want? intersection point on the ray or on the segment??
							// point: raycaster.ray.at( distance ),
							point: interSegment.clone().applyMatrix4( object.matrixWorld ),
							face: null,
							faceIndex: null,
							object: object

						} );

					}

				}

			}

		}

	};

	var intersectDescendants = function ( object, raycaster, intersects ) {

		var descendants = object.getDescendants();

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

			intersectObject( descendants[ i ], raycaster, intersects );

		}
	};

	//

	THREE.Raycaster.prototype.precision = 0.0001;
	THREE.Raycaster.prototype.linePrecision = 1;

	THREE.Raycaster.prototype.set = function ( origin, direction ) {

		this.ray.set( origin, direction );

		// normalized ray.direction required for accurate distance calculations
		if ( this.ray.direction.length() > 0 ) {

			this.ray.direction.normalize();

		}

	};

	THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {

		var intersects = [];

		if ( recursive === true ) {

			intersectDescendants( object, this, intersects );

		}

		intersectObject( object, this, intersects );

		intersects.sort( descSort );

		return intersects;

	};

	THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {

		var intersects = [];

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

			intersectObject( objects[ i ], this, intersects );

			if ( recursive === true ) {

				intersectDescendants( objects[ i ], this, intersects );

			}

		}

		intersects.sort( descSort );

		return intersects;

	};

}( THREE ) );
<commit_msg>Remove remaining ray normalization in Raycaster.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 * @author bhouston / http://exocortex.com/
 * @author stephomi / http://stephaneginier.com/
 */

( function ( THREE ) {

	THREE.Raycaster = function ( origin, direction, near, far ) {

		this.ray = new THREE.Ray( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

		this.near = near || 0;
		this.far = far || Infinity;

	};

	var sphere = new THREE.Sphere();
	var localRay = new THREE.Ray();
	var facePlane = new THREE.Plane();
	var intersectPoint = new THREE.Vector3();
	var matrixPosition = new THREE.Vector3();

	var inverseMatrix = new THREE.Matrix4();

	var descSort = function ( a, b ) {

		return a.distance - b.distance;

	};

	var intersectObject = function ( object, raycaster, intersects ) {

		if ( object instanceof THREE.Particle ) {

			matrixPosition.getPositionFromMatrix( object.matrixWorld );
			var distance = raycaster.ray.distanceToPoint( matrixPosition );

			if ( distance > object.scale.x ) {

				return intersects;

			}

			intersects.push( {

				distance: distance,
				point: object.position,
				face: null,
				object: object

			} );

		} else if ( object instanceof THREE.LOD ) {

			matrixPosition.getPositionFromMatrix( object.matrixWorld );
			var distance = raycaster.ray.origin.distanceTo( matrixPosition );

			intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );

		} else if ( object instanceof THREE.Mesh ) {

			var geometry = object.geometry;

			// Checking boundingSphere distance to ray
			matrixPosition.getPositionFromMatrix( object.matrixWorld );

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			var vertices = geometry.vertices;

			if ( geometry instanceof THREE.BufferGeometry ) {

				var material = object.material;

				if ( material === undefined ) return intersects;
				if ( geometry.dynamic === false ) return intersects;

				var a, b, c;
				var precision = raycaster.precision;

				inverseMatrix.getInverse( object.matrixWorld );

				localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

				var fl;
				var indexed = false;

				if ( geometry.attributes.index ) {

					indexed = true;
					fl = geometry.attributes.index.numItems / 3;

				} else {

					fl = geometry.attributes.position.numItems / 9;

				}

				var vA = new THREE.Vector3();
				var vB = new THREE.Vector3();
				var vC = new THREE.Vector3();

				var offsets = geometry.offsets;
				var indices = geometry.attributes.index.array;
				var positions = geometry.attributes.position.array;
				var offLength = geometry.offsets.length;

				for ( var oi = 0; oi < offLength; ++oi ) {

					var start = offsets[ oi ].start;
					var count = offsets[ oi ].count;
					var index = offsets[ oi ].index;

					for ( var i = start, il = start + count; i < il; i += 3 ) {

						if ( indexed ) {

							a = index + indices[ i ];
							b = index + indices[ i + 1 ];
							c = index + indices[ i + 2 ];

						} else {

							a = index;
							b = index + 1;
							c = index + 2;

						}

						vA.set(
							positions[ a * 3 ],
							positions[ a * 3 + 1 ],
							positions[ a * 3 + 2 ]
						);
						vB.set(
							positions[ b * 3 ],
							positions[ b * 3 + 1 ],
							positions[ b * 3 + 2 ]
						);
						vC.set(
							positions[ c * 3 ],
							positions[ c * 3 + 1 ],
							positions[ c * 3 + 2 ]
						);

						var interPoint = THREE.Triangle.intersectionRay( localRay, vA, vB, vC, material.side !== THREE.DoubleSide );

						if ( !interPoint ) continue;

						interPoint.applyMatrix4( object.matrixWorld );
						var distance = raycaster.ray.origin.distanceTo( interPoint );

						// bail if the ray is too close to the plane
						if ( distance < precision ) continue;

						if ( distance < raycaster.near || distance > raycaster.far ) continue;

						intersects.push( {

							distance: distance,
							point: interPoint,
							face: null,
							faceIndex: null,
							object: object

						} );

					}
				}

			} else if ( geometry instanceof THREE.Geometry ) {

				var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
				var objectMaterials = isFaceMaterial === true ? object.material.materials : null;

				var a, b, c, d;
				var precision = raycaster.precision;

				inverseMatrix.getInverse( object.matrixWorld );

				localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

				for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {

					var face = geometry.faces[ f ];

					var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;

					if ( material === undefined ) continue;

					var interPoint;

					if ( face instanceof THREE.Face3 ) {

						a = vertices[ face.a ];
						b = vertices[ face.b ];
						c = vertices[ face.c ];
						interPoint = THREE.Triangle.intersectionRay( localRay, a, b, c, material.side !== THREE.DoubleSide );

						if ( !interPoint ) {

							continue;

						}

					} else if ( face instanceof THREE.Face4 ) {

						a = vertices[ face.a ];
						b = vertices[ face.b ];
						c = vertices[ face.c ];
						d = vertices[ face.d ];
						interPoint = THREE.Triangle.intersectionRay( localRay, a, b, d, material.side !== THREE.DoubleSide );

						if( !interPoint ) {

						 interPoint = THREE.Triangle.intersectionRay( localRay, b, c, d, material.side !== THREE.DoubleSide  );

						 if( !interPoint ) continue;

						}

					} else {

						// This is added because if we call out of this if/else group when
						// none of the cases match it will add a point to the intersection
						// list erroneously.
						throw Error( "face type not supported" );

					}

					interPoint.applyMatrix4( object.matrixWorld );
					var distance = raycaster.ray.origin.distanceTo( interPoint );

					// bail if the ray is too close to the plane
					if ( distance < precision ) continue;

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						point: interPoint,
						face: face,
						faceIndex: f,
						object: object

					} );

				}

			}

		} else if ( object instanceof THREE.Line ) {

			var precision = raycaster.linePrecision;
			var precisionSq = precision * precision;

			var geometry = object.geometry;

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			// Checking boundingSphere distance to ray
			matrixPosition.getPositionFromMatrix(object.matrixWorld);
			sphere.set( matrixPosition, geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			inverseMatrix.getInverse( object.matrixWorld );
			localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

			var vertices = geometry.vertices;
			var nbVertices = vertices.length;
			var interSegment = new THREE.Vector3();
			var interRay = new THREE.Vector3();
			var step = object.type === THREE.LineStrip ? 1 : 2;

			for ( var i = 0; i < nbVertices - 1; i = i + step ) {

				var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

				if ( distSq <= precisionSq ) {

					var distance = localRay.origin.distanceTo( interRay );

					if ( raycaster.near <= distance && distance <= raycaster.far ) {

						intersects.push( {

							distance: distance,
							// What do we want? intersection point on the ray or on the segment??
							// point: raycaster.ray.at( distance ),
							point: interSegment.clone().applyMatrix4( object.matrixWorld ),
							face: null,
							faceIndex: null,
							object: object

						} );

					}

				}

			}

		}

	};

	var intersectDescendants = function ( object, raycaster, intersects ) {

		var descendants = object.getDescendants();

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

			intersectObject( descendants[ i ], raycaster, intersects );

		}
	};

	//

	THREE.Raycaster.prototype.precision = 0.0001;
	THREE.Raycaster.prototype.linePrecision = 1;

	THREE.Raycaster.prototype.set = function ( origin, direction ) {

		this.ray.set( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

	};

	THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {

		var intersects = [];

		if ( recursive === true ) {

			intersectDescendants( object, this, intersects );

		}

		intersectObject( object, this, intersects );

		intersects.sort( descSort );

		return intersects;

	};

	THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {

		var intersects = [];

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

			intersectObject( objects[ i ], this, intersects );

			if ( recursive === true ) {

				intersectDescendants( objects[ i ], this, intersects );

			}

		}

		intersects.sort( descSort );

		return intersects;

	};

}( THREE ) );
<|endoftext|>