const {client} = require('nightwatch-cucumber');
const {defineSupportCode} = require('cucumber');

const homePage = client.page.home();

defineSupportCode(({Given, Then}) => {

    Given(/^I open the home page$/, () => {
        return homePage
            .navigate()
            .waitForElementVisible('@body', 1000);
    });

    Then(/^the title is "(.*?)"$/, (text) => {
        return client.assert.title(text);
    });

    Then(/^the page should contain text "(.*?)"$/, (text) => {
        return homePage.assert.containsText('@root', text);
    });
});

const {client} = require('nightwatch-cucumber');
const {defineSupportCode} = require('cucumber');

const homePage = client.page.home();

defineSupportCode(({Given, Then}) => {

    Given(/^I open the home page$/, () => {
        return homePage
            .navigate()
            .waitForElementVisible('@body', 1000);
    });

    Then(/^the title is "(.*?)"$/, (text) => {
        return client.assert.title(text);
    });

    Then(/^the page should contain text "(.*?)"$/, (text) => {
        return homePage.expect.element('@root').text.to.contain(text);
    });
});

Use expect api for element assertions


import React from 'react'
import { storiesOf } from '@kadira/storybook'

import { Button } from '../buttons'

storiesOf('Buttons', module)
  .add('Standard button', () => (
    <Button>I'm a button!</Button>
  ))

import React from 'react'
import { storiesOf, action } from '@kadira/storybook'

import { Button } from '../buttons'

storiesOf('Buttons', module)
  .add('Standard button', () => (
    <Button onClick={action('Clicked')}>I'm a button!</Button>
  ))

Add action to button story


jest.dontMock('../lib/twitter-status');

import TwitterStatus from '../lib/twitter-status';
jest.mock('Twit');

var ReadYaml = require('read-yaml');
var Twit = require('twit');
var config = ReadYaml.sync('twitter.yml');
var client = new Twit({});

describe('TwitterStatus', function() {

  describe('#showStatusFor', function() {
    it('calls with correct params', function() {
      var twitterStatus = new TwitterStatus(client);
      twitterStatus.showStatusFor('videodrom_pod' );
      expect(client.get.mock.calls.length).toEqual(1);
      expect(client.get.mock.calls[0][0]).toEqual('statuses/user_timeline')
      expect(client.get.mock.calls[0][1]).toEqual({screen_name: 'videodrom_pod'})
    });
  });

  describe('#displayFollowers', function() {
    it('returns this', function() {
      var tweet = { text: 'Hello Twitter' } ;
      var tweets = [tweet];
      var twitterStatus = new TwitterStatus(client);
      expect(twitterStatus.displayTweets(tweets)).toEqual(twitterStatus);
    });
  });

});

jest.dontMock('../lib/twitter-status');

import TwitterStatus from '../lib/twitter-status';
var Twit = require('twit');
var client = new Twit({});

describe('TwitterStatus', function() {

  describe('#showStatusFor', function() {
    it('calls with correct params', function() {
      var twitterStatus = new TwitterStatus(client);
      twitterStatus.showStatusFor('videodrome_pod' );
      expect(client.get.mock.calls.length).toEqual(1);
      expect(client.get.mock.calls[0][0]).toEqual('statuses/user_timeline')
      expect(client.get.mock.calls[0][1]).toEqual({screen_name: 'videodrome_pod'})
    });
  });

  describe('#displayFollowers', function() {
    it('returns this', function() {
      var tweet = { text: 'Hello Twitter' } ;
      var tweets = [tweet];
      var twitterStatus = new TwitterStatus(client);
      expect(twitterStatus.displayTweets(tweets)).toEqual(twitterStatus);
    });
  });

});

Update TwitterStatus test to remove mock of Twit module


var constantModule = angular.module('uchiwa.constants', []);

// Settings
constantModule.constant('settings', {
  date: 'yyyy-MM-dd HH:mm:ss',
  hideSilenced: true,
  hideOccurrences: true,
  theme: 'default'
});

// Version
constantModule.constant('version', {
  uchiwa: '0.4.0'
});

var constantModule = angular.module('uchiwa.constants', []);

// Settings
constantModule.constant('settings', {
  date: 'yyyy-MM-dd HH:mm:ss',
  hideSilenced: false,
  hideOccurrences: false,
  theme: 'default'
});

// Version
constantModule.constant('version', {
  uchiwa: '0.4.0'
});

Revert hideSilenced constant to default false value, set hideOccurrences to false


FullScreenPokemon.FullScreenPokemon.settings.statistics = {
    "prefix": "FullScreenPokemon::",
    "defaults": {
        "storeLocally": true
    },
    "values": {
        "gameStarted": {
            "valueDefault": false
        },
        "map": {
            "valueDefault": ""
        },
        "area": {
            "valueDefault": ""
        },
        "location": {
            "valueDefault": ""
        },
        "lastPokecenter": {
            "valueDefault": {
                "map": "Pallet Town",
                "location": "Player's House Door"
            }
        },
        "badges": {
            "valueDefault": {
                "Brock": false,
                "Misty": false,
                "LtSurge": false,
                "Erika": false,
                "Koga": false,
                "Sabrina": false,
                "Blaine": false,
                "Giovanni": false
            }
        },
        "items": {
            "valueDefault": []
        },
        "money": {
            "valueDefault": 0,
            "minimum": 0
        },
        "time": {
            "valueDefault": 0
        },
        "name": {},
        "nameRival": {},
        "starter": {},
        "starterRival": {},
        "hasPokedex": {
            "valueDefault": false
        },
        "Pokedex": {
            "valueDefault": []
        },
        "PokemonInParty": {
            "valueDefault": []
        },
        "PokemonInPC": {
            "valueDefault": []
        }
    }
};

FullScreenPokemon.FullScreenPokemon.settings.statistics = {
    "prefix": "FullScreenPokemon::",
    "defaults": {
        "storeLocally": true
    },
    "values": {
        "gameStarted": {
            "valueDefault": false
        },
        "map": {
            "valueDefault": ""
        },
        "area": {
            "valueDefault": ""
        },
        "location": {
            "valueDefault": ""
        },
        "lastPokecenter": {
            "valueDefault": {
                "map": "Pallet Town",
                "location": "Player's House Door"
            }
        },
        "badges": {
            "valueDefault": {
                "Brock": false,
                "Misty": false,
                "LtSurge": false,
                "Erika": false,
                "Koga": false,
                "Sabrina": false,
                "Blaine": false,
                "Giovanni": false
            }
        },
        "items": {
            "valueDefault": []
        },
        "money": {
            "valueDefault": 0,
            "minimum": 0
        },
        "time": {
            "valueDefault": 0
        },
        "name": {},
        "nameRival": {},
        "starter": {},
        "starterRival": {},
        "hasPokedex": {
            "valueDefault": false
        },
        "Pokedex": {
            "valueDefault": {}
        },
        "PokemonInParty": {
            "valueDefault": []
        },
        "PokemonInPC": {
            "valueDefault": []
        }
    }
};

Fix for Pokedex defaulting to [], not {}


var db = require('../app').db;
var generate = require('project-name-generator');
var count;
exports.getRoot = function(req, cb) {
 cb(null, {"title":"Title"});
};

var setPage = exports.setPage = function(req, cb) {
  var id = generate().dashed;
  console.log(id);
  db.get(id, function(err, reply) {
    /*retrying if unique id already exists or
    has error*/
    if (err || reply) {
      if (count > 10) {
        console.log('exhausted..giving up');
        cb("DB is stressed");
      }
      debug('Retrying another word-set');
      setPage(req, cb);
      count++;
    }
    console.log(req.body.url);
    db.set(id, req.body.url);
    cb(null, id.toString());
  });
};

var db = require('../app').db;
var generate = require('project-name-generator');
var count;
exports.getRoot = function(req, cb) {
  cb(null, {
    "title": "Title"
  });
};

var setPage = exports.setPage = function(req, cb) {
  function hasValue(val, cb) {
    return db.exists("val:" + val, cb);
  }

  function setValue() {
    var id = generate().dashed;
    console.log(id);
    db.get(id, function(err, reply) {
      /*retrying if unique id already exists or
      has error*/
      if (err || reply) {
        if (count > 10) {
          console.log('exhausted..giving up');
          cb("DB is stressed");
        }
        debug('Retrying another word-set');
        setPage(req, cb);
        count++;
      }
      console.log(req.body.url);
      db.set("key:" + id, req.body.url);
      db.set("val:" + req.body.url, id);
      cb(null, id.toString());
    });
  }

  var url = req.body.url;
  hasValue(url, function(err, reply) {
    console.log("error", err);
    console.log("reply", reply);
    if (err) {
      return new Error(err);
    }
    if (reply === 0) {
      return setValue();
    }
    var existingId = db.get("val:" + url, function(err, reply) {
      cb(null, reply);
    });
  });
};

Refactor and optimization on redis key/value


/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

/* jshint unused: vars */
export default
    [
        'CreateSelect2',
        function(CreateSelect2) {
            return {
                restrict: 'E',
                scope: false,
                template: '<select ng-cloak class="AddPermissions-selectHide roleSelect2 form-control" ng-model="obj.roles" ng-options="role.label for role in roles track by role.value" multiple required></select>',
                link: function(scope, element, attrs, ctrl) {
                    CreateSelect2({
                        element: '.roleSelect2',
                        multiple: true,
                        placeholder: 'Select roles'
                    });
                }
            };
        }
    ];

/*************************************************
 * Copyright (c) 2015 Ansible, Inc.
 *
 * All Rights Reserved
 *************************************************/

/* jshint unused: vars */
export default
    [
        'CreateSelect2',
        function(CreateSelect2) {
            return {
                restrict: 'E',
                scope: false,
                template: '<select ng-cloak class="AddPermissions-selectHide roleSelect2 form-control" ng-model="obj.roles" ng-options="role.label for role in roles | filter:{label: \'!Read\'} track by role.value" multiple required></select>',
                link: function(scope, element, attrs, ctrl) {
                    CreateSelect2({
                        element: '.roleSelect2',
                        multiple: true,
                        placeholder: 'Select roles'
                    });
                }
            };
        }
    ];

Hide the "Read" role as being something users can select


import React, { PureComponent } from "react";
import { Modal } from "react-bootstrap";

export default class ImageAnswerModal extends PureComponent {
  componentDidMount() {
    window.addEventListener("click", this.windowClicked.bind(this), true);
  }

  componentWillUnmount() {
    window.removeEventListener("click", this.windowClicked.bind(this));
  }

  windowClicked() {
    const { show, onHide } = this.props;
    if (show) {
      // hide the modal with any click in the window and not just the modal background
      onHide();
    }
  }

  render() {
    const { answer, show, onHide } = this.props;
    if (!answer) { return null; }
    return (
      <Modal show={show} onHide={onHide} animation={false}>
        <Modal.Header closeButton closeLabel="" />
        <Modal.Body>

        </Modal.Body>
        <Modal.Footer>

{answer.getIn(["student", "name"])}

{answer.getIn(["answer", "text"])}

        </Modal.Footer>
      </Modal>
    );
  }
}

