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

(function() {
  'use strict';

  /**
   * @ngdoc overview
   * @name queueController
   * @ngController
   *
   * @description
   * Controller for the queues table
   */
  angular
    .module('horizon.dashboard.project.queues')
    .controller('horizon.dashboard.project.queues.table.queueController', queueController);

  queueController.$inject = [
    '$scope',
    'horizon.app.core.openstack-service-api.zaqar',
    'horizon.dashboard.project.queues.basePath',
    'horizon.dashboard.project.queues.events',
    'horizon.dashboard.project.queues.resourceType',
    'horizon.framework.conf.resource-type-registry.service',
  ];

  function queueController($scope, zaqar, base, events, type, registry) {

    var ctrl = this;

    ctrl.queues = [];
    ctrl.queuesSrc = [];
    ctrl.resourceType = registry.getResourceType(type);
    ctrl.subsTemplate = base + 'table/subscription.html';

    init();
    initScope();

    //////////

    function initScope() {
      var createWatcher = $scope.$on(events.CREATE_SUCCESS, onCreateSuccess);
      var deleteWatcher = $scope.$on(events.DELETE_SUCCESS, onDeleteSuccess);
      var updateWatcher = $scope.$on(events.UPDATE_SUCCESS, onUpdateSuccess);
      var subWatcher = $scope.$on(events.SUBSCRIPTION_CREATE_SUCCESS, broadcastEvents);
      $scope.$on('$destroy', function destroy() {
        createWatcher();
        deleteWatcher();
        updateWatcher();
        subWatcher();
      });
    }

    //////////

    function init() {
      registry.initActions(type, $scope);
      zaqar.getQueues().then(showQueues);
    }

    function broadcastEvents(event, data) {
      if (event.targetScope !== $scope) {
        $scope.$broadcast(event.name, data);
      }
    }

    function showQueues(response) {
      // hz-table expects all items to have the id field
      // so we need to manually add name as id here
      ctrl.queuesSrc = response.data;
      ctrl.queuesSrc.map(function addIdentifier(queue, index){
        queue.id = queue.name;
      });
    }

    function onCreateSuccess(e, newQueue) {
      e.stopPropagation();
      newQueue.id = newQueue.name;
      ctrl.queuesSrc.push(newQueue);
    }

    function onDeleteSuccess(e, deletedNames) {
      // remove existing item from table
      e.stopPropagation();
      for (var i = ctrl.queuesSrc.length - 1; i >= 0; i--) {
        var queue = ctrl.queuesSrc[i];
        if (deletedNames.indexOf(queue.name) >= 0) {
          ctrl.queuesSrc.splice(i, 1);
        }
      }
      // clear selections upon deletion
      $scope.$emit('hzTable:clearSelected');
    }

    function onUpdateSuccess(e, queue) {
      e.stopPropagation();
      queue.id = queue.name;
      // update queue
      ctrl.queuesSrc[queue.id] = queue;
    }
  }

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

(function() {
  'use strict';

  /**
   * @ngdoc overview
   * @name queueController
   * @ngController
   *
   * @description
   * Controller for the queues table
   */
  angular
    .module('horizon.dashboard.project.queues')
    .controller('horizon.dashboard.project.queues.table.queueController', queueController);

  queueController.$inject = [
    '$scope',
    'horizon.app.core.openstack-service-api.zaqar',
    'horizon.dashboard.project.queues.basePath',
    'horizon.dashboard.project.queues.events',
    'horizon.dashboard.project.queues.resourceType',
    'horizon.framework.conf.resource-type-registry.service',
  ];

  function queueController($scope, zaqar, base, events, type, registry) {

    var ctrl = this;

    ctrl.queues = [];
    ctrl.queuesSrc = [];
    ctrl.resourceType = registry.getResourceType(type);
    ctrl.subsTemplate = base + 'table/subscription.html';

    init();
    initScope();

    //////////

    function initScope() {
      var createWatcher = $scope.$on(events.CREATE_SUCCESS, onCreateSuccess);
      var deleteWatcher = $scope.$on(events.DELETE_SUCCESS, onDeleteSuccess);
      var updateWatcher = $scope.$on(events.UPDATE_SUCCESS, onUpdateSuccess);
      var subWatcher = $scope.$on(events.SUBSCRIPTION_CREATE_SUCCESS, broadcastEvents);
      $scope.$on('$destroy', function destroy() {
        createWatcher();
        deleteWatcher();
        updateWatcher();
        subWatcher();
      });
    }

    //////////

    function init() {
      ctrl.resourceType.initActions($scope);
      zaqar.getQueues().then(showQueues);
    }

    function broadcastEvents(event, data) {
      if (event.targetScope !== $scope) {
        $scope.$broadcast(event.name, data);
      }
    }

    function showQueues(response) {
      // hz-table expects all items to have the id field
      // so we need to manually add name as id here
      ctrl.queuesSrc = response.data;
      ctrl.queuesSrc.map(function addIdentifier(queue, index){
        queue.id = queue.name;
      });
    }

    function onCreateSuccess(e, newQueue) {
      e.stopPropagation();
      newQueue.id = newQueue.name;
      ctrl.queuesSrc.push(newQueue);
    }

    function onDeleteSuccess(e, deletedNames) {
      // remove existing item from table
      e.stopPropagation();
      for (var i = ctrl.queuesSrc.length - 1; i >= 0; i--) {
        var queue = ctrl.queuesSrc[i];
        if (deletedNames.indexOf(queue.name) >= 0) {
          ctrl.queuesSrc.splice(i, 1);
        }
      }
      // clear selections upon deletion
      $scope.$emit('hzTable:clearSelected');
    }

    function onUpdateSuccess(e, queue) {
      e.stopPropagation();
      queue.id = queue.name;
      // update queue
      ctrl.queuesSrc[queue.id] = queue;
    }
  }

})();
<|endoftext|>


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

import Visualization from '../visualization';
import PassthroughTransformation from '../../tabledata/passthrough';
import HandsonHelper from '../../handsontable/handsonHelper';

/**
 * Visualize data in table format
 */
export default class TableVisualization extends Visualization {
  constructor(targetEl, config) {
    super(targetEl, config);
    console.log('Init table viz');
    targetEl.addClass('table');
    this.passthrough = new PassthroughTransformation(config);
  };

  refresh() {
    this.hot.render();
  };

  render(tableData) {
    var height = this.targetEl.height();
    var container = this.targetEl.css('height', height).get(0);
    var resultRows = tableData.rows;
    var columnNames = _.pluck(tableData.columns, 'name');

    if (this.hot) {
      this.hot.destroy();
    }

    if (!this.columns) {
      this.columns = Array.apply(null, Array(tableData.columns.length)).map(function() {
        return {type: 'text'};
      });
    }

    var handsonHelper = new HandsonHelper();

    this.hot = new Handsontable(container, handsonHelper.getHandsonTableConfig(
      this.columns, columnNames, resultRows));
    this.hot.validateCells(null);
  };

  destroy() {
    if (this.hot) {
      this.hot.destroy();
    }
  };

  getTransformation() {
    return this.passthrough;
  };
}
<commit_msg>[ZEPPELIN-2084] z.show doesn't show dataframe<commit_after>/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Visualization from '../visualization';
import PassthroughTransformation from '../../tabledata/passthrough';
import HandsonHelper from '../../handsontable/handsonHelper';

/**
 * Visualize data in table format
 */
export default class TableVisualization extends Visualization {
  constructor(targetEl, config) {
    super(targetEl, config);
    console.log('Init table viz');
    targetEl.addClass('table');
    this.passthrough = new PassthroughTransformation(config);
  };

  refresh() {
    this.hot.render();
  };

  render(tableData) {
    var height = this.targetEl.height();
    var container = this.targetEl.css('height', height).get(0);
    var resultRows = tableData.rows;
    var columnNames = _.pluck(tableData.columns, 'name');
    var columns = Array.apply(null, Array(tableData.columns.length)).map(function() {
      return {type: 'text'};
    });

    if (this.hot) {
      this.hot.destroy();
    }

    var handsonHelper = new HandsonHelper();
    this.hot = new Handsontable(container, handsonHelper.getHandsonTableConfig(
      columns, columnNames, resultRows));
    this.hot.validateCells(null);
  };

  destroy() {
    if (this.hot) {
      this.hot.destroy();
    }
  };

  getTransformation() {
    return this.passthrough;
  };
}
<|endoftext|>


<commit_before>"use strict";

/* global describe, it, before, sinon  */

// kafka-topics.sh --zookeeper 127.0.0.1:2181/kafka0.8 --create --topic kafka-test-topic --partitions 3 --replication-factor 1

var Promise = require('bluebird');
var Kafka = require('../lib/index');

var producer = new Kafka.Producer({requiredAcks: 1});
var consumer = new Kafka.SimpleConsumer({idleTimeout: 100});

var dataListenerSpy = sinon.spy(function() {});

describe('SimpleConsumer', function () {
    before(function () {
        return Promise.all([
            producer.init(),
            consumer.init()
        ])
        .then(function () {
            consumer.on('data', dataListenerSpy);
        });
    });

    it('required methods', function () {
        return consumer.should
            .respondTo('init')
            .respondTo('subscribe')
            .respondTo('offset')
            .respondTo('unsubscribe');
    });

    it('should receive new messages', function () {
        return consumer.subscribe('kafka-test-topic', 0).then(function () {
            return producer.send({
                topic: 'kafka-test-topic',
                partition: 0,
                message: {value: 'p00'}
            });
        })
        .delay(20)
        .then(function () {
            /* jshint expr: true */
            dataListenerSpy.should.have.been.called;
            dataListenerSpy.lastCall.args[0].should.be.an('array').and.have.length(1);
            dataListenerSpy.lastCall.args[1].should.be.a('string', 'kafka-test-topic');
            dataListenerSpy.lastCall.args[2].should.be.a('number', 0);

            dataListenerSpy.lastCall.args[0][0].should.be.an('object');
            dataListenerSpy.lastCall.args[0][0].should.have.property('message').that.is.an('object');
            dataListenerSpy.lastCall.args[0][0].message.should.have.property('value');
            dataListenerSpy.lastCall.args[0][0].message.value.toString('utf8').should.be.eql('p00');
        });
    });

    it('offset() should return last offset', function () {
        return consumer.offset('kafka-test-topic', 0).then(function (offset) {
            offset.should.be.a('number').and.be.gt(0);
        });
    });

    it('should receive messages from specified offset', function () {
        dataListenerSpy.reset();
        return producer.send([{
            topic: 'kafka-test-topic',
            partition: 0,
            message: {value: 'p000'}
        },{
            topic: 'kafka-test-topic',
            partition: 0,
            message: {value: 'p001'}
        }])
        .then(function () {
            return consumer.offset('kafka-test-topic', 0).then(function (offset) {
                return consumer.subscribe('kafka-test-topic', 0, {offset: offset-2})
                .delay(100) // consumer sleep timeout
                .then(function () {
                    /* jshint expr: true */
                    dataListenerSpy.should.have.been.called;
                    dataListenerSpy.lastCall.args[0].should.be.an('array').and.have.length(2);
                    dataListenerSpy.lastCall.args[0][0].message.value.toString('utf8').should.be.eql('p000');
                    dataListenerSpy.lastCall.args[0][1].message.value.toString('utf8').should.be.eql('p001');
                });
            });
        });
    });

    it('should receive messages in maxBytes batches', function () {
        dataListenerSpy.reset();
        return consumer.offset('kafka-test-topic', 0).then(function (offset) {
            return consumer.subscribe('kafka-test-topic', 0, {offset: offset-2, maxBytes: 30})
            .delay(100) // consumer sleep timeout
            .then(function () {
                /* jshint expr: true */
                dataListenerSpy.should.have.been.calledTwice;
                dataListenerSpy.getCall(0).args[0].should.be.an('array').and.have.length(1);
                dataListenerSpy.getCall(1).args[0].should.be.an('array').and.have.length(1);
                dataListenerSpy.getCall(0).args[0][0].message.value.toString('utf8').should.be.eql('p000');
                dataListenerSpy.getCall(1).args[0][0].message.value.toString('utf8').should.be.eql('p001');
            });
        });
    });

});
<commit_msg>Travis build<commit_after>"use strict";

/* global describe, it, before, sinon  */

// kafka-topics.sh --zookeeper 127.0.0.1:2181/kafka0.8 --create --topic kafka-test-topic --partitions 3 --replication-factor 1

var Promise = require('bluebird');
var Kafka = require('../lib/index');

var producer = new Kafka.Producer({requiredAcks: 1});
var consumer = new Kafka.SimpleConsumer({idleTimeout: 100});

var dataListenerSpy = sinon.spy(function() {});

describe('SimpleConsumer', function () {
    before(function () {
        return Promise.all([
            producer.init(),
            consumer.init()
        ])
        .then(function () {
            consumer.on('data', dataListenerSpy);
        });
    });

    it('required methods', function () {
        return consumer.should
            .respondTo('init')
            .respondTo('subscribe')
            .respondTo('offset')
            .respondTo('unsubscribe');
    });

    it('should receive new messages', function () {
        return consumer.subscribe('kafka-test-topic', 0).then(function () {
            return producer.send({
                topic: 'kafka-test-topic',
                partition: 0,
                message: {value: 'p00'}
            });
        })
        .delay(100)
        .then(function () {
            /* jshint expr: true */
            dataListenerSpy.should.have.been.called;
            dataListenerSpy.lastCall.args[0].should.be.an('array').and.have.length(1);
            dataListenerSpy.lastCall.args[1].should.be.a('string', 'kafka-test-topic');
            dataListenerSpy.lastCall.args[2].should.be.a('number', 0);

            dataListenerSpy.lastCall.args[0][0].should.be.an('object');
            dataListenerSpy.lastCall.args[0][0].should.have.property('message').that.is.an('object');
            dataListenerSpy.lastCall.args[0][0].message.should.have.property('value');
            dataListenerSpy.lastCall.args[0][0].message.value.toString('utf8').should.be.eql('p00');
        });
    });

    it('offset() should return last offset', function () {
        return consumer.offset('kafka-test-topic', 0).then(function (offset) {
            offset.should.be.a('number').and.be.gt(0);
        });
    });

    it('should receive messages from specified offset', function () {
        dataListenerSpy.reset();
        return producer.send([{
            topic: 'kafka-test-topic',
            partition: 0,
            message: {value: 'p000'}
        },{
            topic: 'kafka-test-topic',
            partition: 0,
            message: {value: 'p001'}
        }])
        .then(function () {
            return consumer.offset('kafka-test-topic', 0).then(function (offset) {
                return consumer.subscribe('kafka-test-topic', 0, {offset: offset-2})
                .delay(100) // consumer sleep timeout
                .then(function () {
                    /* jshint expr: true */
                    dataListenerSpy.should.have.been.called;
                    dataListenerSpy.lastCall.args[0].should.be.an('array').and.have.length(2);
                    dataListenerSpy.lastCall.args[0][0].message.value.toString('utf8').should.be.eql('p000');
                    dataListenerSpy.lastCall.args[0][1].message.value.toString('utf8').should.be.eql('p001');
                });
            });
        });
    });

    it('should receive messages in maxBytes batches', function () {
        dataListenerSpy.reset();
        return consumer.offset('kafka-test-topic', 0).then(function (offset) {
            return consumer.subscribe('kafka-test-topic', 0, {offset: offset-2, maxBytes: 30})
            .delay(200)
            .then(function () {
                /* jshint expr: true */
                dataListenerSpy.should.have.been.calledTwice;
                dataListenerSpy.getCall(0).args[0].should.be.an('array').and.have.length(1);
                dataListenerSpy.getCall(1).args[0].should.be.an('array').and.have.length(1);
                dataListenerSpy.getCall(0).args[0][0].message.value.toString('utf8').should.be.eql('p000');
                dataListenerSpy.getCall(1).args[0][0].message.value.toString('utf8').should.be.eql('p001');
            });
        });
    });

});
<|endoftext|>


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

};
<commit_msg>task(address-book): Added notes about isCallTree redundancy<commit_after>
/**
 * @note The isCallTree attribute is quite redundant. If we wanted to find all
 * 		 contacts that are in a call tree we should be able to do a joining
 * 		 operation of some sort to query contacts that aren't embedded in users'
 *		 call trees. Not figured out how to do this yet though.
 */
module.exports = function(Contact) {

};
<|endoftext|>


<commit_before>var assert = require('assert');
var fs = require('fs');
var Canvas = require('canvas');
var sprite = require('../lib/sprite.js');
var ui = require('../lib/ui.js');

var reports_path = __dirname + '/../reports/';

exports.setUp = function (callback) {
	if (!fs.existsSync(reports_path))
		fs.mkdirSync(reports_path);
	this.canvas = new Canvas(800,600);
	this.opts ={};
	this.opts.sprites = sprite.load_sprites(__dirname + '/../static/example/scrolling/mario.chr');
	this.opts.palette = [0x22,0x16,0x27,0x18];
	this.pixel_editor = new ui.PixelEditor(this.canvas, 165, 0, this.opts);
	this.selector = new ui.SpriteSelector(this.canvas, 440, 0, this.opts);
	this.palette = new ui.Palette(this.canvas, 0 , 325, this.opts);
	this.color_picker = new ui.ColorPicker(this.canvas, 165,270,20, this.opts);
	this.preview = new ui.Preview(this.canvas, 0, 0, this.opts);

	//this.pixel_editor.addColorChangeListener(this.palette);
	//this.palette.addColorChangeListener(this.selector);
	//this.palette.addColorChangeListener(this.preview);
	//this.palette.addColorChangeListener(this.pixel_editor);
	//this.color_picker.addColorChangeListener(this.palette);

	//this.selector.addSpriteChangedListener(this.preview);
	//this.preview.addSpriteChangedListener(this.pixel_editor);
	//this.pixel_editor.addRedrawListener(this.preview);
	//this.pixel_editor.addRedrawListener(this.selector);

	callback();
};

exports.tearDown = function (callback) {
	this.canvas = null;
	this.opt = null;
	callback();
};

exports.test_widget_click_outside = function (test){
	assert.equal(false, this.palette.was_clicked(this.palette.position_x -1,this.palette.position_y));
	assert.equal(false, this.palette.was_clicked(this.palette.position_x, this.palette.position_y -1));
	assert.equal(false, this.palette.was_clicked(this.palette.width + 1, this.palette.position_y));
	assert.equal(false, this.palette.was_clicked(this.palette.position_x, this.palette.height + 1));
	test.done();
};

function click_on_palette(palette, color_id){
	var x = palette.position_x + (palette.picker_size * color_id) + (palette.picker_size / 2);
	var y = palette.position_y + (palette.height / 2);
	assert.ok(palette.was_clicked(x, y));
	palette.click(x, y);
}

exports.test_palette_clicks = function (test){
	test.equal(0, this.palette.palette_id);
	click_on_palette(this.palette, 1);
	test.equal(1, this.palette.palette_id);
	click_on_palette(this.palette, 2);
	test.equal(2, this.palette.palette_id);
	click_on_palette(this.palette, 3);
	test.equal(3, this.palette.palette_id);
	click_on_palette(this.palette, 0);
	test.equal(0, this.palette.palette_id);
	test.done();
};

function click_on_pixel_editor(pixel_editor, x, y){
	var line = pixel_editor.position_y + ((pixel_editor.pixelSize + pixel_editor.pixelPadding) * y) + (pixel_editor.pixelSize / 2);
	var col = pixel_editor.position_x + ((pixel_editor.pixelSize + pixel_editor.pixelPadding) * x) + (pixel_editor.pixelSize / 2);
	assert.ok(pixel_editor.was_clicked(col, line));
	pixel_editor.click(col, line);
}

exports.test_pixel_editor_clicks = function (test){
	test.equal(0, this.pixel_editor.sprite_id);
	test.equal(0, this.pixel_editor.palette_id);
	var spr = sprite.get_sprite(0, this.opts.sprites);
	click_on_pixel_editor(this.pixel_editor, 0, 0);
	this.pixel_editor.palette_id = 4; //Cheating
	for (var line = 0; line < 8; line++){
		for (var col=0; col < 8; col++) {
			test.equal(spr[line][col], this.pixel_editor.sprite[line][col]);
			click_on_pixel_editor(this.pixel_editor, col, line);
			test.equal(4, this.pixel_editor.sprite[line][col]);
		}
	}
	test.done();
};

exports.test_pixel_editor_on_color_changed = function (test){
	test.equal(0, this.palette.palette_id);
	test.equal(0, this.pixel_editor.sprite_id);
	test.equal(0, this.pixel_editor.palette_id);
	this.palette.addColorChangeListener(this.pixel_editor);
	click_on_palette(this.palette, 1);
	test.equal(1, this.pixel_editor.palette_id);
	click_on_palette(this.palette, 2);
	test.equal(2, this.pixel_editor.palette_id);
	click_on_palette(this.palette, 3);
	test.equal(3, this.pixel_editor.palette_id);
	click_on_palette(this.palette, 0);
	test.equal(0, this.pixel_editor.palette_id);
	test.done();
};
<commit_msg>testing preview widget<commit_after>var assert = require('assert');
var fs = require('fs');
var Canvas = require('canvas');
var sprite = require('../lib/sprite.js');
var ui = require('../lib/ui.js');

var reports_path = __dirname + '/../reports/';

exports.setUp = function (callback) {
	if (!fs.existsSync(reports_path))
		fs.mkdirSync(reports_path);
	this.canvas = new Canvas(800,600);
	this.opts ={};
	this.opts.sprites = sprite.load_sprites(__dirname + '/../static/example/scrolling/mario.chr');
	this.opts.palette = [0x22,0x16,0x27,0x18];
	this.pixel_editor = new ui.PixelEditor(this.canvas, 165, 0, this.opts);
	this.selector = new ui.SpriteSelector(this.canvas, 440, 0, this.opts);
	this.palette = new ui.Palette(this.canvas, 0 , 325, this.opts);
	this.color_picker = new ui.ColorPicker(this.canvas, 165,270,20, this.opts);
	this.preview = new ui.Preview(this.canvas, 0, 0, this.opts);

	//this.pixel_editor.addColorChangeListener(this.palette);
	//this.palette.addColorChangeListener(this.selector);
	//this.palette.addColorChangeListener(this.preview);
	//this.palette.addColorChangeListener(this.pixel_editor);
	//this.color_picker.addColorChangeListener(this.palette);

	//this.selector.addSpriteChangedListener(this.preview);
	//this.preview.addSpriteChangedListener(this.pixel_editor);
	//this.pixel_editor.addRedrawListener(this.preview);
	//this.pixel_editor.addRedrawListener(this.selector);

	callback();
};

exports.tearDown = function (callback) {
	this.canvas = null;
	this.opt = null;
	callback();
};

exports.test_widget_click_outside = function (test){
	assert.equal(false, this.palette.was_clicked(this.palette.position_x -1,this.palette.position_y));
	assert.equal(false, this.palette.was_clicked(this.palette.position_x, this.palette.position_y -1));
	assert.equal(false, this.palette.was_clicked(this.palette.width + 1, this.palette.position_y));
	assert.equal(false, this.palette.was_clicked(this.palette.position_x, this.palette.height + 1));
	test.done();
};

function click_on_palette(palette, color_id){
	var x = palette.position_x + (palette.picker_size * color_id) + (palette.picker_size / 2);
	var y = palette.position_y + (palette.height / 2);
	assert.ok(palette.was_clicked(x, y));
	palette.click(x, y);
}

exports.test_palette_clicks = function (test){
	test.equal(0, this.palette.palette_id);
	click_on_palette(this.palette, 1);
	test.equal(1, this.palette.palette_id);
	click_on_palette(this.palette, 2);
	test.equal(2, this.palette.palette_id);
	click_on_palette(this.palette, 3);
	test.equal(3, this.palette.palette_id);
	click_on_palette(this.palette, 0);
	test.equal(0, this.palette.palette_id);
	test.done();
};

function click_on_pixel_editor(pixel_editor, x, y){
	var line = pixel_editor.position_y + ((pixel_editor.pixelSize + pixel_editor.pixelPadding) * y) + (pixel_editor.pixelSize / 2);
	var col = pixel_editor.position_x + ((pixel_editor.pixelSize + pixel_editor.pixelPadding) * x) + (pixel_editor.pixelSize / 2);
	assert.ok(pixel_editor.was_clicked(col, line));
	pixel_editor.click(col, line);
}

exports.test_pixel_editor_clicks = function (test){
	test.equal(0, this.pixel_editor.sprite_id);
	test.equal(0, this.pixel_editor.palette_id);
	var spr = sprite.get_sprite(0, this.opts.sprites);
	click_on_pixel_editor(this.pixel_editor, 0, 0);
	this.pixel_editor.palette_id = 4; //Cheating
	for (var line = 0; line < 8; line++){
		for (var col=0; col < 8; col++) {
			test.equal(spr[line][col], this.pixel_editor.sprite[line][col]);
			click_on_pixel_editor(this.pixel_editor, col, line);
			test.equal(4, this.pixel_editor.sprite[line][col]);
		}
	}
	test.done();
};

exports.test_pixel_editor_on_color_changed = function (test){
	test.equal(0, this.palette.palette_id);
	test.equal(0, this.pixel_editor.sprite_id);
	test.equal(0, this.pixel_editor.palette_id);
	this.palette.addColorChangeListener(this.pixel_editor);
	click_on_palette(this.palette, 1);
	test.equal(1, this.pixel_editor.palette_id);
	click_on_palette(this.palette, 2);
	test.equal(2, this.pixel_editor.palette_id);
	click_on_palette(this.palette, 3);
	test.equal(3, this.pixel_editor.palette_id);
	click_on_palette(this.palette, 0);
	test.equal(0, this.pixel_editor.palette_id);
	test.done();
};

function click_on_preview(preview, y, x){
	var line = preview.position_y + ((preview.spriteSize + preview.pixelPadding) * y) + (preview.spriteSize / 2);
	var col = preview.position_x + ((preview.spriteSize + preview.pixelPadding) * x) + (preview.spriteSize / 2);
	assert.ok(preview.was_clicked(col, line));
	preview.click(col, line);

}

exports.test_preview_clicks = function (test) {
	var sprite_id = 0;
	for (var line = 0; line < 4; line++){
		for (var col=0; col < 2; col++, sprite_id++) {
			click_on_preview(this.preview, line, col);
			test.equal(sprite_id, this.preview.sprite_id);
		}
	}
	test.done();
};

exports.test_pixel_editor_on_sprite_changed = function (test){
	this.preview.addSpriteChangedListener(this.pixel_editor);
	test.equal(0, this.pixel_editor.sprite_id);
	var sprite_id = 0;
	for (var line = 0; line < 4; line++){
		for (var col=0; col < 2; col++, sprite_id++) {
			click_on_preview(this.preview, line, col);
			test.equal(sprite_id, this.pixel_editor.sprite_id);
		}
	}
	test.done();
};
<|endoftext|>


<commit_before>export const ADD_CHANNEL = 'ADD_CHANNEL';
export const REMOVE_CHANNEL = 'REMOVE_CHANNEL';
export const LOAD_CHANNELS = 'LOAD_CHANNELS';

const storage = require('electron-json-storage')
import GitHub from 'github-api';
import axios from 'axios';

export function addChannel(channel) {
	let channelName = channel.full_name
	return (dispatch, getState) => {
		let currentUser = getState().auth.currentUser
		let userId = getState().auth.id
		let repo = getState().repo
		var channelStorage
		storage.get('channels', (err, result) => {
			if (err) {
				console.error(err)
				channelStorage = {}
			}

			channelStorage = result
			let userStorage = channelStorage[currentUser]
			userStorage[channelName] = null
			storage.set('channels', {...channelStorage, [currentUser]: userStorage})
		})

		return axios.post(process.env.SERVER_URL + `/api/channels/${userId}`, {
			repoId: channelName
		})
			.then(createdChannel => {
				dispatch({
					type: ADD_CHANNEL,
					channel: channelName
				})
			})
	}
}

export function removeChannel(id) {
	return (dispatch, getState) => {
		console.log('id to delete ', id)
		let userStorage = getState().channels.filter(e => e != id)
		console.log('user storage ', userStorage)
		let currentUser = getState().auth.currentUser
		let userId = getState().auth.id
		storage.get('channels', (err, result) => {
			if (err) console.error
			let channelStorage = result
			console.log({...channelStorage, [currentUser]: userStorage})
			channelStorage[currentUser] = userStorage
			console.log('userstorage here ', channelStorage[currentUser])
			storage.set('channels', channelStorage)
			return axios.put(process.env.SERVER_URL + `/api/channels/remove?channelId=${id}&userId=${userId}`)
				.then(() => {
				dispatch({
					type: LOAD_CHANNELS,
					channels: userStorage
				})
			})
		})

	}
}

export function loadChannels() {
	// storage.clear(err => console.error)
	return (dispatch, getState) => {
		storage.get('channels', (err, cachedChannels) => {
			if (err) console.error(err)

			let currentUser = getState().auth.currentUser
			let channels = Object.keys(cachedChannels[currentUser])
			dispatch({
				type: LOAD_CHANNELS,
				channels
			})
		})
	}
}
<commit_msg>working channels w/ local and db storage<commit_after>export const ADD_CHANNEL = 'ADD_CHANNEL';
export const REMOVE_CHANNEL = 'REMOVE_CHANNEL';
export const LOAD_CHANNELS = 'LOAD_CHANNELS';

const storage = require('electron-json-storage')
import GitHub from 'github-api';
import axios from 'axios';

export function addChannel(channel) {
	let channelName = channel.full_name
	return (dispatch, getState) => {
		let currentUser = getState().auth.currentUser
		let userId = getState().auth.id
		let repo = getState().repo
		let channelStorage
		storage.get('channels', (err, result) => {
			if (err) {
				console.error(err)
				channelStorage = {}
			}

			channelStorage = result
			let userStorage = channelStorage[currentUser]
			userStorage[channelName] = null
			storage.set('channels', {...channelStorage, [currentUser]: userStorage})
			let channels = Object.keys(userStorage)

			return axios.post(process.env.SERVER_URL + `/api/channels/${userId}`, {
				repoId: channelName
			})
				.then(createdChannel => {
					dispatch({
						type: LOAD_CHANNELS,
						channels
					})
				})
		})
	}
}

export function removeChannel(id) {
	return (dispatch, getState) => {
		let currentUser = getState().auth.currentUser
		let userId = getState().auth.id
		let channelStorage
		storage.get('channels', (err, result) => {
			if (err) {
				console.error(err)
				channelStorage = {}
			}
			channelStorage = result
			delete channelStorage[currentUser][id]
			storage.set('channels', channelStorage, err => console.error)
			let channels = Object.keys(channelStorage[currentUser])
			return axios.put(process.env.SERVER_URL + `/api/channels/remove?channelId=${id}&userId=${userId}`)
				.then(() => {
					dispatch({
						type: LOAD_CHANNELS,
						channels
					})
				})
		})

	}
}

export function loadChannels() {
	// storage.clear(err => console.error)
	return (dispatch, getState) => {
		storage.get('channels', (err, channelStorage) => {
			if (err) console.error(err)
			let userId = getState().auth.id
			let currentUser = getState().auth.currentUser
			let userStorage = channelStorage[currentUser] ? channelStorage[ currentUser ] : {}
			let channels
			return axios.get(process.env.SERVER_URL + `/api/users/${userId}`)
				.then(result => {
					let user = result.data

					if (user.channels) {
						user.channels.forEach(channel => {
							if (!userStorage.hasOwnProperty(channel.repoId)) {
								userStorage[channel.repoId] = null
							}
						})
						storage.set('channels', {...channelStorage, [currentUser]: userStorage})
					} else {
						storage.set('channels', {...channelStorage, [currentUser]: {}})
					}
					channels = Object.keys(channelStorage[currentUser])
				})
				.then(() => dispatch({
					type: LOAD_CHANNELS,
					channels
				}))
		})
	}
}
<|endoftext|>


<commit_before>require('dotenv').load();

var mongoose
var mongoose = require('mongoose');

if (process.env.NODE_ENV=== 'production') {
  connectionString = 'proecess.env.MONGOLAB_URI';
  console.log('Using production connectionString');
}
else {
  connectionString = process.env.DATABASE_URL;
  console.log('Using dev connectionString');
}
// var connectionString = process.env.DATABASE_URL;

// define connection string.  'production' will be set if deployed on heroku
// if(process.env.NODE_ENV === 'production'){
//   connectionString = process.env.MONGOLAB_URI;
// }

// alternate way to define string as in class
// var connectionString = process.env.DATABASE_URL || process.env.MONGOLAB_URI;

// console.log("-------------------------------Attempting to connect to Database");
// console.log('process.evn.MOGOLAB_URI: ' + process.env.MONGOLAB_URI);
// console.log('connection string: ' + connectionString);

mongoose.connect(connectionString);

mongoose.connection.on('connected', function() {
  console.log("Connected to Database --> flashNotes");
});

mongoose.connection.on('disconnected', function() {
  console.log("Disconneced From Database --> flashNotes")
});

mongoose.connection.on('error', function(error) {
  console.log('There was an error connecting to the database! ' + error);
});
<commit_msg>fixed production connection string logic<commit_after>require('dotenv').load();

var mongoose
var mongoose = require('mongoose');

if (process.env.NODE_ENV=== 'production') {
  connectionString = 'process.env.MONGOLAB_URI';
  console.log('Using production connectionString');
}
else {
  connectionString = process.env.DATABASE_URL;
  console.log('Using dev connectionString');
}
// var connectionString = process.env.DATABASE_URL;

// define connection string.  'production' will be set if deployed on heroku
// if(process.env.NODE_ENV === 'production'){
//   connectionString = process.env.MONGOLAB_URI;
// }

// alternate way to define string as in class
// var connectionString = process.env.DATABASE_URL || process.env.MONGOLAB_URI;

// console.log("-------------------------------Attempting to connect to Database");
// console.log('process.evn.MOGOLAB_URI: ' + process.env.MONGOLAB_URI);
// console.log('connection string: ' + connectionString);

mongoose.connect(connectionString);

mongoose.connection.on('connected', function() {
  console.log("Connected to Database --> flashNotes");
});

mongoose.connection.on('disconnected', function() {
  console.log("Disconneced From Database --> flashNotes")
});

mongoose.connection.on('error', function(error) {
  console.log('There was an error connecting to the database! ' + error);
});
<|endoftext|>


<commit_before><commit_msg>Remove placeholder js in components folder<commit_after><|endoftext|>


<commit_before>var Promise = require( 'bluebird' ),
    Checkit = require( 'checkit' ),
    express = require( 'express' ),
    _ = require( 'lodash' ),
    NotFoundError = require( '../errors/not-found' ),
    InvalidRequestError = require( '../errors/invalid-request' ),
    bookshelf = require( 'bookshelf' ).bookshelf,
    http = require( '../helpers/promisify-http' ),
    auth = require( '../middlewares/auth' );

var BaseController = module.exports = function( module ) {
    this.module = module;
    this.routes = this.getRoutes();
    this.injectAuthMiddleware();
    this.assignRouteHandlers();
};

BaseController.prototype.getRoutes = function() {
    return {
        index: { method: 'GET', path: '/', middlewares: [] },
        show: { method: 'GET', path: '/:id', middlewares: [] },
        store: { method: 'POST', path: '/', middlewares: [] },
        update: { method: 'PUT', path: '/:id', middlewares: [] },
        patch: { method: 'PATCH', path: '/:id', middlewares: [] },
        delete: { method: 'DELETE', path: '/:id', middlewares: [] }
    };
};

BaseController.prototype.Model = bookshelf.Model;

BaseController.prototype.authorize = false;

BaseController.prototype.injectAuthMiddleware = function() {
    if ( true === this.authorize ) {
        this.authorize = Object.keys( this.routes );
    }

    if ( this.authorize instanceof Array ) {
        var routes = this.routes;
        this.authorize.forEach(function( route ) {
            routes[ route ].middlewares.unshift( auth );
        });
    }
};

BaseController.prototype.assignRouteHandlers = function() {
    var _this = this;

    this.router = express.Router();

    for ( var route in this.routes ) {
        var routeOptions = this.routes[ route ],
            method = routeOptions.method.toLowerCase();

        routeOptions.middlewares.push( http( this[ route ].bind( this ) ) );
        this.router[ method ].apply( this.router, [ routeOptions.path ].concat( routeOptions.middlewares ) );
    }
};

BaseController.prototype.generateResponse = function( response ) {
    var responseKey;
    if ( response instanceof bookshelf.Collection ) {
        responseKey = this.Model.prototype.tableName;
    } else {
        responseKey = this.module;
    }

    return _.object([ [ responseKey, response ] ])
};

BaseController.prototype.index = function() {
    return this.Model.fetchAll().then( this.generateResponse.bind( this ) );
};

BaseController.prototype.show = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then( this.generateResponse.bind( this ) )
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};

