<commit_before>var UTIL = require("../util");
var GeoObject = require("../object").GeoObject;
var WS_UTIL = require("./util");
var Schema = require("../feature/schema").Schema;
var Filter = require("../filter").Filter;
var Projection = require("../proj").Projection;

var geotools = Packages.org.geotools;
var DefaultQuery = geotools.data.DefaultQuery;
var Transaction = geotools.data.Transaction;
var DefaultTransaction = geotools.data.DefaultTransaction;

/** api: (define)
 *  module = workspace
 *  class = Workspace
 */
var Workspace = UTIL.extend(GeoObject, {

    /** api: constructor
     *  .. class:: Workspace
     *
     *      A Workspace instance should not be created directly.
     *      Create an instance of a Workspace subclass instead.
     */
    constructor: function Workspace(config) {
        if (config) {
            UTIL.applyIf(this, config);
            this._store = this._create(config);
        }
    },

    /** private: method[_create]
     *  :arg config: ``Object``
     *  :returns: ``org.geotools.data.AbstractDataStore?``
     *
     *  Create the underlying store for the workspace.
     */
    _create: function(config) {
        throw new Error("Workspace subclasses must implement _create.");
    },

    /** api: property[names]
     *  ``Array``
     *  The available layer names in the workspace.
     */
    get names() {
        var _names = this._store.getTypeNames();
        var len = _names.length;
        var names = new Array(len);
        for (var i=0; i<len; ++i) {
            names[i] = String(_names[i]);
        }
        return names;
    },

    /** api: method[get]
     *  :arg name: ``String`` Layer name.
     *  :returns: :class:`layer.Layer`
     *
     *  Get a layer by name.  Returns ``undefined`` if name doesn't correspond
     *  to a layer source in the workspace.
     */
    get: function(name) {
        var layer;
        if (this.names.indexOf(name) >= 0) {
            try {
                var _source = this._store.getFeatureSource(name);
            } catch (err) {
                throw new Error("Failed to create layer from source named '" + name + "'.");
            }
            var Layer = require("../layer").Layer;
            layer = Layer.from_(_source, this);
        }
        return layer;
    },

    /** api: property[layers]
     *  ``Array``
     *  The available layers in the workspace.
     */
    get layers() {
        var layers = [];
        this.names.forEach(function(name) {
            try {
                var layer = this.get(name);
                if (layer) {
                    layers.push(layer);
                }
            } catch (err) {
                // pass
            }
        }, this);
        return layers;
    },

    /** private: method[_createSource]
     *  :arg _schema:
     *  :returns: ``FeatureSource``
     */
    _createSource: function(_schema, type) {
        this._store.createSchema(_schema);
        return this._store.getFeatureSource(_schema.getName());
    },

    /** api: method[add]
     *  :arg layer: :class:`layer.Layer` The layer to be added.
     *  :arg options: ``Object`` Options for adding the layer.
     *
     *  Options:
     *   * `name`: ``String`` Name for the new layer.
     *   * `filter`: :class:`filter.Filter` Filter to apply to features before adding.
     *   * `projection: :class:`proj.Projection` Destination projection for the layer.
     *
     *  :returns: :class:`layer.Layer`
     *
     *  Create a new layer in this workspace with the features from an existing
     *  layer.  If a layer with the same name already exists in this workspace,
     *  you must provide a new name for the layer.
     */
    add: function(layer, options) {
        var Layer = require("../layer").Layer;
        options = options || {};

        var filter = options.filter || Filter.PASS;
        if (!(filter instanceof Filter)) {
            filter = new Filter(filter);
        }

        var name = options.name || layer.name;
        if (this.get(name)) {
            throw new Error("A layer named '" + options.name + "' already exists in the workspace.");
        }

        var projection = options.projection;
        if (projection && !(projection instanceof Projection)) {
            projection = new Projection(projection);
        }

        // clone the schema, optionally changing geometry projection
        var geomField = layer.schema.geometry;
        var schema = layer.schema.clone({
            name: options.name,
            fields: [{
                name: geomField.name,
                type: geomField.type,
                projection: projection || geomField.projection
            }]
        });

        var _source = this._createSource(schema._schema);

        var query = new DefaultQuery(layer.name, filter._filter);
        if (projection) {
            if (layer.projection) {
                query.setCoordinateSystem(layer.projection._projection);
            }
            query.setCoordinateSystemReproject(projection._projection);
        }

        var reader = layer._source.getDataStore().getFeatureReader(query, Transaction.AUTO_COMMIT);
        var transaction = new DefaultTransaction();
        var writer = _source.getDataStore().getFeatureWriterAppend(schema._schema.getName(), transaction);
        var inFeature, outFeature, geom;

        try {
            while (reader.hasNext()) {
                inFeature = reader.next();
                outFeature = writer.next();
                outFeature.setAttributes(inFeature.getAttributes());

                // mask empty geometry or PostGIS will complain
                geom = outFeature.getDefaultGeometry();
                if (geom != null && geom.isEmpty()) {
                    outFeature.setDefaultGeometry(null);
                }

                writer.write();
            }
            transaction.commit();
        } finally {
            // TODO deal with failures closing and before
            transaction.close();
        }

        return Layer.from_(_source, this);
    },

    /** private: method[_onFeatureAdd]
     *  :arg feature: :class:`feature.Feature`
     *
     *  Do any specific processing on a feature before it is added to a layer.
     */
    _onFeatureAdd: function(feature) {
        // pass
    },

    /** private: property[config]
     */
    get config() {
        return {
            type: this.constructor.name
        };
    },

    /** api: method[close]
     *
     *  Close the workspace.  This discards any existing connection to the
     *  underlying data store and discards the reference to the store.
     */
    close: function() {
        if (this._store) {
            this._store.dispose();
            delete this._store;
        }
    },

    /** private: method[toFullString]
     */
    toFullString: function() {
        return '["' + this.names.join('", "') + '"]';
    }

});

/** private: staticmethod[from_]
 *  :arg _store: ``org.geotools.data.DataStore`` A GeoTools store.
 *  :returns: :class`Workspace`
 *
 *  Create a geoscript workspace object from a GeoTools store.
 */
Workspace.from_ = function(_store) {
    var workspace;
    try {
        workspace = WS_UTIL.from_(_store);
    } catch (err) {
        // as a fallback, use a generic workspace and hope for the best
        workspace = new Workspace();
        workspace._store = _store;
    }
    return workspace;
};

exports.Workspace = Workspace;
<commit_msg>Correct name in error message.<commit_after>var UTIL = require("../util");
var GeoObject = require("../object").GeoObject;
var WS_UTIL = require("./util");
var Schema = require("../feature/schema").Schema;
var Filter = require("../filter").Filter;
var Projection = require("../proj").Projection;

var geotools = Packages.org.geotools;
var DefaultQuery = geotools.data.DefaultQuery;
var Transaction = geotools.data.Transaction;
var DefaultTransaction = geotools.data.DefaultTransaction;

/** api: (define)
 *  module = workspace
 *  class = Workspace
 */
var Workspace = UTIL.extend(GeoObject, {

    /** api: constructor
     *  .. class:: Workspace
     *
     *      A Workspace instance should not be created directly.
     *      Create an instance of a Workspace subclass instead.
     */
    constructor: function Workspace(config) {
        if (config) {
            UTIL.applyIf(this, config);
            this._store = this._create(config);
        }
    },

    /** private: method[_create]
     *  :arg config: ``Object``
     *  :returns: ``org.geotools.data.AbstractDataStore?``
     *
     *  Create the underlying store for the workspace.
     */
    _create: function(config) {
        throw new Error("Workspace subclasses must implement _create.");
    },

    /** api: property[names]
     *  ``Array``
     *  The available layer names in the workspace.
     */
    get names() {
        var _names = this._store.getTypeNames();
        var len = _names.length;
        var names = new Array(len);
        for (var i=0; i<len; ++i) {
            names[i] = String(_names[i]);
        }
        return names;
    },

    /** api: method[get]
     *  :arg name: ``String`` Layer name.
     *  :returns: :class:`layer.Layer`
     *
     *  Get a layer by name.  Returns ``undefined`` if name doesn't correspond
     *  to a layer source in the workspace.
     */
    get: function(name) {
        var layer;
        if (this.names.indexOf(name) >= 0) {
            try {
                var _source = this._store.getFeatureSource(name);
            } catch (err) {
                throw new Error("Failed to create layer from source named '" + name + "'.");
            }
            var Layer = require("../layer").Layer;
            layer = Layer.from_(_source, this);
        }
        return layer;
    },

    /** api: property[layers]
     *  ``Array``
     *  The available layers in the workspace.
     */
    get layers() {
        var layers = [];
        this.names.forEach(function(name) {
            try {
                var layer = this.get(name);
                if (layer) {
                    layers.push(layer);
                }
            } catch (err) {
                // pass
            }
        }, this);
        return layers;
    },

    /** private: method[_createSource]
     *  :arg _schema:
     *  :returns: ``FeatureSource``
     */
    _createSource: function(_schema, type) {
        this._store.createSchema(_schema);
        return this._store.getFeatureSource(_schema.getName());
    },

    /** api: method[add]
     *  :arg layer: :class:`layer.Layer` The layer to be added.
     *  :arg options: ``Object`` Options for adding the layer.
     *
     *  Options:
     *   * `name`: ``String`` Name for the new layer.
     *   * `filter`: :class:`filter.Filter` Filter to apply to features before adding.
     *   * `projection: :class:`proj.Projection` Destination projection for the layer.
     *
     *  :returns: :class:`layer.Layer`
     *
     *  Create a new layer in this workspace with the features from an existing
     *  layer.  If a layer with the same name already exists in this workspace,
     *  you must provide a new name for the layer.
     */
    add: function(layer, options) {
        var Layer = require("../layer").Layer;
        options = options || {};

        var filter = options.filter || Filter.PASS;
        if (!(filter instanceof Filter)) {
            filter = new Filter(filter);
        }

        var name = options.name || layer.name;
        if (this.get(name)) {
            throw new Error("A layer named '" + name + "' already exists in the workspace.");
        }

        var projection = options.projection;
        if (projection && !(projection instanceof Projection)) {
            projection = new Projection(projection);
        }

        // clone the schema, optionally changing geometry projection
        var geomField = layer.schema.geometry;
        var schema = layer.schema.clone({
            name: options.name,
            fields: [{
                name: geomField.name,
                type: geomField.type,
                projection: projection || geomField.projection
            }]
        });

        var _source = this._createSource(schema._schema);

        var query = new DefaultQuery(layer.name, filter._filter);
        if (projection) {
            if (layer.projection) {
                query.setCoordinateSystem(layer.projection._projection);
            }
            query.setCoordinateSystemReproject(projection._projection);
        }

        var reader = layer._source.getDataStore().getFeatureReader(query, Transaction.AUTO_COMMIT);
        var transaction = new DefaultTransaction();
        var writer = _source.getDataStore().getFeatureWriterAppend(schema._schema.getName(), transaction);
        var inFeature, outFeature, geom;

        try {
            while (reader.hasNext()) {
                inFeature = reader.next();
                outFeature = writer.next();
                outFeature.setAttributes(inFeature.getAttributes());

                // mask empty geometry or PostGIS will complain
                geom = outFeature.getDefaultGeometry();
                if (geom != null && geom.isEmpty()) {
                    outFeature.setDefaultGeometry(null);
                }

                writer.write();
            }
            transaction.commit();
        } finally {
            // TODO deal with failures closing and before
            transaction.close();
        }

        return Layer.from_(_source, this);
    },

    /** private: method[_onFeatureAdd]
     *  :arg feature: :class:`feature.Feature`
     *
     *  Do any specific processing on a feature before it is added to a layer.
     */
    _onFeatureAdd: function(feature) {
        // pass
    },

    /** private: property[config]
     */
    get config() {
        return {
            type: this.constructor.name
        };
    },

    /** api: method[close]
     *
     *  Close the workspace.  This discards any existing connection to the
     *  underlying data store and discards the reference to the store.
     */
    close: function() {
        if (this._store) {
            this._store.dispose();
            delete this._store;
        }
    },

    /** private: method[toFullString]
     */
    toFullString: function() {
        return '["' + this.names.join('", "') + '"]';
    }

});

