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

'use strict';

var util = require('../util/util');
var examiner = require('../testharness/examiner');
var KeyEvent = require('../util/util').KeyEvent;

var test = require('../commands/test');
var helpers = require('./helpers');
var createTerminalAutomator = require('./automators/terminal').createTerminalAutomator;
require('./suite');

/**
 * Some tricks to make studying the command line state easier
 */
var addDebugAids = exports.addDebugAids = function(options) {
  window.createDebugCheck = function() {
    helpers._createDebugCheck(options).then(function() {
      // Don't inline this - chrome console suckage
      console.log.apply(console, arguments);
    }, util.errorHandler);
  };

  window.summaryJson = function() {
    var args = [ 'Requisition: ' ];
    var summary = options.terminal.language.requisition._summaryJson;
    Object.keys(summary).forEach(function(name) {
      args.push(' ' + name + '=');
      args.push(summary[name]);
    });
    console.log.apply(console, args);

    console.log('Focus: ' +
                'tooltip=', options.terminal.focusManager._shouldShowTooltip(),
                'output=', options.terminal.focusManager._shouldShowOutput());
  };

  document.addEventListener('keyup', function(ev) {
    if (ev.keyCode === KeyEvent.DOM_VK_F2) {
      window.createDebugCheck();
    }
    if (ev.keyCode === KeyEvent.DOM_VK_F4) {
      window.summaryJson();
    }
  }, true);
};

/**
 * This is the equivalent of gcli/index.createTerminal() except it:
 * - Sets window.display: to actual Display object (not the thin proxy
 *   returned by gcli/index.createTerminal() and this function)
 * - Registers all the test commands, and provides a function to re-register
 *   them - window.testCommands() (running the test suite un-registers them)
 * - Runs the unit tests automatically on startup
 * - Registers a 'test' command to re-run the unit tests
 */
exports.run = function(terminal, isRemote) {
  var options = {
    terminal: terminal,
    window: window,
    automator: createTerminalAutomator(terminal),
    requisition: terminal.language.requisition,
    isNode: false,
    isFirefox: false,
    isPhantomjs: (window.navigator.userAgent.indexOf('hantom') !== -1),
    isRemote: isRemote,
    hideExec: true
  };

  addDebugAids(options);

  // phantom-test.js does phantom.exit() on `document.complete = true`
  var closeIfPhantomJs = function() {
    if (options.isPhantomjs) {
      document.complete = true;
    }
  };

  // PhantomJS may tell us to tell the server to shutdown
  if (window.location.href.indexOf('shutdown=true') > 0) {
    shutdownServer(terminal.language.requisition).then(closeIfPhantomJs, closeIfPhantomJs);
    return;
  }

  test.optionsContainer.push(options);

  helpers.resetResponseTimes();
  examiner.reset();

  setMocks(options, true).then(function() {
    examiner.run(options).then(function() {
      var name = options.isPhantomjs ? '\nPhantomJS' : 'Browser';

      console.log(examiner.detailedResultLog(name));
      console.log(helpers.timingSummary);
      document.testStatus = examiner.status.name;

      setMocks(options, false).then(closeIfPhantomJs).catch(function(ex) {
        console.error(ex);
        closeIfPhantomJs();
      });
    });
  });

};

/**
 * Turn mock commands and settings on/off
 */
function setMocks(options, state) {
  var command = 'mocks ' + (state ? 'on' : 'off');
  return options.requisition.updateExec(command).then(function(data) {
    if (data.error) {
      throw new Error('Failed to turn mocks on');
    }
  });
}

/**
 * If the server is started with `--xhr` then we can shut it down remotely.
 * Useful for automated testing.
 */
function shutdownServer(requisition) {
  return requisition.updateExec('connect remote').then(function(output) {
    console.log('exec: connect remote -> ' + output.data);
    return requisition.updateExec('remote server stop').then(function(output2) {
      console.log('exec: remote server stop -> ' + output2.data);
    });
  });
}
<commit_msg>runat-1128988: Improve error handling<commit_after>/*
 * Copyright 2012, Mozilla Foundation and contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var util = require('../util/util');
var examiner = require('../testharness/examiner');
var KeyEvent = require('../util/util').KeyEvent;

var test = require('../commands/test');
var helpers = require('./helpers');
var createTerminalAutomator = require('./automators/terminal').createTerminalAutomator;
require('./suite');

/**
 * Some tricks to make studying the command line state easier
 */
var addDebugAids = exports.addDebugAids = function(options) {
  window.createDebugCheck = function() {
    helpers._createDebugCheck(options).then(function() {
      // Don't inline this - chrome console suckage
      console.log.apply(console, arguments);
    }, util.errorHandler);
  };

  window.summaryJson = function() {
    var args = [ 'Requisition: ' ];
    var summary = options.terminal.language.requisition._summaryJson;
    Object.keys(summary).forEach(function(name) {
      args.push(' ' + name + '=');
      args.push(summary[name]);
    });
    console.log.apply(console, args);

    console.log('Focus: ' +
                'tooltip=', options.terminal.focusManager._shouldShowTooltip(),
                'output=', options.terminal.focusManager._shouldShowOutput());
  };

  document.addEventListener('keyup', function(ev) {
    if (ev.keyCode === KeyEvent.DOM_VK_F2) {
      window.createDebugCheck();
    }
    if (ev.keyCode === KeyEvent.DOM_VK_F4) {
      window.summaryJson();
    }
  }, true);
};

/**
 * This is the equivalent of gcli/index.createTerminal() except it:
 * - Sets window.display: to actual Display object (not the thin proxy
 *   returned by gcli/index.createTerminal() and this function)
 * - Registers all the test commands, and provides a function to re-register
 *   them - window.testCommands() (running the test suite un-registers them)
 * - Runs the unit tests automatically on startup
 * - Registers a 'test' command to re-run the unit tests
 */
exports.run = function(terminal, isRemote) {
  var options = {
    terminal: terminal,
    window: window,
    automator: createTerminalAutomator(terminal),
    requisition: terminal.language.requisition,
    isNode: false,
    isFirefox: false,
    isPhantomjs: (window.navigator.userAgent.indexOf('hantom') !== -1),
    isRemote: isRemote,
    hideExec: true
  };

  addDebugAids(options);

  // phantom-test.js does phantom.exit() on `document.complete = true`
  var closeIfPhantomJs = function() {
    if (options.isPhantomjs) {
      document.complete = true;
    }
  };

  // PhantomJS may tell us to tell the server to shutdown
  if (window.location.href.indexOf('shutdown=true') > 0) {
    shutdownServer(terminal.language.requisition).then(closeIfPhantomJs, closeIfPhantomJs);
    return;
  }

  test.optionsContainer.push(options);

  helpers.resetResponseTimes();
  examiner.reset();

  setMocks(options, true).then(function() {
    return examiner.run(options).then(function() {
      var name = options.isPhantomjs ? '\nPhantomJS' : 'Browser';

      console.log(examiner.detailedResultLog(name));
      console.log(helpers.timingSummary);
      document.testStatus = examiner.status.name;

      setMocks(options, false).then(closeIfPhantomJs).catch(function(ex) {
        console.error(ex);
        closeIfPhantomJs();
      });
    });
  }, util.errorHandler);
};

/**
 * Turn mock commands and settings on/off
 */
function setMocks(options, state) {
  var command = 'mocks ' + (state ? 'on' : 'off');
  return options.requisition.updateExec(command).then(function(data) {
    if (data.error) {
      throw new Error('Failed to toggle mocks');
    }
  });
}

/**
 * If the server is started with `--xhr` then we can shut it down remotely.
 * Useful for automated testing.
 */
function shutdownServer(requisition) {
  return requisition.updateExec('connect remote').then(function(output) {
    console.log('exec: connect remote -> ' + output.data);
    return requisition.updateExec('remote server stop').then(function(output2) {
      console.log('exec: remote server stop -> ' + output2.data);
    });
  });
}
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var MapView = require('../../../src/geo/map-view');
var Map = require('../../../src/geo/map');
var CartoDBLayer = require('../../../src/geo/map/cartodb-layer');
var TooltipManager = require('../../../src/vis/tooltip-manager');