BaseController.prototype.store = function( body, options ) {
    return new this.Model()
        .save( body )
        .then( this.generateResponse.bind( this ) )
        .catch( Checkit.Error, function() {
            return Promise.reject( new InvalidRequestError() );
        });
};

BaseController.prototype.update = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then(function( resource ) {
            return resource.save( body );
        })
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};

BaseController.prototype.patch = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then(function( resource ) {
            return resource.save( body, { patch: true });
        })
        .then( this.generateResponse.bind( this ) )
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};

BaseController.prototype.delete = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then(function( resource ) {
            return resource.destroy();
        })
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};<commit_msg>Wrap response resource on update<commit_after>var Promise = require( 'bluebird' ),
    Checkit = require( 'checkit' ),
    express = require( 'express' ),
    _ = require( 'lodash' ),
    NotFoundError = require( '../errors/not-found' ),
    InvalidRequestError = require( '../errors/invalid-request' ),
    bookshelf = require( 'bookshelf' ).bookshelf,
    http = require( '../helpers/promisify-http' ),
    auth = require( '../middlewares/auth' );

var BaseController = module.exports = function( module ) {
    this.module = module;
    this.routes = this.getRoutes();
    this.injectAuthMiddleware();
    this.assignRouteHandlers();
};

BaseController.prototype.getRoutes = function() {
    return {
        index: { method: 'GET', path: '/', middlewares: [] },
        show: { method: 'GET', path: '/:id', middlewares: [] },
        store: { method: 'POST', path: '/', middlewares: [] },
        update: { method: 'PUT', path: '/:id', middlewares: [] },
        patch: { method: 'PATCH', path: '/:id', middlewares: [] },
        delete: { method: 'DELETE', path: '/:id', middlewares: [] }
    };
};