/** private: staticmethod[from_]
 *  :arg _store: ``org.geotools.data.DataStore`` A GeoTools store.
 *  :returns: :class`Workspace`
 *
 *  Create a geoscript workspace object from a GeoTools store.
 */
Workspace.from_ = function(_store) {
    var workspace;
    try {
        workspace = WS_UTIL.from_(_store);
    } catch (err) {
        // as a fallback, use a generic workspace and hope for the best
        workspace = new Workspace();
        workspace._store = _store;
    }
    return workspace;
};

exports.Workspace = Workspace;
<|endoftext|>


<commit_before>var gl;
var program;
var transY1 = 0.0;
var transY2 = 0.0;

var transYLoc;

var keys = {};

var leftpaddle, rightpaddle, ball;

function initObjects() {
  leftpaddle = {
    x: -0.875,
    y: 0,
    w: 0.05,
    h: 0.5,
    speed: 0,
    vertices: [
      vec2(-0.9, 0.25),
      vec2(-0.85, 0.25),
      vec2(-0.85, -0.25),
      vec2(-0.9, -0.25)
    ]
  };

  rightpaddle = {
    x: 0,
    y: 0,
    w: 0.05,
    h: 0.5,
    speed: 0,
    vertices: [
      vec2(0.85, 0.25),
      vec2(0.9, 0.25),
      vec2(0.9, -0.25),
      vec2(0.85, -0.25)
    ]
  };

  ball = {
    x: 0,
    y: 0,
    w: 0.04,
    h: 0.04,
    speed: 0,
    vertices: [
      vec2(-0.02, 0.02),
      vec2(0.02, 0.02),
      vec2(0.02, -0.02),
      vec2(-0.02, -0.02)
    ]
  };
}