import React, { PureComponent } from "react";
import { Modal } from "react-bootstrap";
import { renderInvalidAnswer } from "../../util/answer-utils";

export default class ImageAnswerModal extends PureComponent {
  componentDidMount() {
    window.addEventListener("click", this.windowClicked.bind(this), true);
  }

  componentWillUnmount() {
    window.removeEventListener("click", this.windowClicked.bind(this));
  }

  windowClicked() {
    const { show, onHide } = this.props;
    if (show) {
      // hide the modal with any click in the window and not just the modal background
      onHide();
    }
  }

  render() {
    const { answer, show, onHide } = this.props;
    if(!answer) {
      return null;
    } else {
      if (!(answer.getIn(["answer", "imageUrl"]))) { return renderInvalidAnswer(answer, "response is missing answer field"); }
    }
    return (
      <Modal show={show} onHide={onHide} animation={false}>
        <Modal.Header closeButton closeLabel="" />
        <Modal.Body>

        </Modal.Body>
        <Modal.Footer>

{answer.getIn(["student", "name"])}

{answer.getIn(["answer", "text"])}

        </Modal.Footer>
      </Modal>
    );
  }
}

Add error mesage to report image carousel


var io = require('socket.io').listen(8001)
  , amqp = require('amqp')
  ;

io.set('log level', 1)

var connection = amqp.createConnection()

connection.on('ready', function(){

    connection.queue("", {"autoDelete": true}, function(queue){

        queue.bind("amq.topic", "");
        queue.subscribe(function(message, headers, deliveryInfo){
            console.log(message.data.toString());
        });
    });

    io.sockets.on('connection', function(socket) {

        console.log("Client connected.");
        connection.queue("", {"autoDelete": true}, function(queue){

            queue.bind("amq.topic", "event.*");
            queue.subscribe(function(message, headers, deliveryInfo){
                console.log(deliveryInfo.routingKey);
                socket.emit(deliveryInfo.routingKey, message.data.toString());
            });
        });
    });
});

var io = require('socket.io').listen(8001)
  , amqp = require('amqp')
  ;

io.set('log level', 1)

var connection = amqp.createConnection()

connection.on('ready', function(){

    connection.queue("", {"autoDelete": true}, function(queue){

        queue.bind("amq.topic", "");
        queue.subscribe(function(message, headers, deliveryInfo){
            console.log(message.data.toString());
        });
    });

    io.sockets.on('connection', function(socket) {

        console.log("Client connected.");
        connection.queue("", {"autoDelete": true}, function(queue){

            queue.bind("amq.topic", "event.*");
            queue.subscribe(function(message, headers, deliveryInfo){
                console.log(deliveryInfo.routingKey);
                socket.emit(deliveryInfo.routingKey, message.data.toString());
            });

            socket.on('disconnect', function(){
                console.log("Client disconnected.");
                queue.destroy();
            });
        });
    });
});

Fix bug with leaking queues


const { defaults: tsjPreset } = require("ts-jest/presets");
const path = require("path");

module.exports = {
  projects: [
    {
      displayName: "smc-webapp",
      testMatch: [
        "<rootDir>/smc-webapp/**/*test.ts",
        "<rootDir>/smc-webapp/**/*test.tsx",
      ],
      transform: {
        ...tsjPreset.transform
      },
      testPathIgnorePatterns: ["/node_modules/", "/test-mocha/", "/data/"],
      moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
      modulePaths: [
        path.resolve(__dirname, "smc-util"),
        path.resolve(__dirname, "smc-util/misc"),
        path.resolve(__dirname, "smc-webapp"),
        path.resolve(__dirname, "smc-webapp/node_modules")
      ],

      // Setup Enzyme
      snapshotSerializers: ["enzyme-to-json/serializer"],
      setupFilesAfterEnv: ["<rootDir>/setupEnzyme.ts"]
    }
  ]
};

const { defaults: tsjPreset } = require("ts-jest/presets");
const path = require("path");

module.exports = {
  projects: [
    {
      displayName: "smc-webapp",
      testMatch: [
        "<rootDir>/smc-webapp/**/*test.ts",
        "<rootDir>/smc-webapp/**/*test.tsx",
      ],
      transform: {
        ...tsjPreset.transform
      },
      testPathIgnorePatterns: ["/node_modules/", "/test-mocha/", "/data/"],
      moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
      modulePaths: [
        path.resolve(__dirname, "smc-util"),
        path.resolve(__dirname, "smc-util/misc"),
        path.resolve(__dirname, "smc-webapp"),
        path.resolve(__dirname, "smc-webapp/node_modules")
      ],

      // Setup Enzyme
      snapshotSerializers: ["enzyme-to-json/serializer"],
      setupFilesAfterEnv: ["<rootDir>/setupEnzyme.ts"]
    },
    {
      displayName: "smc-util",
      testMatch: [
        "<rootDir>/smc-util/**/*test.ts"
      ],
      transform: {
        ...tsjPreset.transform
      },
      testPathIgnorePatterns: ["/node_modules/", "/test-mocha/", "/data/"],
      moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
      modulePaths: [
        path.resolve(__dirname, "smc-util"),
        path.resolve(__dirname, "smc-util/misc"),
        path.resolve(__dirname, "smc-webapp"),
        path.resolve(__dirname, "smc-webapp/node_modules")
      ],
    }
  ]
};

Add smc-util project to jest


/**
 * @ignore
 */
exports['Should correctly stop reconnection attempts after limit reached'] = {
  metadata: { requires: { topology: ['single'] } },

  // The actual test we wish to run
  test: function(configuration, test) {
    // Create a new db instance
    var db = configuration.newDbInstance({w:1}, {
        poolSize:1
      , auto_reconnect:true
      , reconnectTries: 2
      , reconnectInterval: 100
    });

    db.open(function(err, db) {
      // Now let's stop the server
      configuration.manager.stop(function() {

        db.collection('waiting_for_reconnect').insert({a:1}, function(err, r) {
          test.ok(err != null);
          db.close();

          configuration.manager.start(function() {
            test.done();
          });
        });
      });
    });
  }
}

/**
 * @ignore
 */
exports['Should correctly stop reconnection attempts after limit reached'] = {
  metadata: { requires: { topology: ['single'] }, ignore: { travis:true } },

  // The actual test we wish to run
  test: function(configuration, test) {
    // Create a new db instance
    var db = configuration.newDbInstance({w:1}, {
        poolSize:1
      , auto_reconnect:true
      , reconnectTries: 2
      , reconnectInterval: 100
    });

    db.open(function(err, db) {
      // Now let's stop the server
      configuration.manager.stop(function() {

        db.collection('waiting_for_reconnect').insert({a:1}, function(err, r) {
          test.ok(err != null);
          db.close();

          configuration.manager.start(function() {
            test.done();
          });
        });
      });
    });
  }
}

Set reconnect test to ignore on travis


import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ReduxRouter } from 'redux-router';
import App from './containers/App';
import configureStore from './store/configureStore';
let injectTapEventPlugin = require('react-tap-event-plugin');

//Set the initial state and initialize the store with the initial state
const initialState = {page: {currentPage: 1}};
const store = configureStore(initialState);

// This is a shim for material-ui tap handling
injectTapEventPlugin();

render(
  <Provider store={store}>
  	<ReduxRouter />
    <App />
  </Provider>,
  document.getElementById('root')
);

import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ReduxRouter } from 'redux-router';
import App from './containers/App';
import configureStore from './store/configureStore';
let injectTapEventPlugin = require('react-tap-event-plugin');

//Set the initial state and initialize the store with the initial state
const initialState = {};
const store = configureStore(initialState);

// This is a shim for material-ui tap handling
injectTapEventPlugin();

render(
  <Provider store={store}>
  	<div>
	  	<ReduxRouter />
    </div>
  </Provider>,
  document.getElementById('root')
);

Refactor entry javascript to use ReduxRouter as the entry component into the application


import gravity from "lib/loaders/legacy/gravity"
import OrderedSet from "./ordered_set"
import { GraphQLString, GraphQLNonNull, GraphQLList, GraphQLBoolean, GraphQLInt } from "graphql"

const OrderedSets = {
  type: new GraphQLList(OrderedSet.type),
  description: "A collection of OrderedSets",
  args: {
    key: {
      type: new GraphQLNonNull(GraphQLString),
      description: "Key to the OrderedSet or group of OrderedSets",
    },
    public: {
      type: GraphQLBoolean,
      defaultValue: true,
    },
    page: {
      type: GraphQLInt,
    },
    size: {
      type: GraphQLInt,
    },
  },
  resolve: (root, options) => gravity("sets", options),
}

export default OrderedSets

import gravity from "lib/loaders/legacy/gravity"
import OrderedSet from "./ordered_set"
import { GraphQLString, GraphQLNonNull, GraphQLList, GraphQLBoolean, GraphQLInt } from "graphql"

const OrderedSets = {
  type: new GraphQLList(OrderedSet.type),
  description: "A collection of OrderedSets",
  args: {
    key: {
      type: new GraphQLNonNull(GraphQLString),
      description: "Key to the OrderedSet or group of OrderedSets",
    },
    public: {
      type: GraphQLBoolean,
      defaultValue: true,
    },
    page: {
      type: GraphQLInt,
      defaultValue: 1,
    },
    size: {
      type: GraphQLInt,
      defaultValue: 10,
    },
  },
  resolve: (root, options) => gravity("sets", options),
}

export default OrderedSets

Add default values for params


import { moduleFor, test } from 'ember-qunit';

moduleFor('route:dashboard', 'Unit | Route | dashboard', {
    // Specify the other units that are required for this test.
    // needs: ['controller:foo']
});

test('it exists', function(assert) {
    const route = this.subject();
    assert.ok(route);
});

import { moduleFor, test } from 'ember-qunit';

moduleFor('route:dashboard', 'Unit | Route | dashboard', {
    // Specify the other units that are required for this test.
    needs: ['service:metrics'],
});

test('it exists', function(assert) {
    const route = this.subject();
    assert.ok(route);
});

Add 'service:metrics' to dashboard route test