describe('src/vis/tooltip-manager.js', function () {
  beforeEach(function () {
    var windshaftMap = new Backbone.Model({});
    windshaftMap.isNamedMap = function () { return false; };
    this.map = new Map({}, {
      windshaftMap: windshaftMap
    });
    this.layerView = new Backbone.Model();
    var layerViewFactory = jasmine.createSpyObj('layerViewFactory', ['createLayerView']);
    layerViewFactory.createLayerView.and.returnValue(this.layerView);

    this.mapView = new MapView({
      map: this.map,
      layerViewFactory: layerViewFactory
    });
    this.mapView.getNativeMap = function () {};
    this.mapView._addLayerToMap = function () {};
    this.mapView.latLonToPixel = function () { return { x: 0, y: 0 }; };
    this.mapView.getSize = function () { return { x: 1000, y: 1000 }; };

    this.vis = {
      mapView: this.mapView
    };
  });

  it('should add a new tooltip view to the map view when new layers are reseted', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }]
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer ]);
    expect(this.mapView.addOverlay).toHaveBeenCalled();
  });

  it('should add a new tooltip view to the map view when new layers are added', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }]
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer ]);
    expect(this.mapView.addOverlay).toHaveBeenCalled();
  });

  it('should NOT add a new infowindow view to the map view when new layers share the same layerView', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer1 = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }]
      }
    });

    var layer2 = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'description',
          'title': true,
          'position': 1
        }]
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer1, layer2 ]);

    expect(this.mapView.addOverlay).toHaveBeenCalled();
    expect(this.mapView.addOverlay.calls.count()).toEqual(1);
  });

  it('should NOT add a new infowindow view to the map view when new layers are added if layer doesn\'t have infowindow fields', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer = new CartoDBLayer({
      tooltip: {
        fields: []
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer ]);
    expect(this.mapView.addOverlay).not.toHaveBeenCalled();
  });

  it('should correctly bind the featureOver event to the corresponding layerView', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer1 = new CartoDBLayer({
      tooltip: {
        template: 'template1',
        template_type: 'underscore',
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }],
        alternative_names: 'alternative_names1'
      }
    });
    var layer2 = new CartoDBLayer({
      tooltip: {
        template: 'template2',
        template_type: 'underscore',
        fields: [{
          'name': 'description',
          'title': true,
          'position': 1
        }],
        alternative_names: 'alternative_names2'
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer1, layer2 ]);

    expect(this.mapView.addOverlay).toHaveBeenCalled();
    var tooltipView = this.mapView.addOverlay.calls.mostRecent().args[0];

    spyOn(tooltipView, 'setTemplate');
    spyOn(tooltipView, 'setFields');
    spyOn(tooltipView, 'setAlternativeNames');

    this.layerView.model = {
      layers: new Backbone.Collection([ layer1, layer2 ])
    };

    // Simulate the featureOver event on layer #0
    this.layerView.trigger('featureOver', {}, [100, 200], undefined, { cartodb_id: 10 }, 0);

    expect(tooltipView.setTemplate).toHaveBeenCalledWith('template1');
    expect(tooltipView.setFields).toHaveBeenCalledWith([{
      'name': 'name',
      'title': true,
      'position': 1
    }]);
    expect(tooltipView.setAlternativeNames).toHaveBeenCalledWith('alternative_names1');

    // Simulate the featureOver event on layer #1
    this.layerView.trigger('featureOver', {}, [100, 200], undefined, { cartodb_id: 10 }, 1);

    expect(tooltipView.setTemplate).toHaveBeenCalledWith('template2');
    expect(tooltipView.setFields).toHaveBeenCalledWith([{
      'name': 'description',
      'title': true,
      'position': 1
    }]);
    expect(tooltipView.setAlternativeNames).toHaveBeenCalledWith('alternative_names2');
  });
});
<commit_msg>Fixed lint errors<commit_after>var Backbone = require('backbone');
var MapView = require('../../../src/geo/map-view');
var Map = require('../../../src/geo/map');
var CartoDBLayer = require('../../../src/geo/map/cartodb-layer');
var TooltipManager = require('../../../src/vis/tooltip-manager');