function initGL(){
  var canvas = document.getElementById( "canvas" );

  gl = WebGLUtils.setupWebGL( canvas );
  if ( !gl ) { alert( "WebGL isn't available" ); }

  gl.viewport( 0, 0, 800, 800);
  gl.clearColor( 0.0, 0.0, 0.0, 1.0 );

  initObjects();

  program = initShaders( gl, "vertex-shader", "fragment-shader" );
  gl.useProgram( program );

  var vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

  var vertexPositionLoc = gl.getAttribLocation(program, "vertexPosition");
  gl.vertexAttribPointer(vertexPositionLoc, 2, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(vertexPositionLoc);

  transYLoc = gl.getUniformLocation(program, "transY");

  render();
}

function render() {
  gl.clear(gl.COLOR_BUFFER_BIT);

  renderLeftPaddle();
  renderBall();
  renderRightPaddle();

  var fragColorLoc = gl.getUniformLocation(program, "fragColor");
  gl.uniform4f(fragColorLoc, 1.0, 1.0, 1.0, 1.0);

  keyUpdate();

  requestAnimFrame(render);
}

function renderLeftPaddle() {
  gl.bufferData(gl.ARRAY_BUFFER, flatten(leftpaddle.vertices), gl.STATIC_DRAW);
  gl.uniform1f(transYLoc, transY1);
  gl.drawArrays(gl.TRIANGLE_FAN, 0, leftpaddle.vertices.length);
}

function renderRightPaddle() {
  gl.bufferData(gl.ARRAY_BUFFER, flatten(rightpaddle.vertices), gl.STATIC_DRAW);
  gl.uniform1f(transYLoc, transY2);
  gl.drawArrays(gl.TRIANGLE_FAN, 0, rightpaddle.vertices.length);
}

function renderBall() {
  gl.bufferData(gl.ARRAY_BUFFER, flatten(ball.vertices), gl.STATIC_DRAW);
  gl.uniform1f(transYLoc, 0);
  gl.drawArrays(gl.TRIANGLE_FAN, 0, ball.vertices.length);
}

function keyUpdate() {
  if(keys[87]) transY1 += 0.05;
  if(keys[83]) transY1 -= 0.05;

  if(keys[38]) transY2 += 0.05;
  if(keys[40]) transY2 -= 0.05;
}

function keyDown(event) {
  keys[event.keyCode] = true;
}

function keyUp(event) {
  keys[event.keyCode] = false;
}
<commit_msg>Top/Bottom collision<commit_after>var gl;
var program;

var transY1 = 0.0;
var transY2 = 0.0;

var transYLoc;

var keys = {};

var leftpaddle, rightpaddle, ball;

function initObjects() {
  leftpaddle = {
    x: -0.875,
    y: 0,
    w: 0.05,
    h: 0.5,
    speed: 0,
    vertices: [
      vec2(-0.9, 0.25),
      vec2(-0.85, 0.25),
      vec2(-0.85, -0.25),
      vec2(-0.9, -0.25)
    ]
  };

  rightpaddle = {
    x: 0,
    y: 0,
    w: 0.05,
    h: 0.5,
    speed: 0,
    vertices: [
      vec2(0.85, 0.25),
      vec2(0.9, 0.25),
      vec2(0.9, -0.25),
      vec2(0.85, -0.25)
    ]
  };

  ball = {
    x: 0,
    y: 0,
    w: 0.04,
    h: 0.04,
    speed: 0,
    vertices: [
      vec2(-0.02, 0.02),
      vec2(0.02, 0.02),
      vec2(0.02, -0.02),
      vec2(-0.02, -0.02)
    ]
  };
}

function initGL(){
  var canvas = document.getElementById( "canvas" );

  gl = WebGLUtils.setupWebGL( canvas );
  if ( !gl ) { alert( "WebGL isn't available" ); }

  gl.viewport( 0, 0, 800, 800);
  gl.clearColor( 0.0, 0.0, 0.0, 1.0 );

  initObjects();

  program = initShaders( gl, "vertex-shader", "fragment-shader" );
  gl.useProgram( program );

  var vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

  var vertexPositionLoc = gl.getAttribLocation(program, "vertexPosition");
  gl.vertexAttribPointer(vertexPositionLoc, 2, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(vertexPositionLoc);

  transYLoc = gl.getUniformLocation(program, "transY");

  render();
}

function render() {
  gl.clear(gl.COLOR_BUFFER_BIT);

  renderLeftPaddle();
  renderBall();
  renderRightPaddle();

  var fragColorLoc = gl.getUniformLocation(program, "fragColor");
  gl.uniform4f(fragColorLoc, 1.0, 1.0, 1.0, 1.0);

  keyUpdate();
  ballCollisionUpdate();

  requestAnimFrame(render);
}

function renderLeftPaddle() {
  gl.bufferData(gl.ARRAY_BUFFER, flatten(leftpaddle.vertices), gl.STATIC_DRAW);
  gl.uniform1f(transYLoc, transY1);
  gl.drawArrays(gl.TRIANGLE_FAN, 0, leftpaddle.vertices.length);
}

function renderRightPaddle() {
  gl.bufferData(gl.ARRAY_BUFFER, flatten(rightpaddle.vertices), gl.STATIC_DRAW);
  gl.uniform1f(transYLoc, transY2);
  gl.drawArrays(gl.TRIANGLE_FAN, 0, rightpaddle.vertices.length);
}

var foo = 0;
var meow = 1;

function renderBall() {
  gl.bufferData(gl.ARRAY_BUFFER, flatten(ball.vertices), gl.STATIC_DRAW);
  gl.uniform1f(transYLoc, ball.y);
  gl.drawArrays(gl.TRIANGLE_FAN, 0, ball.vertices.length);
  foo = 0.01 * meow;
  ball.y = ball.y + foo;
}

function ballCollisionUpdate() {
  console.log(foo);
  console.log(ball.y);
  if(ball.y > 1) {
    meow = -1;
  }
  if(ball.y < -1) {
    meow = 1;
  }
}

function keyUpdate() {
  if(keys[87]) transY1 += 0.05;
  if(keys[83]) transY1 -= 0.05;

  if(keys[38]) transY2 += 0.05;
  if(keys[40]) transY2 -= 0.05;
}

function keyDown(event) {
  keys[event.keyCode] = true;
}

function keyUp(event) {
  keys[event.keyCode] = false;
}
<|endoftext|>


<commit_before>//Javascript Basic Exercises | http://www.w3resource.com/javascript-exercises/javascript-basic-exercises.php
//Exercise 1

$('#timeButton').on('click', function() {

  var date = new Date();
  showTime(date)

})

function showTime(date) {
  var elToClear = '#time'
  clear(elToClear)
  var today = date.getDay();
  var daysArr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  var hours = date.getHours();
  var regHours = hours - 12;
  var minutes = fixMinutes(date)
  var seconds = date.getSeconds()
  var el = ('
' + "Today is " + daysArr[today] + " and the time is " + regHours + ":" + minutes + " p.m." + " and " + seconds + " seconds." + '
')

  $('#ex1').after(el)
}

function fixMinutes(date) {

  if (date.getMinutes() < 10) {

    var minutes = '0' +  date.getMinutes().toString()
    return minutes;
  }
}

function clear(data) {

  $(data).remove()

}
<commit_msg>debugged error with minutes beyond 9 displaying as undefined<commit_after>//Javascript Basic Exercises | http://www.w3resource.com/javascript-exercises/javascript-basic-exercises.php
//Exercise 1

$('#timeButton').on('click', function() {

  var date = new Date();
  showTime(date)

})

function showTime(date) {
  var elToClear = '#time'
  clear(elToClear)
  var today = date.getDay();
  var daysArr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  var hours = date.getHours();
  var regHours = hours - 12;

  if (date.getMinutes() < 10) { fixMinutes(date) } else { var minutes = date.getMinutes() }

  var seconds = date.getSeconds()
  var el = ('
' + "Today is " + daysArr[today] + " and the time is " + regHours + ":" + minutes + " p.m." + " and " + seconds + " seconds." + '
')

  $('#ex1').after(el)
}

function fixMinutes(date) {

  if (date.getMinutes() < 10) {

    var minutes = '0' +  date.getMinutes().toString()
    return minutes;
  }
}

function clear(data) {

  $(data).remove()

}
<|endoftext|>


<commit_before>const express = require('express');
const usersController = require(__dirname+'/../controllers/resources/users_controller.js');
const externalAccountsController = require(__dirname+'/../controllers/resources/external_accounts_controller.js');
const externalTransactionsController = require(__dirname+'/../controllers/resources/external_transactions_controller.js');
const rippleAddressesController = require(__dirname+'/../controllers/resources/ripple_addresses_controller.js');
const rippleTransactionsController = require(__dirname+'/../controllers/resources/ripple_transactions_controller.js');
const policiesController = require(__dirname+'/../controllers/resources/policies_controller.js');

var router = new express.Router();

router.post('/users', usersController.create);
router.get('/users', usersController.index);
router.get('/users/:id', usersController.show);
router.put('/users/:id', usersController.update);
router.delete('/users/:id', usersController.destroy);

router.post('/external_accounts', externalAccountsController.create);
router.get('/external_accounts', externalAccountsController.index);
router.get('/external_accounts/:id', externalAccountsController.show);
router.put('/external_accounts/:id', externalAccountsController.update);
router.delete('/external_accounts/:id', externalAccountsController.destroy);

router.post('/external_transactions', externalTransactionsController.create);
router.get('/external_transactions', externalTransactionsController.index);
router.get('/external_transactions/:id', externalTransactionsController.show);
router.put('/external_transactions/:id', externalTransactionsController.update);
router.delete('/external_transactions/:id', externalTransactionsController.destroy);

router.get('/ripple_addresses', rippleAddressesController.index);
router.get('/ripple_addresses/:id', rippleAddressesController.show);
router.post('/ripple_addresses', rippleAddressesController.create);
router.put('/ripple_addresses', rippleAddressesController.update);
router.delete('/ripple_addresses', rippleAddressesController.destroy);

router.get('/ripple_transactions', rippleTransactionsController.index);
router.get('/ripple_transactions/:id', rippleTransactionsController.show);
router.post('/ripple_transactions', rippleTransactionsController.create);
router.put('/ripple_transactions', rippleTransactionsController.update);
router.delete('/ripple_transactions', rippleTransactionsController.destroy);

router.get('/policies', policiesController.index);
router.get('/policies/:id', policiesController.show);
router.post('/policies', policiesController.create);
router.put('/policies', policiesController.update);
router.delete('/policies', policiesController.destroy);

module.exports = router;

<commit_msg>[FIX] Match correct routes to controllers methods<commit_after>const express = require('express');
const usersController = require(__dirname+'/../controllers/resources/users_controller.js');
const externalAccountsController = require(__dirname+'/../controllers/resources/external_accounts_controller.js');
const externalTransactionsController = require(__dirname+'/../controllers/resources/external_transactions_controller.js');
const rippleAddressesController = require(__dirname+'/../controllers/resources/ripple_addresses_controller.js');
const rippleTransactionsController = require(__dirname+'/../controllers/resources/ripple_transactions_controller.js');
const policiesController = require(__dirname+'/../controllers/resources/policies_controller.js');

var router = new express.Router();

router.post('/users', usersController.create);
router.get('/users', usersController.index);
router.get('/users/:id', usersController.show);
router.put('/users/:id', usersController.update);
router.delete('/users/:id', usersController.destroy);

router.post('/external_accounts', externalAccountsController.create);
router.get('/external_accounts', externalAccountsController.index);
router.get('/external_accounts/:id', externalAccountsController.show);
router.put('/external_accounts/:id', externalAccountsController.update);
router.delete('/external_accounts/:id', externalAccountsController.destroy);

router.post('/external_transactions', externalTransactionsController.create);
router.get('/external_transactions', externalTransactionsController.index);
router.get('/external_transactions/:id', externalTransactionsController.show);
router.put('/external_transactions/:id', externalTransactionsController.update);
router.delete('/external_transactions/:id', externalTransactionsController.destroy);

router.get('/ripple_addresses', rippleAddressesController.index);
router.get('/ripple_addresses/:id', rippleAddressesController.show);
router.post('/ripple_addresses', rippleAddressesController.create);
router.put('/ripple_addresses/:id', rippleAddressesController.update);
router.delete('/ripple_addresses/:id', rippleAddressesController.destroy);

router.get('/ripple_transactions', rippleTransactionsController.index);
router.get('/ripple_transactions/:id', rippleTransactionsController.show);
router.post('/ripple_transactions', rippleTransactionsController.create);
router.put('/ripple_transactions/:id', rippleTransactionsController.update);
router.delete('/ripple_transactions/:id', rippleTransactionsController.destroy);

router.get('/policies', policiesController.index);
router.get('/policies/:id', policiesController.show);
router.post('/policies', policiesController.create);
router.put('/policies/:id', policiesController.update);
router.delete('/policies/:id', policiesController.destroy);

module.exports = router;

<|endoftext|>


<commit_before>var chess = require('chess'),
    twilio = require('twilio'),
    express = require('express'),
    qs = require('querystring'),
    uuid = require('node-uuid');

var renderBoard = require('./lib/chess-renderer.js').renderBoard;

twilioClient = twilio('AC7bb2f43a783c6c974a8571d786605fa2', process.env.AUTH_TOKEN);

var app = express();

// create a game client
var board = chess.create(),
    m = null,
    status = null;

// look at the valid moves
status = board.getStatus();

console.log(renderBoard(status));

// make a move
m = board.move('a4');

// look at the status again after the move to see
// the opposing side's available moves
status = board.getStatus();

/*
twilio.sendMessage({

  to:'+16515556677', // Any number Twilio can deliver to
  from: '+14506667788', // A number you bought from Twilio and can use for outbound communication
  body: 'word to your mother.' // body of the SMS message

}, function(err, responseData) { //this function is executed when a response is received from Twilio

  if (!err) { // "err" is an error received during the request, if any

    "responseData" is a JavaScript object containing data received from Twilio.
      // A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript):
      // http://www.twilio.com/docs/api/rest/sending-sms#example-1

      console.log(responseData.from); // outputs "+14506667788"
    console.log(responseData.body); // outputs "word to your mother."

  }
});
*/
var phoneNumbers = {};

var games = {};
app.post('/sms/reply/', function (req, res) {
  var body = '';

  req.on('data', function (data) {
    body += data;
  });

  req.on('end', function () {

    var POST = qs.parse(body);

    console.log('text body', POST);

    //validate incoming request is from twilio using your auth token and the header from Twilio
    var token = process.env.AUTH_TOKEN,
    header = req.headers['x-twilio-signature'];

    //validateRequest returns true if the request originated from Twilio
    if (twilio.validateRequest(token, header, 'http://nicki.fn.lc:8183/sms/reply/', POST)) {

        //generate a TwiML response
        var resp = new twilio.TwimlResponse();
        var respMessage = '';

        if(!phoneNumbers.hasOwnProperty(POST.To)){
          phoneNumbers[POST.To] = {
            gameId: uuid.v1(),
          };

          var currGameId = phoneNumbers[POST.To].gameId;

          //create new game
          games[currGameId] = {
            board: chess.create(),
            players: [],
          };
          games[currGameId].players.push(POST.To);

          respMessage = 'Add your friends phone # to start a game';

        }

        else{
          var currGame = games[phoneNumbers[POST.To].gameId];
          var smsBody = POST.Body.replace(/^\s+|\s+$/g, '');

          //Check if we should add opponent or not
          if(currGame.players.length === 1){

            //Add person
            if(smsBody.length === 10){
              currGame.players.push(smsBody);
              respMessage = 'Opponent with # '+smsBody+' successfully added';
            }else {
              respMessage = 'incorrect number. Try adding a correct friends #';
            }
          }
          //Play Chess Game
          else{
            //If we lose or stalemate
            if(currGame.board.isCheckmate || currGame.board.isStalemate){
              //remove game
              delete game[phoneNumbers[POST.To].gameId];

              if(currGame.board.isCheckmate){
                respMessage = 'Checkmate. Game Over'
              }else {
                respMessage = 'Stalemate. Gameover'
              }
            }
            //If we aren't losing
            else{

              //if we have a valid message
              //TODO: need to do proper validation
              if(smsBody.length > 4){

                console.log(smsBody);
                console.log(smsBody.slice(1,3));
                //If we have a move command
                if(smsBody.slice(1,3) === 'to'){
                  var piece_pos = smsBody.slice(0,1);

                  var move_pos = smsBody.reverse().slice(0,1);

                    //Error message
                    try{
                      currGame.board.move(piece_pos, move_pos);
                    }catch(err){
                      resp.message('Error'+err.message);
                      res.writeHead(200, { 'Content-Type':'text/xml' });
                      res.end(resp.toString());
                      return;
                    }
                    resp.message('Piece moved from '+piece_pos+' to '+move_pos);
                }else if(smsBody.slice(0,4) === 'undo'){
                  currGame.board.undo();
                  resp.message('Move successfully undo');
                }
              }else{

                respMessage = 'Board\n' + renderBoard(currGame.board.getStatus());
              }
            }
          }

        }

      resp.message(respMessage);
      //Write headers
      res.writeHead(200, { 'Content-Type':'text/xml' });
      res.end(resp.toString());
    }else {
      res.writeHead(403, { 'Content-Type':'text/plain' });
      res.end('you are not twilio - take a hike.');
    }
  });
});

var server = app.listen(8183, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('CheSMS listening at http://%s:%s', host, port);
});
<commit_msg>added console.log for smsBody<commit_after>var chess = require('chess'),
    twilio = require('twilio'),
    express = require('express'),
    qs = require('querystring'),
    uuid = require('node-uuid');

var renderBoard = require('./lib/chess-renderer.js').renderBoard;

twilioClient = twilio('AC7bb2f43a783c6c974a8571d786605fa2', process.env.AUTH_TOKEN);

var app = express();

// create a game client
var board = chess.create(),
    m = null,
    status = null;

// look at the valid moves
status = board.getStatus();

console.log(renderBoard(status));

// make a move
m = board.move('a4');

// look at the status again after the move to see
// the opposing side's available moves
status = board.getStatus();

/*
twilio.sendMessage({

  to:'+16515556677', // Any number Twilio can deliver to
  from: '+14506667788', // A number you bought from Twilio and can use for outbound communication
  body: 'word to your mother.' // body of the SMS message

}, function(err, responseData) { //this function is executed when a response is received from Twilio

  if (!err) { // "err" is an error received during the request, if any

    "responseData" is a JavaScript object containing data received from Twilio.
      // A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript):
      // http://www.twilio.com/docs/api/rest/sending-sms#example-1

      console.log(responseData.from); // outputs "+14506667788"
    console.log(responseData.body); // outputs "word to your mother."

  }
});
*/
var phoneNumbers = {};

var games = {};
app.post('/sms/reply/', function (req, res) {
  var body = '';

  req.on('data', function (data) {
    body += data;
  });

  req.on('end', function () {

    var POST = qs.parse(body);

    console.log('text body', POST);

    //validate incoming request is from twilio using your auth token and the header from Twilio
    var token = process.env.AUTH_TOKEN,
    header = req.headers['x-twilio-signature'];

    //validateRequest returns true if the request originated from Twilio
    if (twilio.validateRequest(token, header, 'http://nicki.fn.lc:8183/sms/reply/', POST)) {

        //generate a TwiML response
        var resp = new twilio.TwimlResponse();
        var respMessage = '';

        if(!phoneNumbers.hasOwnProperty(POST.To)){
          phoneNumbers[POST.To] = {
            gameId: uuid.v1(),
          };

          var currGameId = phoneNumbers[POST.To].gameId;

          //create new game
          games[currGameId] = {
            board: chess.create(),
            players: [],
          };
          games[currGameId].players.push(POST.To);

          respMessage = 'Add your friends phone # to start a game';

        }

        else{
          var currGame = games[phoneNumbers[POST.To].gameId];
          var smsBody = POST.Body.replace(/^\s+|\s+$/g, '');

          //Check if we should add opponent or not
          if(currGame.players.length === 1){

            //Add person
            if(smsBody.length === 10){
              currGame.players.push(smsBody);
              respMessage = 'Opponent with # '+smsBody+' successfully added';
            }else {
              respMessage = 'incorrect number. Try adding a correct friends #';
            }
          }
          //Play Chess Game
          else{
            //If we lose or stalemate
            if(currGame.board.isCheckmate || currGame.board.isStalemate){
              //remove game
              delete game[phoneNumbers[POST.To].gameId];

              if(currGame.board.isCheckmate){
                respMessage = 'Checkmate. Game Over'
              }else {
                respMessage = 'Stalemate. Gameover'
              }
            }
            //If we aren't losing
            else{

              //if we have a valid message
              //TODO: need to do proper validation
              if(smsBody.length => 4){

                console.log(smsBody);
                console.log(smsBody.slice(2,4));
                //If we have a move command
                if(smsBody.split(' ')[1] === 'to'){
                  var piece_pos = smsBody.slice(0,1);

                  var move_pos = smsBody.reverse().slice(0,1);

                    //Error message
                    try{
                      currGame.board.move(piece_pos, move_pos);
                    }catch(err){
                      resp.message('Error'+err.message);
                      res.writeHead(200, { 'Content-Type':'text/xml' });
                      res.end(resp.toString());
                      return;
                    }
                    resp.message('Piece moved from '+piece_pos+' to '+move_pos);
                }else if(smsBody.split(' ')[0] === 'undo'){
                  currGame.board.undo();
                  resp.message('Move successfully undo');
                }
              }else{

                respMessage = 'Board\n' + renderBoard(currGame.board.getStatus());
              }
            }
          }

        }

      resp.message(respMessage);
      //Write headers
      res.writeHead(200, { 'Content-Type':'text/xml' });
      res.end(resp.toString());
    }else {
      res.writeHead(403, { 'Content-Type':'text/plain' });
      res.end('you are not twilio - take a hike.');
    }
  });
});

var server = app.listen(8183, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('CheSMS listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>(function() {

var gui = require('nw.gui');
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var clj_fuzzy = require('clj-fuzzy');
var xdg = require('./xdg');
var win = gui.Window.get();

// Useful DOM objects:
var searchTextbox = document.getElementById("search");
var results = document.getElementById("results");
var footer = document.getElementById("footer");

// Execute arbitrary command, removing the XDG .desktop file specific stuff
// until we figure out what to do with them.
function executeCommand(path) {
	path = path.replace(/%[UufF]/g, "");
	console.log("Executing: " + path);
	exec(path);  // dun dun dun
	win.close();
}

// Reads a desktop file. Returns an object with an "exists" attribute as false
// if not found (because screw the idea of null!)
function fileToEntry(filename) {
	if (filename.indexOf(".desktop") != -1) {
		var contents = fs.readFileSync(filename).toString();
		var executable = xdg.extractKey(contents, "Exec");
		var title = xdg.extractKey(contents, "Name");
		var icon = xdg.extractKey(contents, "Icon");
		return {
			"title": title,
			"icon": xdg.iconToPath(icon),
			"path": executable,
			"exists": true
		}
	}
	return {"exists": false};
}

// Searches applciations directory under the data for .desktop files, and adds
// entry objects for each of them.
function addEntries(entries, dataDir) {
	var dir = path.join(dataDir, 'applications');
	if (fs.existsSync(dir)) {
		var desktopFiles = fs.readdirSync(dir);
		for (var j= 0, len = desktopFiles.length; j < len; j++) {
			entries.push(fileToEntry(path.join(dir, desktopFiles[j])));
		}
	}
}

// Filters out the first 5 entries that match the query.
function getQueryResults(entries, query) {
	if (query === "") {""
		return [];
	}
	var lowerQuery = query.toLowerCase();

	function addScore(entry) {
		var lowerTitle = entry.title.toLowerCase();
		entry.score = clj_fuzzy.metrics.jaccard(lowerTitle, lowerQuery);
		return entry;
	}

	function entryMatches(entry) {
		if (!entry.exists) {
			return false;
		}
		var lowerTitle = entry.title.toLowerCase();
		var contains = lowerQuery.indexOf(lowerTitle) != -1;
		var wildcardRegex = new RegExp(lowerQuery.split("").join(".*"), "i");
		var wildcardMatch = wildcardRegex.test(lowerTitle);
		return contains || wildcardMatch;
	}

	return entries.filter(entryMatches)
	              .map(addScore)
	              .sort(function (a, b) { return a.score - b.score; })
	              .slice(0, 5);
}

// Converts an entry number into a display string for the  appropriate shortcut.
// Currently hardcoded as "Return" for the first entry, and Alt+n for the nth
// entry. Should be configurable in the future.
function getShortcut(entryNumber) {
	if (entryNumber == 0) {
		return "\u23CE";  // return symbol
	} else {
		return "Alt+" + (entryNumber + 1);
	}
}

// Converts an entry object to HTML for display purposes
function entryToHTML(queryResult, entryNumber) {
	var elem = document.createElement("li");
	elem.className = "menu-item";

	var icon = document.createElement("img");
	icon.className = "icon";
	icon.src = queryResult.icon;

	var text = document.createElement("div");
	text.className = "text";

	var title = document.createElement("span");
	title.className = "title";
	title.appendChild(document.createTextNode(queryResult.title));
	text.appendChild(title);

	var path = document.createElement("span");
	path.className = "path";
	path.appendChild(document.createTextNode(queryResult.path));
	text.appendChild(path);

	var shortcut = document.createElement("span");
	shortcut.className = "shortcut";
	shortcut.appendChild(document.createTextNode(getShortcut(entryNumber)));

	elem.appendChild(icon);
	elem.appendChild(text);
	elem.appendChild(shortcut);

	elem.addEventListener('click', function (e) {
		executeCommand(queryResult.path);
	}, true);
	return elem;

}

// Updates the DOM with the entry objects
function updateResults(queryResults) {
	// Change elements
	while (results.hasChildNodes()) {
		results.removeChild(results.lastChild);
	}
	for (var i = 0, len = queryResults.length; i < len; i++) {
		var queryResult = queryResults[i];
		results.appendChild(entryToHTML(queryResult, i));
	}

	// Don't display footer if 1 or fewer elements.
	if (queryResults.length > 1) {
		footer.style.display = "block";
	} else {
		footer.style.display = "none";
	}
}

// Value to use as "negative"
function clearSelect() {
	return -1;
}

// User hit down, so increase the index value (maxing out at # of results)
function selectDown(highlighted) {
	return Math.min(highlighted + 1, results.childNodes.length - 1);
}

// User hit up, so decrease the index value (stopping at 0)
function selectUp(highlighted) {
	return Math.max(highlighted - 1, 0);
}

// Gets the selected application to run. If the user hit enter and something was
// highlighted via arrow keys, use that one. Otherwise, use the firs tone.
// If the user hit Alt+n, return n.
function getNumSelected(highlighted, e) {
	var selected = clearSelect();
	// Enter
	if (e.keyCode == 13) {
		selected = highlighted == clearSelect() ? 1 : highlighted + 1;
	}
	// Alt + number
	var numPressed = parseInt(String.fromCharCode(e.keyCode), 10);
	if (e.altKey && !isNaN(numPressed)) {
		selected = numPressed;
	}
	return selected;
}

// Updates the DOM to reflect the current highlighted entry.
function updateHighlighted(highlighted) {
	var numEntries = results.childNodes.length;
	for (var i = 0; i < numEntries; i++) {
		results.childNodes[i].className = 'menu-item';
		if (i == highlighted) {
			results.childNodes[i].className += ' selected';
		}
	}
}

function listenForEscapeToClose() {
	document.addEventListener('keyup', function (e) {
		if (e.keyCode == 27) {  // escape
			var win = gui.Window.get();
			win.close();
		}
	}, true);
}

function main() {
	listenForEscapeToClose();

	var highlighted = -1;  // none
	var entries = [];
	xdg.forEachDataDir(function (dataDir) {
		addEntries(entries, dataDir);
	});

	searchTextbox.addEventListener('keyup', function (e) {
		var query = e.target.value;
		var queryResults = getQueryResults(entries, query);
		updateResults(queryResults);

		if (e.keyCode == 40) {  // down arrow
			highlighted = selectDown(highlighted);
		} else if (e.keyCode == 38) {  // up arrow
			highlighted = selectUp(highlighted);
		} else if (e.keyCode != 13) {  // anything but Enter clears the selected
			highlighted = clearSelect();
		}
		updateHighlighted(highlighted);

		var numSelected = getNumSelected(highlighted, e);  // 1-based
		if (numSelected != -1 && queryResults.length >= numSelected) {
			var selectedEntry = queryResults[numSelected - 1];
			var path = selectedEntry.path;
			executeCommand(path);
		}
	}, true);

	win.on('blur', function () {
		win.close();
	}, true);
}

main();

})();<commit_msg>searchTextbox does not need to be global.<commit_after>(function() {

var gui = require('nw.gui');
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var clj_fuzzy = require('clj-fuzzy');
var xdg = require('./xdg');
var win = gui.Window.get();

// Useful DOM objects:
var results = document.getElementById("results");
var footer = document.getElementById("footer");

// Execute arbitrary command, removing the XDG .desktop file specific stuff
// until we figure out what to do with them.
function executeCommand(path) {
	path = path.replace(/%[UufF]/g, "");
	console.log("Executing: " + path);
	exec(path);  // dun dun dun
	win.close();
}

// Reads a desktop file. Returns an object with an "exists" attribute as false
// if not found (because screw the idea of null!)
function fileToEntry(filename) {
	if (filename.indexOf(".desktop") != -1) {
		var contents = fs.readFileSync(filename).toString();
		var executable = xdg.extractKey(contents, "Exec");
		var title = xdg.extractKey(contents, "Name");
		var icon = xdg.extractKey(contents, "Icon");
		return {
			"title": title,
			"icon": xdg.iconToPath(icon),
			"path": executable,
			"exists": true
		}
	}
	return {"exists": false};
}

// Searches applciations directory under the data for .desktop files, and adds
// entry objects for each of them.
function addEntries(entries, dataDir) {
	var dir = path.join(dataDir, 'applications');
	if (fs.existsSync(dir)) {
		var desktopFiles = fs.readdirSync(dir);
		for (var j= 0, len = desktopFiles.length; j < len; j++) {
			entries.push(fileToEntry(path.join(dir, desktopFiles[j])));
		}
	}
}

// Filters out the first 5 entries that match the query.
function getQueryResults(entries, query) {
	if (query === "") {""
		return [];
	}
	var lowerQuery = query.toLowerCase();

	function addScore(entry) {
		var lowerTitle = entry.title.toLowerCase();
		entry.score = clj_fuzzy.metrics.jaccard(lowerTitle, lowerQuery);
		return entry;
	}

	function entryMatches(entry) {
		if (!entry.exists) {
			return false;
		}
		var lowerTitle = entry.title.toLowerCase();
		var contains = lowerQuery.indexOf(lowerTitle) != -1;
		var wildcardRegex = new RegExp(lowerQuery.split("").join(".*"), "i");
		var wildcardMatch = wildcardRegex.test(lowerTitle);
		return contains || wildcardMatch;
	}

	return entries.filter(entryMatches)
	              .map(addScore)
	              .sort(function (a, b) { return a.score - b.score; })
	              .slice(0, 5);
}

// Converts an entry number into a display string for the  appropriate shortcut.
// Currently hardcoded as "Return" for the first entry, and Alt+n for the nth
// entry. Should be configurable in the future.
function getShortcut(entryNumber) {
	if (entryNumber == 0) {
		return "\u23CE";  // return symbol
	} else {
		return "Alt+" + (entryNumber + 1);
	}
}

// Converts an entry object to HTML for display purposes
function entryToHTML(queryResult, entryNumber) {
	var elem = document.createElement("li");
	elem.className = "menu-item";

	var icon = document.createElement("img");
	icon.className = "icon";
	icon.src = queryResult.icon;

	var text = document.createElement("div");
	text.className = "text";

	var title = document.createElement("span");
	title.className = "title";
	title.appendChild(document.createTextNode(queryResult.title));
	text.appendChild(title);

	var path = document.createElement("span");
	path.className = "path";
	path.appendChild(document.createTextNode(queryResult.path));
	text.appendChild(path);

	var shortcut = document.createElement("span");
	shortcut.className = "shortcut";
	shortcut.appendChild(document.createTextNode(getShortcut(entryNumber)));

	elem.appendChild(icon);
	elem.appendChild(text);
	elem.appendChild(shortcut);

	elem.addEventListener('click', function (e) {
		executeCommand(queryResult.path);
	}, true);
	return elem;

}

// Updates the DOM with the entry objects
function updateResults(queryResults) {
	// Change elements
	while (results.hasChildNodes()) {
		results.removeChild(results.lastChild);
	}
	for (var i = 0, len = queryResults.length; i < len; i++) {
		var queryResult = queryResults[i];
		results.appendChild(entryToHTML(queryResult, i));
	}

	// Don't display footer if 1 or fewer elements.
	if (queryResults.length > 1) {
		footer.style.display = "block";
	} else {
		footer.style.display = "none";
	}
}

// Value to use as "negative"
function clearSelect() {
	return -1;
}

// User hit down, so increase the index value (maxing out at # of results)
function selectDown(highlighted) {
	return Math.min(highlighted + 1, results.childNodes.length - 1);
}

// User hit up, so decrease the index value (stopping at 0)
function selectUp(highlighted) {
	return Math.max(highlighted - 1, 0);
}

// Gets the selected application to run. If the user hit enter and something was
// highlighted via arrow keys, use that one. Otherwise, use the firs tone.
// If the user hit Alt+n, return n.
function getNumSelected(highlighted, e) {
	var selected = clearSelect();
	// Enter
	if (e.keyCode == 13) {
		selected = highlighted == clearSelect() ? 1 : highlighted + 1;
	}
	// Alt + number
	var numPressed = parseInt(String.fromCharCode(e.keyCode), 10);
	if (e.altKey && !isNaN(numPressed)) {
		selected = numPressed;
	}
	return selected;
}

// Updates the DOM to reflect the current highlighted entry.
function updateHighlighted(highlighted) {
	var numEntries = results.childNodes.length;
	for (var i = 0; i < numEntries; i++) {
		results.childNodes[i].className = 'menu-item';
		if (i == highlighted) {
			results.childNodes[i].className += ' selected';
		}
	}
}

function listenForEscapeToClose() {
	document.addEventListener('keyup', function (e) {
		if (e.keyCode == 27) {  // escape
			var win = gui.Window.get();
			win.close();
		}
	}, true);
}

function main() {
	listenForEscapeToClose();

	var highlighted = -1;  // none
	var entries = [];
	xdg.forEachDataDir(function (dataDir) {
		addEntries(entries, dataDir);
	});

	var searchTextbox = document.getElementById("search");
	searchTextbox.addEventListener('keyup', function (e) {
		var query = e.target.value;
		var queryResults = getQueryResults(entries, query);
		updateResults(queryResults);

		if (e.keyCode == 40) {  // down arrow
			highlighted = selectDown(highlighted);
		} else if (e.keyCode == 38) {  // up arrow
			highlighted = selectUp(highlighted);
		} else if (e.keyCode != 13) {  // anything but Enter clears the selected
			highlighted = clearSelect();
		}
		updateHighlighted(highlighted);

		var numSelected = getNumSelected(highlighted, e);  // 1-based
		if (numSelected != -1 && queryResults.length >= numSelected) {
			var selectedEntry = queryResults[numSelected - 1];
			var path = selectedEntry.path;
			executeCommand(path);
		}
	}, true);

	win.on('blur', function () {
		win.close();
	}, true);
}

main();

})();<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global Tangram, gui */

(function () {
    'use strict';

    var map_start_location = [40.7238, -73.9881, 16]; // NYC

    /*** URL parsing ***/

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');

    if (url_hash.length == 3) {
        map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
        // convert from strings
        map_start_location = map_start_location.map(Number);
    }

    /*** Map ***/

    var map = L.map('map',
        {'keyboardZoomOffset': .05}
    );

    var layer = Tangram.leafletLayer({
        scene: 'scene.yaml',
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;

    map.setView(map_start_location.slice(0, 2), map_start_location[2]);

    var hash = new L.Hash(map);

    // Resize map to window
    function resizeMap() {
        document.getElementById('map').style.width = window.innerWidth + 'px';
        document.getElementById('map').style.height = window.innerHeight + 'px';
        map.invalidateSize(false);
    }

    window.addEventListener('resize', resizeMap);
    resizeMap();

    function setCamera(type) {
        if (scene.view.camera.type != type) {
            scene.config.cameras.camera1.type = type;
            scene.config.lights.light1.radius = [controllerByName("radius_inner").getValue()+"px", controllerByName("radius_outer").getValue()+"px"];
            scene.config.lights.light1.attenuation = controllerByName("attenuation").getValue();
            scene.updateConfig();
            switch(type) {
                case "perspective":
                    controllerByName("axis_toggle").setValue(false);
                    scene.view.camera.focal_length = controllerByName("focal_length").getValue();
                    break;
                case "isometric":
                    controllerByName("vanishing_point_toggle").setValue(false);
                    break;
            }
        }
    }
    function setLight(type) {
        if (scene.lights.light1.type != type) {
            scene.config.lights.light1.type = type;
            scene.config.cameras.camera1.focal_length = controllerByName("focal_length").getValue();
            scene.config.cameras.camera1.axis = {x: controllerByName("axis_x").getValue(), y: controllerByName("axis_y").getValue()};
            scene.updateConfig();
            switch(type) {
                case "directional":
                    controllerByName("point_toggle").setValue(false);
                case "point":
                    controllerByName("direction_toggle").setValue(false);
                    scene.config.lights.light1.radius = [controllerByName("radius_inner").getValue()+"px", controllerByName("radius_outer").getValue()+"px"];
                    scene.config.lights.light1.attenuation = controllerByName("attenuation").getValue();
                    scene.updateConfig();
            }
        }
    }

    function controllerByName(which) {
        for (var i = 0; i < gui.__controllers.length; i++) {
            if (gui.__controllers[i].property == which) {
                return gui.__controllers[i];
            }
        }
    }

    // GUI options for rendering modes/effects
    var controls = {
        'Perspective' : function() {
            setCamera("perspective");
        },
        'Isometric' : function() {
            setCamera("isometric");
        },
        'Flat' : function() {
            setCamera("flat");
        },
        'focal_length' : 2,
        'axis_x' : 0,
        'axis_y' : 1,
        'axis_toggle' : false,
        'vanishing_point_x' : 0,
        'vanishing_point_y' : 0,
        'vanishing_point_toggle' : false,
        'Directional' : function() {
            setLight("directional");
        },
        'direction_x' : 0,
        'direction_y' : 1,
        'direction_z' : 0,
        'direction_toggle' : false,
        'direction_diffuse' : 1,
        'direction_ambient' : .3,
        'Point' : function() {
            setLight("point");
        },
        'point_x' : 0,
        'point_y' : 0,
        'point_z' : 50,
        'point_toggle' : false,
        'point_diffuse' : 1,
        'point_ambient' : .5,
        'attenuation' : 2,
        'radius_inner' : 100,
        'radius_outer' : 250,

    };
    var vanishing_point_mouse = false;
    var axis_mouse = false;
    var directional_mouse = false;
    var point_mouse = false;
    // Create dat GUI
    var gui = new dat.GUI({ autoPlace: true, width: 300 });
    function addGUI () {
        gui.domElement.parentNode.style.zIndex = 500;
        window.gui = gui;
        var folder = gui.addFolder("Click a style:");
        folder.open(); // this just points the arrow downward

        // CAMERAS
        gui.add(controls, 'Perspective').name("Perspective Camera");
        gui.add(controls, 'focal_length', 0.1, 5).name("  focal_length").onChange(function(value) {
            setCamera("perspective");
            scene.view.camera.focal_length = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'vanishing_point_x', -1000, 1000).name("  vanishing_point x").onChange(function(value) {
            setCamera("perspective");
            scene.view.camera.vanishing_point[0] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'vanishing_point_y', -1000, 1000).name("  vanishing_point y").onChange(function(value) {
            setCamera("perspective");
            scene.view.camera.vanishing_point[1] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'vanishing_point_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setCamera("perspective");
            }
            vanishing_point_mouse = value;
        });
        gui.add(controls, 'Isometric').name("Isometric Camera");
        gui.add(controls, 'axis_x', -5, 5).name("  axis x").onChange(function(value) {
            setCamera("isometric");
            scene.view.camera.axis.x = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'axis_y', -5, 5).name("  axis y").onChange(function(value) {
            setCamera("isometric");
            scene.view.camera.axis.y = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'axis_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setCamera("isometric");
            }
            axis_mouse = value;
        });
        gui.add(controls, 'Flat').name("Flat Camera");

        // LIGHTS
        gui.add(controls, 'Directional').name("Directional Light");
        gui.add(controls, 'direction_x', -1, 1).name("  direction x").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.direction[0] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_y', -1, 1).name("  direction y").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.direction[1] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_z', -1, 1).name("  direction z").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.direction[2] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setLight("directional");
            }
            directional_mouse = value;
        });
        gui.add(controls, 'direction_diffuse', 0, 2).name("  diffuse").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.diffuse = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_ambient', 0, 1).name("  ambient").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.ambient = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'Point').name("Point Light");
        gui.add(controls, 'point_x', -1000, 1000).name("  point x").onChange(function(value) {
            setLight("point");
            scene.lights.light1.position[0] = value+"px";
            scene.requestRedraw();
        });
        gui.add(controls, 'point_y', -1000, 1000).name("  point y").onChange(function(value) {
            setLight("point");
            scene.lights.light1.position[1] = value+"px";
            scene.requestRedraw();
        });
        gui.add(controls, 'point_z', -1000, 1000).name("  point z").onChange(function(value) {
            setLight("point");
            scene.lights.light1.position[2] = value+"px";
            scene.requestRedraw();
        });
        gui.add(controls, 'point_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setLight("point");
            }
            point_mouse = value;
        });
        gui.add(controls, 'point_diffuse', 0, 2).name("  diffuse").onChange(function(value) {
            setLight("point");
            scene.lights.light1.diffuse = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'point_ambient', 0, 1).name("  ambient").onChange(function(value) {
            setLight("point");
            scene.lights.light1.ambient = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'attenuation', 0, 10).name("  attenuation").onChange(function(value) {
            setLight("point");
            scene.lights.light1.attenuation = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'radius_inner', 0, 500).name("  radius_inner").onChange(function(value) {
            setLight("point");
            scene.lights.light1.radius = [value+"px", (scene.lights.light1.radius === null) ? 0 : scene.lights.light1.radius[1]];
            scene.requestRedraw();
        });
        gui.add(controls, 'radius_outer', 0, 500).name("  radius_outer").onChange(function(value) {
            setLight("point");
            scene.lights.light1.radius = [(scene.lights.light1.radius === null) ? 0 : scene.lights.light1.radius[0], value+"px"];
            scene.requestRedraw();
        });

    }

    // mouse position listener

    var mouse_monitor = function(e) {
        var height = document.body.clientHeight;
        var width = document.body.clientWidth;

        var x = e.clientX;
        var y = e.clientY;
        var xpos = ((x - (width / 2)));
        var ypos = ((y - (height / 2)))*-1.;
        var xpercent = x/width * 2. - 1.;
        var ypercent = y/height * 2. - 1.;

        if (vanishing_point_mouse) {
            scene.view.camera.vanishing_point = [xpos,ypos];
            gui.__controllers[2].setValue(scene.view.camera.vanishing_point[0]);
            gui.__controllers[3].setValue(scene.view.camera.vanishing_point[1]);
            scene.requestRedraw();
        }
        if (axis_mouse) {
            scene.view.camera.axis = {x: xpos/(width/5), y: ypos/(height/5)};
            gui.__controllers[6].setValue(scene.view.camera.axis.x);
            gui.__controllers[7].setValue(scene.view.camera.axis.y);
            scene.requestRedraw();
        }
        if (directional_mouse) {
            scene.lights.light1.direction = [xpercent,ypercent*-1,scene.lights.light1.direction[2]];
            gui.__controllers[11].setValue(scene.lights.light1.direction[0]);
            gui.__controllers[12].setValue(scene.lights.light1.direction[1]);
            scene.requestRedraw();
        }
        if (point_mouse) {
            scene.lights.light1.position = [xpos,ypos,scene.lights.light1.position[2]];
            gui.__controllers[18].setValue(scene.lights.light1.position[0]);
            gui.__controllers[19].setValue(scene.lights.light1.position[1]);
            scene.requestRedraw();
        }

    }

    window.onload = function() {
      this.addEventListener('mousemove', mouse_monitor);
    }

    /***** Render loop *****/
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
            addGUI();
        });
        layer.addTo(map);

    });

}());
<commit_msg>start in lower manhattan<commit_after>/*jslint browser: true*/
/*global Tangram, gui */