BaseController.prototype.Model = bookshelf.Model;

BaseController.prototype.authorize = false;

BaseController.prototype.injectAuthMiddleware = function() {
    if ( true === this.authorize ) {
        this.authorize = Object.keys( this.routes );
    }

    if ( this.authorize instanceof Array ) {
        var routes = this.routes;
        this.authorize.forEach(function( route ) {
            routes[ route ].middlewares.unshift( auth );
        });
    }
};

BaseController.prototype.assignRouteHandlers = function() {
    var _this = this;

    this.router = express.Router();

    for ( var route in this.routes ) {
        var routeOptions = this.routes[ route ],
            method = routeOptions.method.toLowerCase();

        routeOptions.middlewares.push( http( this[ route ].bind( this ) ) );
        this.router[ method ].apply( this.router, [ routeOptions.path ].concat( routeOptions.middlewares ) );
    }
};

BaseController.prototype.generateResponse = function( response ) {
    var responseKey;
    if ( response instanceof bookshelf.Collection ) {
        responseKey = this.Model.prototype.tableName;
    } else {
        responseKey = this.module;
    }

    return _.object([ [ responseKey, response ] ])
};

BaseController.prototype.index = function() {
    return this.Model.fetchAll().then( this.generateResponse.bind( this ) );
};