describe('src/vis/tooltip-manager.js', function () {
  beforeEach(function () {
    var windshaftMap = new Backbone.Model({});
    windshaftMap.isNamedMap = function () { return false; };
    this.map = new Map({}, {
      windshaftMap: windshaftMap
    });
    this.layerView = new Backbone.Model();
    var layerViewFactory = jasmine.createSpyObj('layerViewFactory', ['createLayerView']);
    layerViewFactory.createLayerView.and.returnValue(this.layerView);

    this.mapView = new MapView({
      map: this.map,
      layerViewFactory: layerViewFactory
    });
    this.mapView.getNativeMap = function () {};
    this.mapView._addLayerToMap = function () {};
    this.mapView.latLonToPixel = function () { return { x: 0, y: 0 }; };
    this.mapView.getSize = function () { return { x: 1000, y: 1000 }; };

    this.vis = {
      mapView: this.mapView
    };
  });

  it('should add a new tooltip view to the map view when new layers are reseted', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }]
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer ]);
    expect(this.mapView.addOverlay).toHaveBeenCalled();
  });

  it('should add a new tooltip view to the map view when new layers are added', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }]
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer ]);
    expect(this.mapView.addOverlay).toHaveBeenCalled();
  });

  it('should NOT add a new infowindow view to the map view when new layers share the same layerView', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer1 = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }]
      }
    });

    var layer2 = new CartoDBLayer({
      tooltip: {
        fields: [{
          'name': 'description',
          'title': true,
          'position': 1
        }]
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer1, layer2 ]);

    expect(this.mapView.addOverlay).toHaveBeenCalled();
    expect(this.mapView.addOverlay.calls.count()).toEqual(1);
  });

  it('should NOT add a new infowindow view to the map view when new layers are added if layer doesn\'t have infowindow fields', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer = new CartoDBLayer({
      tooltip: {
        fields: []
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer ]);
    expect(this.mapView.addOverlay).not.toHaveBeenCalled();
  });

  it('should correctly bind the featureOver event to the corresponding layerView', function () {
    spyOn(this.mapView, 'addOverlay');

    var layer1 = new CartoDBLayer({
      tooltip: {
        template: 'template1',
        template_type: 'underscore',
        fields: [{
          'name': 'name',
          'title': true,
          'position': 1
        }],
        alternative_names: 'alternative_names1'
      }
    });
    var layer2 = new CartoDBLayer({
      tooltip: {
        template: 'template2',
        template_type: 'underscore',
        fields: [{
          'name': 'description',
          'title': true,
          'position': 1
        }],
        alternative_names: 'alternative_names2'
      }
    });

    var tooltipManager = new TooltipManager(this.vis);
    tooltipManager.manage(this.mapView, this.map);

    this.map.layers.reset([ layer1, layer2 ]);

    expect(this.mapView.addOverlay).toHaveBeenCalled();
    var tooltipView = this.mapView.addOverlay.calls.mostRecent().args[0];

    spyOn(tooltipView, 'setTemplate');
    spyOn(tooltipView, 'setFields');
    spyOn(tooltipView, 'setAlternativeNames');

    this.layerView.model = {
      layers: new Backbone.Collection([ layer1, layer2 ])
    };

    // Simulate the featureOver event on layer #0
    this.layerView.trigger('featureOver', {}, [100, 200], undefined, { cartodb_id: 10 }, 0);

    expect(tooltipView.setTemplate).toHaveBeenCalledWith('template1');
    expect(tooltipView.setFields).toHaveBeenCalledWith([{
      'name': 'name',
      'title': true,
      'position': 1
    }]);
    expect(tooltipView.setAlternativeNames).toHaveBeenCalledWith('alternative_names1');

    // Simulate the featureOver event on layer #1
    this.layerView.trigger('featureOver', {}, [100, 200], undefined, { cartodb_id: 10 }, 1);

    expect(tooltipView.setTemplate).toHaveBeenCalledWith('template2');
    expect(tooltipView.setFields).toHaveBeenCalledWith([{
      'name': 'description',
      'title': true,
      'position': 1
    }]);
    expect(tooltipView.setAlternativeNames).toHaveBeenCalledWith('alternative_names2');
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var serialPort = require('serialport').SerialPort;

var portName = '/dev/ttyACM0';
var readData = "";
var sp = new serialPort(portName, {
    baudRate: 57600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false,
});
var PORT = 3000;

io.sockets.on('connection', function (socket, debug) {
    if (debug == false) {
        socketServer.set('log level', 1);
    }
    socket.on('button', function (data) {
        var status = data.lampstatus;
        console.log("data from client: " + status);

        sp.open(function () {
            console.log('open');
            sp.on('data', function(data) {
                console.log('data received: ' + data);
            });

            sp.write(status, function(err, result){
                if(err) console.log('[ERROR] '+err);
                console.log(result);
            });
        });
    })
});

app.configure(function () {
    app.use(express.static(__dirname + '/public'));
});

app.get('/', function (req, res) {
    res.sendfile(__dirname + '/public/index.html');
});

server.listen(PORT, function(){
    console.log('listen on port '+PORT);
});
<commit_msg>Cleanup<commit_after>var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var serialPort = require('serialport').SerialPort;

var PORT = 3000;
var portName = '/dev/ttyACM0';
var sp = new serialPort(portName, {
    baudRate: 57600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false,
});

io.sockets.on('connection', function (socket, debug) {
    if (debug == false) {
        socketServer.set('log level', 1);
    }
    socket.on('button', function (data) {
        var status = data.lampstatus;
        console.log("[Client] " + status);

        sp.open(function () {
            console.log('open');
            sp.on('data', function(data) {
                console.log('[Received] ' + data);
            });

            sp.write(status, function(err, result){
                if(err) console.log('[ERROR] '+err);
                console.log(result);
            });
        });
    })
});

app.configure(function () {
    app.use(express.static(__dirname + '/public'));
});

app.get('/', function (req, res) {
    res.sendfile(__dirname + '/public/index.html');
});

server.listen(PORT, function(){
    console.log('Listen on port '+PORT);
});
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------------------------------------------------------
// Main lsdg-light-site module.
//
// @module server.js
// ---------------------------------------------------------------------------------------------------------------------

var path = require('path');
var app = require('omega-wf').app;
var views = require('./server/views');

// ---------------------------------------------------------------------------------------------------------------------

app.router.add(
    {
        url: '/*',
        path: path.join(__dirname, 'build')
    },
    {
        url: /^\/(?!admin)/,
        get: views.index
    }
);

// Set the application's name
app.setName('lsdg-light-site');

// Start the omega-wf app.
app.listen();

// ---------------------------------------------------------------------------------------------------------------------
<commit_msg>Added vendor serving.<commit_after>// ---------------------------------------------------------------------------------------------------------------------
// Main lsdg-light-site module.
//
// @module server.js
// ---------------------------------------------------------------------------------------------------------------------

var path = require('path');
var app = require('omega-wf').app;
var views = require('./server/views');

// ---------------------------------------------------------------------------------------------------------------------

app.router.add(
    {
        url: '/vendor/*',
        path: path.join(__dirname, 'vendor')
    },
    {
        url: '/*',
        path: path.join(__dirname, 'build')
    },
    {
        url: /^\/(?!admin)/,
        get: views.index
    }
);

// Set the application's name
app.setName('lsdg-light-site');

// Start the omega-wf app.
app.listen();

// ---------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>//get libraries required
var express = require('express');
var app = express();
var req = require('request');
var auto = require('run-auto');
var spotifyToken, categories = [], playList = [];
app.use(express.static(__dirname + '/'));//set the base directory to find resources
/*
* Function that gets initialized when navigating to base url. This function initially
* gets the token from spotify.
* @return /index.html page
*/
app.get('/', function(request, response) {
  auto({
    token: function(callback) {
      console.log('trying to get token');
      getToken(function(token) {
        callback(null, token);
      });
    },
  },
    function() {
    response.sendFile(__dirname + '/index.html');
  });
});
/*
* Function that gets called when /getMusic is called. Initially tries to get token,
* calls category, and finally playlist.
* @return response.playlist
*/
app.get('/getMusic', function (request, response) {
  auto({
    token: function(callback) {
      console.log('trying to get token');
      getToken(function(token) {
        callback(null, token);
      });
    },
    category: ['token', function(results, callback) {
      console.log('trying to get categories');
      getCategories(request, response, function(cat) {
        callback(null, cat);
      });
    }],
    playlist: ['token', 'category', function(results, callback) {
      console.log('trying to get playlist');
      request.playListId = categories[randomizer(categories.length)].playlistid;
      getPlayList(request, response, function(list) {
        callback(null, response.send(list));
      });
    }]
  });
});
app.get('/getLyrics', function(request, response) {
  auto({
    lyrics: function(callback) {
      console.log('trying to get lyrics');
      getLyrics(request, response, function(lyric) {
        callback(null, response.send(lyric));
      });
    }
  });
});
/*
* Start up node and listen on a specified port
*/
listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});
/*
* Function to get client credentials token from spotify
*/
function getToken(callback) {
  var time = new Date();
  //checks if spotifytoken if not defined and the lifetime of the token
  if (spotifyToken === undefined || spotifyToken.expires_on <= (Date.now() / 1000.0)) {
    spotifyToken = undefined;
    /*
    * Authentication options used by spotify api for client credentials work flow
    */
    var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      headers: {
        'Authorization': 'Basic ' + (new Buffer(process.env.client_id + ':' + process.env.client_secret).toString('base64'))
      },
      form: {
        grant_type: 'client_credentials'
      },
      json: true
    };
    //Function to make the post to spotify for the token
    auto({
      postToken: function(callback) {
        req.post(authOptions, function(error, response, body) {
          if (!error && response.statusCode === 200) {//if status 200
            spotifyToken = {token : body.access_token, expires_on : (Date.now() / 1000.0) + body.expires_in};//store token
            callback(null, spotifyToken.token);
          }
        });
      }
    },
      function(err, results) {
        console.log('err = ', err);
        console.log('results = ', results);
        callback(results);
    });
  } else {
    //Function that returns if we already have a token
    auto({
      haveToken: function(callback) {
        callback(null, spotifyToken.token);
      }
    },
      function(err, results) {
        console.log('err = ', err);
        console.log('results = ', results);
        callback(results);
    });
  }
}
/*
* Function to get the categories from the spotify server
* @require request.category = 'pop';
*/
function getCategories(request, response, callback) {
  //Url for request along with header
  var searchInfo = {
    url: 'https://api.spotify.com/v1/browse/categories/' + request.query.category + '/playlists',
    headers: {
      'Authorization': 'Bearer ' + spotifyToken.token
    }
  };
  //Function to get a categories list of specific genre
  auto({
    getCat: function(callback) {
      req.get(searchInfo, function(error, response, body) {
        if (!error && response.statusCode === 200) {//if status 200
          categories = JSON.parse(body);
          //Filter lists with less than 50 tracks
          categories = categories.playlists.items.filter(function(item) {
            if (item.tracks.total > 50)//minimum number of songs needed for quiz with space for null values
              return item;
          })
          //return object with needed data
          .map(function(obj) {
              var temp = {playlistName: obj.name, playlistid: obj.id};
              return temp;
            });
          callback(null, categories);
        }
      });
    }
  },
    function(err, results) {
      console.log('err = ', err);
      console.log('results = ', results);
      callback(results);
  });
}
//Function to get random number
function randomizer(number) {
  return parseInt(Math.random() * (number));
}
/*
* Function to get the playlist using a playListId
* @return response.playlist
*/
function getPlayList(request, response, callback) {
  //URL and header
  var searchInfo = {
    url: 'https://api.spotify.com/v1/users/spotify/playlists/' + request.playListId,
    headers: {
      'Authorization': 'Bearer ' + spotifyToken.token
    }
  };
  //Function to get the list of music
  auto({
    getlist: function(callback) {
      req.get(searchInfo, function(error, response, body) {
        if (!error && response.statusCode === 200) {//if status 200
           playList = JSON.parse(body);
           //filter out items with null values
           playList = playList.tracks.items.filter(function(item) {
             //ensure all values are not null
             if (item.track.name && item.track.preview_url && item.track.artists[0].name && item.track.album.images[2].url){
               return item;
             }
           })
           //create map of information needed
           .map(function(item) {
             var temp = {songName: item.track.name, songUrl: item.track.preview_url, songArtist: item.track.artists[0].name,
             album: item.track.album.images[2].url};
             return temp;
           });
           callback(null, playList);
        }
      });
    }
  },
    function(err, results) {
      console.log('err = ', err);
      console.log('results = ', results);
      callback(results);
  });
}
/*
* Function to get the lyrics from musixmatch.
* @require request.songName = 'Same Old Love';request.songArtist = 'Selena Gomez';
* @return lyrics
*/
function getLyrics(request, response, callback) {

  var searchInfo = {
    url: 'http://api.musixmatch.com/ws/1.1/matcher.lyrics.get?apikey=' + process.env.apikey + '&q_track=' + request.query.songName + '&q_artist=' + request.query.songArtist
  };
  auto({
    getLyrics: function(callback){
        req.get(searchInfo, function(error, response, body) {
          lyrics = JSON.parse(body);
          callback(null, lyrics.message.body.lyrics.lyrics_body);
        });
    }
  }, function(err, results) {
    console.log('err = ', err);
    console.log('results = ', results);
    callback(results);
});
}
<commit_msg>Changed album image selection from spotify in favor of larger image.<commit_after>//get libraries required
var express = require('express');
var app = express();
var req = require('request');
var auto = require('run-auto');
var spotifyToken, categories = [], playList = [];
app.use(express.static(__dirname + '/'));//set the base directory to find resources
/*
* Function that gets initialized when navigating to base url. This function initially
* gets the token from spotify.
* @return /index.html page
*/
app.get('/', function(request, response) {
  auto({
    token: function(callback) {
      console.log('trying to get token');
      getToken(function(token) {
        callback(null, token);
      });
    },
  },
    function() {
    response.sendFile(__dirname + '/index.html');
  });
});
/*
* Function that gets called when /getMusic is called. Initially tries to get token,
* calls category, and finally playlist.
* @return response.playlist
*/
app.get('/getMusic', function (request, response) {
  auto({
    token: function(callback) {
      console.log('trying to get token');
      getToken(function(token) {
        callback(null, token);
      });
    },
    category: ['token', function(results, callback) {
      console.log('trying to get categories');
      getCategories(request, response, function(cat) {
        callback(null, cat);
      });
    }],
    playlist: ['token', 'category', function(results, callback) {
      console.log('trying to get playlist');
      request.playListId = categories[randomizer(categories.length)].playlistid;
      getPlayList(request, response, function(list) {
        callback(null, response.send(list));
      });
    }]
  });
});
app.get('/getLyrics', function(request, response) {
  auto({
    lyrics: function(callback) {
      console.log('trying to get lyrics');
      getLyrics(request, response, function(lyric) {
        callback(null, response.send(lyric));
      });
    }
  });
});
/*
* Start up node and listen on a specified port
*/
listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
});
/*
* Function to get client credentials token from spotify
*/
function getToken(callback) {
  var time = new Date();
  //checks if spotifytoken if not defined and the lifetime of the token
  if (spotifyToken === undefined || spotifyToken.expires_on <= (Date.now() / 1000.0)) {
    spotifyToken = undefined;
    /*
    * Authentication options used by spotify api for client credentials work flow
    */
    var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      headers: {
        'Authorization': 'Basic ' + (new Buffer(process.env.client_id + ':' + process.env.client_secret).toString('base64'))
      },
      form: {
        grant_type: 'client_credentials'
      },
      json: true
    };
    //Function to make the post to spotify for the token
    auto({
      postToken: function(callback) {
        req.post(authOptions, function(error, response, body) {
          if (!error && response.statusCode === 200) {//if status 200
            spotifyToken = {token : body.access_token, expires_on : (Date.now() / 1000.0) + body.expires_in};//store token
            callback(null, spotifyToken.token);
          }
        });
      }
    },
      function(err, results) {
        console.log('err = ', err);
        console.log('results = ', results);
        callback(results);
    });
  } else {
    //Function that returns if we already have a token
    auto({
      haveToken: function(callback) {
        callback(null, spotifyToken.token);
      }
    },
      function(err, results) {
        console.log('err = ', err);
        console.log('results = ', results);
        callback(results);
    });
  }
}
/*
* Function to get the categories from the spotify server
* @require request.category = 'pop';
*/
function getCategories(request, response, callback) {
  //Url for request along with header
  var searchInfo = {
    url: 'https://api.spotify.com/v1/browse/categories/' + request.query.category + '/playlists',
    headers: {
      'Authorization': 'Bearer ' + spotifyToken.token
    }
  };
  //Function to get a categories list of specific genre
  auto({
    getCat: function(callback) {
      req.get(searchInfo, function(error, response, body) {
        if (!error && response.statusCode === 200) {//if status 200
          categories = JSON.parse(body);
          //Filter lists with less than 50 tracks
          categories = categories.playlists.items.filter(function(item) {
            if (item.tracks.total > 50)//minimum number of songs needed for quiz with space for null values
              return item;
          })
          //return object with needed data
          .map(function(obj) {
              var temp = {playlistName: obj.name, playlistid: obj.id};
              return temp;
            });
          callback(null, categories);
        }
      });
    }
  },
    function(err, results) {
      console.log('err = ', err);
      console.log('results = ', results);
      callback(results);
  });
}
//Function to get random number
function randomizer(number) {
  return parseInt(Math.random() * (number));
}
/*
* Function to get the playlist using a playListId
* @return response.playlist
*/
function getPlayList(request, response, callback) {
  //URL and header
  var searchInfo = {
    url: 'https://api.spotify.com/v1/users/spotify/playlists/' + request.playListId,
    headers: {
      'Authorization': 'Bearer ' + spotifyToken.token
    }
  };
  //Function to get the list of music
  auto({
    getlist: function(callback) {
      req.get(searchInfo, function(error, response, body) {
        if (!error && response.statusCode === 200) {//if status 200
           playList = JSON.parse(body);
           //filter out items with null values
           playList = playList.tracks.items.filter(function(item) {
             //ensure all values are not null
             if (item.track.name && item.track.preview_url && item.track.artists[0].name && item.track.album.images[1].url){
               return item;
             }
           })
           //create map of information needed
           .map(function(item) {
             var temp = {songName: item.track.name, songUrl: item.track.preview_url, songArtist: item.track.artists[0].name,
             album: item.track.album.images[1].url};
             return temp;
           });
           callback(null, playList);
        }
      });
    }
  },
    function(err, results) {
      console.log('err = ', err);
      console.log('results = ', results);
      callback(results);
  });
}
/*
* Function to get the lyrics from musixmatch.
* @require request.songName = 'Same Old Love';request.songArtist = 'Selena Gomez';
* @return lyrics
*/
function getLyrics(request, response, callback) {

  var searchInfo = {
    url: 'http://api.musixmatch.com/ws/1.1/matcher.lyrics.get?apikey=' + process.env.apikey + '&q_track=' + request.query.songName + '&q_artist=' + request.query.songArtist
  };
  auto({
    getLyrics: function(callback){
        req.get(searchInfo, function(error, response, body) {
          lyrics = JSON.parse(body);
          callback(null, lyrics.message.body.lyrics.lyrics_body);
        });
    }
  }, function(err, results) {
    console.log('err = ', err);
    console.log('results = ', results);
    callback(results);
});
}
<|endoftext|>