(function () {
    'use strict';

    var map_start_location = [40.7064, -74.0088, 16]; // NYC

    /*** URL parsing ***/

    // leaflet-style URL hash pattern:
    // #[zoom],[lat],[lng]
    var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');

    if (url_hash.length == 3) {
        map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
        // convert from strings
        map_start_location = map_start_location.map(Number);
    }

    /*** Map ***/

    var map = L.map('map',
        {'keyboardZoomOffset': .05}
    );

    var layer = Tangram.leafletLayer({
        scene: 'scene.yaml',
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;
    var scene = layer.scene;
    window.scene = scene;

    map.setView(map_start_location.slice(0, 2), map_start_location[2]);

    var hash = new L.Hash(map);

    // Resize map to window
    function resizeMap() {
        document.getElementById('map').style.width = window.innerWidth + 'px';
        document.getElementById('map').style.height = window.innerHeight + 'px';
        map.invalidateSize(false);
    }

    window.addEventListener('resize', resizeMap);
    resizeMap();

    function setCamera(type) {
        if (scene.view.camera.type != type) {
            scene.config.cameras.camera1.type = type;
            scene.config.lights.light1.radius = [controllerByName("radius_inner").getValue()+"px", controllerByName("radius_outer").getValue()+"px"];
            scene.config.lights.light1.attenuation = controllerByName("attenuation").getValue();
            scene.updateConfig();
            switch(type) {
                case "perspective":
                    controllerByName("axis_toggle").setValue(false);
                    scene.view.camera.focal_length = controllerByName("focal_length").getValue();
                    break;
                case "isometric":
                    controllerByName("vanishing_point_toggle").setValue(false);
                    break;
            }
        }
    }
    function setLight(type) {
        if (scene.lights.light1.type != type) {
            scene.config.lights.light1.type = type;
            scene.config.cameras.camera1.focal_length = controllerByName("focal_length").getValue();
            scene.config.cameras.camera1.axis = {x: controllerByName("axis_x").getValue(), y: controllerByName("axis_y").getValue()};
            scene.updateConfig();
            switch(type) {
                case "directional":
                    controllerByName("point_toggle").setValue(false);
                case "point":
                    controllerByName("direction_toggle").setValue(false);
                    scene.config.lights.light1.radius = [controllerByName("radius_inner").getValue()+"px", controllerByName("radius_outer").getValue()+"px"];
                    scene.config.lights.light1.attenuation = controllerByName("attenuation").getValue();
                    scene.updateConfig();
            }
        }
    }

    function controllerByName(which) {
        for (var i = 0; i < gui.__controllers.length; i++) {
            if (gui.__controllers[i].property == which) {
                return gui.__controllers[i];
            }
        }
    }

    // GUI options for rendering modes/effects
    var controls = {
        'Perspective' : function() {
            setCamera("perspective");
        },
        'Isometric' : function() {
            setCamera("isometric");
        },
        'Flat' : function() {
            setCamera("flat");
        },
        'focal_length' : 2,
        'axis_x' : 0,
        'axis_y' : 1,
        'axis_toggle' : false,
        'vanishing_point_x' : 0,
        'vanishing_point_y' : 0,
        'vanishing_point_toggle' : false,
        'Directional' : function() {
            setLight("directional");
        },
        'direction_x' : 0,
        'direction_y' : 1,
        'direction_z' : 0,
        'direction_toggle' : false,
        'direction_diffuse' : 1,
        'direction_ambient' : .3,
        'Point' : function() {
            setLight("point");
        },
        'point_x' : 0,
        'point_y' : 0,
        'point_z' : 50,
        'point_toggle' : false,
        'point_diffuse' : 1,
        'point_ambient' : .5,
        'attenuation' : 2,
        'radius_inner' : 100,
        'radius_outer' : 250,

    };
    var vanishing_point_mouse = false;
    var axis_mouse = false;
    var directional_mouse = false;
    var point_mouse = false;
    // Create dat GUI
    var gui = new dat.GUI({ autoPlace: true, width: 300 });
    function addGUI () {
        gui.domElement.parentNode.style.zIndex = 500;
        window.gui = gui;
        var folder = gui.addFolder("Click a style:");
        folder.open(); // this just points the arrow downward

        // CAMERAS
        gui.add(controls, 'Perspective').name("Perspective Camera");
        gui.add(controls, 'focal_length', 0.1, 5).name("  focal_length").onChange(function(value) {
            setCamera("perspective");
            scene.view.camera.focal_length = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'vanishing_point_x', -1000, 1000).name("  vanishing_point x").onChange(function(value) {
            setCamera("perspective");
            scene.view.camera.vanishing_point[0] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'vanishing_point_y', -1000, 1000).name("  vanishing_point y").onChange(function(value) {
            setCamera("perspective");
            scene.view.camera.vanishing_point[1] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'vanishing_point_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setCamera("perspective");
            }
            vanishing_point_mouse = value;
        });
        gui.add(controls, 'Isometric').name("Isometric Camera");
        gui.add(controls, 'axis_x', -5, 5).name("  axis x").onChange(function(value) {
            setCamera("isometric");
            scene.view.camera.axis.x = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'axis_y', -5, 5).name("  axis y").onChange(function(value) {
            setCamera("isometric");
            scene.view.camera.axis.y = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'axis_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setCamera("isometric");
            }
            axis_mouse = value;
        });
        gui.add(controls, 'Flat').name("Flat Camera");

        // LIGHTS
        gui.add(controls, 'Directional').name("Directional Light");
        gui.add(controls, 'direction_x', -1, 1).name("  direction x").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.direction[0] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_y', -1, 1).name("  direction y").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.direction[1] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_z', -1, 1).name("  direction z").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.direction[2] = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setLight("directional");
            }
            directional_mouse = value;
        });
        gui.add(controls, 'direction_diffuse', 0, 2).name("  diffuse").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.diffuse = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'direction_ambient', 0, 1).name("  ambient").onChange(function(value) {
            setLight("directional");
            scene.lights.light1.ambient = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'Point').name("Point Light");
        gui.add(controls, 'point_x', -1000, 1000).name("  point x").onChange(function(value) {
            setLight("point");
            scene.lights.light1.position[0] = value+"px";
            scene.requestRedraw();
        });
        gui.add(controls, 'point_y', -1000, 1000).name("  point y").onChange(function(value) {
            setLight("point");
            scene.lights.light1.position[1] = value+"px";
            scene.requestRedraw();
        });
        gui.add(controls, 'point_z', -1000, 1000).name("  point z").onChange(function(value) {
            setLight("point");
            scene.lights.light1.position[2] = value+"px";
            scene.requestRedraw();
        });
        gui.add(controls, 'point_toggle').name("  mouse control").onChange(function(value) {
            if (value) {
                setLight("point");
            }
            point_mouse = value;
        });
        gui.add(controls, 'point_diffuse', 0, 2).name("  diffuse").onChange(function(value) {
            setLight("point");
            scene.lights.light1.diffuse = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'point_ambient', 0, 1).name("  ambient").onChange(function(value) {
            setLight("point");
            scene.lights.light1.ambient = [value, value, value, 1];
            scene.requestRedraw();
        });
        gui.add(controls, 'attenuation', 0, 10).name("  attenuation").onChange(function(value) {
            setLight("point");
            scene.lights.light1.attenuation = value;
            scene.requestRedraw();
        });
        gui.add(controls, 'radius_inner', 0, 500).name("  radius_inner").onChange(function(value) {
            setLight("point");
            scene.lights.light1.radius = [value+"px", (scene.lights.light1.radius === null) ? 0 : scene.lights.light1.radius[1]];
            scene.requestRedraw();
        });
        gui.add(controls, 'radius_outer', 0, 500).name("  radius_outer").onChange(function(value) {
            setLight("point");
            scene.lights.light1.radius = [(scene.lights.light1.radius === null) ? 0 : scene.lights.light1.radius[0], value+"px"];
            scene.requestRedraw();
        });

    }

    // mouse position listener

    var mouse_monitor = function(e) {
        var height = document.body.clientHeight;
        var width = document.body.clientWidth;

        var x = e.clientX;
        var y = e.clientY;
        var xpos = ((x - (width / 2)));
        var ypos = ((y - (height / 2)))*-1.;
        var xpercent = x/width * 2. - 1.;
        var ypercent = y/height * 2. - 1.;

        if (vanishing_point_mouse) {
            scene.view.camera.vanishing_point = [xpos,ypos];
            gui.__controllers[2].setValue(scene.view.camera.vanishing_point[0]);
            gui.__controllers[3].setValue(scene.view.camera.vanishing_point[1]);
            scene.requestRedraw();
        }
        if (axis_mouse) {
            scene.view.camera.axis = {x: xpos/(width/5), y: ypos/(height/5)};
            gui.__controllers[6].setValue(scene.view.camera.axis.x);
            gui.__controllers[7].setValue(scene.view.camera.axis.y);
            scene.requestRedraw();
        }
        if (directional_mouse) {
            scene.lights.light1.direction = [xpercent,ypercent*-1,scene.lights.light1.direction[2]];
            gui.__controllers[11].setValue(scene.lights.light1.direction[0]);
            gui.__controllers[12].setValue(scene.lights.light1.direction[1]);
            scene.requestRedraw();
        }
        if (point_mouse) {
            scene.lights.light1.position = [xpos,ypos,scene.lights.light1.position[2]];
            gui.__controllers[18].setValue(scene.lights.light1.position[0]);
            gui.__controllers[19].setValue(scene.lights.light1.position[1]);
            scene.requestRedraw();
        }

    }

    window.onload = function() {
      this.addEventListener('mousemove', mouse_monitor);
    }

    /***** Render loop *****/
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
            addGUI();
        });
        layer.addTo(map);

    });

}());
<|endoftext|>