BaseController.prototype.show = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then( this.generateResponse.bind( this ) )
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};

BaseController.prototype.store = function( body, options ) {
    return new this.Model()
        .save( body )
        .then( this.generateResponse.bind( this ) )
        .catch( Checkit.Error, function() {
            return Promise.reject( new InvalidRequestError() );
        });
};

BaseController.prototype.update = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then(function( resource ) {
            return resource.save( body );
        })
        .then( this.generateResponse.bind( this ) )
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};

BaseController.prototype.patch = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then(function( resource ) {
            return resource.save( body, { patch: true });
        })
        .then( this.generateResponse.bind( this ) )
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};

BaseController.prototype.delete = function( body, options ) {
    var model = new this.Model();

    return model
        .query( 'where', model.idAttribute, '=', options.id )
        .fetch({ require: true })
        .then(function( resource ) {
            return resource.destroy();
        })
        .catch( this.Model.NotFoundError, function() {
            return Promise.reject( new NotFoundError() );
        });
};<|endoftext|>


<commit_before>var express = require('express'),
  router = express.Router(),
  mongoose = require('mongoose'),
  Article = mongoose.model('Article'),
  sessionManager = require('../sessionManager').SessionManager;

module.exports = function (app)
{
  app.use('/', router);
};

router.get('/', function (req, res, next)
{
  Article.find(function (err, articles)
  {
    if (err) return next(err);
    console.log(sessionManager);
    sessionManager.startSession();
    res.render('index', {
      title: 'Generator-Express MVC',
      articles: articles
    });
  });
});
<commit_msg>- handle json response for main page<commit_after>var express = require('express'),
  router = express.Router(),
  mongoose = require('mongoose'),
  Article = mongoose.model('Article'),
  sessionManager = require('../sessionManager').SessionManager;

module.exports = function (app)
{
  app.use('/', router);
};

router.get('/', function (req, res, next)
{
  Article.find(function (err, articles)
  {
    let body = {
      title: 'Generator-Express MVC',
      articles: articles
    };
    if (err) return next(err);
    console.log(sessionManager);
    sessionManager.startSession();

    // handle html and json responses, so that unit tests can get a sane
    // response.
    if (req.accepts('json'))
    {
      res.send(body);
    }
    else
    {
      res.render('index', body);
    }
  });
});
<|endoftext|>