;(function()
{
	// CommonJS
	typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;

	function Brush()
	{
		this.regexList = [
			{ regex: /^\+\+\+ .*$/gm,	css: 'color2' },	// new file
			{ regex: /^\-\-\- .*$/gm,	css: 'color2' },	// old file
			{ regex: /^\s.*$/gm,		css: 'color1' },	// unchanged
			{ regex: /^@@.*@@.*$/gm,	css: 'variable' },	// location
			{ regex: /^\+.*$/gm,		css: 'comments' },	// additions
			{ regex: /^\-.*$/gm,		css: 'color3' }		// deletions
			];
	};

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases	= ['diff', 'patch'];

	SyntaxHighlighter.brushes.Diff = Brush;

	// CommonJS
	typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();

;(function()
{
	// CommonJS
	typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;

	function Brush()
	{
		this.regexList = [
			{ regex: /^\+\+\+ .*$/gm,	css: 'color2' },	// new file
			{ regex: /^\-\-\- .*$/gm,	css: 'color2' },	// old file
			{ regex: /^\s.*$/gm,		css: 'color1' },	// unchanged
			{ regex: /^@@.*@@.*$/gm,	css: 'variable' },	// location
			{ regex: /^\+.*$/gm,		css: 'string' },	// additions
			{ regex: /^\-.*$/gm,		css: 'color3' }		// deletions
			];
	};

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases	= ['diff', 'patch'];

	SyntaxHighlighter.brushes.Diff = Brush;

	// CommonJS
	typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();

Change additions from green to blue for accessibility


var Http = require('http');
var Hapi = require('hapi');
var EventEmitter = require('events').EventEmitter;
var GoodFile = require('../');

var server = new Hapi.Server('127.0.0.1', 31337);

var reporter = new GoodFile('./test/fixtures/example', { request: '*' });

server.start(function() {

    reporter.start(server, function(err) {

        if (err) {
            console.error(err);
            process.exit(1);
        }

        console.info('Server started at ' + server.info.uri);
        console.info('*** Starting triage ***');

        for (var i = 0; i <= 100; ++i) {
            Http.get(server.info.uri);
        }
        console.info('Done');
    });
});

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        server.emit('report', 'request', {
            event: 'request',
            timestamp: Date.now(),
            path: request.path,
            id: request.id
        });

        reply(200);
    }
});

var Http = require('http');
var Os = require('os');
var Fs = require('fs');

var Hapi = require('hapi');
<<<<<<< Updated upstream
var EventEmitter = require('events').EventEmitter;
=======
var Hoek = require('hoek');
>>>>>>> Stashed changes
var GoodFile = require('../');

var server = new Hapi.Server('127.0.0.1', 31337);

var reporter = new GoodFile(Hoek.uniqueFilename(Os.tmpDir()), { request: '*' });

server.start(function() {

    reporter.start(server, function(err) {

        if (err) {
            console.error(err);
            process.exit(1);
        }

        console.info('Server started at ' + server.info.uri);
        console.info('*** Starting triage ***');

        for (var i = 0; i <= 100; ++i) {
            Http.get(server.info.uri);
        }
        console.info('Done');
        console.info('Check %s for file results', reporter._writeStream.path);
    });
});

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {

        server.emit('report', 'request', {
            event: 'request',
            timestamp: Date.now(),
            path: request.path,
            id: request.id
        });

<<<<<<< Updated upstream
        reply(200);
=======
        reply().code(200);
>>>>>>> Stashed changes
    }
});

Update example to it works again.


'use strict';

module.exports = function(config, ircbot) {
	const Rcon = require('rcon');

	const client = new Rcon(config.rcon.host, config.rcon.port, config.rcon.password);

	client.on('auth', function() {
		console.log('RCON authentication successful');
	}).on('response', function(str) {
		console.log('RCON got response: ' + str);
	}).on('end', function() {
		console.log('RCON socket closed');
	});

	client.connect();

	ircbot.addListener('action', function(from, to, text) {
		if (to !== config.channel) {
			return;
		}

		client.send('say IRC> * ' + from + ' ' + text);
	});

	ircbot.addListener('message' + config.channel, function(from, text) {
		client.send('say IRC> <' + from + '> ' + text);
	});
};

'use strict';

module.exports = function(config, ircbot) {
	const Rcon = require('rcon');

	const client = new Rcon(config.rcon.host, config.rcon.port, config.rcon.password);

	client.on('auth', function() {
		console.log('RCON authentication successful');
	}).on('response', function(str) {
		console.log('RCON got response: ' + str);
	}).on('end', function() {
		console.log('RCON socket closed');
	});

	client.connect();

	ircbot.addListener('action', function(from, to, text) {
		if (to !== config.channel) {
			return;
		}

		client.send('say * ' + from + ' ' + text);
	});

	ircbot.addListener('message' + config.channel, function(from, text) {
		client.send('say <' + from + '> ' + text);
	});
};

Remove prefix in the forwarded messages from IRC


import Ember from 'ember';

export default Ember.Route.extend({
  queryParams: {
    page: {
      refreshModel: true
    }
  },

  model(params) {
    let now = new Date();
    let twoMonthsAgo = new Date(now.getFullYear(),
                                now.getMonth() - 2,
                                now.getDate());

    let queryParams = {
      ordering: '-arrivaldate,artist,title',
      min_arrival: moment(twoMonthsAgo).format('YYYY-MM-DD'),
      page: params.page
    };

    return this.store.query('release', queryParams);
  },

});

import Ember from 'ember';

export default Ember.Route.extend({
  queryParams: {
    page: {
      refreshModel: true
    }
  },

  model(params) {
    let now = new Date();
    let twoMonthsAgo = new Date(now.getFullYear(),
                                now.getMonth() - 2,
                                now.getDate());

    let queryParams = {
      ordering: '-arrivaldate,artist,title',
      min_arrival: moment(twoMonthsAgo).format('YYYY-MM-DD'),
      page: params.page
    };

    return this.store.query('release', queryParams);
  },

  afterModel() {
    window.scrollTo(0,0);
  }

});

Reset scroll on back/next pages.


module.exports = (sequelize, DataTypes) => {
  const Group = sequelize.define('Group', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    description: {
      type: DataTypes.STRING,
      allowNull: false,
    }
  });
  Group.associate = (models) => {
    Group.hasMany(models.Message, {
      foreignKey: 'GroupId',
      as: 'groupMesages',
    });
    Group.belongsToMany(models.User, {
      as: 'Groups',
      foreignKey: 'UserId',
      through: 'UserGroup',
    });
  };
  return Group;
};

module.exports = (sequelize, DataTypes) => {
  const Group = sequelize.define('Group', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    description: {
      type: DataTypes.STRING,
      allowNull: false,
    }
  });
  Group.associate = (models) => {
    Group.hasMany(models.Message, {
      foreignKey: 'GroupId',
      as: 'groupMesages',
    });
    Group.belongsToMany(models.User, {
      // as: 'Groups',
      foreignKey: 'userId',
      through: 'UserGroup',
    });
  };
  return Group;
};

Edit code to fix bug


// ------------------------
//  Launch a backbone powered entry box when someone clicks the new-person button
// ------------------------

define(
  [
    'jquery',
    'underscore',
    'instance-admin/views/list-item-edit'
  ],
  function (
    $,
    _,
    ListItemEditView
  ) {
    "use strict";

    return function (args) {

      var collection = args.collection;
      var defaults = args.defaults || {};

      return function(event) {
        event.preventDefault();

        var $link    = $(this),
            $element = $link.closest('li');

        if (!$element.length) {
            $element = $('<li/>');
            $link.closest('section').find('ul').prepend($element);
        }

        var cid = $element.data('id'),
            object;

        // create contact. Might be existing one, or a new one.
        if (cid) {
            object = collection.get(cid);
            object.exists = true;
        } else {
            object = new collection.model(defaults, { collection: collection });
            object.exists = false;
            $element.data('id', object.cid);
        }
        object.direct = args.direct;

        // create the view. Hook it up to the enclosing element.
        var view = new ListItemEditView({
          template: _.template(args.template),
          model:    object,
          el:       $element
        });

        view.render();
      };
    };

  }
);

// ------------------------
//  Launch a backbone powered entry box when someone clicks the new-person button
// ------------------------

define(
  [
    'jquery',
    'underscore',
    'instance-admin/views/list-item-edit'
  ],
  function (
    $,
    _,
    ListItemEditView
  ) {
    "use strict";

    return function (args) {

      var collection = args.collection;
      var defaults = args.defaults || {};

      return function(event) {
        event.preventDefault();

        var $link    = $(this);
        var $element = $link.hasClass('add') ?
            null :
            $link.closest('li');

        if (!$element || !$element.length) {
            $element = $('<li/>');
            $link.closest('ul').prepend($element);
        }

        var cid = $element.data('id'),
            object;

        // create contact. Might be existing one, or a new one.
        if (cid) {
            object = collection.get(cid);
            object.exists = true;
        } else {
            object = new collection.model(defaults, { collection: collection });
            object.exists = false;
            $element.data('id', object.cid);
        }
        object.direct = args.direct;

        // create the view. Hook it up to the enclosing element.
        var view = new ListItemEditView({
          template: _.template(args.template),
          model:    object,
          el:       $element
        });

        view.render();
      };
    };

  }
);

Fix placement of newly added list items


// This file is part of the API Platform project.
//
// (c) Kévin Dunglas <dunglas@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

window.onload = () => {
  const data = JSON.parse(document.getElementById('swagger-data').innerText);
  const ui = SwaggerUIBundle({
    spec: data.spec,
    dom_id: '#swagger-ui',
    validatorUrl: null,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: 'StandaloneLayout'
  });

  const storageKey = 'nelmio_api_auth';

  // if we have auth in storage use it
  if (sessionStorage.getItem(storageKey)) {
    try {
      ui.authActions.authorize(JSON.parse(sessionStorage.getItem(storageKey)));
    } catch (ignored) {
      // catch any errors here so it does not stop script execution
    }
  }

  // hook into authorize to store the auth in local storage when user performs authorization
  const currentAuthorize = ui.authActions.authorize;
  ui.authActions.authorize = function (payload) {
    sessionStorage.setItem(storageKey, JSON.stringify(payload));
    return currentAuthorize(payload);
  };

  // hook into logout to clear auth from storage if user logs out
  const currentLogout = ui.authActions.logout;
  ui.authActions.logout = function (payload) {
    sessionStorage.removeItem(storageKey);
    return currentLogout(payload);
  };

  window.ui = ui;
};

// This file is part of the API Platform project.
//
// (c) Kévin Dunglas <dunglas@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

window.onload = function() {
  const data = JSON.parse(document.getElementById('swagger-data').innerText);
  const ui = SwaggerUIBundle({
    spec: data.spec,
    dom_id: '#swagger-ui',
    validatorUrl: null,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: 'StandaloneLayout'
  });

  const storageKey = 'nelmio_api_auth';

  // if we have auth in storage use it
  if (sessionStorage.getItem(storageKey)) {
    try {
      ui.authActions.authorize(JSON.parse(sessionStorage.getItem(storageKey)));
    } catch (ignored) {
      // catch any errors here so it does not stop script execution
    }
  }

  // hook into authorize to store the auth in local storage when user performs authorization
  const currentAuthorize = ui.authActions.authorize;
  ui.authActions.authorize = function (payload) {
    sessionStorage.setItem(storageKey, JSON.stringify(payload));
    return currentAuthorize(payload);
  };

  // hook into logout to clear auth from storage if user logs out
  const currentLogout = ui.authActions.logout;
  ui.authActions.logout = function (payload) {
    sessionStorage.removeItem(storageKey);
    return currentLogout(payload);
  };

  window.ui = ui;
};

Change arrow function to an IE11 compatible function


const DrawCard = require('../../drawcard.js');