<commit_before>// takes an IR function object and returns a list of Scratch blocks

module.exports.ffi = {};

var functionContext = {
	locals: {},
	localDepth: 0,
	params: []
}

module.exports.generateFunctionHat = function(func) {
	var spec = func.funcName;
	var inputs = [];
	var defaults = [];

	functionContext.params = [];

	for(var i = 0; i < func.paramList.length; ++i) {
		var pName = "param" + i;

		if(func.paramList[i][1])
			pName = func.paramList[i][1];

		inputs.push(pName);
		functionContext.params.push(pName);

		defaults.push(defaultForType(func.paramList[i][0]));
		spec += " "+specifierForType(func.paramList[i][0]);
	}

	return ["procDef", spec, inputs, defaults, false];

}

module.exports.compileFunction = function(func) {
	console.log("Compiling "+JSON.stringify(func)+"...");

	var blockList = [module.exports.generateFunctionHat(func)]
					.concat(initLocal());

	functionContext.locals = {};
	functionContext.localDepth = 0;

	for(var i = 0; i < func.code.length; ++i) {
		console.log(func.code[i]);
		blockList = blockList.concat(compileInstruction(func.code[i]));
	}

	//blockList = blockList.concat(returnBlock());

	return blockList;
}

function compileInstruction(block) {
	if(block.type == "call") {
		// calling a (potentially foreign) function
		return callBlock(block);
	} else if(block.type == "ffi") {
		// FFI block
		// load the code from the options
		return module.exports.ffi[block.ffiBlock];
	} else if(block.type == "set") {
		return compileInstruction(block.computation)
				.concat(allocateLocal(block.val, block.name));
	} else if(block.type == "ret") {
		return returnBlock(block.value);
	}

	return [];
}