<commit_before>var connect = require('connect');
var serveStatic = require('serve-static');
var fs = require('fs');
var request = require('request');
var qs = require('querystring');
//var gm = require('gm');
var gm = require('gm').subClass({ imageMagick: true });

// Init
var app = connect();
var server;
var indexPage;
var host = 'localhost';
var port = 3000;

// Handle POSIX signals
process.on('SIGINT', function() {
    process.stdout.write("Stopping webserver. Bye\n");
    server.close();
    process.exit(0);
});

process.on('SIGHUP', function() {
    fs.readFile(path + '/index.html', function(err, contents) {
        if (err) throw err;
        indexPage = contents;
        process.stdout.write("Reloaded index file\n");
    })
});

// Serve static file
app.use(serveStatic('build', {index: false}));

function readIndex(next) {
    // Read index.html and listen
    fs.readFile('build/index.html', "utf-8", next);
}

function startServer() {

    server = app.listen(port, host, function() {
        process.stdout.write("Listening on " + (host ? 'http://' + host + ':' : 'port ') + port + "\n");
    });
}

/* This function resends an image received from a post back, if
 * a correct post was made to /save-image.
 *
 * The image size limit is roughly 100mb.
 *
 * Returns true if a response was send.
 */
function saveImageRouter(req, res) {
    if (req.method == "POST" && req.url == "/save-image") {
        var body = '';
        req.on('data', function (data) {
            body += data;

            // kill connection if too much data (100mb).
            if (body.length > 100 * 1e6) {
                console.log("message is to long:", body.length);
                request.connection.destroy();
            }
        });

        req.on('end', function () {
            var post = qs.parse(body);
            if (!post['image-data'] && !post['image-name']) {
                res.writeHead(400, { "Content-Type": "text/plain" });
                res.end("");
                return;
            }

            var inputBuffer = new Buffer(post['image-data'], 'base64');

            gm(inputBuffer, "input.png")
                .flip()
                .toBuffer('PNG',function (err, buffer) {
                    if (err) {
                        console.log("error", err);
                        res.writeHead(500, { "Content-Type": "text/plain" });
                        res.end("");
                        return;
                    }

                    res.writeHead(200, {
                        "Content-Type": "Content-type: image/png" ,
                        'Content-Disposition': 'attachment; filename="' + post["image-name"]
                    });

                    res.end(buffer.toString("binary"), "binary");
                    return;
                });
        });

        return true;
    }

    return false;
}

/*
 * Starts the servers and index.html is only loaded once at startup.
 */
function staticServe() {
    readIndex(function(err, content) {
        if (err) throw err;

        app.use(function(req, res) {
            if (saveImageRouter(req, res)) {
                return;
            }

            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(content);
        });

        startServer();
    });
}

/*
 * Starts the server. Every request for index.html receives an updated version.
 */
function dynamicServe() {
    app.use(function(req, res) {
        if (saveImageRouter(req, res)) {
            return;
        }

        readIndex(function(err, content) {
            if (err) {
                res.writeHead(404, { "Content-Type": "text/plain" });
                res.end("File not Found.");
                return;
            }

            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(content);
        });
    });

    startServer();
}