class YoungHarrier extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Prevent other characters from being dishonored',
            cost: ability.costs.dishonorSelf(),
            handler: () => {
                this.game.addMessage('{0} dishonors {1} to prevent Crane characters from being dishonored this phase', this.controller, this);
                this.untilEndOfPhase(ability => ({
                    match: card => card.factions['crane'] >= 0 && card.controller === this.controller && card.getType() === 'character',
                    effect: ability.effects.cannotBecomeDishonored()
                }));
            }
        });
    }
}

YoungHarrier.id = 'young-harrier';

module.exports = YoungHarrier;

const DrawCard = require('../../drawcard.js');

class YoungHarrier extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Prevent other characters from being dishonored',
            cost: ability.costs.dishonorSelf(),
            handler: () => {
                this.game.addMessage('{0} dishonors {1} to prevent Crane characters from being dishonored this phase', this.controller, this);
                this.controller.cardsInPlay.each(card => {
                    if(card.isFaction('crane')) {
                        this.untilEndOfPhase(ability => ({
                            match: card,
                            effect: ability.effects.cannotBeDishonored()
                        }));
                    }
                });
            }
        });
    }
}

YoungHarrier.id = 'young-harrier';

module.exports = YoungHarrier;

Add a lasting effect to each eligible card


let HL = 0;
let VL = 1;
let VC = 2;
let VR = 3;
let HR = 4;

class Data {
    static getData(cb) {
        xhr.get('/api/settings', cb);
    }

    static sendData(data, cb) {
        xhr.put('/api/settings', data, cb);
    }
}

Use XHR to get/send thruster settings


'use strict';

const request = require('request'),
      trans = require('trans'),
      chalk = require('chalk');

module.exports = (state, opts, cb) => {
  const url = state.conf('api:url'),
        existing = state.feed.id,
        newCount = state.posts.length,
        postCount = Object.keys(state.postGuids).length + newCount;

  let dates = trans(state.postGuids).array().pluck('value.date').value();
  dates = dates.concat(trans(state.posts).pluck('date').value());
  dates = trans(dates).sort(':desc').value();

  state.feed.postCount = postCount;
  state.feed.lastPostDate = dates[0];

  state.log.info(`saving feed ${chalk.green(state.feed.uri)} (${chalk.magenta(newCount)}/${chalk.blue(postCount)})`);

  request({
    url: existing ? `${url}/feeds/${state.feed.id}` : `${url}/feeds`,
    method: existing ? 'PUT' : 'POST',
    body: state.feed,
    json: true
  }, (err, _, body) => {
    if (err) {
      state.log.error(`failed to update feed ${state.feed.uri}`);
      cb(err);
    } else {
      state.feed = body;
      cb();
    }
  });
};

'use strict';

const request = require('request'),
      trans = require('trans'),
      chalk = require('chalk');

module.exports = (state, opts, cb) => {
  const url = state.conf('api:url'),
        existing = state.feed.id,
        newCount = state.posts.length,
        postCount = Object.keys(state.postGuids).length + newCount;

  let dates = trans(state.postGuids).array().pluck('value.date').value();
  dates = dates.concat(trans(state.posts).pluck('date').value());
  dates = trans(dates).sort(':desc').value();

  state.feed.postCount = postCount;
  state.feed.lastPostDate = dates[0];

  state.log.info(`saving feed ${chalk.green(state.feed.uri)} (${chalk.magenta(newCount)}/${chalk.blue(postCount)})`);

  request({
    url: existing ? `${url}/feeds/${state.feed.id}` : `${url}/feeds`,
    method: existing ? 'PUT' : 'POST',
    body: state.feed,
    json: true
  }, (err, _, body) => {
    if (err) {
      state.log.error(`failed to update feed ${state.feed.uri}`);
      cb(err);
    } else {
      state.feed = body;
      state.feed.isNew = !existing;
      cb();
    }
  });
};

Set the isNew flag when finding a feed


var socket = io();

$('.btn-green').click(function() {
    socket.emit('changeColor', 'green');
});

$('.btn-yellow').click(function() {
    socket.emit('changeColor', 'yellow');
});

$('.btn-red').click(function() {
    socket.emit('changeColor', 'red');
});

socket.on('colorChanged', function(currColor) {
    $('current-status').removeClass();
    $('#current-status').addClass('jumbotron');
    $('#current-status').addclass('bg-' + currColor);
});

var socket = io();

$('.btn-green').click(function() {
    socket.emit('changeColor', 'green');
});

$('.btn-yellow').click(function() {
    socket.emit('changeColor', 'yellow');
});

$('.btn-red').click(function() {
    socket.emit('changeColor', 'red');
});

socket.on('colorChanged', function(currColor) {
    $('#current-status').removeClass();
    $('#current-status').addClass('jumbotron');
    $('#current-status').addClass('bg-' + currColor);
});

Fix current status color change


import Ember from 'ember';

export default Ember.ObjectController.extend({
  cells: Ember.computed.alias('content.board.cells'),
  spinner: Ember.computed.alias('content.board.spinner'),
  actions: {
    newGameClick: function() {
      this.get('content').newGame();
    },
    cellClick: function(cell) {
      if (this.get('spinner').indexOf(cell.get('value')) > -1) {
        cell.set('value', 'X');
        this.get('board').incrementProperty('covered');
      }
    },
    spinClick: function() {
      if (this.get('spins') < this.get('maxSpins')) {
        this.incrementProperty('spins');
        this.get('board').spin();
      }
    }
  }
});

import Ember from 'ember';

export default Ember.ObjectController.extend({
  cells: Ember.computed.alias('content.board.cellMatrix'),
  spinner: Ember.computed.alias('content.board.spinner'),
  score: Ember.computed.alias('content.score'),
  horizontalComplete: Ember.computed.alias('content.board.horizontalComplete'),
  verticalComplete: Ember.computed.alias('content.board.verticalComplete'),
  actions: {
    newGameClick: function() {
      this.get('content').newGame();
    },
    cellClick: function(cell) {
      if (this.get('spinner')[cell.get('col')].get('value') === cell.get('value') || this.get('spinner')[cell.get('col')].get('isJoker')) {
        cell.set('value', 'X');
        this.get('content').addScoreValue(200);
      }
    },
    spinClick: function() {
      var _this = this;
      if (this.get('spins') < this.get('maxSpins')) {
        this.incrementProperty('spins');
        this.get('board').spin();
        this.get('spinner').forEach( function(cell) {

          if(cell.get('isCoin')) {
            _this.get('content').addScoreValue(1000);
          }

          if(cell.get('isDevil')) {
            var score = _this.get('content.score');
            var penalty = score * -1 / 2;
            _this.get('content').addScoreValue(penalty);
          }
        });
      }
    }
  }
});

Adjust score for devil and coin


'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
// angular.module('pickControl.services', [function () {

// }]);

angular.module('pickControl.services', []).
    factory('websocket', function() {
        var websocket = {
            emit: function (topic, body) {
                console.log(topic);
                console.log(body);
            },
        }
        //factory function body that constructs websocket
        return websocket;
    });

'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
// angular.module('pickControl.services', [function () {

// }]);

angular.module('pickControl.services', []).
    factory('websocket', function() {
        var websocket, make_message, parse_message, con;
        make_message = function (topic, body) {
            return topic + " " + JSON.stringify(body);
        }
        parse_message = function (msg) {
            var topic, body, parts;
            parts = msg.split(" ", 1);
            topic = parts[0];
            body = JSON.parse(msg.substring(topic.length + 1));
            return {"topic": topic, "body": body};
        }
        con = new window.WebSocket("ws://automation.azurestandard.com:9000/bin");
        con.onerror = function (error) {
            console.log("WebSocket Error " + error);
        };

        // Log messages from the server
        con.onmessage = function (msg) {
            var parsed;
            parsed = parse_message(msg.data);
            //Call registered handlers then
            $scope.$apply();
        };

        websocket = {
            emit: function (topic, body) {
                console.log(topic);
                console.log(body);
            },
            register: function (topic, func) {
            },
            send: function (msg) {
            },
            make_message: function (topic, body) {
            },
        }
        //factory function body that constructs websocket
        return websocket;
    });

Use the mock service, add features as needed


const trace = require('./lib/trace')();

// register a JS listener
trace.on('trace', (category, trace_obj) => {
  console.log(category, trace_obj);
});

// send a trace
trace.trace('joshgav-trace', { message: "stuff happened" });

const trace = require('../lib/trace')();

// register a JS listener
trace.on('trace', (category, trace_obj) => {
  console.log(category, trace_obj);
});

// send a trace
trace.trace('joshgav-trace', { message: "stuff happened" });

Fix reference in example script.


/**
 * @flow
 */

import React from 'react';
import { Picker, StyleSheet, View } from 'react-native';

const PickerExample = props => (
  <View style={styles.root}>
    <Picker {...props}>
      <Picker.Item label="Sourcerer's Stone" value="book-1" />
      <Picker.Item label="Chamber of Secrets" value="book-2" />
      <Picker.Item label="Prisoner of Azkaban" value="book-3" />
      <Picker.Item label="Goblet of Fire" value="book-4" />
      <Picker.Item label="Order of the Phoenix" value="book-5" />
      <Picker.Item label="Half-Blood Prince" value="book-6" />
      <Picker.Item label="Deathly Hallows" value="book-7" />
    </Picker>
  </View>
);

const styles = StyleSheet.create({
  root: {
    alignItems: 'flex-start'
  }
});

export default PickerExample;

/**
 * @flow
 */

import React from 'react';
import { Picker, StyleSheet, View } from 'react-native';

const PickerExample = props => (
  <View style={styles.root}>
    <Picker {...props}>
      <Picker.Item label="Sorcerer's Stone" value="book-1" />
      <Picker.Item label="Chamber of Secrets" value="book-2" />
      <Picker.Item label="Prisoner of Azkaban" value="book-3" />
      <Picker.Item label="Goblet of Fire" value="book-4" />
      <Picker.Item label="Order of the Phoenix" value="book-5" />
      <Picker.Item label="Half-Blood Prince" value="book-6" />
      <Picker.Item label="Deathly Hallows" value="book-7" />
    </Picker>
  </View>
);

const styles = StyleSheet.create({
  root: {
    alignItems: 'flex-start'
  }
});

export default PickerExample;

Fix typo in examples text


'use strict';

const expect        = require('../../helpers/expect');
const fs            = require('fs');
const sizeOf        = require('image-size');

const RasterizeList = require('../../../src/utils/rasterize-list');

describe('RasterizeList', function() {
  // Hitting the file system is slow
  this.timeout(0);

  context('when src and toRasterize', () => {
    const src = 'node-tests/fixtures/icon.svg';
    const toRasterize = [
      {
        size: 60,
        name: 'icon-60',
        path: 'tmp/icon-60.png'
      }
    ];
    let subject;

    before(() => {
      subject = RasterizeList({src: src, toRasterize: toRasterize});
    });

    after(() => {
      toRasterize.forEach((rasterize) => {
        fs.unlinkSync(rasterize.path);
      });
    });

    it('returns a promise that resolves to an array', (done) => {
      expect(subject).to.eventually.be.a('array').notify(done);
    });

    it('writes the files to rasterize at the right size', (done) => {
      subject.then(() => {
        toRasterize.forEach((rasterize) => {
          expect(fs.existsSync(rasterize.path)).to.equal(true);
          expect(sizeOf(rasterize.path).width).to.equal(rasterize.size);
          expect(sizeOf(rasterize.path).height).to.equal(rasterize.size);
        });
        done();
      });
    });
  });
});