// fixme: stub
function defaultForType(type) {
	console.log(type);
	return 0;
}

// fixme: stub
function specifierForType(type) {
	return "%s";
}

// fixme: stub
function formatValue(type, value) {
	console.log("FORMAT: "+type+","+value);

	if(value[0] == '%') {
		return fetchByName(value);
	}

	return value;
}

function getOffset(value) {
	return functionContext.localDepth - functionContext.locals[value];
}

// higher-level code generation
function initLocal() {
	return [
		["append:toList:", "0", "# of locals"]
	]
}

function allocateLocal(val, name) {
	if(name) {
		console.log(name+","+val);
		functionContext.locals[name] = ++functionContext.localDepth;
	}

	return [
		["setLine:ofList:to:", "last", "# of locals", ["+", ["getLine:ofList:", "last", "# of locals"], 1]],
		["append:toList:", val, "Stack"]
	];
}

function freeLocals() {
	return [
		["doRepeat", ["getLine:ofList:", "last", "# of locals"], [["deleteLine:ofList:", "last", "Stack"]]],
		["deleteLine:ofList:", "last", "# of locals"]
	];
}

function fetchByName(n) {
	if(functionContext.locals[n])
		return ["getLine:ofList:", ["-", ["lineCountOfList:", "Stack"], getOffset(n)], "Stack"];
	else if(functionContext.params.indexOf(n) > -1)
		return ["getParam", n, "r"];
	else
		return 0;
}