<commit_before>var UserController = Ember.Controller.extend({
  content: null,
  isLoggedIn: Ember.computed.bool('content'),
  username:  Ember.computed.oneWay('content.github_login'),
  avatarUrl: function(){
    return "https://secure.gravatar.com/avatar/" + this.get('content.gravatar_id');
  }.property('content'),
  githubClientId: function(){
    // TODO: Not this here:
    var key = 'github_client_id';
    return Ember.$('meta[name='+ key + ']').attr('content');
  }.property(),
  exchangeGithubOauthCode: function(authCode){
    var self = this;
    Ember.$.ajax({
      type: 'post',
      url: 'http://localhost:8000' + "/api/oauth/github/exchange?code=" + authCode
    }).then(function(accessToken) {
      self.loginWithGithub(accessToken);
    }).then(null, Conductor.error);
  },
  logout: function() {
    document.cookie = "login=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
    this.setCurrentUser(null);
  },
  loginWithGithub: function(githubAccessToken) {
    var self = this;
    return Ember.$.ajax({
      url: '/api/session.json',
      type: 'POST',
      data: {
        github_access_token: githubAccessToken
      }
    }).then(function(data){
      Ember.run(function(){
        self.set('content', data.user);
      });
    }).then(null, Conductor.error);
  },
  setCurrentUser: function (user) {
    var accessToken = null;
    if (user) {
      accessToken = user.github_access_token;
      delete user.github_access_token;
    }
    this.set('content', user);
    this.set('accessToken', accessToken);
  }
});
export = UserController;
<commit_msg>Fix hardcoded path in oauth flow @lukemelia / @kselden<commit_after>var UserController = Ember.Controller.extend({
  content: null,
  isLoggedIn: Ember.computed.bool('content'),
  username:  Ember.computed.oneWay('content.github_login'),
  avatarUrl: function(){
    return "https://secure.gravatar.com/avatar/" + this.get('content.gravatar_id');
  }.property('content'),
  githubClientId: function(){
    // TODO: Not this here:
    var key = 'github_client_id';
    return Ember.$('meta[name='+ key + ']').attr('content');
  }.property(),
  exchangeGithubOauthCode: function(authCode){
    var self = this;
    Ember.$.ajax({
      type: 'post',
      url: "/api/oauth/github/exchange?code=" + authCode
    }).then(function(accessToken) {
      self.loginWithGithub(accessToken);
    }).then(null, Conductor.error);
  },
  logout: function() {
    document.cookie = "login=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
    this.setCurrentUser(null);
  },
  loginWithGithub: function(githubAccessToken) {
    var self = this;
    return Ember.$.ajax({
      url: '/api/session.json',
      type: 'POST',
      data: {
        github_access_token: githubAccessToken
      }
    }).then(function(data){
      Ember.run(function(){
        self.set('content', data.user);
      });
    }).then(null, Conductor.error);
  },
  setCurrentUser: function (user) {
    var accessToken = null;
    if (user) {
      accessToken = user.github_access_token;
      delete user.github_access_token;
    }
    this.set('content', user);
    this.set('accessToken', accessToken);
  }
});
export = UserController;
<|endoftext|>


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

import FauxtonAPI from "./base";
import React from "react";
import ReactDOM from "react-dom";
import Backbone from "backbone";

var RouteObject = function (options) {
  this._options = options;
  this.reactComponents = {};

  this._configure(options || {});
  this.initialize.apply(this, arguments);
  this.addEvents();
};

var broadcaster = {};
_.extend(broadcaster, Backbone.Events);

RouteObject.on = function (eventName, fn) {
  broadcaster.on(eventName, fn);
};

/* How Route Object events work
 To listen to a specific route objects events:

 myRouteObject = FauxtonAPI.RouteObject.extend({
  events: {
    "beforeRender": "beforeRenderEvent"
  },

  beforeRenderEvent: function (view, selector) {
    console.log('Hey, beforeRenderEvent triggered',arguments);
  },
 });

  It is also possible to listen to events triggered from all Routeobjects.
  This is great for more general things like adding loaders, hooks.

  FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
    console.log('hey, this will trigger when any routeobject renders a view');
  });

 Current Events to subscribe to:
  * beforeFullRender -- before a full render is being done
  * beforeEstablish -- before the routeobject calls establish
  * afterEstablish -- after the routeobject has run establish
  * beforeRender -- before a view is rendered
  * afterRender -- a view is finished being rendered
  * renderComplete -- all rendering is complete

*/

// Piggy-back on Backbone's self-propagating extend function
RouteObject.extend = Backbone.Model.extend;

var routeObjectOptions = ["views", "routes", "events", "roles", "crumbs", "layout", "apiUrl", "establish"];

_.extend(RouteObject.prototype, Backbone.Events, {
  // Should these be default vals or empty funcs?
  views: {},
  routes: {},
  events: {},
  crumbs: [],
  layout: "with_sidebar",
  apiUrl: null,
  hideNotificationPanel: null,
  disableLoader: false,
  loaderClassname: 'loader',
  renderedState: false,
  establish: function () {},
  route: function () {},
  roles: [],
  _promises: [],
  initialize: function () {}
}, {

  renderWith: function (route, masterLayout, args) {

    // set the options for this render
    var options = {
      masterLayout: masterLayout,
      route: route,
      args: args
    };

    var promiseLayout = this.setTemplateOnFullRender(masterLayout);

    this.triggerBroadcast('beforeEstablish');

    var renderAllViews = _.bind(this.renderAllViews, this, options),
        establishError = _.bind(this.establishError, this),
        renderComplete = _.bind(this.renderComplete, this),
        callEstablish = _.bind(this.callEstablish, this),
        renderReactComponents = _.bind(this.renderReactComponents, this),
        promise = this.establish();

    // Only start the view rendering process once the template has been rendered
    // otherwise we get double renders
    promiseLayout.then(function () {
      renderReactComponents();
      callEstablish(promise)
        .then(renderAllViews, establishError)
        .then(renderComplete);
    });
  },

  setTemplateOnFullRender: function (masterLayout) {

    var promise = $.Deferred();

    // Only want to redo the template if its a full render
    if (!this.renderedState) {
      this.triggerBroadcast('beforeFullRender');
      masterLayout.setTemplate(this.layout).then(promise.resolve, promise.reject);
    } else {
      promise.resolve();
    }

    return promise;
  },

  renderReactComponents: function () {
    _.each(this.reactComponents, function (componentInfo, selector) {
      if ($(selector)[0]) {
        ReactDOM.render(React.createElement(componentInfo.component, componentInfo.props), $(selector)[0]);
      }
    });
  },

  callEstablish: function (establishPromise) {
    this.addPromise(establishPromise);
    return FauxtonAPI.when(establishPromise);
  },

  renderAllViews: function (options, resp) {
    var routeObject = this,
        renderView = _.bind(this.renderView, this, routeObject, options);

    this.triggerBroadcast('afterEstablish');

    var promises = _.map(routeObject.getViews(), renderView, this);
    return FauxtonAPI.when(promises);
  },

  renderView: function (routeObject, options, view, selector) {
    var viewInfo = {
      view: view,
      selector: selector,
      masterLayout: options.masterLayout
    };

    var renderViewOnLayout = _.bind(this.renderViewOnLayout, this, viewInfo);

    if (view.hasRendered) {
      this.triggerBroadcast('viewHasRendered', view, selector);
      return;
    }

    this.triggerBroadcast('beforeRender', view, selector);

    return this.callEstablish(view.establish()).then(renderViewOnLayout, this.establishError);
  },

  renderViewOnLayout: function (viewInfo, resp, xhr) {
    var masterLayout = viewInfo.masterLayout,
        triggerBroadcast = _.bind(this.triggerBroadcast, this);

    masterLayout.setView(viewInfo.selector, viewInfo.view);
    var promise = masterLayout.renderView(viewInfo.selector).promise();

    promise.then(function () {
      triggerBroadcast('afterRender', viewInfo.view, viewInfo.selector);
    });

    return promise;
  },

  establishError: function (resp) {
    if (!resp || !resp.responseText) { return; }
    FauxtonAPI.addNotification({
          msg: 'An Error occurred: ' + JSON.parse(resp.responseText).reason,
          type: 'error',
          clear: true
    });
  },

  renderComplete: function () {
    // Track that we've done a full initial render
    this.setRenderedState(true);
    this.triggerBroadcast('renderComplete');
  },

  setRenderedState: function (bool) {
    this.renderedState = bool;
  },

  triggerBroadcast: function (eventName) {
    var args = Array.prototype.slice.call(arguments);
    this.trigger.apply(this, args);

    args.splice(0, 1, eventName, this);
    broadcaster.trigger.apply(broadcaster, args);
  },

  get: function (key) {
    return _.isFunction(this[key]) ? this[key]() : this[key];
  },

  addEvents: function (events) {
    events = events || this.get('events');
    _.each(events, function (method, event) {
      if (!_.isFunction(method) && !_.isFunction (this[method])) {
        throw new Error("Invalid method: " + method);
      }
      method = _.isFunction(method) ? method : this[method];

      this.on(event, method);
    }, this);
  },

  _configure: function (options) {
    _.each(_.intersection(_.keys(options), routeObjectOptions), function (key) {
      this[key] = options[key];
    }, this);
  },

  getView: function (selector) {
    return this.views[selector];
  },

  setView: function (selector, view) {
    this.removeView(selector);
    this.removeComponent(selector);
    this.views[selector] = view;
    return view;
  },

  setComponent: function (selector, component, props) {
    this.removeView(selector);
    this.removeComponent(selector);
    this.reactComponents[selector] = {
      component: component,
      props: props || null
    };
  },

  removeComponent: function (selector) {
    if (_.has(this.reactComponents, selector)) {
      if ($(selector)[0]) {
        ReactDOM.unmountComponentAtNode($(selector)[0]);
      }
      this.reactComponents[selector] = null;
      delete this.reactComponents[selector];
    }
  },

  removeComponents: function () {
    _.each(this.reactComponents, function (component, selector) {
      this.removeComponent(selector);
    }, this);

    this.reactComponents = {};
  },

  getViews: function () {
    return this.views;
  },

  removeView: function (selector) {
    if (_.has(this.views, selector)) {
      this.views[selector].remove();
      this.views[selector] = null;
      delete this.views[selector];
    }
  },

  removeViews: function () {
    _.each(this.views, function (view, selector) {
      view.remove();
      delete this.views[selector];
      view = null;
    }, this);
  },

  addPromise: function (promise) {
    if (_.isEmpty(promise)) { return; }

    if (!_.isArray(promise)) {
      return this._promises.push(promise);
    }

    _.each(promise, function (p) {
      this._promises.push(p);
    }, this);
  },

  cleanup: function () {
    this.removeComponents();
    this.removeViews();
    this.rejectPromises();
  },

  rejectPromises: function () {
    _.each(this._promises, function (promise) {
      if (promise.state() === "resolved") { return; }
      if (promise.abort) {
        return promise.abort("Route change");
      }

      promise.reject && promise.reject();
    }, this);

    this._promises = [];
  },

  getRouteUrls: function () {
    return _.keys(this.get('routes'));
  },

  hasRoute: function (route) {
    if (this.get('routes')[route]) {
      return true;
    }
    return false;
  },

  routeCallback: function (route, args) {
    var routes = this.get('routes'),
    routeObj = routes[route],
    routeCallback;

    if (typeof routeObj === 'object') {
      routeCallback = this[routeObj.route];
    } else {
      routeCallback = this[routeObj];
    }

    routeCallback.apply(this, args);
  },

  getRouteRoles: function (routeUrl) {
    var route = this.get('routes')[routeUrl];

    if ((typeof route === 'object') && route.roles) {
      return route.roles;
    }

    return this.roles;
  }

});
export default RouteObject;
<commit_msg>provide debugging help for monkey patched established methods<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import FauxtonAPI from "./base";
import React from "react";
import ReactDOM from "react-dom";
import Backbone from "backbone";