'use strict';

const expect        = require('../../helpers/expect');
const fs            = require('fs');
const sizeOf        = require('image-size');

const RasterizeList = require('../../../src/utils/rasterize-list');

describe('RasterizeList', function() {
  // Hitting the file system is slow
  this.timeout(0);

  context('when src and toRasterize', () => {
    const src = 'node-tests/fixtures/icon.svg';
    const toRasterize = [
      {
        size: 60,
        name: 'icon-60',
        path: 'tmp/icon-60.png'
      }
    ];
    let subject;

    before(() => {
      subject = RasterizeList({src: src, toRasterize: toRasterize});
    });

    after(() => {
      toRasterize.forEach((rasterize) => {
        fs.unlinkSync(rasterize.path);
      });
    });

    it('returns a promise that resolves to an array', (done) => {
      expect(subject).to.eventually.be.a('array').notify(done);
    });

    it('writes the files to rasterize at the right size', (done) => {
      subject.then(() => {
        try {
          toRasterize.forEach((rasterize) => {
            expect(fs.existsSync(rasterize.path)).to.equal(true);
            expect(sizeOf(rasterize.path).width).to.equal(rasterize.size);
            expect(sizeOf(rasterize.path).height).to.equal(rasterize.size);
          });
          done();
        } catch(e) {
          done(e);
        }
      });
    });
  });
});

Update test to not hang on failed promise-dependant expecation


'use strict';

angular.module('ddsApp').directive('ddsDateMonthYear', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.push(function(viewValue) {
                var result = moment(viewValue, ['MM/YY', 'MM/YYYY', 'MMMM YYYY']);

                ctrl.$setValidity('ddsDateMonthYear', result.isValid());

                return result;
            });

            ctrl.$formatters.push(function(momentInstance) {
                if (! momentInstance) return;

                return momentInstance.format('MMM YYYY');
            });
        }
    };
});

'use strict';

angular.module('ddsApp').directive('ddsDateMonthYear', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.push(function(viewValue) {
                var result = moment(viewValue, ['MM/YY', 'MM/YYYY', 'MMMM YYYY', 'L', 'DD/MM/YY']);

                ctrl.$setValidity('ddsDateMonthYear', result.isValid());

                return result;
            });

            ctrl.$formatters.push(function(momentInstance) {
                if (! momentInstance) return;

                return momentInstance.format('MMM YYYY');
            });
        }
    };
});

Support giving full dates in month-year inputs


  var Promise = require('bluebird');
  var fs = Promise.promisifyAll(require('fs'));

  exports.read = function read(filename){
    fs.readFileAsync(filename, 'UTF-8').then(function(data){
      console.log(data)
    })
  }

  var Promise = require('bluebird');
  var fs = Promise.promisifyAll(require('fs'));
/*
  exports.read = function read(filename){
    fs.readFileAsync(filename, 'UTF-8').then(function(data){
      console.log(data)
      //return data
    })
  }
*/
  exports.read = async function read(filename){
    let data = await fs.readFileAsync(filename, 'UTF-8');
      console.log(data)
      //return data
    }

  exports.write = function write(filename,data){
    fs.writeFileAsync(filename, data).then(function(data){
      //written to disk
    })
  }

Rewrite read function with async/await


/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @emails oncall+relay
 */

'use strict';

var RelayTestUtils = require('RelayTestUtils');
RelayTestUtils.unmockRelay();

var Relay = require('Relay');
var isCompatibleRelayFragmentType = require('isCompatibleRelayFragmentType');

describe('isCompatibleRelayFragmentType', () => {
  const {getNode} = RelayTestUtils;

  it('returns false for different concrete types', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on User{id}`),
      'Page'
    ));
  });

  it('returns true for equal concrete types', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on User{id}`),
      'User'
    ));
  });

  it('returns true for abstract fragments', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on Node{id}`),
      'User'
    ));
  });

  it('returns true for client records', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on User{id}`),
      null
    ));
  });
});

/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @emails oncall+relay
 */

'use strict';

var RelayTestUtils = require('RelayTestUtils');
RelayTestUtils.unmockRelay();

var Relay = require('Relay');
var isCompatibleRelayFragmentType = require('isCompatibleRelayFragmentType');