function returnBlock(val) {
	var proc = freeLocals();

	if(val) {
		proc.push(["setVar:to:", "return value", formatValue(val[0], val[1])]);
	}

	proc.push(["stopScripts", "this script"]);

	return proc;
}

function callBlock(block) {
	var spec = block.funcName;
	var args = [];

	for(var a = 0; a < block.paramList.length; ++a) {
		args.push(formatValue(block.paramList[a][0], block.paramList[a][1]));
		spec += " "+specifierForType(block.paramList[a][0]);
	}

	return [
		["call", spec].concat(args)
	];
}

// TODO: more robust implementation to support heap

function dereferenceAndSet(ptr) {
	return [
		[
			"setLine:ofList:to",
			fetchByName(ptr),
			"Stack"
		]
	];
}<commit_msg>Store backend; better dereferenceAndSet implementation<commit_after>// takes an IR function object and returns a list of Scratch blocks

module.exports.ffi = {};

var functionContext = {
	locals: {},
	localDepth: 0,
	params: []
}

module.exports.generateFunctionHat = function(func) {
	var spec = func.funcName;
	var inputs = [];
	var defaults = [];

	functionContext.params = [];

	for(var i = 0; i < func.paramList.length; ++i) {
		var pName = "param" + i;

		if(func.paramList[i][1])
			pName = func.paramList[i][1];

		inputs.push(pName);
		functionContext.params.push(pName);

		defaults.push(defaultForType(func.paramList[i][0]));
		spec += " "+specifierForType(func.paramList[i][0]);
	}

	return ["procDef", spec, inputs, defaults, false];

}

module.exports.compileFunction = function(func) {
	console.log("Compiling "+JSON.stringify(func)+"...");

	var blockList = [module.exports.generateFunctionHat(func)]
					.concat(initLocal());

	functionContext.locals = {};
	functionContext.localDepth = 0;

	for(var i = 0; i < func.code.length; ++i) {
		console.log(func.code[i]);
		blockList = blockList.concat(compileInstruction(func.code[i]));
	}

	//blockList = blockList.concat(returnBlock());

	return blockList;
}