var RouteObject = function (options) {
  this._options = options;
  this.reactComponents = {};

  this._configure(options || {});
  this.initialize.apply(this, arguments);
  this.addEvents();
};

var broadcaster = {};
_.extend(broadcaster, Backbone.Events);

RouteObject.on = function (eventName, fn) {
  broadcaster.on(eventName, fn);
};

/* How Route Object events work
 To listen to a specific route objects events:

 myRouteObject = FauxtonAPI.RouteObject.extend({
  events: {
    "beforeRender": "beforeRenderEvent"
  },

  beforeRenderEvent: function (view, selector) {
    console.log('Hey, beforeRenderEvent triggered',arguments);
  },
 });

  It is also possible to listen to events triggered from all Routeobjects.
  This is great for more general things like adding loaders, hooks.

  FauxtonAPI.RouteObject.on('beforeRender', function (routeObject, view, selector) {
    console.log('hey, this will trigger when any routeobject renders a view');
  });

 Current Events to subscribe to:
  * beforeFullRender -- before a full render is being done
  * beforeEstablish -- before the routeobject calls establish
  * afterEstablish -- after the routeobject has run establish
  * beforeRender -- before a view is rendered
  * afterRender -- a view is finished being rendered
  * renderComplete -- all rendering is complete

*/

// Piggy-back on Backbone's self-propagating extend function
RouteObject.extend = Backbone.Model.extend;

var routeObjectOptions = ["views", "routes", "events", "roles", "crumbs", "layout", "apiUrl", "establish"];

_.extend(RouteObject.prototype, Backbone.Events, {
  // Should these be default vals or empty funcs?
  views: {},
  routes: {},
  events: {},
  crumbs: [],
  layout: "with_sidebar",
  apiUrl: null,
  hideNotificationPanel: null,
  disableLoader: false,
  loaderClassname: 'loader',
  renderedState: false,
  establish: function () {},
  route: function () {},
  roles: [],
  _promises: [],
  initialize: function () {}
}, {

  renderWith: function (route, masterLayout, args) {

    // set the options for this render
    var options = {
      masterLayout: masterLayout,
      route: route,
      args: args
    };

    var promiseLayout = this.setTemplateOnFullRender(masterLayout);

    this.triggerBroadcast('beforeEstablish');

    var renderAllViews = _.bind(this.renderAllViews, this, options),
        establishError = _.bind(this.establishError, this),
        renderComplete = _.bind(this.renderComplete, this),
        callEstablish = _.bind(this.callEstablish, this),
        renderReactComponents = _.bind(this.renderReactComponents, this);

    const promise = this.establish();

    // Only start the view rendering process once the template has been rendered
    // otherwise we get double renders
    promiseLayout.then(function () {
      renderReactComponents();

      callEstablish(promise)
        .then(renderAllViews, establishError)
        .then(renderComplete, (err) => {
          console.error('renderpipeline broke');
          console.error('check your establish method');

          console.log(this.establish.toString());
          console.error(err);
        });

    }.bind(this));
  },

  setTemplateOnFullRender: function (masterLayout) {

    var promise = $.Deferred();

    // Only want to redo the template if its a full render
    if (!this.renderedState) {
      this.triggerBroadcast('beforeFullRender');
      masterLayout.setTemplate(this.layout).then(promise.resolve, promise.reject);
    } else {
      promise.resolve();
    }

    return promise;
  },

  renderReactComponents: function () {
    _.each(this.reactComponents, function (componentInfo, selector) {
      if ($(selector)[0]) {
        ReactDOM.render(React.createElement(componentInfo.component, componentInfo.props), $(selector)[0]);
      }
    });
  },

  callEstablish: function (establishPromise) {
    this.addPromise(establishPromise);
    return FauxtonAPI.when(establishPromise);
  },

  renderAllViews: function (options, resp) {
    var routeObject = this,
        renderView = _.bind(this.renderView, this, routeObject, options);

    this.triggerBroadcast('afterEstablish');

    var promises = _.map(routeObject.getViews(), renderView, this);
    return FauxtonAPI.when(promises);
  },

  renderView: function (routeObject, options, view, selector) {
    var viewInfo = {
      view: view,
      selector: selector,
      masterLayout: options.masterLayout
    };

    var renderViewOnLayout = _.bind(this.renderViewOnLayout, this, viewInfo);

    if (view.hasRendered) {
      this.triggerBroadcast('viewHasRendered', view, selector);
      return;
    }

    this.triggerBroadcast('beforeRender', view, selector);

    return this.callEstablish(view.establish()).then(renderViewOnLayout, this.establishError);
  },

  renderViewOnLayout: function (viewInfo, resp, xhr) {
    var masterLayout = viewInfo.masterLayout,
        triggerBroadcast = _.bind(this.triggerBroadcast, this);

    masterLayout.setView(viewInfo.selector, viewInfo.view);
    var promise = masterLayout.renderView(viewInfo.selector).promise();

    promise.then(function () {
      triggerBroadcast('afterRender', viewInfo.view, viewInfo.selector);
    });

    return promise;
  },

  establishError: function (resp) {
    if (!resp || !resp.responseText) { return; }
    FauxtonAPI.addNotification({
          msg: 'An Error occurred: ' + JSON.parse(resp.responseText).reason,
          type: 'error',
          clear: true
    });
  },

  renderComplete: function () {
    // Track that we've done a full initial render
    this.setRenderedState(true);
    this.triggerBroadcast('renderComplete');
  },

  setRenderedState: function (bool) {
    this.renderedState = bool;
  },

  triggerBroadcast: function (eventName) {
    var args = Array.prototype.slice.call(arguments);
    this.trigger.apply(this, args);

    args.splice(0, 1, eventName, this);
    broadcaster.trigger.apply(broadcaster, args);
  },

  get: function (key) {
    return _.isFunction(this[key]) ? this[key]() : this[key];
  },

  addEvents: function (events) {
    events = events || this.get('events');
    _.each(events, function (method, event) {
      if (!_.isFunction(method) && !_.isFunction (this[method])) {
        throw new Error("Invalid method: " + method);
      }
      method = _.isFunction(method) ? method : this[method];

      this.on(event, method);
    }, this);
  },

  _configure: function (options) {
    _.each(_.intersection(_.keys(options), routeObjectOptions), function (key) {
      this[key] = options[key];
    }, this);
  },

  getView: function (selector) {
    return this.views[selector];
  },

  setView: function (selector, view) {
    this.removeView(selector);
    this.removeComponent(selector);
    this.views[selector] = view;
    return view;
  },

  setComponent: function (selector, component, props) {
    this.removeView(selector);
    this.removeComponent(selector);
    this.reactComponents[selector] = {
      component: component,
      props: props || null
    };
  },

  removeComponent: function (selector) {
    if (_.has(this.reactComponents, selector)) {
      if ($(selector)[0]) {
        ReactDOM.unmountComponentAtNode($(selector)[0]);
      }
      this.reactComponents[selector] = null;
      delete this.reactComponents[selector];
    }
  },

  removeComponents: function () {
    _.each(this.reactComponents, function (component, selector) {
      this.removeComponent(selector);
    }, this);

    this.reactComponents = {};
  },

  getViews: function () {
    return this.views;
  },

  removeView: function (selector) {
    if (_.has(this.views, selector)) {
      this.views[selector].remove();
      this.views[selector] = null;
      delete this.views[selector];
    }
  },

  removeViews: function () {
    _.each(this.views, function (view, selector) {
      view.remove();
      delete this.views[selector];
      view = null;
    }, this);
  },

  addPromise: function (promise) {
    if (_.isEmpty(promise)) { return; }

    if (!_.isArray(promise)) {
      return this._promises.push(promise);
    }

    _.each(promise, function (p) {
      this._promises.push(p);
    }, this);
  },

  cleanup: function () {
    this.removeComponents();
    this.removeViews();
    this.rejectPromises();
  },

  rejectPromises: function () {
    _.each(this._promises, function (promise) {
      if (promise.state() === "resolved") { return; }
      if (promise.abort) {
        return promise.abort("Route change");
      }

      promise.reject && promise.reject();
    }, this);

    this._promises = [];
  },

  getRouteUrls: function () {
    return _.keys(this.get('routes'));
  },

  hasRoute: function (route) {
    if (this.get('routes')[route]) {
      return true;
    }
    return false;
  },

  routeCallback: function (route, args) {
    var routes = this.get('routes'),
    routeObj = routes[route],
    routeCallback;

    if (typeof routeObj === 'object') {
      routeCallback = this[routeObj.route];
    } else {
      routeCallback = this[routeObj];
    }

    routeCallback.apply(this, args);
  },

  getRouteRoles: function (routeUrl) {
    var route = this.get('routes')[routeUrl];

    if ((typeof route === 'object') && route.roles) {
      return route.roles;
    }

    return this.roles;
  }

});
export default RouteObject;
<|endoftext|>


<commit_before><commit_msg>Issue #8 part 2: Reapply blank line rules<commit_after><|endoftext|>


<commit_before>const fs = require('fs');
const cp = require('child_process');
const im = require('imagemagick');
const commandLineArgs = require('command-line-args');

const fullWidth = 1920;
const fullHeight = 1080;
const outDir = 'clips';
const charPerLine = 30;

const optionDefinitions = [
  { name: 'background', alias: 'b', type: String },
  { name: 'color', alias: 'c', type: String },
  { name: 'font', alias: 'f', type: String },
  { name: 'image', alias: 'i', type: String },
  { name: 'line', alias: 'l', type: Number },
  { name: 'play', alias: 'p', type: String },
];
const options = commandLineArgs(optionDefinitions);