describe('isCompatibleRelayFragmentType', () => {
  const {getNode} = RelayTestUtils;

  it('returns false for different concrete types', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on User{id}`),
      'Page'
    )).toBe(false);
  });

  it('returns true for equal concrete types', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on User{id}`),
      'User'
    )).toBe(true);
  });

  it('returns true for abstract fragments', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on Node{id}`),
      'User'
    )).toBe(true);
  });

  it('returns true for client records', () => {
    expect(isCompatibleRelayFragmentType(
      getNode(Relay.QL`fragment on User{id}`),
      null
    )).toBe(true);
  });
});

Add missing expectations in test


const config = require('./config/config');
const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const path = require('path');
require('./config/mongo'); // don't much like this bare require

const app = express();

app.use(helmet());
app.use(compression());

// Add public API routes
const publicRoutes = require('./routes/public');
app.use('/api', publicRoutes);

// Serve the built admin UI from /admin
app.use('/admin', express.static(path.join(__dirname, 'www-admin')));
app.get('/admin/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'www-admin', 'index.html'));
});

// Serve the built UI from the root
app.use(express.static(path.join(__dirname, 'www')));
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'www', 'index.html'));
});

// auto-init if this app is not being initialised by another module
if (!module.parent) {
  app.listen(config.app.port, () => {
    /* eslint-disable-next-line no-console */
    console.log(`Listening on port ${config.app.port}`);
  });
}

module.exports = app;

const config = require('./config/config');
const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const path = require('path');
require('./config/mongo'); // don't much like this bare require

const app = express();

// we can make some nicer assumptions about security if query values are only
// ever strings, not arrays or objects
app.set('query parser', 'simple');

app.use(helmet());
app.use(compression());

// Add public API routes
const publicRoutes = require('./routes/public');
app.use('/api', publicRoutes);

// Serve the built admin UI from /admin
app.use('/admin', express.static(path.join(__dirname, 'www-admin')));
app.get('/admin/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'www-admin', 'index.html'));
});

// Serve the built UI from the root
app.use(express.static(path.join(__dirname, 'www')));
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'www', 'index.html'));
});

// auto-init if this app is not being initialised by another module
if (!module.parent) {
  app.listen(config.app.port, () => {
    /* eslint-disable-next-line no-console */
    console.log(`Listening on port ${config.app.port}`);
  });
}

module.exports = app;

Use dumb query parsing to avoid a DoS attack where a { $regex } matcher with evil regex could be inserted into a query


import React, {Component} from 'react'
import {connect} from 'react-redux'

import {httpRequestSelector} from 'gComponents/organizations/show/httpRequestSelector'
import {organizationMemberSelector} from 'gComponents/organizations/show/organizationMemberSelector'
import Card, {CardListElement} from 'gComponents/utility/card/index'
import {MemberAddForm} from '../shared/MemberAddForm/index'

import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'

export class LocalAddMembers extends Component {
  render() {
    const {organizationId} = this.props
    return (

          <MemberAddForm organizationId={organizationId}/>

Finish Registration

 Organization Members

Organization members will be able to see and edit all organization models.

As an organization admin, you will be able to invite, add, and remove members in the future.

    )
  }
}

import React, {Component} from 'react'
import {connect} from 'react-redux'

import {httpRequestSelector} from 'gComponents/organizations/show/httpRequestSelector'
import {organizationMemberSelector} from 'gComponents/organizations/show/organizationMemberSelector'
import Card, {CardListElement} from 'gComponents/utility/card/index'
import {MemberAddForm} from '../shared/MemberAddForm/index'

import * as userOrganizationMembershipActions from 'gModules/userOrganizationMemberships/actions'
import {organization} from 'gEngine/engine'

export class LocalAddMembers extends Component {
  render() {
    const {organizationId} = this.props
    return (

          <MemberAddForm organizationId={organizationId}/>

          Finish Registration

 Organization Members

Organization members will be able to see and edit all organization models.

As an organization admin, you will be able to invite, add, and remove members in the future.

    )
  }
}

Make sure that organization new button goes to organization page


module.exports = function(grunt) {

    grunt.initConfig({

        jasmine: {
            src : 'assets/require.js',
            helpers : 'test/lib/*.js',
            timeout : 10000
        }
    });

    grunt.loadNpmTasks('grunt-jasmine-runner');

};

module.exports = function(grunt) {

    grunt.initConfig({

        lint: {
            files: ['assets/T*.js', 'assets/UserStatus.js', 'test/spec/*.js']
        },

        watch: {
            files: ['assets/*js', 'test/spec/*,js'],
            tasks: 'jasmine'
        },

        jasmine: {
            src : 'assets/require.js',
            helpers : 'test/lib/*.js',
            timeout : 10000
        }
    });

    grunt.loadNpmTasks('grunt-jasmine-runner');

    grunt.registerTask('default', 'lint jasmine');
};

Add lint and watch config.


require('leaflet');
require('proj4leaflet');

/*global L:true*/
/*global assetPath:true*/

// specify the path to the leaflet images folder
L.Icon.Default.imagePath = assetPath + '/images/leaflet';

require('leaflet');
require('proj4leaflet');

/*global L:true*/
/*global assetPath:true*/

// specify the path to the leaflet images folder
L.Icon.Default.imagePath = assetPath + '/images/leaflet/';

Fix leaflet marker icon missing


require('./lib/boot/logger');

var defaultConfig = {
  amqpUrl: process.env.AMQP_URL || 'amqp://localhost',
  amqpPrefetch: process.env.AMQP_PREFETCH || 0,
  amqpRequeue: true
};

module.exports = function(config) {
  for (var key in config) {
    if (config.hasOwnProperty(key) && defaultConfig.hasOwnProperty(key)) {
      defaultConfig[key] = config[key];
    }
  }

  defaultConfig.amqpPrefetch = parseInt(defaultConfig.amqpPrefetch);

  return {
    producer: require('./lib/producer')(defaultConfig),
    consumer: require('./lib/consumer')(defaultConfig)
  };
};

require('./lib/boot/logger');

var defaultConfig = {
  amqpUrl: process.env.AMQP_URL || 'amqp://localhost',
  amqpPrefetch: process.env.AMQP_PREFETCH || 5,
  amqpRequeue: true
};

module.exports = function(config) {
  for (var key in config) {
    if (config.hasOwnProperty(key) && defaultConfig.hasOwnProperty(key)) {
      defaultConfig[key] = config[key];
    }
  }

  defaultConfig.amqpPrefetch = parseInt(defaultConfig.amqpPrefetch) || 5;

  return {
    producer: require('./lib/producer')(defaultConfig),
    consumer: require('./lib/consumer')(defaultConfig)
  };
};

Set the prefetch to 5 if not setted


const nodemon = require("nodemon")
module.exports = function () {
  this.nodemon = function (opts) {

  }
}

const nodemon = require("nodemon")

var server = undefined

module.exports = function () {
  this.nodemon = function (opts) {
    if (!server) {
      server = nodemon(opts)
        .on("start", function () {
        this.log("nodemon started.")
        })
        .on("crash", function () {
          this.error("script crashed for some reason")
        })
    } else {
      server.emit("restart")
    }
  }
}

Add conditional start/restart logic :construction:


'use strict';

var assign = Object.assign || require('object.assign');

function hasOwnKey(key, object) {
    return object != null && object.hasOwnProperty(key);
}

function objectsHaveOwnKey() {
    var key = arguments[0],
        objects = [].slice.call(arguments, 1);

    return objects.every(hasOwnKey.bind(null, key));
}

function strictAssign() {
    var target = arguments[0],
        sources = [].slice.call(arguments, 1),
        assignArgs = [].concat({}, sources),
        i,
        key,
        strippedTarget;

    sources.forEach(function stripTarget(source) {
        for (key in source) {
            if (objectsHaveOwnKey(key, source, target)
                && !hasOwnKey(key, strippedTarget) {
                strippedTarget[key] = target[key];
            }
        }
    });

    assignArgs.push(strippedTarget);
    return assign.apply(null, assignArgs);
}

module.exports = strictAssign;

'use strict';

var assign = Object.assign || require('object.assign');

function hasOwnKey(key, object) {
    return object != null && object.hasOwnProperty(key);
}

function objectsHaveOwnKey() {
    var key = arguments[0],
        objects = [].slice.call(arguments, 1);

    return objects.every(hasOwnKey.bind(null, key));
}

function strictAssign() {
    var target = arguments[0],
        sources = [].slice.call(arguments, 1),
        assignArgs = [].concat({}, sources),
        i,
        key,
        strippedTarget;

    sources.forEach(function stripTarget(source) {
        for (key in source) {
            if (objectsHaveOwnKey(key, source, target)
                && !hasOwnKey(key, strippedTarget)) {
                strippedTarget[key] = target[key];
            }
        }
    });

    assignArgs.push(strippedTarget);
    return assign.apply(null, assignArgs);
}

module.exports = strictAssign;

Add missing paren to if statement.


/*!
 * global-modules <https://github.com/jonschlinkert/global-modules>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var prefix = require('global-prefix');
var isWindows = require('is-windows');

if (isWindows()) {
  module.exports = path.resolve(prefix, 'node_modules');
} else {
  module.exports = path.resolve(prefix, 'lib/node_modules');
}

/*!
 * global-modules <https://github.com/jonschlinkert/global-modules>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var prefix = require('global-prefix');
var isWindows = require('is-windows');

if (isWindows === true || isWindows()) {
  module.exports = path.resolve(prefix, 'node_modules');
} else {
  module.exports = path.resolve(prefix, 'lib/node_modules');
}

Fix "isWindows is not a function" on electron


module.exports = {

  onLoad: function(callback) {
    if (typeof callback !== 'function') {
      throw new Error('"onLoad" must have a callback function');
    }

    withLiveReactload(setupOnLoadHandlers);
    withoutLiveReactload(function() {
      setupOnLoadHandlers({})
    });

    function setupOnLoadHandlers(lrload) {
      var winOnload = window.onload;
      if (!winOnload || !winOnload.__is_livereactload) {
        window.onload = function () {
          // initial load event
          callback(lrload.state);
          lrload.winloadDone = true;
          if (typeof winOnload === 'function' && !winOnload.__is_livereactload) {
            winOnload();
          }
        }
      }
      window.onload.__is_livereactload = true;
      if (lrload.winloadDone) {
        // reload event
        callback(lrload.state)
      }
    }
  },

  setState: function(state) {
    withLiveReactload(function(lrload) {
      lrload.state = state;
    })
  },

  expose: function(cls, id) {
    if (!id) throw new Error('ID value is missing. ID is mandatory when exposing anonymous React components')
    var mod = { exports: cls };
    withLiveReactload(function(lrload) {
      if (lrload.makeExportsHot) {
        lrload.makeExportsHot('CUSTOM_' + id, mod);
      }
    });
    return mod.exports;
  }

};

function withLiveReactload(cb) {
  if (typeof window !== 'undefined') {
    var lrload = window.__livereactload;
    if (lrload) {
      cb(lrload);
    }
  }
}

function withoutLiveReactload(cb) {
  if (typeof window === 'undefined' || !window.__livereactload) {
    cb();
  }
}

module.exports = {

  onReload: function(callback) {
    withLiveReactload(function(lrload) {
      if (!lrload.onReloadCallbacks) {
        lrload.onReloadCallbacks = [];
      }
      lrload.onReloadCallbacks.push(callback);
    });
  },

  setState: function(name, state) {
    var numArgs = arguments.length;
    withLiveReactload(function(lrload) {
      if (numArgs > 1) {
        if (!lrload.namedStates) {
          lrload.namedStates = {};
        }
        lrload.namedStates[name] = state;
      } else {
        state = name;
        lrload.state = state;
      }
    });
  },

  getState: function(name) {
    var state;
    var numArgs = arguments.length;
    withLiveReactload(function(lrload) {
      if (numArgs > 0) {
        state = lrload.namedStates ? lrload.namedStates[name] : undefined;
      } else {
        state = lrload.state;
      }
    });
    return state;
  }

};

function withLiveReactload(cb) {
  if (typeof window !== 'undefined') {
    var lrload = window.__livereactload;
    if (lrload) {
      cb(lrload);
    }
  }
}

Update API. Not backwards compatible


//var dbus = module.exports = require('node-dbus');
var dbus = require('node-dbus');

module.exports = function() {
	var self = this;

	this.init = function(callback) {
		dbus.start(function() {
			self.systemBus = dbus.system_bus();
			self.manager = dbus.get_interface(self.systemBus, 'net.connman', '/', 'net.connman.Manager');
			self.properties = self.manager.GetProperties();

			console.log(self.manager);

			callback();
		});
	};

	this.__defineGetter__('AvailableTechnologies', function() {
		return self.properties.AvailableTechnologies;
	});

	this.__defineGetter__('GetState', function() {
		return self.manager.GetState();
	});

	this.__defineGetter__('OfflineMode', function() {
		return self.manager.GetProperties().OfflineMode;
	});

	this.__defineSetter__('OfflineMode', function(value) {
		return self.manager.SetProperty('OfflineMode', false);
	});
};

//var dbus = module.exports = require('node-dbus');
var dbus = require('node-dbus');

module.exports = function() {
	var self = this;

	this.init = function(callback) {
		dbus.start(function() {
			self.systemBus = dbus.system_bus();
			self.manager = dbus.get_interface(self.systemBus, 'net.connman', '/', 'net.connman.Manager');
			self.properties = self.manager.GetProperties();

			console.log(self.manager.GetProperties());
//			console.log(self.manager);

			callback();
		});
	};

	this.__defineGetter__('AvailableTechnologies', function() {
		return self.manager.GetProperties().AvailableTechnologies;
	});

	this.__defineGetter__('EnabledTechnologies', function() {
		return self.manager.GetProperties().EnabledTechnologies;
	});

	this.__defineGetter__('ConnectedTechnologies', function() {
		return self.manager.GetProperties().ConnectedTechnologies;
	});

	this.__defineGetter__('GetState', function() {
		return self.manager.GetState();
	});

	this.__defineGetter__('OfflineMode', function() {
		return self.manager.GetProperties().OfflineMode;
	});

	this.__defineSetter__('OfflineMode', function(value) {
		return self.manager.SetProperty('OfflineMode', false);
	});
};

Support ConnectedTechnologies and EnabledTechnologies Properties


var winston = require("winston");

var logger = new winston.Logger({
    transports: [
        new winston.transports.File({
            level: "error",
            filename: "./" + logDir + "error.log",
            handleExceptions: true,
            json: true,
            maxsize: 50000000,
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.Console({
            level: "debug",
            handleExceptions: true,
            json: false,
            colorize: true
        })
    ],
    exitOnError: false
});

var fallback = function(err, req, res, next) {
    logger.error(err);
    res.status(500).json({
        message: "Oh ooh... Something went terribly wrong."
    });
};

module.exports = logger;
module.exports.fallback = fallback;

var winston = require("winston");
var fs = require("fs");

var logDir = "logs/";
if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
}

var logger = new winston.Logger({
    transports: [
        new winston.transports.File({
            level: "error",
            filename: "./" + logDir + "error.log",
            handleExceptions: true,
            json: true,
            maxsize: 50000000,
            maxFiles: 5,
            colorize: false
        }),
        new winston.transports.Console({
            level: "debug",
            handleExceptions: true,
            json: false,
            colorize: true
        })
    ],
    exitOnError: false
});

var fallback = function(err, req, res, next) {
    logger.error(err);
    res.status(500).json({
        message: "Oh ooh... Something went terribly wrong."
    });
};

module.exports = logger;
module.exports.fallback = fallback;

Create log dir if not available


var screenfull = require('screenfull');

var FullscreenMixin = {

  getInitialState: function() {
    return {
      hasFullscreen: false
    };
  },

  componentDidMount: function () {
    var enabled = screenfull.enabled;

    if (enabled) {
      document.addEventListener(screenfull.raw.fullscreenchange, this.onChangeFullscreen);

      this.setState({
        hasFullscreen: enabled
      });
    }
  },

  requestFullscreen: function (ref) {
    if (ref && ref.getDOMNode) {
      var elem = ref.getDOMNode();
      screenfull.request(elem);
    } else {
      screenfull.request();
    }
  },

  exitFullscreen: function () {
    screenfull.exit();
  },

  onChangeFullscreen: function (e) {
    var isFullscreen = screenfull.isFullscreen;
    this.setState({
      isFullscreen: isFullscreen,
      fullScreenElement: screenfull.element
    });

    if (isFullscreen) {
      typeof this.onEnterFullscreen === 'function' && this.onEnterFullscreen(e);
    } else {
      typeof this.onExitFullscreen === 'function' && this.onExitFullscreen(e);
    }
  }
};

module.exports = FullscreenMixin;

var screenfull = require('screenfull');

var FullscreenMixin = {

  getInitialState: function() {
    return {
      hasFullscreen: false
    };
  },

  componentDidMount: function () {
    var enabled = screenfull.enabled;

    if (enabled) {
      document.addEventListener(screenfull.raw.fullscreenchange, this.onChangeFullscreen);

      this.setState({
        hasFullscreen: enabled,
        isFullscreen: screenfull.isFullscreen,
        fullScreenElement: screenfull.element
      });
    }
  },

  requestFullscreen: function (ref) {
    if (ref && ref.getDOMNode) {
      var elem = ref.getDOMNode();
      screenfull.request(elem);
    } else {
      screenfull.request();
    }
  },

  exitFullscreen: function () {
    screenfull.exit();
  },

  onChangeFullscreen: function (e) {
    var isFullscreen = screenfull.isFullscreen;
    this.setState({
      isFullscreen: isFullscreen,
      fullScreenElement: screenfull.element
    });

    if (isFullscreen) {
      typeof this.onEnterFullscreen === 'function' && this.onEnterFullscreen(e);
    } else {
      typeof this.onExitFullscreen === 'function' && this.onExitFullscreen(e);
    }
  }
};

module.exports = FullscreenMixin;

Check if fullscreen is already enabled on mount


var path = require('path');
var gutil = require('gulp-util');
var map = require('map-stream');
var JSON5 = require('JSON5');

var PluginError = gutil.PluginError;

const PLUGIN_NAME = 'gulp-json5';

module.exports = function(options) {

  options = typeof options !== 'object' ? {} : options;
  options.beautify = options.hasOwnProperty('beautify') ? !!options.beautify : true;

  function parseJSON5(file, callback) {
    var obj = {};
    if (!file.isNull()) {
      try {
        obj = JSON5.parse(file.contents + '');
      } catch (err) {
        throw new PluginError(PLUGIN_NAME, "JSON5 parser error", err);
      }
    }
    file.contents = new Buffer(JSON5.stringify(obj, null, options['beautify'] ? 4 : null));
    file.path = path.join(file.base, path.basename(file.path, path.extname(file.path)) + '.json');
    callback(null, file);
  }

  return map(parseJSON5);

}

var path = require('path');
var gutil = require('gulp-util');
var map = require('map-stream');
var JSON5 = require('json5');

var PluginError = gutil.PluginError;

const PLUGIN_NAME = 'gulp-json5';

module.exports = function(options) {

  options = typeof options !== 'object' ? {} : options;
  options.beautify = options.hasOwnProperty('beautify') ? !!options.beautify : true;

  function parseJSON5(file, callback) {
    var obj = {};
    if (!file.isNull()) {
      try {
        obj = JSON5.parse(file.contents + '');
      } catch (err) {
        throw new PluginError(PLUGIN_NAME, "JSON5 parser error", err);
      }
    }
    file.contents = new Buffer(JSON5.stringify(obj, null, options['beautify'] ? 4 : null));
    file.path = path.join(file.base, path.basename(file.path, path.extname(file.path)) + '.json');
    callback(null, file);
  }

  return map(parseJSON5);

}

Make plugin work on case-sensitive systems


var express = require('express');
var app = express();

app.set('port', (process.env.POT || 5000));

app.use(express.static(__dirname + '/public'));

app.get('/', function(request, response) {
  response.sendFile('views/pages/index.html', { root: __dirname });
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

app.get('/', function(request, response) {
  response.sendFile('views/pages/index.html', { root: __dirname });
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

Fix stupid POT/PORT typogit add .git add .


var katex = require("katex");
var cheerio = require("cheerio");

module.exports = {
    book: {
        assets: "./book",
        js: []
    },
    hooks: {
        page: function(page) {
            for (var i in page.sections) {
                section = page.sections[i];
                if ( section.type != "normal" ) continue;

                var $ = cheerio.load(section.content);
                $("script").each(function() {
                    // Check is math
                    var type = $(this).attr("type") || "";
                    if (type.indexOf("math/tex") < 0) return;

                    var math = $(this).html().replace(/\\/gi,"/");
                    $(this).replaceWith(katex.renderToString(math));
                });

                // Replace by transform
                section.content = $.html();
            }

            return page;
        }
    }
};

var katex = require("katex");
var cheerio = require("cheerio");

module.exports = {
    book: {
        assets: "./book",
        js: []
    },
    hooks: {
        page: function(page) {
            for (var i in page.sections) {
                section = page.sections[i];
                if ( section.type != "normal" ) continue;

                var $ = cheerio.load(section.content);
                $("script").each(function() {
                    // Check is math
                    var type = $(this).attr("type") || "";
                    if (type.indexOf("math/tex") < 0) return;

                    var math = $(this).html().toString("utf8");
                    console.log("convert '"+math+"'");
                    $(this).replaceWith(katex.renderToString(math));
                });

                // Replace by transform
                section.content = $.html();
            }

            return page;
        }
    }
};

Revert "Fix backslashes before rendering math"


'use strict';

const Hapi = require('hapi');
const Mongoose = require('mongoose');

const MONGODB_URI = process.env.MONGOLAB_URI || process.env.MONGODB_URI;
const HTTP_PORT = process.env.PORT || 3000;

const server = new Hapi.Server({
  debug: false
});

server.connection({port: HTTP_PORT});

const routes = require('./routes');
server.route(routes);

if (!module.parent) {
  Mongoose.connect(MONGODB_URI, (err) => {
    if (err) {
      console.error('Failed to connect to MongoDB:', MONGODB_URI);
    } else {
      console.log('Connected to MongoDB:', MONGODB_URI);
    }
  })
  server.start(() => {
    console.log('Server started at', server.info.uri);
  });
}

module.exports = server;

'use strict';

const Hapi = require('hapi');
const Mongoose = require('mongoose');

const MONGODB_URI = process.env.MONGOLAB_URI || process.env.MONGODB_URI;
const HTTP_PORT = process.env.PORT || 3000;

const server = new Hapi.Server({
  debug: module.parent ? false : undefined,
});

server.connection({port: HTTP_PORT});

const routes = require('./routes');
server.route(routes);

if (!module.parent) {
  Mongoose.connect(MONGODB_URI, (err) => {
    if (err) {
      console.error('Failed to connect to MongoDB:', MONGODB_URI);
    } else {
      console.log('Connected to MongoDB:', MONGODB_URI);
    }
  })
  server.start(() => {
    console.log('Server started at', server.info.uri);
  });
}

module.exports = server;

Disable Hapi debugging only for tests


var map = require("./map.json");
var meteorAliases = {};

Object.keys(map).forEach(function (id) {
  if (typeof map[id] === "string") {
    var aliasParts = module.id.split("/");
    aliasParts.pop();
    aliasParts.push("node_modules", map[id]);
    exports[id] = meteorAliases[id + ".js"] =
      aliasParts.join("/");
  } else {
    exports[id] = map[id];
    meteorAliases[id + ".js"] = function(){};
  }
});

if (typeof meteorInstall === "function") {
  meteorInstall({
    // Install the aliases into a node_modules directory one level up from
    // the root directory, so that they do not clutter the namespace
    // available to apps and packages.
    "..": {
      node_modules: meteorAliases
    }
  });
}

// If Buffer is not defined globally, but the "buffer" built-in stub is
// installed and can be imported, use it to define global.Buffer so that
// modules like core-util-is/lib/util.js can refer to Buffer without
// crashing application startup.
if (typeof global.Buffer !== "function") {
  try {
    // Use (0, require)(...) to avoid registering a dependency on the
    // "buffer" stub, in case it is not otherwise bundled.
    global.Buffer = (0, require)("buffer");
  } catch (ok) {
    // Failure to import "buffer" is fine as long as the Buffer global
    // variable is not used.
  }
}

Define Buffer globally if buffer built-in module installed.


/**
 * index.js
 * Client entry point.
 *
 * @author Francis Brito <fr.br94@gmail.com>
 * @license MIT
 */
'use strict';

var Client = function Client() {};

module.exports = {
    Client: Client
};

/**
 * index.js
 * Client entry point.
 *
 * @author Francis Brito <fr.br94@gmail.com>
 * @license MIT
 */
'use strict';

var Client = function Client(apiKey, opts) {
    if (!apiKey) {
        throw new Error('No API key provided.');
    }
};

module.exports = {
    Client: Client
};

Make client should throw if no API key is provided test pass.


var stop = /,$/;
module.exports = function list(args) {
  var res = [];

  var temp = [];
  var max = args.length;
  for (var i = 0; i < max; i++) {
    var arg = args[i];
    if (stop.test(arg)) {
      temp.push(arg.slice(0, -1));
      res.push(temp);
      temp = [];
    } else {
      temp.push(arg);
    }
  }
  res.push(temp);

  return res;
};

module.exports = function list(args) {
  var res = [];
  var temp = [];
  for (var i = 0, max = args.length; i < max; i++) {
    var arg = args[i];
    if (arg[arg.length - 1] === ',') {
      temp.push(arg.slice(0, -1));
      res.push(temp);
      temp = [];
    } else {
      temp.push(arg);
    }
  }
  res.push(temp);
  return res;
};

Use comparision instead of regex.


'use strict'

const Schema = use('Schema')

class WordSchema extends Schema {
  up () {
    this.create('words', (table) => {
      table.increments()
      table.string('name').notNullable()
      table.integer('syllablesCount').unsigned()
      table.string('ultima')
      table.boolean('hasCheckedSynonyms').default(false)
      table.boolean('isEmpty').default(false);
      table.timestamp('createdAt');
      table.timestamp('updatedAt');
    })
  }

  down () {
    this.drop('words')
  }
}

module.exports = WordSchema

'use strict'

const Schema = use('Schema')

class WordSchema extends Schema {
  up () {
    this.create('words', (table) => {
      table.increments()

      table.string('name').notNullable()
      table.unique('name');

      table.integer('syllablesCount').unsigned()
      table.string('ultima')
      table.boolean('hasCheckedSynonyms').default(false)
      table.boolean('isEmpty').default(false);
      table.timestamp('createdAt');
      table.timestamp('updatedAt');
    })
  }

  down () {
    this.drop('words')
  }
}

module.exports = WordSchema

Add unique index to name


'use strict';

var Slack = require('slack-client');

var token = '' || process.env.SLACK_API_TOKEN;

var slack = new Slack(token, true, true);

slack.on('open', function () {
  console.log("Connected to ", slack.team.name, "  as @", slack.self.name);
});

slack.on('message', function (message) {
  console.log('A new message: ', message.text);

  var channel = slack.getChannelGroupOrDMByID(message.channel);

  channel.send('codybot has recieved your message but doesn\'t know what to do.');
});

slack.on('error', function (err) {
  console.error(err);
});

slack.login();

'use strict';

var Slack = require('slack-client');

var token = '' || process.env.SLACK_API_TOKEN;

var slack = new Slack(token, true, true);

slack.on('open', function () {
  console.log("Connected to ", slack.team.name, "  as @", slack.self.name);
});

slack.on('message', function (message) {
  console.log('A new message: ', message.text);

  // var channel = slack.getChannelGroupOrDMByID(message.channel);

  // channel.send('codybot has recieved your message but doesn\'t know what to do.');
});

slack.on('error', function (err) {
  console.error(err);
});

slack.login();

Make codybot shut up for a bit


'use strict';

module.exports = Response;

/**
 * A response from a web request
 *
 * @param {Number} statusCode
 * @param {Object} headers
 * @param {Buffer} body
 */
function Response(statusCode, headers, body, url) {
  if (typeof statusCode !== 'number') {
    throw new TypeError('statusCode must be a number but was ' + (typeof statusCode));
  }
  if (headers === null) {
    throw new TypeError('headers cannot be null');
  }
  if (typeof headers !== 'object') {
    throw new TypeError('headers must be an object but was ' + (typeof headers));
  }
  this.statusCode = statusCode;
  this.headers = {};
  for (var key in headers) {
    this.headers[key.toLowerCase()] = headers[key];
  }
  this.body = body;
  this.url = url;
}

Response.prototype.getBody = function (encoding) {
  if (this.statusCode >= 300) {
    var err = new Error('Server responded with status code '
                    + this.statusCode + ':\n' + this.body.toString());
    err.statusCode = this.statusCode;
    err.headers = this.headers;
    err.body = this.body;
    throw err;
  }
  return encoding ? this.body.toString(encoding) : this.body;
};

'use strict';

module.exports = Response;

/**
 * A response from a web request
 *
 * @param {Number} statusCode
 * @param {Object} headers
 * @param {Buffer} body
 * @param {String} url
 */
function Response(statusCode, headers, body, url) {
  if (typeof statusCode !== 'number') {
    throw new TypeError('statusCode must be a number but was ' + (typeof statusCode));
  }
  if (headers === null) {
    throw new TypeError('headers cannot be null');
  }
  if (typeof headers !== 'object') {
    throw new TypeError('headers must be an object but was ' + (typeof headers));
  }
  this.statusCode = statusCode;
  this.headers = {};
  for (var key in headers) {
    this.headers[key.toLowerCase()] = headers[key];
  }
  this.body = body;
  this.url = url;
}

Response.prototype.getBody = function (encoding) {
  if (this.statusCode >= 300) {
    var err = new Error('Server responded with status code '
                    + this.statusCode + ':\n' + this.body.toString());
    err.statusCode = this.statusCode;
    err.headers = this.headers;
    err.body = this.body;
    err.url = this.url;
    throw err;
  }
  return encoding ? this.body.toString(encoding) : this.body;
};

Add `err.url` to match `res.url`


function Plugin(app, chat, options)
{
    if(!options) {
        throw new Error('No options specified for plugin.');
    }

    if(!options.name) {
        throw new Error('No name specified for plugin');
    }

    this.name = options.name;
    if(!options.version) {
        throw new Error('No version specified for plugin ' + this.name);
    }

    this.version = options.version;
    if(options.models) {
        this.models = options.models;
    }

    this.app = app;
    this.chat = chat;
}

Plugin.prototype.init = function(callback) {
    callback();
};

Plugin.prototype.enable = function(callback) {
    callback();
};

Plugin.prototype.disable = function() {
};

module.exports = Plugin;

function Plugin(app, chat, options)
{
    if(!options) {
        throw new Error('No options specified for plugin.');
    }

    if(!options.name) {
        throw new Error('No name specified for plugin');
    }

    this.name = options.name;
    if(!options.version) {
        throw new Error('No version specified for plugin ' + this.name);
    }

    this.version = options.version;
    if(options.models) {
        this.models = options.models;
    }

    if(options.routes) {
        this.routes = options.routes;
    }

    this.app = app;
    this.chat = chat;
}

Plugin.prototype.init = function(callback) {
    callback();
};

Plugin.prototype.enable = function(callback) {
    callback();
};

Plugin.prototype.disable = function() {
};

module.exports = Plugin;

Set routes if provided in options.


const { exec } = require('child_process');

let curPid;
let uids = {};

const setCwd = (pid) =>
  exec(`lsof -p ${pid} | grep cwd | awk '$4 == "cwd" {print $9}'`, (err, cwd) => {
    if (err) {
      console.error(err);
    } else {
      cwd = cwd.trim();
      store.dispatch({
        type: 'SESSION_SET_CWD',
        cwd
      });
    }
  });

exports.middleware = (store) => (next) => (action) => {
  switch (action.type) {
    case 'SESSION_PTY_DATA':
      if (curPid && uids[action.uid] === curPid) setCwd(curPid);
      break;
    case 'SESSION_ADD':
      uids[action.uid] = action.pid;
      curPid = action.pid;
      setCwd(curPid);
      break;
    case 'SESSION_SET_ACTIVE':
      curPid = uids[action.uid];
      setCwd(curPid);
      break;
    case 'SESSION_PTY_EXIT':
      delete uids[action.uid];
      break;
    case 'SESSION_USER_EXIT':
      delete uids[action.uid];
      break;
  }
  next(action);
};

const { exec } = require('child_process');

let curPid;
let uids = {};

const setCwd = (pid) =>
  exec(`lsof -p ${pid} | grep cwd | tr -s ' ' | cut -d ' ' -f9-`, (err, cwd) => {
    if (err) {
      console.error(err);
    } else {
      cwd = cwd.trim();
      store.dispatch({
        type: 'SESSION_SET_CWD',
        cwd
      });
    }
  });

exports.middleware = (store) => (next) => (action) => {
  switch (action.type) {
    case 'SESSION_PTY_DATA':
      if (curPid && uids[action.uid] === curPid) setCwd(curPid);
      break;
    case 'SESSION_ADD':
      uids[action.uid] = action.pid;
      curPid = action.pid;
      setCwd(curPid);
      break;
    case 'SESSION_SET_ACTIVE':
      curPid = uids[action.uid];
      setCwd(curPid);
      break;
    case 'SESSION_PTY_EXIT':
      delete uids[action.uid];
      break;
    case 'SESSION_USER_EXIT':
      delete uids[action.uid];
      break;
  }
  next(action);
};

Fix opening new tab on directories with spaces


'use strict';

var fs = require('fs');
var exec = require('child_process').exec;
var plist = require('simple-plist');
var decompress = require('decompress-zip');
var which = require('which');
var provisioning = require('provisioning');
var entitlements = require('entitlements');

var rimraf = require('rimraf');
var tmp = require('temporary');
var glob = require("glob");

var output = new tmp.Dir();

module.exports = function (file, callback){
  var data = {};

  var unzipper = new decompress(file);
  unzipper.extract({
    path: output.path
  });

  unzipper.on('error', cleanUp);
  unzipper.on('extract', function() {
    var path = glob.sync(output.path + '/Payload/*/')[0];

    data.metadata = plist.readFileSync(path + 'Info.plist');

    if(!fs.existsSync(path + 'embedded.mobileprovision')){
      return cleanUp();
    }

    provisioning(path + 'embedded.mobileprovision', function(error, output){
      if(error){
        return cleanUp(error);
      }

      data.provisioning = output;
      delete data.provisioning.DeveloperCertificates;

      if(!which.sync('codesign')){
        return cleanUp();
      }

      entitlements(path, function(error, entitlement) {
        data.entitlements = entitlement;

        return cleanUp();
      });
    });
  });

  function cleanUp(error){
    rimraf.sync(output.path);
    return callback(error, data);
  }
};

'use strict';

var fs = require('fs');
var exec = require('child_process').exec;
var plist = require('simple-plist');
var decompress = require('decompress-zip');
var which = require('which');
var provisioning = require('provisioning');
var entitlements = require('entitlements');

var rimraf = require('rimraf');
var tmp = require('temporary');
var glob = require("glob");

var output = new tmp.Dir();

module.exports = function (file, callback){
  var data = {};

  var unzipper = new decompress(file);
  unzipper.extract({
    path: output.path
  });

  unzipper.on('error', cleanUp);
  unzipper.on('extract', function() {
    var path = glob.sync(output.path + '/Payload/*/')[0];

    data.metadata = plist.readFileSync(path + 'Info.plist');

    if(!fs.existsSync(path + 'embedded.mobileprovision')){
      return cleanUp();
    }

    provisioning(path + 'embedded.mobileprovision', function(error, provision){
      if(error){
        return cleanUp(error);
      }

      data.provisioning = provision;
      delete data.provisioning.DeveloperCertificates;

      if(!which.sync('codesign')){
        return cleanUp();
      }

      entitlements(path, function(error, entitlement) {
        data.entitlements = entitlement;

        return cleanUp();
      });
    });
  });

  function cleanUp(error){
    rimraf.sync(output.path);
    return callback(error, data);
  }
};

Change argument naming in provisioning callback function


/*global require, module, window, document */

'use strict';

if (!(window && window.getComputedStyle && window.addEventListener)) {
    return;
}

var Emitter = require('tiny-emitter');
var emitter = new Emitter();
var cssDeclaration = window.getComputedStyle(document.body, ':after');
var lastBreakpoint;

var checkBreakpoint = function() {
    var currentBreakpoint = cssDeclaration
        .getPropertyValue('content')
        .replace(/'|"/g, '');

    if (currentBreakpoint !== lastBreakpoint) {
        emitter
            .emit(currentBreakpoint)
            .emit('change', currentBreakpoint);

        lastBreakpoint = currentBreakpoint;
    }
};

window.addEventListener('load', checkBreakpoint);
window.addEventListener('resize', checkBreakpoint);

module.exports = emitter;

Change indentation to 2 spaces instead of 4


var jinaga_app = require('jinaga.app');
var Roster = require('./roster/roster');

var server = jinaga_app.start(__dirname);
var app = server.app;
var j = server.j;

var roster = new Roster(j);
roster.start();

app.get("/roster/:office.csv", function(req, res, next) {
    var office = req.params.office;
    res.send(roster.get(office));
    res.end();
});

var jinaga_app = require('jinaga.app');
var Roster = require('./roster/roster');

var server = jinaga_app.start(__dirname);
var app = server.app;
var j = server.j;

var roster = new Roster(j);
roster.start();

app.get("/roster/:office.csv", function(req, res, next) {
    var office = req.params.office;
    res.setHeader('content-type', 'text/csv');
    res.send(roster.get(office));
    res.end();
});

Set the content header to CSV.


var params = location.hash.slice(1).split("/"),
    url = "http://localhost:5000",
    email = params[0],
    ids = params[1].split(",");

function showError() {
  $(".alert").html(
    "Sorry. There was an error. Are your order numbers correct?"
  ).removeClass("hidden");
};

function showStatus(data) {
  $.each(data.orders, function(_, order) {
    $(".js-status-rows").append(
      [ '
',
          '
',
            '
',
              '',
                order.number,
              '',
              order.progress + " " + order.message,
            '
',
          '
',
          '
',
            order.description,
          '
',
        '
'
      ].join("")
    );
  });
};

$.get(
  [url, email, ids.join(",")].join("/")
).done(function(data) {
  $(".status").removeClass("hidden");
  showStatus(data);
}).fail(function() {
  showError();
}).always(function() {
  $(".spinner").addClass("hidden");
});

var params = location.hash.slice(1).split("/"),
    url = "",
    email = params[0],
    ids = params[1].split(",");

function showError() {
  $(".alert").html(
    "Sorry. There was an error. Are your order numbers correct?"
  ).removeClass("hidden");
};

function showStatus(data) {
  $.each(data.orders, function(_, order) {
    $(".js-status-rows").append(
      [ '
',
          '
',
            '
',
              '',
                order.number,
              '',
              order.progress + " " + order.message,
            '
',
          '
',
          '
',
            order.description,
          '
',
        '
'
      ].join("")
    );
  });
};

$.get(
  [url, email, ids.join(",")].join("/")
).done(function(data) {
  $(".status").removeClass("hidden");
  showStatus(data);
}).fail(function() {
  showError();
}).always(function() {
  $(".spinner").addClass("hidden");
});

Stop fetching status from my laptop please