function compileInstruction(block) {
	if(block.type == "call") {
		// calling a (potentially foreign) function
		return callBlock(block);
	} else if(block.type == "ffi") {
		// FFI block
		// load the code from the options
		return module.exports.ffi[block.ffiBlock];
	} else if(block.type == "set") {
		return compileInstruction(block.computation)
				.concat(allocateLocal(block.val, block.name));
	} else if(block.type == "ret") {
		return returnBlock(block.value);
	} else if(block.type == "store") {
		return dereferenceAndSet(block.destination.value, block.src.value);fetchByName(
	}

	return [];
}

// fixme: stub
function defaultForType(type) {
	console.log(type);
	return 0;
}

// fixme: stub
function specifierForType(type) {
	return "%s";
}

// fixme: stub
function formatValue(type, value) {
	console.log("FORMAT: "+type+","+value);

	if(value[0] == '%') {
		return fetchByName(value);
	}

	return value;
}

function getOffset(value) {
	return functionContext.localDepth - functionContext.locals[value];
}

// higher-level code generation
function initLocal() {
	return [
		["append:toList:", "0", "# of locals"]
	]
}

function allocateLocal(val, name) {
	if(name) {
		console.log(name+","+val);
		functionContext.locals[name] = ++functionContext.localDepth;
	}

	return [
		["setLine:ofList:to:", "last", "# of locals", ["+", ["getLine:ofList:", "last", "# of locals"], 1]],
		["append:toList:", val, "Stack"]
	];
}

function freeLocals() {
	return [
		["doRepeat", ["getLine:ofList:", "last", "# of locals"], [["deleteLine:ofList:", "last", "Stack"]]],
		["deleteLine:ofList:", "last", "# of locals"]
	];
}

function fetchByName(n) {
	if(functionContext.locals[n])
		return ["getLine:ofList:", ["-", ["lineCountOfList:", "Stack"], getOffset(n)], "Stack"];
	else if(functionContext.params.indexOf(n) > -1)
		return ["getParam", n, "r"];
	else
		return 0;
}

function returnBlock(val) {
	var proc = freeLocals();

	if(val) {
		proc.push(["setVar:to:", "return value", formatValue(val[0], val[1])]);
	}

	proc.push(["stopScripts", "this script"]);

	return proc;
}

function callBlock(block) {
	var spec = block.funcName;
	var args = [];

	for(var a = 0; a < block.paramList.length; ++a) {
		args.push(formatValue(block.paramList[a][0], block.paramList[a][1]));
		spec += " "+specifierForType(block.paramList[a][0]);
	}

	return [
		["call", spec].concat(args)
	];
}

// TODO: more robust implementation to support heap

function dereferenceAndSet(ptr, content) {
	return [
		[
			"setLine:ofList:to",
			fetchByName(ptr),
			"Stack",
			fetchByName(content)
		]
	];
}<|endoftext|>


<commit_before>// @flow
import React, { Component, PropTypes } from 'react';
import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import WalletTransactionsList from '../../components/wallet/home/WalletTransactionsList';
import WalletTransactionsSearch from '../../components/wallet/home/WalletTransactionsSearch';
import WalletNoTransactions from '../../components/wallet/home/WalletNoTransactions';
import CachedRequest from '../../stores/lib/CachedRequest';

const messages = defineMessages({
  noTransactions: {
    id: 'wallet.transactions.no.transactions',
    defaultMessage: '!!!No transactions',
    description: 'Message shown when wallet has no transactions yet.'
  },
  noTransactionsFound: {
    id: 'wallet.transactions.no.transactions.found',
    defaultMessage: '!!!No transactions found',
    description: 'Message shown when wallet transaction search returns zero results.'
  }
});

@inject('stores', 'actions') @observer
export default class WalletTransactionsPage extends Component {

  static propTypes = {
    stores: PropTypes.shape({
      transactions: PropTypes.shape({
        searchOptions: PropTypes.shape({
          searchTerm: PropTypes.string.isRequired,
          searchLimit: PropTypes.number.isRequired,
        }),
        allTransactionsRequest: PropTypes.instanceOf(CachedRequest),
        filtered: MobxPropTypes.arrayOrObservableArray.isRequired,
        hasAnyFiltered: PropTypes.bool.isRequired,
        totalFilteredAvailable: PropTypes.number.isRequired,
      })
    }).isRequired,
    actions: PropTypes.shape({
      filterTransactions: PropTypes.func.isRequired
    }).isRequired
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  _handleSearchInputChange = (value: string, event: Object) => {
    this.props.actions.filterTransactions({ searchTerm: event.target.value });
  };

  render() {
    const { intl } = this.context;
    const actions = this.props.actions;
    const { transactions } = this.props.stores;
    const {
      searchOptions,
      searchRequest,
      hasAny,
      totalAvailable,
      filtered,
    } = transactions;
    const { searchLimit, searchTerm } = searchOptions;
    const wasSearched = searchTerm !== '';
    let walletTransactions = null;
    let transactionSearch = null;
    const noTransactionsLabel = intl.formatMessage(messages.noTransactions);
    const noTransactionsFoundLabel = intl.formatMessage(messages.noTransactionsFound);

    // if (wasSearched || hasAny) {
    //   transactionSearch = (
    //

    //       <WalletTransactionsSearch
    //         searchTerm={searchTerm}
    //         onChange={this._handleSearchInputChange}
    //       />
    //

    //   );
    // }

    if (searchRequest.isExecutingFirstTime || hasAny) {
      walletTransactions = (
        <WalletTransactionsList
          transactions={filtered}
          isLoadingTransactions={searchRequest.isExecutingFirstTime}
          hasMoreToLoad={totalAvailable > searchLimit}
          onLoadMore={actions.loadMoreTransactions}
        />
      );
    } else if (wasSearched && !hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsFoundLabel} />;
    } else if (!hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsLabel} />;
    }

    return (

        {transactionSearch}
        {walletTransactions}

    );
  }

}
<commit_msg>fixes small ui glitch on transactions page<commit_after>// @flow
import React, { Component, PropTypes } from 'react';
import { observer, inject, PropTypes as MobxPropTypes } from 'mobx-react';
import { defineMessages, intlShape } from 'react-intl';
import WalletTransactionsList from '../../components/wallet/home/WalletTransactionsList';
import WalletTransactionsSearch from '../../components/wallet/home/WalletTransactionsSearch';
import WalletNoTransactions from '../../components/wallet/home/WalletNoTransactions';
import CachedRequest from '../../stores/lib/CachedRequest';

const messages = defineMessages({
  noTransactions: {
    id: 'wallet.transactions.no.transactions',
    defaultMessage: '!!!No transactions',
    description: 'Message shown when wallet has no transactions yet.'
  },
  noTransactionsFound: {
    id: 'wallet.transactions.no.transactions.found',
    defaultMessage: '!!!No transactions found',
    description: 'Message shown when wallet transaction search returns zero results.'
  }
});

@inject('stores', 'actions') @observer
export default class WalletTransactionsPage extends Component {

  static propTypes = {
    stores: PropTypes.shape({
      transactions: PropTypes.shape({
        searchOptions: PropTypes.shape({
          searchTerm: PropTypes.string.isRequired,
          searchLimit: PropTypes.number.isRequired,
        }),
        allTransactionsRequest: PropTypes.instanceOf(CachedRequest),
        filtered: MobxPropTypes.arrayOrObservableArray.isRequired,
        hasAnyFiltered: PropTypes.bool.isRequired,
        totalFilteredAvailable: PropTypes.number.isRequired,
      })
    }).isRequired,
    actions: PropTypes.shape({
      filterTransactions: PropTypes.func.isRequired
    }).isRequired
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  _handleSearchInputChange = (value: string, event: Object) => {
    this.props.actions.filterTransactions({ searchTerm: event.target.value });
  };

  render() {
    const { intl } = this.context;
    const actions = this.props.actions;
    const { transactions } = this.props.stores;
    const {
      searchOptions,
      searchRequest,
      hasAny,
      totalAvailable,
      filtered,
    } = transactions;
    const { searchLimit, searchTerm } = searchOptions;
    const wasSearched = searchTerm !== '';
    let walletTransactions = null;
    let transactionSearch = null;
    const noTransactionsLabel = intl.formatMessage(messages.noTransactions);
    const noTransactionsFoundLabel = intl.formatMessage(messages.noTransactionsFound);

    // if (wasSearched || hasAny) {
    //   transactionSearch = (
    //

    //       <WalletTransactionsSearch
    //         searchTerm={searchTerm}
    //         onChange={this._handleSearchInputChange}
    //       />
    //

    //   );
    // }

    if (searchRequest.isExecutingFirstTime || hasAny) {
      walletTransactions = (
        <WalletTransactionsList
          transactions={filtered}
          isLoadingTransactions={searchRequest.isExecutingFirstTime}
          hasMoreToLoad={totalAvailable > searchLimit}
          onLoadMore={actions.loadMoreTransactions}
        />
      );
    } else if (wasSearched && !hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsFoundLabel} />;
    } else if (!hasAny) {
      walletTransactions = <WalletNoTransactions label={noTransactionsLabel} />;
    }

    return (

        {transactionSearch}
        {walletTransactions}

    );
  }

}
<|endoftext|>


<commit_before>'use strict'

var shimmer = require('shimmer')
var debug = require('debug')('opbeat')

module.exports = function (https, agent) {
  debug('shimming https.request function')

  shimmer.wrap(https, 'request', function (orig, name) {
    return function () {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to https.request %o', { uuid: uuid })

      var req = orig.apply(this, arguments)
      if (!trace) return req
      if (req._headers.host === agent._apiHost) {
        debug('ignore http request to opbeat server %o', { uuid: uuid })
        return req
      }

      var name = req.method + ' ' + req._headers.host
      trace.start(name, 'ext.https.http')
      req.on('response', onresponse)

      return req

      function onresponse (res) {
        debug('intercepted http.ClientRequest response event %o', { uuid: uuid })
        res.on('end', function () {
          debug('intercepted http.IncomingMessage end event %o', { uuid: uuid })
          trace.end()
        })
      }
    }
  })

  return https
}
<commit_msg>Improve outgoing https request debugging<commit_after>'use strict'

var shimmer = require('shimmer')
var debug = require('debug')('opbeat')

module.exports = function (https, agent) {
  debug('shimming https.request function')

  shimmer.wrap(https, 'request', function (orig, name) {
    return function () {
      var trace = agent.buildTrace()
      var uuid = trace && trace.transaction._uuid

      debug('intercepted call to https.request %o', { uuid: uuid })

      var req = orig.apply(this, arguments)
      if (!trace) return req
      if (req._headers.host === agent._apiHost) {
        debug('ignore http request to opbeat server %o', { uuid: uuid })
        return req
      } else {
        debug('detected host: %s %o', req._headers.host, { uuid: uuid })
      }

      var name = req.method + ' ' + req._headers.host
      trace.start(name, 'ext.https.http')
      req.on('response', onresponse)

      return req

      function onresponse (res) {
        debug('intercepted http.ClientRequest response event %o', { uuid: uuid })
        res.on('end', function () {
          debug('intercepted http.IncomingMessage end event %o', { uuid: uuid })
          trace.end()
        })
      }
    }
  })

  return https
}
<|endoftext|>