if (
      !options.hasOwnProperty('font')
   || !options.hasOwnProperty('image')
   || !options.hasOwnProperty('line')
   || !options.hasOwnProperty('play')
   ) {
  // Can't do anything useful without input
  return;
}

var background = options.hasOwnProperty('background') ? options.background : 'lightgray';
var foreground = options.hasOwnProperty('color') ? options.color : 'black';
var fontFile = options.font;
var imageFile = options.image;
var lineNumber = options.line;
var playFile = options.play;
var imageBaseName = imageFile.split('/').pop();
var screenplay = fs.readFileSync(playFile).toString().split('\n');
screenplay.unshift('');

var lineRead = screenplay[lineNumber];
var audioName = 'output/speech' + lineNumber + '.wav';
var proc = cp.spawnSync('/usr/bin/soxi', [ '-D', audioName ]);
var time = parseFloat(proc.stdout.toString().trim(), 10);
var width = 0;
var height = 0;
var rSwitch = Math.round(Math.random());

im.identify(imageFile, function (err, features) {
  if (err) throw err;
  var linelen = 100;
  var dir = 'Center';
  var geo = '+100+100';
  width = features.width;
  height = features.height;
  if (width > height) {
    var xScale = fullWidth / width;
    linelen = Math.round((fullWidth - 200) / charPerLine);
    if (rSwitch == 1) {
      dir = 'South';
      geo = '+100+100';
    } else {
      dir = 'North';
      geo = '+100+' + (height * xScale + 50);
    }
  } else {
    var yScale = fullHeight / height;
    linelen = Math.round((fullWidth - width * yScale - 200) / charPerLine);
    if (rSwitch == 1) {
      dir = 'East';
      geo = '+100+100';
    } else {
      dir = 'West';
      geo = '+' + (100 + Math.round(width * yScale)) + '+100';
    }
  }
  var words = lineRead.replace(/_/g, '').split(' ');
  var chars = 0;
  lineRead = '';
  for (var i = 0; i < words.length; i++) {
    var wd = words[i];
    chars += wd.length + 1;
    if (chars > linelen) {
      chars = 0;
      lineRead += '\n';
    }
    lineRead += wd + ' ';
    if (wd.length > linelen) {
      chars = 0;
      lineRead += '\n';
    }
  }
  im.convert([
      imageFile,
      '-resize', fullWidth + 'x' + fullHeight,
      '-gravity', dir,
      '-background', background,
      '-opaque', foreground,
      '-extent', fullWidth + 'x' + fullHeight,
      'resized_' + imageBaseName
    ], function (err, output) {
    if (err) {
      console.log(err);
    }
    im.convert([
      'resized_' + imageBaseName,
      '-fill', foreground,
      '-font', fontFile,
      '-pointsize', 48,
      '-annotate', geo,
      lineRead,
      'text_' + imageBaseName
      ], function (err, output) {
      var videoName = outDir + '/video' + ('00000' + lineNumber).slice(-5) + '.mp4';
      fs.unlink('resized_' + imageBaseName);
      cp.spawnSync('/usr/bin/ffmpeg', [
        '-framerate', '1/' + time,
        '-i', 'text_' + imageBaseName,
        '-safe', '0',
        '-strict', '-2',
        '-c:v', 'libx264',
        '-b:a', '4.5M',
        '-b:v', '4.5M',
        '-minrate', '4.5M',
        '-maxrate', '4.5M',
        '-bufsize', '4.5M',
        '-r', '30',
        '-pix_fmt', 'yuv420p',
        videoName
      ]);
      fs.unlink('text_' + imageBaseName);
    });
  });
});
<commit_msg>Remove unused arguments<commit_after>const fs = require('fs');
const cp = require('child_process');
const im = require('imagemagick');
const commandLineArgs = require('command-line-args');

const fullWidth = 1920;
const fullHeight = 1080;
const outDir = 'clips';
const charPerLine = 30;

const optionDefinitions = [
  { name: 'background', alias: 'b', type: String },
  { name: 'color', alias: 'c', type: String },
  { name: 'font', alias: 'f', type: String },
  { name: 'image', alias: 'i', type: String },
  { name: 'line', alias: 'l', type: Number },
  { name: 'play', alias: 'p', type: String },
];
const options = commandLineArgs(optionDefinitions);

if (
      !options.hasOwnProperty('font')
   || !options.hasOwnProperty('image')
   || !options.hasOwnProperty('line')
   || !options.hasOwnProperty('play')
   ) {
  // Can't do anything useful without input
  return;
}

var background = options.hasOwnProperty('background') ? options.background : 'lightgray';
var foreground = options.hasOwnProperty('color') ? options.color : 'black';
var fontFile = options.font;
var imageFile = options.image;
var lineNumber = options.line;
var playFile = options.play;
var imageBaseName = imageFile.split('/').pop();
var screenplay = fs.readFileSync(playFile).toString().split('\n');
screenplay.unshift('');

var lineRead = screenplay[lineNumber];
var audioName = 'output/speech' + lineNumber + '.wav';
var proc = cp.spawnSync('/usr/bin/soxi', [ '-D', audioName ]);
var time = parseFloat(proc.stdout.toString().trim(), 10);
var width = 0;
var height = 0;
var rSwitch = Math.round(Math.random());

im.identify(imageFile, function (err, features) {
  if (err) throw err;
  var linelen = 100;
  var dir = 'Center';
  var geo = '+100+100';
  width = features.width;
  height = features.height;
  if (width > height) {
    var xScale = fullWidth / width;
    linelen = Math.round((fullWidth - 200) / charPerLine);
    if (rSwitch == 1) {
      dir = 'South';
      geo = '+100+100';
    } else {
      dir = 'North';
      geo = '+100+' + (height * xScale + 50);
    }
  } else {
    var yScale = fullHeight / height;
    linelen = Math.round((fullWidth - width * yScale - 200) / charPerLine);
    if (rSwitch == 1) {
      dir = 'East';
      geo = '+100+100';
    } else {
      dir = 'West';
      geo = '+' + (100 + Math.round(width * yScale)) + '+100';
    }
  }
  var words = lineRead.replace(/_/g, '').split(' ');
  var chars = 0;
  lineRead = '';
  for (var i = 0; i < words.length; i++) {
    var wd = words[i];
    chars += wd.length + 1;
    if (chars > linelen) {
      chars = 0;
      lineRead += '\n';
    }
    lineRead += wd + ' ';
    if (wd.length > linelen) {
      chars = 0;
      lineRead += '\n';
    }
  }
  im.convert([
      imageFile,
      '-resize', fullWidth + 'x' + fullHeight,
      '-gravity', dir,
      '-background', background,
      '-opaque', foreground,
      '-extent', fullWidth + 'x' + fullHeight,
      'resized_' + imageBaseName
    ], function (err) {
    if (err) {
      console.log(err);
    }
    im.convert([
      'resized_' + imageBaseName,
      '-fill', foreground,
      '-font', fontFile,
      '-pointsize', 48,
      '-annotate', geo,
      lineRead,
      'text_' + imageBaseName
      ], function () {
      var videoName = outDir + '/video' + ('00000' + lineNumber).slice(-5) + '.mp4';
      fs.unlink('resized_' + imageBaseName);
      cp.spawnSync('/usr/bin/ffmpeg', [
        '-framerate', '1/' + time,
        '-i', 'text_' + imageBaseName,
        '-safe', '0',
        '-strict', '-2',
        '-c:v', 'libx264',
        '-b:a', '4.5M',
        '-b:v', '4.5M',
        '-minrate', '4.5M',
        '-maxrate', '4.5M',
        '-bufsize', '4.5M',
        '-r', '30',
        '-pix_fmt', 'yuv420p',
        videoName
      ]);
      fs.unlink('text_' + imageBaseName);
    });
  });
});
<|endoftext|>


<commit_before><commit_msg>testing dynamic landing<commit_after><|endoftext|>


<commit_before>'use strict';
const http = require('http');
const Promise = require('bluebird');

let PromiseRequest = Promise.method(options => {
    return new Promise((resolve, reject) => {
        let request = http.request(options, response => {
            let chunks = [];
            response.on('data', chunk => {
                chunks.push(chunk);
            });
            response.on('end', () => {
                let result = {
                    'httpVersion': response.httpVersion,
                    'httpStatusCode': response.statusCode,
                    'headers': response.headers,
                    'body': Buffer.concat(chunks) || ''//,
                    //'trailers': response.trailers,
                };
                resolve(result);
            });
        });
        request.on('error', error => {
            console.log('Problem with request:', error.message);
            reject(error);
        });
        if (options.timeout) {
            request.setTimeout(options.timeout, () => {
                request.abort();
            })
        }
        request.end();
    });
});
module.exports = PromiseRequest;
<commit_msg>fix promise error bug😑<commit_after>'use strict';
const http = require('http');
const Promise = require('bluebird');

let PromiseRequest = Promise.method(options => {
    return new Promise((resolve, reject) => {
        let request = http.request(options, response => {
            let chunks = [];
            response.on('data', chunk => {
                chunks.push(chunk);
            });
            response.on('end', () => {
                let result = {
                    'httpVersion': response.httpVersion,
                    'httpStatusCode': response.statusCode,
                    'headers': response.headers,
                    'body': Buffer.concat(chunks) || ''//,
                    //'trailers': response.trailers,
                };
                resolve(result);
            });
        });
        request.on('error', error => {
            console.log('Problem with request:', error.message);
            reject(new Error(error));
        });
        if (options.timeout) {
            request.setTimeout(options.timeout, () => {
                request.abort();
            })
        }
        request.end();
    });
});
module.exports = PromiseRequest;
<|endoftext|>


<commit_before>'use strict';

var readJson = require('./readJson')
var Promise = require('bluebird')
var _ = require('lodash')
var add = require('./add')
var db = require('./db')
var buildDeptNum = require('./deptNum').buildDeptNum
var deptNumToCrsidCache = require('./getCourses').deptNumToCrsidCache

var logDataLoading = false

function storeCourses(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeCourses')

		var courses = _.map(item.data.courses, function(course) {
			course.sourcePath = item.meta.path
			course.deptnum = buildDeptNum(course)
			deptNumToCrsidCache[course.deptnum] = course.crsid
			return course
		})

		db.store('courses').batch(courses)
			.then(function(results) {
				resolve(item)
			}).catch(function (records, err) {
				reject(err)
			})
	})
}