if (process.argv.indexOf("--production") !== -1) {
    console.log("Starting server in production mode...");
    staticServe();
}
else {
    console.log("Starting server in development mode...");
    dynamicServe();
}<commit_msg>Fix image name<commit_after>var connect = require('connect');
var serveStatic = require('serve-static');
var fs = require('fs');
var request = require('request');
var qs = require('querystring');
//var gm = require('gm');
var gm = require('gm').subClass({ imageMagick: true });

// Init
var app = connect();
var server;
var indexPage;
var host = 'localhost';
var port = 3000;

// Handle POSIX signals
process.on('SIGINT', function() {
    process.stdout.write("Stopping webserver. Bye\n");
    server.close();
    process.exit(0);
});

process.on('SIGHUP', function() {
    fs.readFile(path + '/index.html', function(err, contents) {
        if (err) throw err;
        indexPage = contents;
        process.stdout.write("Reloaded index file\n");
    })
});

// Serve static file
app.use(serveStatic('build', {index: false}));

function readIndex(next) {
    // Read index.html and listen
    fs.readFile('build/index.html', "utf-8", next);
}

function startServer() {

    server = app.listen(port, host, function() {
        process.stdout.write("Listening on " + (host ? 'http://' + host + ':' : 'port ') + port + "\n");
    });
}

/* This function resends an image received from a post back, if
 * a correct post was made to /save-image.
 *
 * The image size limit is roughly 100mb.
 *
 * Returns true if a response was send.
 */
function saveImageRouter(req, res) {
    if (req.method == "POST" && req.url == "/save-image") {
        var body = '';
        req.on('data', function (data) {
            body += data;

            // kill connection if too much data (100mb).
            if (body.length > 100 * 1e6) {
                console.log("message is to long:", body.length);
                request.connection.destroy();
            }
        });

        req.on('end', function () {
            var post = qs.parse(body);
            if (!post['image-data'] && !post['image-name']) {
                res.writeHead(400, { "Content-Type": "text/plain" });
                res.end("");
                return;
            }

            var inputBuffer = new Buffer(post['image-data'], 'base64');

            gm(inputBuffer, "input.png")
                .flip()
                .toBuffer('PNG',function (err, buffer) {
                    if (err) {
                        console.log("error", err);
                        res.writeHead(500, { "Content-Type": "text/plain" });
                        res.end("");
                        return;
                    }

                    res.writeHead(200, {
                        "Content-Type": "Content-type: image/png" ,
                        'Content-Disposition': 'attachment; filename="' + post["image-name"] + '"'
                    });

                    res.end(buffer.toString("binary"), "binary");
                    return;
                });
        });

        return true;
    }

    return false;
}

/*
 * Starts the servers and index.html is only loaded once at startup.
 */
function staticServe() {
    readIndex(function(err, content) {
        if (err) throw err;

        app.use(function(req, res) {
            if (saveImageRouter(req, res)) {
                return;
            }

            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(content);
        });

        startServer();
    });
}

/*
 * Starts the server. Every request for index.html receives an updated version.
 */
function dynamicServe() {
    app.use(function(req, res) {
        if (saveImageRouter(req, res)) {
            return;
        }

        readIndex(function(err, content) {
            if (err) {
                res.writeHead(404, { "Content-Type": "text/plain" });
                res.end("File not Found.");
                return;
            }

            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(content);
        });
    });

    startServer();
}

if (process.argv.indexOf("--production") !== -1) {
    console.log("Starting server in production mode...");
    staticServe();
}
else {
    console.log("Starting server in development mode...");
    dynamicServe();
}<|endoftext|>


<commit_before>var Twit = require('twit')

var fs = require('fs'),
    path = require('path'),
    Twit = require('twit'),

    config = require(path.join(__dirname, 'config.js'));

var T = new Twit(config);

var bot = ['2:50 AM'];

var bot = bot[Math.floor(Math.random() * bot.length)];
var post = function () {

T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

}

//post();

var ontime = require('ontime')

ontime({
    cycle: '2:50:00'
}, function (ot) {
    // do your job here

post();
console.log('Hi');
ot.done()
    return
})

//setInterval(post, 10000);

/*setInterval(function() {
T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

 }*/

/*setInterval(
T.post('statuses/update', { status: '....' }, function(err, data, response) {

	console.log(data);
});

}
  //post_tweet (),
  10000
);*/ <commit_msg>Set time<commit_after>var Twit = require('twit')

var fs = require('fs'),
    path = require('path'),
    Twit = require('twit'),

    config = require(path.join(__dirname, 'config.js'));

var T = new Twit(config);

var bot = ['2:57 AM'];

var bot = bot[Math.floor(Math.random() * bot.length)];
var post = function () {

T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

}

//post();

var ontime = require('ontime')

ontime({
    cycle: '2:57:00'
}, function (ot) {
    // do your job here

post();
console.log('Hi');
ot.done()
    return
})

//setInterval(post, 10000);

/*setInterval(function() {
T.post('statuses/update', { status: bot }, function(err, data, response) {

console.log('success');

});

 }*/

/*setInterval(
T.post('statuses/update', { status: '....' }, function(err, data, response) {

	console.log(data);
});

}
  //post_tweet (),
  10000
);*/ <|endoftext|>


<commit_before>var expect = require('chai').expect;
var Transformer = require('./../../lib/transformer');
var transformer = new Transformer({'obj-method': true});

function test(script) {
  return transformer.run(script);
}

describe('Object methods', function () {

  it('should convert a function inside an object to method', function () {
    expect(test(
      '({\n' +
      '  someMethod: function(a, b, c) {\n' +
      '    return a + b + c;\n' +
      '  }\n' +
      '});'
    )).to.equal(
      '({\n' +
      '  someMethod(a, b, c) {\n' +
      '    return a + b + c;\n' +
      '  }\n' +
      '});'
    );
  });

  it('should ignore non-function properties of object', function () {
    expect(test(
      '({\n' +
      '  foo: 123,\n' +
      '  method1: function() {\n' +
      '  },\n' +
      '  bar: [],\n' +
      '  method2: function() {\n' +
      '  },\n' +
      '});'
    )).to.equal(
      '({\n' +
      '  foo: 123,\n' +
      '  method1() {\n' +
      '  },\n' +
      '  bar: [],\n' +
      '  method2() {\n' +
      '  },\n' +
      '});'
    );
  });

});
<commit_msg>Add tests that fail with current implementation<commit_after>var expect = require('chai').expect;
var Transformer = require('./../../lib/transformer');
var transformer = new Transformer({'obj-method': true});

function test(script) {
  return transformer.run(script);
}

function expectNoChange(script) {
  expect(test(script)).to.equal(script);
}

describe('Object methods', function () {

  it('should convert a function inside an object to method', function () {
    expect(test(
      '({\n' +
      '  someMethod: function(a, b, c) {\n' +
      '    return a + b + c;\n' +
      '  }\n' +
      '});'
    )).to.equal(
      '({\n' +
      '  someMethod(a, b, c) {\n' +
      '    return a + b + c;\n' +
      '  }\n' +
      '});'
    );
  });

  it('should ignore non-function properties of object', function () {
    expect(test(
      '({\n' +
      '  foo: 123,\n' +
      '  method1: function() {\n' +
      '  },\n' +
      '  bar: [],\n' +
      '  method2: function() {\n' +
      '  },\n' +
      '});'
    )).to.equal(
      '({\n' +
      '  foo: 123,\n' +
      '  method1() {\n' +
      '  },\n' +
      '  bar: [],\n' +
      '  method2() {\n' +
      '  },\n' +
      '});'
    );
  });

  xit('should convert function properties in nested object literal', function () {
    expect(test(
      '({\n' +
      '  nested: {\n' +
      '    method: function() {\n' +
      '    }\n' +
      '  }\n' +
      '});'
    )).to.equal(
      '({\n' +
      '  nested: {\n' +
      '    method() {\n' +
      '    }\n' +
      '  }\n' +
      '});'
    );
  });

  xit('should not convert named function expressions', function () {
    expectNoChange(
      '({\n' +
      '  foo: function foo() {\n' +
      '    return foo();\n' +
      '  }\n' +
      '});'
    );
  });

  xit('should not convert computed properties', function () {
    expectNoChange(
      '({\n' +
      '  ["foo" + count]: function() {\n' +
      '  }\n' +
      '});'
    );
  });

});
<|endoftext|>


<commit_before>var FSTK = require('fstk')
  , Async = require('async')
  , _ = require('underscore')
  , Belt = require('jsbelt')
  , Optionall = require('optionall')
  , Path = require('path')
;

module.exports = function(Seme, O){
  var Opts = O || new Optionall({'__dirname': Path.normalize(module.filename + '/../..')});

  var M = {};
  M.settings = Belt.extend({

  }, [Opts]);

  //faker lorem
  M['random'] = Seme.services.faker.Lorem;
  M['random'].phrase = Seme.services.faker.Company.catchPhrase;
  M['random'].adjective = Seme.services.faker.Company.bsAdjective;
  M['random'].descriptor = Seme.services.faker.Company.catchPhraseDescriptor;
  M['random'].noun = Seme.services.faker.Company.bsNoun;
  M['random'].buzz = Seme.services.faker.Company.bsBuzz;

  M['sources'] = {
    'Frankenstein': {
      'sections': 17
    , 'title': function(s){ return 'Frankenstein/Chapter_' + s; }
    }
  , 'Hamlet': {
      'sections': 5
    , 'title': function(s){ return 'The_Tragedy_of_Hamlet,_Prince_of_Denmark/Act_' + s; }
    }
  , 'Moby_Dick': {
      'sections': 135
    , 'title': function(s){ return 'Moby-Dick/Chapter_' + s; }
    }
  , 'Abelard': {
      'sections': 6
    , 'title': function(s){ return 'Letters_of_Abélard_and_Héloïse/Letter_' + s; }
    }
  };

  M['get_source'] = function(options, callback){
    var a = Belt.argulint(arguments)
      , self = this;
    a.o = _.defaults(a.o, {
      'source': self.sources[_.sample(_.keys(self.sources))]
    });
    a.o = _.defaults(a.o, {
      'section': Belt.random_int(1, Belt._get(a.o, 'sources.sections') + 1)
    });
    return Seme.services.wikisource.getArticle(a.o.source.title(a.o.section)
    , function(s){ return a.cb(null, s); });
  };

  M['get_article'] = function(topic, options, callback){
    var a = Belt.argulint(arguments)
      , self = this;
    a.o = _.defaults(a.o, {

    });

    return Seme.services.wikipedia.getArticle(topic
    , function(s){ return a.cb(null, s); });
  };

  M['get_quotes'] = function(speaker, options, callback){
    var a = Belt.argulint(arguments)
      , self = this;
    a.o = _.defaults(a.o, {

    });

    return Seme.services.wikiquote.getArticle(speaker
    , function(s){ return a.cb(null, s); });
  };

  return M;
};
<commit_msg>need to refactor faker bits<commit_after>var FSTK = require('fstk')
  , Async = require('async')
  , _ = require('underscore')
  , Belt = require('jsbelt')
  , Optionall = require('optionall')
  , Path = require('path')
;

module.exports = function(Seme, O){
  var Opts = O || new Optionall({'__dirname': Path.normalize(module.filename + '/../..')});

  var M = {};
  M.settings = Belt.extend({

  }, [Opts]);

  //faker lorem
  M['random'] = Seme.services.faker.Lorem;
  /*M['random'].phrase = Seme.services.faker.Company.catchPhrase;
  M['random'].adjective = Seme.services.faker.Company.bsAdjective;
  M['random'].descriptor = Seme.services.faker.Company.catchPhraseDescriptor;
  M['random'].noun = Seme.services.faker.Company.bsNoun;
  M['random'].buzz = Seme.services.faker.Company.bsBuzz;*/

  M['sources'] = {
    'Frankenstein': {
      'sections': 17
    , 'title': function(s){ return 'Frankenstein/Chapter_' + s; }
    }
  , 'Hamlet': {
      'sections': 5
    , 'title': function(s){ return 'The_Tragedy_of_Hamlet,_Prince_of_Denmark/Act_' + s; }
    }
  , 'Moby_Dick': {
      'sections': 135
    , 'title': function(s){ return 'Moby-Dick/Chapter_' + s; }
    }
  , 'Abelard': {
      'sections': 6
    , 'title': function(s){ return 'Letters_of_Abélard_and_Héloïse/Letter_' + s; }
    }
  };

  M['get_source'] = function(options, callback){
    var a = Belt.argulint(arguments)
      , self = this;
    a.o = _.defaults(a.o, {
      'source': self.sources[_.sample(_.keys(self.sources))]
    });
    a.o = _.defaults(a.o, {
      'section': Belt.random_int(1, Belt._get(a.o, 'sources.sections') + 1)
    });
    return Seme.services.wikisource.getArticle(a.o.source.title(a.o.section)
    , function(s){ return a.cb(null, s); });
  };

  M['get_article'] = function(topic, options, callback){
    var a = Belt.argulint(arguments)
      , self = this;
    a.o = _.defaults(a.o, {

    });

    return Seme.services.wikipedia.getArticle(topic
    , function(s){ return a.cb(null, s); });
  };

  M['get_quotes'] = function(speaker, options, callback){
    var a = Belt.argulint(arguments)
      , self = this;
    a.o = _.defaults(a.o, {

    });

    return Seme.services.wikiquote.getArticle(speaker
    , function(s){ return a.cb(null, s); });
  };

  return M;
};
<|endoftext|>


<commit_before>require('dotenv').load();
var mongoose = require('mongoose'),
    config = require('./config/config')();

var db = mongoose.connect(config.db.uri);
mongoose.connection.once('open', function(){
  console.log("Connection successful");
});

var appServer = require('./config/express')();
var smtpServer = require('./config/smtp-server')();

appServer.listen(config.server.port);
smtpServer.listen(config.smtp.port);

exports = module.exports = appServer;
exports = module.exports = smtpServer;<commit_msg>Commented out SMTP listening to test origin of errors on heroku deployment<commit_after>require('dotenv').load();
var mongoose = require('mongoose'),
    config = require('./config/config')();

var db = mongoose.connect(config.db.uri);
mongoose.connection.once('open', function(){
  console.log("Connection successful");
});

var appServer = require('./config/express')();
var smtpServer = require('./config/smtp-server')();

appServer.listen(config.server.port);
//smtpServer.listen(config.smtp.port);

exports = module.exports = appServer;
exports = module.exports = smtpServer;<|endoftext|>


<commit_before>//dummy.js

let doNothing = function(){};
let __2Dcontext = {
    save: doNothing,
    translate: doNothing,
    rotate: doNothing,
    scale: doNothing,
    drawImage: doNothing,
    beginPath: doNothing,
    arc: doNothing,
    stroke: doNothing,
    moveTo: doNothing,
    lineTo: doNothing,
    closePath: doNothing,
    restore: doNothing
};//end __2Dcontext
let __canvasElement = {
    width: 300,
    height: 150,
    clientWidth: 300,
    clientHeight: 150,
    offsetLeft: 0,
    offsetTop: 0,
    getContext: function(arg){
        if(arg === '2d'){
            return __2Dcontext;
        }//end if
    }//end getContext
};//end __canvasElement
let dummy = {
    Image: function(){},
    querySelector: function(){
        return null;
    },//end querySelector
    createElement: function(arg){
        if(arg === 'canvas'){
            return __canvasElement;
        }//end if
    },//end createElement
    body: {
        appendChild: doNothing
    }//end body
};//end dummy

export default dummy;
<commit_msg>add clearRect method to dummy object<commit_after>//dummy.js

let doNothing = function(){};
let __2Dcontext = {
    save: doNothing,
    translate: doNothing,
    rotate: doNothing,
    scale: doNothing,
    drawImage: doNothing,
    beginPath: doNothing,
    arc: doNothing,
    stroke: doNothing,
    moveTo: doNothing,
    lineTo: doNothing,
    closePath: doNothing,
    restore: doNothing,
    clearRect: doNothing
};//end __2Dcontext
let __canvasElement = {
    width: 300,
    height: 150,
    clientWidth: 300,
    clientHeight: 150,
    offsetLeft: 0,
    offsetTop: 0,
    getContext: function(arg){
        if(arg === '2d'){
            return __2Dcontext;
        }//end if
    }//end getContext
};//end __canvasElement
let dummy = {
    Image: function(){},
    querySelector: function(){
        return null;
    },//end querySelector
    createElement: function(arg){
        if(arg === 'canvas'){
            return __canvasElement;
        }//end if
    },//end createElement
    body: {
        appendChild: doNothing
    }//end body
};//end dummy

export default dummy;
<|endoftext|>


<commit_before>var express = require('express')
  , markdown = new (require('./public/lib/mdext/src/showdown').Showdown.converter)()
  , mongoose = require('mongoose')
  , _ = require('underscore')
  , app = module.exports = express.createServer();

// By default Jade will kill itself inside a MathJax configuration script
// So we need this filter