function storeArea(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeArea')

		var area = item.data.info
		area.sourcePath = item.meta.path

		db.store('areas').put(area)
			.then(function(results) {
				resolve(item)
			})
			.catch(function(records, err) {
				reject(err)
			})
	})
}

function storeItem(item) {
	if (item.type === 'courses') {
		return storeCourses(item)
	} else if (item.type === 'areas') {
		return storeArea(item)
	}
}

function cleanPriorData(item) {
	return new Promise(function (resolve, reject) {
		var path = item.meta.path
		console.info('deleting ' + item.type + ' from ' + path)

		var deleteItemsPromise = db.store(item.type).del(path)

		deleteItemsPromise
			.then(function() {
				localStorage.removeItem(path)
				resolve(item)
			})
			.catch(function(err) {
				reject(err)
			})
	})
}

function cacheItemHash(item) {
	return new Promise(function(resolve, reject) {
		console.info(item.meta.path + ' called cacheItemHash')
		localStorage.setItem(item.meta.path, item.meta.hash)
		resolve(item)
	})
}

var lookup = {
	'courses': 'courses',
	'areas': 'info'
}

function updateDatabase(itemType, infoFromServer) {
	infoFromServer.path = '/data/' + itemType + '/' + infoFromServer.path
	var oldHash = localStorage.getItem(infoFromServer.path)
	var newHash = infoFromServer.hash
	var itemPath = infoFromServer.path

	if (newHash === oldHash) {
		if (logDataLoading) {
			console.log('skipped ' + itemPath)
		}
		return Promise.resolve(false)
	}

	if (logDataLoading) {
		console.log('need to add ' + itemPath)
	}

	return readJson(itemPath)
		.then(function(data) {
			return {
				data: data,
				meta: infoFromServer,
				type: itemType,
				count: _.size(data[lookup[itemType]]) || 1,
			}
		})
		.then(cleanPriorData)
		.then(storeItem)
		.then(cacheItemHash)
		.catch(function(err) {
			return Promise.reject(err.stack)
		})
		.done(function(item) {
			if (logDataLoading) {
				console.log('added '+item.meta.path+' ('+item.count+' '+item.type+')')
			}
			return Promise.resolve(true)
		})
}

function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	return Promise.all(_.map(infoFile.info, function(files) {
		return Promise.all(_.map(files, function(file) {
			return updateDatabase(infoFile.type, file)
		}))
	}))
}

/*
function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	var progress = 0;
	var notification = new Cortex({
		message: 'Updating ' + infoFile.type,
		hasProgress: true,
		progressValue: progress,
		maxProgressValue: _.chain(infoFile.info).mapValues(_.size).reduce(add).value(),
		ident: infoFile.type
	})
	window.notifications.push(notification.val())

	return Promise.all(_.map(infoFile.info, function(files) {
		var allFilesLoadedPromise = Promise.all(_.map(files, function(file) {
			var dbUpdatedPromise = updateDatabase(infoFile.type, file)
			dbUpdatedPromise.then(function() {
				notification.progressValue.set(progress += 1)
			})
			return dbUpdatedPromise
		}))

		allFilesLoadedPromise.then(function() {
			setTimeout(notification.remove, 200)
		})

		return allFilesLoadedPromise
	}))
}
*/

function loadInfoFile(url) {
	console.log('loading', url)
	return readJson(url).then(loadDataFiles)
}

function loadData() {
	var infoFiles = [
		'/data/areas/info.json',
		'/data/courses/info.json',
	]
	return Promise.all(_.map(infoFiles, loadInfoFile))
}

module.exports = window.loadData = loadData
<commit_msg>Update cleanPriorData<commit_after>'use strict';

var readJson = require('./readJson')
var Promise = require('bluebird')
var _ = require('lodash')
var add = require('./add')
var db = require('./db')
var buildDeptNum = require('./deptNum').buildDeptNum
var deptNumToCrsidCache = require('./getCourses').deptNumToCrsidCache

var logDataLoading = false

function storeCourses(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeCourses')

		var courses = _.map(item.data.courses, function(course) {
			course.sourcePath = item.meta.path
			course.deptnum = buildDeptNum(course)
			deptNumToCrsidCache[course.deptnum] = course.crsid
			return course
		})

		db.store('courses').batch(courses)
			.then(function(results) {
				resolve(item)
			}).catch(function (records, err) {
				reject(err)
			})
	})
}

function storeArea(item) {
	return new Promise(function(resolve, reject) {
		console.log(item.meta.path, 'called storeArea')

		var area = item.data.info
		area.sourcePath = item.meta.path

		db.store('areas').put(area)
			.then(function(results) {
				resolve(item)
			})
			.catch(function(records, err) {
				reject(err)
			})
	})
}

function storeItem(item) {
	if (item.type === 'courses') {
		return storeCourses(item)
	} else if (item.type === 'areas') {
		return storeArea(item)
	}
}

function cleanPriorData(item) {
	return new Promise(function (resolve, reject) {
		var path = item.meta.path
		console.info('deleting ' + item.type + ' from ' + path)

		db.store(item.type)
			.index('sourcePath')
			.get(path)
			.then(function(items) {
				return _.map(items, function(item) {
					var result = Object.create(null)
					result[item.clbid] = null
					return result
				})
			})
			.then(function(items) {
				return db.store(item.type).batch(items)
			})
			.then(function(items) {
				localStorage.removeItem(path)
				resolve(item)
			})
			.catch(function(err) {
				reject(err)
			})
	})
}

function cacheItemHash(item) {
	return new Promise(function(resolve, reject) {
		console.info(item.meta.path + ' called cacheItemHash')
		localStorage.setItem(item.meta.path, item.meta.hash)
		resolve(item)
	})
}

var lookup = {
	'courses': 'courses',
	'areas': 'info'
}

function updateDatabase(itemType, infoFromServer) {
	infoFromServer.path = '/data/' + itemType + '/' + infoFromServer.path
	var oldHash = localStorage.getItem(infoFromServer.path)
	var newHash = infoFromServer.hash
	var itemPath = infoFromServer.path

	if (newHash === oldHash) {
		if (logDataLoading) {
			console.log('skipped ' + itemPath)
		}
		return Promise.resolve(false)
	}

	if (logDataLoading) {
		console.log('need to add ' + itemPath)
	}

	return readJson(itemPath)
		.then(function(data) {
			return {
				data: data,
				meta: infoFromServer,
				type: itemType,
				count: _.size(data[lookup[itemType]]) || 1,
			}
		})
		.then(cleanPriorData)
		.then(storeItem)
		.then(cacheItemHash)
		.catch(function(err) {
			return Promise.reject(err.stack)
		})
		.done(function(item) {
			if (logDataLoading) {
				console.log('added '+item.meta.path+' ('+item.count+' '+item.type+')')
			}
			return Promise.resolve(true)
		})
}

function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	return Promise.all(_.map(infoFile.info, function(files) {
		return Promise.all(_.map(files, function(file) {
			return updateDatabase(infoFile.type, file)
		}))
	}))
}

/*
function loadDataFiles(infoFile) {
	console.log('load data files', infoFile)

	var progress = 0;
	var notification = new Cortex({
		message: 'Updating ' + infoFile.type,
		hasProgress: true,
		progressValue: progress,
		maxProgressValue: _.chain(infoFile.info).mapValues(_.size).reduce(add).value(),
		ident: infoFile.type
	})
	window.notifications.push(notification.val())

	return Promise.all(_.map(infoFile.info, function(files) {
		var allFilesLoadedPromise = Promise.all(_.map(files, function(file) {
			var dbUpdatedPromise = updateDatabase(infoFile.type, file)
			dbUpdatedPromise.then(function() {
				notification.progressValue.set(progress += 1)
			})
			return dbUpdatedPromise
		}))

		allFilesLoadedPromise.then(function() {
			setTimeout(notification.remove, 200)
		})

		return allFilesLoadedPromise
	}))
}
*/

function loadInfoFile(url) {
	console.log('loading', url)
	return readJson(url).then(loadDataFiles)
}

function loadData() {
	var infoFiles = [
		'/data/areas/info.json',
		'/data/courses/info.json',
	]
	return Promise.all(_.map(infoFiles, loadInfoFile))
}

module.exports = window.loadData = loadData
<|endoftext|>


<commit_before>define([
  'app',
  'backbone'
], function(App, Backbone) {

  var Entities = App.module('Entities');

  //==============================
  // Entities
  //==============================

  Entities.Book = Backbone.Model.extend({
    urlRoot: '/api/book/'
  });

  Entities.Books = Backbone.Collection.extend({
    model: Entities.Book,
    url: '/api/book/'
  });

  //==============================
  // API access layer
  //==============================

  var API = {
    getBookById: function(bookId) {
      var book = new Entities.Book({ id: bookId }),
        defer = $.Deferred();

      book.fetch({
        success: function(data) {
          defer.resolve(data);
        },
        error: function(data) {
          defer.resolve(undefined);
        }
      });

      return defer.promise();
    },

    getBooks: function() {
      var books = new Entities.Books(),
        defer = $.Deferred();

      books.fetch({
        success: function(data) {
          defer.resolve(data);
        },
        error: function(data) {
          defer.resolve(undefined);
        }
      });

      return defer.promise();
    }
  };

  //==============================
  // Application handlers
  //==============================

  App.reqres.setHandler('book:entity', function(bookId) {
    return API.getBookById(bookId);
  });

  App.reqres.setHandler('book:entities', function() {
    return API.getBooks();
  });

  return Entities;

});
<commit_msg>On failed fetch, reject defered instead of resolve<commit_after>define([
  'app',
  'backbone'
], function(App, Backbone) {

  var Entities = App.module('Entities');

  //==============================
  // Entities
  //==============================

  Entities.Book = Backbone.Model.extend({
    urlRoot: '/api/book/'
  });

  Entities.Books = Backbone.Collection.extend({
    model: Entities.Book,
    url: '/api/book/'
  });

  //==============================
  // API access layer
  //==============================

  var API = {
    getBookById: function(bookId) {
      var book = new Entities.Book({ id: bookId }),
        defer = $.Deferred();

      book.fetch({
        success: function(data) {
          defer.resolve(data);
        },
        error: function(data) {
          defer.reject();
        }
      });

      return defer.promise();
    },

    getBooks: function() {
      var books = new Entities.Books(),
        defer = $.Deferred();

      books.fetch({
        success: function(data) {
          defer.resolve(data);
        },
        error: function(data) {
          defer.reject();
        }
      });

      return defer.promise();
    }
  };

  //==============================
  // Application handlers
  //==============================

  App.reqres.setHandler('book:entity', function(bookId) {
    return API.getBookById(bookId);
  });

  App.reqres.setHandler('book:entities', function() {
    return API.getBooks();
  });

  return Entities;

});
<|endoftext|>