require('jade').filters.protect = function (text) { return text; }

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'your secret here' }));
  app.use(express.compiler({ src: __dirname + '/public', enable: ['sass'] }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Configure the markdown parser

_.extend(markdown.config, {
  stripHTML: true,
  tables: true,
  math: true,
  figures: true,
  refprint: true,
  github_flavouring: true
});

// Mongoose connection and Model

mongoose.connect('mongodb://localhost/techpages');

var PageSchema = new mongoose.Schema({
  iden : { type: String, index: { unique: true } },
  text : String,
  hash : String
});
mongoose.model('Page', PageSchema);

var PageModel = mongoose.model('Page');

// Utility functions for generating random URL and mobile detection

function rstring(len) {
  var text = "", possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for( var i=0; i < 6; i++ ) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

function isMobileBrowser(useragent) {
  return (/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(useragent)
  ||
  /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(useragent.substr(0,4)));
}

// Middleware for processing page id and extension

function prePage(req, res, next) {
  req.params.id = req.params[0];
  if (req.params[1] !== undefined) {
    req.params.extn = req.params[1];
  } else {
    req.params.extn = "html";
  }
  next();
}

// Routes

app.get('/', function(req, res) {
  res.render("front", {randid: rstring(6)});
});

app.post(/^\/([a-zA-Z0-9_-]{2,})\.?(json)?$/, prePage, express.bodyParser(), function(req, res, next) {
  PageModel.findOne({iden: req.params.id}, function (err, post) {
    if (err) {
      res.send({status:"failure", message:"Internal error."}, 500);
      return;
    } else if (post) {
      if ((req.body.password || (post.hash !== "false")) && (post.hash !== req.body.password)) {
        res.send({status:"failure",message:"Invalid password."}, 403);
      } else {
        post.text = req.body.text;
        post.save(function(err) {
          if (!err) res.send({status:"success",message:"Page updated."}, 200);
          console.log("Updated " + page.iden + ".");
        });
      }
    } else {
      post = new PageModel();
      post.iden = req.params.id;
      post.text = req.body.text;
      if (req.body.password) {
        post.hash = req.body.password;
      } else {
        post.hash = false;
      }
      post.save(function (err) {
        if (!err) res.send({status:"success",message:"Page created."}, 200);
        console.log("Created " + page.iden + ".");
      });
    }
  });
});

app.get(/^\/([a-zA-Z0-9_-]{2,})\.?(json)?$/, prePage, function(req, res, next) {
  var page = {
    pagename: req.params.id
  }

  PageModel.findOne({iden: req.params.id}, function (err, post) {
    if (err) {
      res.send("Something went wrong.", 500);
      return;
    }

    if (post && post.hash !== "false") {
      page.passreq = "true";
    } else {
      page.passreq = "false";
    }

    if (!err && post) {
      if (req.params.extn === "json") {
        console.log("Returned " + page.pagename + " as json.");
        res.send({text:post.text});
        return;
      } else {
        page.editing = "false";
        page.content = markdown.makeHtml(post.text);
      }
    } else {
      page.editing = "true";
      page.content = "";
    }

    if (req.headers["user-agent"] && isMobileBrowser(req.headers["user-agent"])) {
      console.log("Rendered " + page.pagename + " for mobile. (new: " + page.editing + ")");
      res.render('mobile', { page: page });
    } else {
      console.log("Rendered " + page.pagename + " for browser. (new: " + page.editing + ")");
      res.render('page', { page: page });
    }
  });
});

// Start the server

if (!module.parent) {
  app.listen(8888);
  console.log("Express server listening on port %d", app.address().port);
}<commit_msg>Bugfix status messages<commit_after>var express = require('express')
  , markdown = new (require('./public/lib/mdext/src/showdown').Showdown.converter)()
  , mongoose = require('mongoose')
  , _ = require('underscore')
  , app = module.exports = express.createServer();

// By default Jade will kill itself inside a MathJax configuration script
// So we need this filter

require('jade').filters.protect = function (text) { return text; }

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ secret: 'your secret here' }));
  app.use(express.compiler({ src: __dirname + '/public', enable: ['sass'] }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Configure the markdown parser

_.extend(markdown.config, {
  stripHTML: true,
  tables: true,
  math: true,
  figures: true,
  refprint: true,
  github_flavouring: true
});

// Mongoose connection and Model

mongoose.connect('mongodb://localhost/techpages');

var PageSchema = new mongoose.Schema({
  iden : { type: String, index: { unique: true } },
  text : String,
  hash : String
});
mongoose.model('Page', PageSchema);

var PageModel = mongoose.model('Page');

// Utility functions for generating random URL and mobile detection

function rstring(len) {
  var text = "", possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for( var i=0; i < 6; i++ ) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

function isMobileBrowser(useragent) {
  return (/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(useragent)
  ||
  /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(useragent.substr(0,4)));
}

// Middleware for processing page id and extension

function prePage(req, res, next) {
  req.params.id = req.params[0];
  if (req.params[1] !== undefined) {
    req.params.extn = req.params[1];
  } else {
    req.params.extn = "html";
  }
  next();
}

// Routes

app.get('/', function(req, res) {
  res.render("front", {randid: rstring(6)});
});

app.post(/^\/([a-zA-Z0-9_-]{2,})\.?(json)?$/, prePage, express.bodyParser(), function(req, res, next) {
  PageModel.findOne({iden: req.params.id}, function (err, post) {
    if (err) {
      res.send({status:"failure", message:"Internal error."}, 500);
      return;
    } else if (post) {
      if ((req.body.password || (post.hash !== "false")) && (post.hash !== req.body.password)) {
        res.send({status:"failure",message:"Invalid password."}, 403);
      } else {
        post.text = req.body.text;
        post.save(function(err) {
          if (!err) res.send({status:"success",message:"Page updated."}, 200);
          console.log("Updated " + post.iden + ".");
        });
      }
    } else {
      post = new PageModel();
      post.iden = req.params.id;
      post.text = req.body.text;
      if (req.body.password) {
        post.hash = req.body.password;
      } else {
        post.hash = false;
      }
      post.save(function (err) {
        if (!err) res.send({status:"success",message:"Page created."}, 200);
        console.log("Created " + post.iden + ".");
      });
    }
  });
});

app.get(/^\/([a-zA-Z0-9_-]{2,})\.?(json)?$/, prePage, function(req, res, next) {
  var page = {
    pagename: req.params.id
  }

  PageModel.findOne({iden: req.params.id}, function (err, post) {
    if (err) {
      res.send("Something went wrong.", 500);
      return;
    }

    if (post && post.hash !== "false") {
      page.passreq = "true";
    } else {
      page.passreq = "false";
    }

    if (!err && post) {
      if (req.params.extn === "json") {
        console.log("Returned " + page.pagename + " as json.");
        res.send({text:post.text});
        return;
      } else {
        page.editing = "false";
        page.content = markdown.makeHtml(post.text);
      }
    } else {
      page.editing = "true";
      page.content = "";
    }

    if (req.headers["user-agent"] && isMobileBrowser(req.headers["user-agent"])) {
      console.log("Rendered " + page.pagename + " for mobile. (new: " + page.editing + ")");
      res.render('mobile', { page: page });
    } else {
      console.log("Rendered " + page.pagename + " for browser. (new: " + page.editing + ")");
      res.render('page', { page: page });
    }
  });
});

// Start the server

if (!module.parent) {
  app.listen(8888);
  console.log("Express server listening on port %d", app.address().port);
}<|endoftext|>


<commit_before>//var http = require('http');

//http.createServer(function (req, res) {
//    console.log(req);
//    console.log("Request received");
//    res.writeHead(200, { 'Content-Type': 'text/html' });
//    res.end('');

//}).listen(process.env.PORT || 8080);

//console.log("Server running");

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>Reverting previous commit<commit_after>var http = require('http');

http.createServer(function (req, res) {
    console.log(req);
    console.log("Request received");
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('');

}).listen(process.env.PORT || 8080);

console.log("Server running");

//var express = require('express');
//var path = require('path');
//var favicon = require('serve-favicon');
//var logger = require('morgan');
//var cookieParser = require('cookie-parser');
//var bodyParser = require('body-parser');

//var routes = require('./routes/index');
//var users = require('./routes/users');

//var app = express();

//// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');

//// uncomment after placing your favicon in /public
////app.use(favicon(__dirname + '/public/favicon.ico'));
//app.use(logger('dev'));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
//app.use(cookieParser());
//app.use(express.static(path.join(__dirname, 'public')));

//app.use('/', routes);
//app.use('/users', users);

//// catch 404 and forward to error handler
//app.use(function(req, res, next) {
//  var err = new Error('Not Found');
//  err.status = 404;
//  next(err);
//});

//// error handlers

//// development error handler
//// will print stacktrace
//if (app.get('env') === 'development') {
//  app.use(function(err, req, res, next) {
//    res.status(err.status || 500);
//    res.render('error', {
//      message: err.message,
//      error: err
//    });
//  });
//}

//// production error handler
//// no stacktraces leaked to user
//app.use(function(err, req, res, next) {
//  res.status(err.status || 500);
//  res.render('error', {
//    message: err.message,
//    error: {}
//  });
//});

//module.exports = app;
<|endoftext|>


<commit_before>/*jslint white: false, indent: 4 */
var EventEmitter = require("events").EventEmitter;
var request = require('request');

var octopart = {};

//// private helper functions ////
var formatArgs = function (args) {
    var i, val, akey, result = {};
    Object.keys(args).forEach(function (key) {
        val = args[key];
        if (Array.isArray(val)) {
            for (i = 0; i < val.length; i++) {
                akey = key + '[' + i + ']';
                result[akey] = val[i];
            }
        }
        else {
            result[key] = val;
        }
    });
    return result;
};

//// exported octopart module functions ////
octopart.baseurl = "http://octopart.com/api/v3";
octopart.apikey = 'replace-me';

octopart.chunks = function (array, size) {
    var chunks = [];
    while (array.length) {
        chunks.push(array.splice(0, size));
    }
    return chunks;
};

octopart.request = function (endpoint, args) {
    var e = new EventEmitter();

    args.apikey = octopart.apikey;
    args = formatArgs(args);

    request({
        uri: octopart.baseurl + endpoint,
        qs: args,
        json: true
    }, function (error, response, body) {
        if (!error && response.statusCode !== 200) {
            error = new Error("Invalid status code");
            error.statusCode = response.statusCode;
        }
        if (error) {
            e.emit('failure', error);
        }
        else {
            e.emit('success', body);
        }
        e.emit('complete', error, body);
    });

    // Return EventEmitter
    var self = {};
    self.complete = function (f) {
        e.on('complete', f);
        return self;
    };
    self.success = function (f) {
        e.on('success', f);
        return self;
    };
    self.failure = function (f) {
        e.on('failure', f);
        return self;
    };
    return self;
};

octopart.brands = {
    get: function (uids, options) {
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/brands/get_multi", options);
    },
    search: function (q, options) {
        options.q = q;
        return octopart.request("/brands/search", options);
    }
};

octopart.categories = {
    get: function (uids, options) {
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/categories/get_multi", options);
    },
    search: function (q, options) {
        options.q = q;
        return octopart.request("/categories/search", options);
    }
};

octopart.parts = {
    get: function (uids, options) {
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/parts/get_multi", options);
    },
    match: function (queries, options) {
        options.queries = JSON.stringify(queries);
        return octopart.request("/parts/match", options);
    },
    search: function (q, options) {
        options.q = q;
        return octopart.request("/parts/search", options);
    }
};

octopart.sellers = {
    get: function (uids, options) {
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/sellers/get_multi", options);
    },
    search: function (q, options) {
        options.q = q;
        return octopart.request("/sellers/get_multi", options);
    }
};

module.exports = octopart;<commit_msg>Make options argument optional for all endpoints<commit_after>/*jslint white: false, indent: 4 */
var EventEmitter = require("events").EventEmitter;
var request = require('request');

var octopart = {};

//// private helper functions ////
var formatArgs = function (args) {
    var i, val, akey, result = {};
    Object.keys(args).forEach(function (key) {
        val = args[key];
        if (Array.isArray(val)) {
            for (i = 0; i < val.length; i++) {
                akey = key + '[' + i + ']';
                result[akey] = val[i];
            }
        }
        else {
            result[key] = val;
        }
    });
    return result;
};

//// exported octopart module functions ////
octopart.baseurl = "http://octopart.com/api/v3";
octopart.apikey = 'replace-me';

octopart.chunks = function (array, size) {
    var chunks = [];
    while (array.length) {
        chunks.push(array.splice(0, size));
    }
    return chunks;
};

octopart.request = function (endpoint, args) {
    var e = new EventEmitter();

    args.apikey = octopart.apikey;
    args = formatArgs(args);

    request({
        uri: octopart.baseurl + endpoint,
        qs: args,
        json: true
    }, function (error, response, body) {
        if (!error && response.statusCode !== 200) {
            error = new Error("Invalid status code");
            error.statusCode = response.statusCode;
        }
        if (error) {
            e.emit('failure', error);
        }
        else {
            e.emit('success', body);
        }
        e.emit('complete', error, body);
    });

    // Return EventEmitter
    var self = {};
    self.complete = function (f) {
        e.on('complete', f);
        return self;
    };
    self.success = function (f) {
        e.on('success', f);
        return self;
    };
    self.failure = function (f) {
        e.on('failure', f);
        return self;
    };
    return self;
};

octopart.brands = {
    get: function (uids, options) {
        options = options || {};
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/brands/get_multi", options);
    },
    search: function (q, options) {
        options = options || {};
        options.q = q;
        return octopart.request("/brands/search", options);
    }
};

octopart.categories = {
    get: function (uids, options) {
        options = options || {};
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/categories/get_multi", options);
    },
    search: function (q, options) {
        options = options || {};
        options.q = q;
        return octopart.request("/categories/search", options);
    }
};

octopart.parts = {
    get: function (uids, options) {
        options = options || {};
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/parts/get_multi", options);
    },
    match: function (queries, options) {
        options = options || {};
        options.queries = JSON.stringify(queries);
        return octopart.request("/parts/match", options);
    },
    search: function (q, options) {
        options = options || {};
        options.q = q;
        return octopart.request("/parts/search", options);
    }
};

octopart.sellers = {
    get: function (uids, options) {
        options = options || {};
        options.uids = Array.isArray(uids) ? uids : [uids];
        return octopart.request("/sellers/get_multi", options);
    },
    search: function (q, options) {
        options = options || {};
        options.q = q;
        return octopart.request("/sellers/get_multi", options);
    }
};

module.exports = octopart;<|endoftext|>


<commit_before>require('dotenv').config();
const Hapi = require('hapi');
const Path = require('path');
const Vision = require('vision');
const Inert = require('inert');
const NunjucksHapi = require('nunjucks-hapi');
const Good = require('good');

const postgresPool = require('./plugins/postgres-pool.js');

const Api = require('./api');
const Views = require('./views');

const setup = {
  host: process.env.NODE_ENV === 'production' ? '0.0.0.0' : 'localhost',
  port: process.env.PORT || '8080',
};

const BasicServer = new Hapi.Server({
  connections: {
    routes: {
      files: {
        relativeTo: Path.join(__dirname, 'static'),
      },
    },
  },
});
BasicServer.connection({
  host: setup.host,
  port: setup.port,
});

BasicServer.register(postgresPool);
BasicServer.register(Api, {
  routes: {
    prefix: '/api',
  },
});

BasicServer.register(Inert);
BasicServer.register(Vision, () => {
  BasicServer.views({
    engines: {
      html: NunjucksHapi,
    },
    path: Path.join(__dirname, 'templates'),
  });
});
BasicServer.register(Views);

BasicServer.register({
  register: Good,
  options: {
    ops: {
      interval: 1000,
    },
    reporters: {
      console: [{
        module: 'good-squeeze',
        name: 'Squeeze',
        args: [{
          log: '*',
          response: '*',
        }],
      }, {
        module: 'good-console',
      }, 'stdout'],
    },
  },
}, (err) => {
  if (err) BasicServer.log(['error', 'good'], err);
});

BasicServer.start(() => {
  BasicServer.log(['info', 'BasicServer'], `Server started on ${setup.host}:${setup.port}`);
});

module.exports = BasicServer;
<commit_msg>ESLint appeasement commit<commit_after>require('dotenv').config();
const Hapi = require('hapi');
const Path = require('path');
const Vision = require('vision');
const Inert = require('inert');
const NunjucksHapi = require('nunjucks-hapi');
const Good = require('good');

// const postgresPool = require('./plugins/postgres-pool.js');

const Api = require('./api');
const Views = require('./views');

const setup = {
  host: process.env.NODE_ENV === 'production' ? '0.0.0.0' : 'localhost',
  port: process.env.PORT || '8080',
};

const BasicServer = new Hapi.Server({
  connections: {
    routes: {
      files: {
        relativeTo: Path.join(__dirname, 'static'),
      },
    },
  },
});
BasicServer.connection({
  host: setup.host,
  port: setup.port,
});

BasicServer.register(postgresPool);
BasicServer.register(Api, {
  routes: {
    prefix: '/api',
  },
});

BasicServer.register(Inert);
BasicServer.register(Vision, () => {
  BasicServer.views({
    engines: {
      html: NunjucksHapi,
    },
    path: Path.join(__dirname, 'templates'),
  });
});
BasicServer.register(Views);

BasicServer.register({
  register: Good,
  options: {
    ops: {
      interval: 1000,
    },
    reporters: {
      console: [{
        module: 'good-squeeze',
        name: 'Squeeze',
        args: [{
          log: '*',
          response: '*',
        }],
      }, {
        module: 'good-console',
      }, 'stdout'],
    },
  },
}, (err) => {
  if (err) BasicServer.log(['error', 'good'], err);
});

BasicServer.start(() => {
  BasicServer.log(['info', 'BasicServer'], `Server started on ${setup.host}:${setup.port}`);
});

module.exports = BasicServer;
<|endoftext|>