<commit_before>'use strict';

/**
 * Module dependencies.
 **/
var _ = require('lodash'),
    async = require('async'),
    mongoose = require('mongoose'),
    chalk = require('chalk'),
    path = require('path');

function Seeder() {
    this.connected = false;
}

Seeder.prototype.connect = function(db, cb) {
    var _this = this;
    /*
		switch (mongoose.connection.readyState) {
			case 0 : Disconnected;
			case 1 : Connected;
			case 2 : Connecting;
			case 3 : Disconnecting;
		}
		source http://mongoosejs.com/docs/api.html#connection_Connection-readyState
	*/
    if (mongoose.connection.readyState == 1) {
        _this.connected = true;
        console.log('Successfully initialized mongoose-seed');
        cb();
    }
    mongoose.connect(db, function(err) {
        // Log Error
        if (err) {
            console.error(chalk.red('Could not connect to MongoDB!'));
            console.log(err);
        } else {
            _this.connected = true;
            console.log('Successfully initialized mongoose-seed');
            cb();
        }
    });
};

Seeder.prototype.loadModels = function(modelPaths) {
    console.log(modelPaths);
    modelPaths.forEach(function(modelPath) {
        var model = require(path.resolve(modelPath));
        if (model instanceof Function) {
            model();
        }
    });
};

Seeder.prototype.invalidModelCheck = function(models, cb) {
    var invalidModels = [];

    models.forEach(function(model) {
        if (_.indexOf(mongoose.modelNames(), model) === -1) {
            invalidModels.push(model);
        }
    });

    if (invalidModels.length) {
        cb(new Error('Models not registered in Mongoose: ' + invalidModels));
    } else {
        cb();
    }
};

Seeder.prototype.clearModels = function(models, cb) {
    if (!this.connected) {
        return new Error('Not connected to db, exiting function');
    }

    var modelNames = [];

    // Convert to array if not already
    if (Array.isArray(models)) {
        modelNames = models;
    } else if (typeof(models) === 'string') {
        modelNames.push(models);
    } else {
        console.error(chalk.red('Error: Invalid model type'));
        return;
    }

    // Confirm that all Models have been registered in Mongoose
    this.invalidModelCheck(modelNames, function(err) {
        if (err) {
            console.error(chalk.red('Error: ' + err.message));
            return;
        }

        // Clear each model
        async.each(modelNames, function(modelName, done) {
            var Model = mongoose.model(modelName);
            Model.remove({}, function(err) {
                if (err) {
                    console.error(chalk.red('Error: ' + err.message));
                    return;
                }
                console.log(modelName + 's collection cleared');
                done();
            });
        }, function(err) {
            // Final async callback
            if (err) {
                return;
            }
            cb();
        });
    });
};

Seeder.prototype.populateModels = function(seedData, cb) {
    if (!this.connected) {
        return new Error('Not connected to db, exiting function');
    }

    var modelNames = _.unique(_.pluck(seedData, 'model'));

    // Confirm that all Models have been registered in Mongoose
    var invalidModels = this.invalidModelCheck(modelNames, function(err) {
        if (err) {
            console.error(chalk.red('Error: ' + err.message));
            return;
        }

        // Populate each model
        async.eachOf(seedData, function(entry, i, outerCallback) {
            var Model = mongoose.model(entry.model);
            async.eachOf(entry.documents, function(document, j, innerCallback) {
                Model.create(document, function(err) {
                    if (err) {
                        console.error(chalk.red('Error creating document [' + j + '] of ' + entry.model + ' model'));
                        console.error(chalk.red('Error: ' + err.message));
                    } else {
                        console.log('Successfully created document [' + j + '] of ' + entry.model + ' model');
                    }
                    innerCallback();
                });
            }, function(err) {
                outerCallback();
            });
        }, function(err) {
            cb();
        });
    });
};

module.exports = new Seeder();
<commit_msg>Removed second mongoose connection when connection already exists.<commit_after>'use strict';

/**
 * Module dependencies.
 **/
var _ = require('lodash'),
    async = require('async'),
    mongoose = require('mongoose'),
    chalk = require('chalk'),
    path = require('path');

function Seeder() {
    this.connected = false;
}

Seeder.prototype.connect = function(db, cb) {
    var _this = this;
    /*
		switch (mongoose.connection.readyState) {
			case 0 : Disconnected;
			case 1 : Connected;
			case 2 : Connecting;
			case 3 : Disconnecting;
		}
		source http://mongoosejs.com/docs/api.html#connection_Connection-readyState
	*/
    if (mongoose.connection.readyState === 1) {
        _this.connected = true;
        console.log('Successfully initialized mongoose-seed');
        cb();
    } else {
        mongoose.connect(db, function(err) {
            // Log Error
            if (err) {
                console.error(chalk.red('Could not connect to MongoDB!'));
                console.log(err);
            } else {
                _this.connected = true;
                console.log('Successfully initialized mongoose-seed');
                cb();
            }
        });
    }
};

Seeder.prototype.loadModels = function(modelPaths) {
    console.log(modelPaths);
    modelPaths.forEach(function(modelPath) {
        var model = require(path.resolve(modelPath));
        if (model instanceof Function) {
            model();
        }
    });
};

Seeder.prototype.invalidModelCheck = function(models, cb) {
    var invalidModels = [];

    models.forEach(function(model) {
        if (_.indexOf(mongoose.modelNames(), model) === -1) {
            invalidModels.push(model);
        }
    });

    if (invalidModels.length) {
        cb(new Error('Models not registered in Mongoose: ' + invalidModels));
    } else {
        cb();
    }
};

Seeder.prototype.clearModels = function(models, cb) {
    if (!this.connected) {
        return new Error('Not connected to db, exiting function');
    }

    var modelNames = [];

    // Convert to array if not already
    if (Array.isArray(models)) {
        modelNames = models;
    } else if (typeof(models) === 'string') {
        modelNames.push(models);
    } else {
        console.error(chalk.red('Error: Invalid model type'));
        return;
    }

    // Confirm that all Models have been registered in Mongoose
    this.invalidModelCheck(modelNames, function(err) {
        if (err) {
            console.error(chalk.red('Error: ' + err.message));
            return;
        }

        // Clear each model
        async.each(modelNames, function(modelName, done) {
            var Model = mongoose.model(modelName);
            Model.remove({}, function(err) {
                if (err) {
                    console.error(chalk.red('Error: ' + err.message));
                    return;
                }
                console.log(modelName + 's collection cleared');
                done();
            });
        }, function(err) {
            // Final async callback
            if (err) {
                return;
            }
            cb();
        });
    });
};

Seeder.prototype.populateModels = function(seedData, cb) {
    if (!this.connected) {
        return new Error('Not connected to db, exiting function');
    }

    var modelNames = _.unique(_.pluck(seedData, 'model'));

    // Confirm that all Models have been registered in Mongoose
    var invalidModels = this.invalidModelCheck(modelNames, function(err) {
        if (err) {
            console.error(chalk.red('Error: ' + err.message));
            return;
        }

        // Populate each model
        async.eachOf(seedData, function(entry, i, outerCallback) {
            var Model = mongoose.model(entry.model);
            async.eachOf(entry.documents, function(document, j, innerCallback) {
                Model.create(document, function(err) {
                    if (err) {
                        console.error(chalk.red('Error creating document [' + j + '] of ' + entry.model + ' model'));
                        console.error(chalk.red('Error: ' + err.message));
                    } else {
                        console.log('Successfully created document [' + j + '] of ' + entry.model + ' model');
                    }
                    innerCallback();
                });
            }, function(err) {
                outerCallback();
            });
        }, function(err) {
            cb();
        });
    });
};

module.exports = new Seeder();
<|endoftext|>


<commit_before>
var React = require('react')
var ReactDOMServer = require('react-dom/server')
var inject = require('connect-inject')
var path = require('path')
var fs = require('fs')
var layout

function getComponent(file){
    var r = require(file);
    if(r.__esModule && r.default){
        return r.default
    } else {
        return r
    }
}

function cleanOptions(options){
    var opts = options
    delete opts['settings']
    delete opts['_locals']
    delete opts['_csrf']
    delete opts['enrouten']
    delete opts['cache']
    return opts
}

function handler(html, name, options){
    var script = [
        '',
        ''
    ].join('\n')
    return html.replace('', script + '')

}

exports = module.exports = loader = {
    setLayout: function(l) { layout = l },
    list : [],

    initJSX : function(){
        return require('node-jsx').install();
    },

    engine : function (filePath, options, callback){
        delete require.cache[require.resolve(filePath)]

        if(layout){
            var layoutPath = path.join(options.settings.views, layout)
            delete require.cache[require.resolve(layoutPath)]
            var Layout = getComponent(layoutPath)
        }

        var client = getComponent(filePath)

        var data = cleanOptions(options)
        var clientApp = React.createFactory(client)(data)
        var Template = Layout ? React.createFactory(Layout)(data, clientApp) : clientApp
        var name = client.name;
        var markup = ReactDOMServer.renderToString(Template);
        markup = '<!DOCTYPE html>' + handler(markup, client.name, options)

        return callback(null, markup)
    }

}
<commit_msg>minor mistake<commit_after>
var React = require('react')
var ReactDOMServer = require('react-dom/server')
var inject = require('connect-inject')
var path = require('path')
var fs = require('fs')
var layout

function getComponent(file){
    var r = require(file);
    if(r.__esModule && r.default){
        return r.default
    } else {
        return r
    }
}

function cleanOptions(options){
    var opts = options
    delete opts['settings']
    delete opts['_locals']
    delete opts['_csrf']
    delete opts['enrouten']
    delete opts['cache']
    return opts
}

function handler(html, name, options){
    var script = [
        '',
        ''
    ].join('\n')
    return html.replace('', script + '')

}

exports = module.exports = loader = {
    setLayout: function(l) { layout = l },
    list : [],

    initJSX : function(){
        return require('node-jsx').install();
    },

    engine : function (filePath, options, callback){
        delete require.cache[require.resolve(filePath)]

        if(layout){
            var layoutPath = path.join(options.settings.views, layout)
            delete require.cache[require.resolve(layoutPath)]
            var Layout = getComponent(layoutPath)
        }

        var client = getComponent(filePath)

        var data = cleanOptions(options)
        var clientApp = React.createFactory(client)(data)
        var Template = Layout ? React.createFactory(Layout)(data, clientApp) : clientApp
        var name = client.name;
        var markup = ReactDOMServer.renderToString(Template);
        markup = '<!DOCTYPE html>' + handler(markup, client.name, options)

        return callback(null, markup)
    }

}
<|endoftext|>


<commit_before>import { h, render } from 'preact';
import thunkMiddleware from 'redux-thunk';
import persistState from 'redux-localstorage';
import { createLogger } from 'redux-logger';

const NEW_ADS = "new_ads";
const HIDE_AD = "hide_ad";
const LOGIN = "login";

const hideAd = (ad) => ({
  type: HIDE_AD,
  value: ad
});

const newAds = (ads) => ({
  type: NEW_ADS,
  value: ads
});

const login = (credentials) => ({
  type: LOGIN,
  value: credentials
});

const credentials = (state = {}, action) => {
  switch(action.type) {
  case LOGIN:
    return action.value;
  default:
    return state;
  }
};

const login = (username, password) => {
  // create jwt
  return (dispatch) => {
    const token = { username, password };
    return fetch("/facebook-ads/login", {
      method: "POST",
      headers: new Headers({
        "Authorization": "Bearer " + token
      }).then(() => dispatch(login(token)))
    });
  };
};

const ads = (state = [], action) => {
  switch(action.type) {
  case NEW_ADS:
    return action.value;
  case HIDE_AD:
    return state.map(ad => {
      if(ad.id === action.id) {
        return { ...ad, suppressed: action.value };
      }
      return ad;
    });
  default:
    return state;
  }
};

const suppressAd = (ad) => {
  return (dispatch, getState) => {
    let body = {
      ...ad,
      suppressed: true
    };
    dispatch(hideAd(ad));

    return fetch("/facebook-ads/suppress", {
      method: "POST",
      body: JSON.stringify(body),
      headers: new Headers({
        "Authorization": "Bearer " + getState().credentials
      })
    }).then((resp) => resp.json())
      .then((ads) => dispatch(newAds(ads)));
  };
};
<commit_msg>createJWT<commit_after>import { h, render } from 'preact';
import { applyMiddleware, compose, combineReducers, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import persistState from 'redux-localstorage';
import { createLogger } from 'redux-logger';

const NEW_ADS = "new_ads";
const HIDE_AD = "hide_ad";
const LOGIN = "login";

const hideAd = (ad) => ({
  type: HIDE_AD,
  value: ad
});

const newAds = (ads) => ({
  type: NEW_ADS,
  value: ads
});

const login = (credentials) => ({
  type: LOGIN,
  value: credentials
});

const credentials = (state = {}, action) => {
  switch(action.type) {
  case LOGIN:
    return action.value;
  default:
    return state;
  }
};

const createJWT = (username, password) = {
  const header = {
    alg: "HS256",
    "typ": "JWT"
  };
  const payload = {
    username, password
  };

  const token = `${btoa(JSON.stringify(header))}.${btoa(JSON.stringify(payload))}`;
  cosnt buf = new TextEncoder("utf-8").encode(token);
  return `${token}.${}`
};

const login = (username, password) => {
  // create jwt
  return (dispatch) => {
    const token = createJWT(username, password);
    return fetch("/facebook-ads/login", {
      method: "POST",
      headers: new Headers({
        "Authorization": `Bearer ${token}`
      }).then(() => dispatch(login(token)))
    });
  };
};

const ads = (state = [], action) => {
  switch(action.type) {
  case NEW_ADS:
    return action.value;
  case HIDE_AD:
    return state.map(ad => {
      if(ad.id === action.id) {
        return { ...ad, suppressed: action.value };
      }
      return ad;
    });
  default:
    return state;
  }
};

const suppressAd = (ad) => {
  return (dispatch, getState) => {
    let body = {
      ...ad,
      suppressed: true
    };
    dispatch(hideAd(ad));

    return fetch("/facebook-ads/suppress", {
      method: "POST",
      body: JSON.stringify(body),
      headers: new Headers({
        "Authorization": "Bearer " + getState().credentials
      })
    }).then((resp) => resp.json())
      .then((ads) => dispatch(newAds(ads)));
  };
};

const reducer = combineReducers({
  credentials,
  login
});
const middleware = [thunkMiddleware, createLogger()];
const store = createStore(reducer, compose(...[persistState(), applyMiddleware(...middleware)]));
<|endoftext|>


<commit_before>module.exports = Hoodie

var Store = require('hoodie-client-store')
var Account = require('hoodie-client-account')
var ConnectionStatus = require('hoodie-client-connection-status')
var Log = require('hoodie-client-log')

var getState = require('./lib/get-state')

function Hoodie (options) {
  var state = getState(options)

  var api = {
    get url () {
      return state.url + '/hoodie'
    }
  }

  var account = new Account({ url: api.url + '/account/api' })

  var CustomStore = Store.defaults({
    remoteBaseUrl: api.url + '/store/api'
  })
  var dbName = 'user/' + account.id
  var store = new CustomStore(dbName, {
    ajax: function () {
      var session = api.account.get('session')
      if (!session) {
        return
      }

      return {
        headers: {
          authorization: 'Bearer ' + session.id
        }
      }
    }
  })

  // core modules
  api.account = account
  api.store = store
  api.request = require('./lib/request').bind(this, state)
  api.connectionStatus = new ConnectionStatus(api.url)
  api.log = new Log('hoodie')
  api.plugin = require('./lib/plugin')

  // events
  api.on = require('./lib/events').on.bind(this, state)
  api.one = require('./lib/events').one.bind(this, state)
  api.off = require('./lib/events').off.bind(this, state)
  api.trigger = require('./lib/events').trigger.bind(this, state)

  // glue code
  account.on('signout', function () {
    // TODO: prevent data loss on sign out:
    //       https://github.com/hoodiehq/hoodie-client/issues/22
    store.clear()
  })

  account.on('signin', function () {
    store.connect()
  })

  return api
}
<commit_msg>fix(index): reset store on signin<commit_after>module.exports = Hoodie

var Store = require('hoodie-client-store')
var Account = require('hoodie-client-account')
var ConnectionStatus = require('hoodie-client-connection-status')
var Log = require('hoodie-client-log')

var getState = require('./lib/get-state')

function Hoodie (options) {
  var state = getState(options)

  var api = {
    get url () {
      return state.url + '/hoodie'
    }
  }

  var account = new Account({ url: api.url + '/account/api' })

  var CustomStore = Store.defaults({
    remoteBaseUrl: api.url + '/store/api'
  })
  var dbName = 'user/' + account.id
  var store = new CustomStore(dbName, {
    ajax: function () {
      var session = api.account.get('session')
      if (!session) {
        return
      }

      return {
        headers: {
          authorization: 'Bearer ' + session.id
        }
      }
    }
  })

  // core modules
  api.account = account
  api.store = store
  api.request = require('./lib/request').bind(this, state)
  api.connectionStatus = new ConnectionStatus(api.url)
  api.log = new Log('hoodie')
  api.plugin = require('./lib/plugin')

  // events
  api.on = require('./lib/events').on.bind(this, state)
  api.one = require('./lib/events').one.bind(this, state)
  api.off = require('./lib/events').off.bind(this, state)
  api.trigger = require('./lib/events').trigger.bind(this, state)

  // glue code
  account.on('signout', function () {
    // TODO: prevent data loss on sign out:
    //       https://github.com/hoodiehq/hoodie-client/issues/22
    store.clear()
  })

  account.on('signin', function () {
    store.reset().then(
      store.connect
    )
  })

  return api
}
<|endoftext|>


<commit_before>const html = require('choo/html');
const assets = require('../../common/assets');
const notFound = require('./notFound');
const { allowedCopy, delay, fadeOut } = require('../utils');

module.exports = function(state, emit) {
  const file = state.storage.getFileById(state.params.id);
  if (!file) {
    return notFound(state, emit);
  }
  const div = html`

${state.translate('uploadSuccessTimingHeader')}

${state.translate('copyUrlFormLabelWithName', {
        filename: file.name
      })}

        <input id="link" type="url" value="${file.url}" readonly="true"/>
        <button id="copy-btn" class="btn" onclick=${copyLink}>${state.translate(
    'copyUrlFormButton'
  )}</button>

      <button id="delete-file" class="btn" onclick=${deleteFile}>${state.translate(
    'deleteFileButton'
  )}</button>
      ${state.translate(
    'sendAnotherFileLink'
  )}

  `;

  async function sendNew(e) {
    e.preventDefault();
    await fadeOut('share-link');
    emit('pushState', '/');
  }

  async function copyLink() {
    if (allowedCopy()) {
      emit('copy', { url: file.url, location: 'success-screen' });
      const copyBtn = document.getElementById('copy-btn');
      copyBtn.disabled = true;
      copyBtn.replaceChild(
        html`<img src="${assets.get('check-16.svg')}" class="icon-check">`,
        copyBtn.firstChild
      );
      await delay(2000);
      copyBtn.disabled = false;
      copyBtn.textContent = state.translate('copyUrlFormButton');
    }
  }

  async function deleteFile() {
    emit('delete', { file, location: 'success-screen' });
    await fadeOut('share-link');
    emit('pushState', '/');
  }
  return div;
};
<commit_msg>fixes #545 copy effect<commit_after>const html = require('choo/html');
const assets = require('../../common/assets');
const notFound = require('./notFound');
const { allowedCopy, delay, fadeOut } = require('../utils');

module.exports = function(state, emit) {
  const file = state.storage.getFileById(state.params.id);
  if (!file) {
    return notFound(state, emit);
  }
  const div = html`

${state.translate('uploadSuccessTimingHeader')}

${state.translate('copyUrlFormLabelWithName', {
        filename: file.name
      })}

        <input id="link" type="url" value="${file.url}" readonly="true"/>
        <button id="copy-btn" class="btn" onclick=${copyLink}>${state.translate(
    'copyUrlFormButton'
  )}</button>

      <button id="delete-file" class="btn" onclick=${deleteFile}>${state.translate(
    'deleteFileButton'
  )}</button>
      ${state.translate(
    'sendAnotherFileLink'
  )}

  `;

  async function sendNew(e) {
    e.preventDefault();
    await fadeOut('share-link');
    emit('pushState', '/');
  }

  async function copyLink() {
    if (allowedCopy()) {
      emit('copy', { url: file.url, location: 'success-screen' });
      const input = document.getElementById('link');
      input.disabled = true;
      const copyBtn = document.getElementById('copy-btn');
      copyBtn.disabled = true;
      copyBtn.replaceChild(
        html`<img src="${assets.get('check-16.svg')}" class="icon-check">`,
        copyBtn.firstChild
      );
      await delay(2000);
      input.disabled = false;
      copyBtn.disabled = false;
      copyBtn.textContent = state.translate('copyUrlFormButton');
    }
  }

  async function deleteFile() {
    emit('delete', { file, location: 'success-screen' });
    await fadeOut('share-link');
    emit('pushState', '/');
  }
  return div;
};
<|endoftext|>


<commit_before>export {
  version
} from "./build/package";

export {
  Axis,
  AxisBottom,
  AxisLeft,
  AxisRight,
  AxisTop,
  date
} from "d3plus-axis";

export {
  add,
  assign,
  contrast,
  defaults,
  legible,
  lighter,
  subtract
} from "d3plus-color";

export {
  accessor,
  attrize,
  BaseClass,
  closest,
  constant,
  elem,
  locale,
  merge,
  prefix,
  stylize
} from "d3plus-common";

export {
  Geomap
} from "d3plus-geomap";

export {
  Tree,
  Treemap
} from "d3plus-hierarchy";

export {
  Legend
} from "d3plus-legend";

export {
  AreaPlot,
  LinePlot,
  Plot,
  StackedArea
} from "d3plus-plot";

export {
  Priestley
} from "d3plus-priestley";

export {
  Area,
  Circle,
  Image,
  Line,
  Path,
  pointDistance,
  Rect,
  Shape
} from "d3plus-shape";

export {
  stringify,
  strip,
  TextBox,
  textSplit,
  textWidth,
  textWrap,
  titleCase
} from "d3plus-text";

export {
  Timeline
} from "d3plus-timeline";

export {
  Tooltip
} from "d3plus-tooltip";

export {
  Viz
} from "d3plus-viz";
<commit_msg>exports Donut and Pie from d3plus-hierarchy<commit_after>export {
  version
} from "./build/package";

export {
  Axis,
  AxisBottom,
  AxisLeft,
  AxisRight,
  AxisTop,
  date
} from "d3plus-axis";

export {
  add,
  assign,
  contrast,
  defaults,
  legible,
  lighter,
  subtract
} from "d3plus-color";

export {
  accessor,
  attrize,
  BaseClass,
  closest,
  constant,
  elem,
  locale,
  merge,
  prefix,
  stylize
} from "d3plus-common";

export {
  Geomap
} from "d3plus-geomap";

export {
  Donut,
  Pie,
  Tree,
  Treemap
} from "d3plus-hierarchy";

export {
  Legend
} from "d3plus-legend";

export {
  AreaPlot,
  LinePlot,
  Plot,
  StackedArea
} from "d3plus-plot";

export {
  Priestley
} from "d3plus-priestley";

export {
  Area,
  Circle,
  Image,
  Line,
  Path,
  pointDistance,
  Rect,
  Shape
} from "d3plus-shape";

export {
  stringify,
  strip,
  TextBox,
  textSplit,
  textWidth,
  textWrap,
  titleCase
} from "d3plus-text";

export {
  Timeline
} from "d3plus-timeline";

export {
  Tooltip
} from "d3plus-tooltip";

export {
  Viz
} from "d3plus-viz";
<|endoftext|>


<commit_before>"use strict";

/**
 * @fileoverview Leap本用のCylonJsのヒナ型
 * @copyright LeapMotion Developers Jp
 * @author
 * @license MIT
 * @version 1.0.0
 */

var chalk = require("chalk");
var clear = require("clear");
var CLI = require("clui");
var figlet = require("figlet");
var inquirer = require("inquirer");
var Cylon = require("cylon");
var TrackingHand = require("./lib/tracking_hand");

clear();
console.log(
  chalk.yellow(
    figlet.textSync("LeapMotion Developers Jp", {horizontalLayout: "default"})
  )
);

inquirer.prompt([
  {
    type: "list",
    name: "size",
    message: "Which chapter no do you run",
    choices: ["ch0", "ch1", "ch2"],
    filter: function (val) {
      return val.toLowerCase();
    }
  }
], function(answers) {
  console.log(JSON.stringify(answers, null, "  "));
}).then(function(response){
  console.log(response.size);
  switch (response.size) {
    case "ch2":
      break;
    default:
      runCylon();
      break;
  }
});

function runCylon() {
  Cylon.robot({
    connections: {
      leapmotion: {adaptor: "leapmotion"}
    },
    devices: {
      leapmotion: {driver: "leapmotion"}
    },
    work: function work(my) {
      new TrackingHand(my).start();
    }
  }).start();
}<commit_msg>refactor<commit_after>"use strict";

/**
 * @fileoverview サンプルファイルの実行インターフェース
 * @copyright LeapMotion Developers Jp
 * @author K90j1
 * @license MIT
 * @version 1.0.0
 */

var chalk = require("chalk");
var clear = require("clear");
var figlet = require("figlet");
var inquirer = require("inquirer");
var Cylon = require("cylon");
var TrackingHand = require("./lib/tracking_hand");

clear();
console.log(
  chalk.yellow(
    figlet.textSync("LeapMotion Developers Jp", {horizontalLayout: "default"})
  )
);
inquirer.prompt([
  {
    type: "list",
    name: "number",
    message: "Which chapter do you run",
    choices: ["ch0", "ch1", "ch2", "ch3", "ch4", "ch5", "ch6", "ch7", "ch8", "ch9"]
  }
], function(answers) {
  console.log(JSON.stringify(answers, null, "  "));
}).then(function(response) {
  switch (response.number) {
  case "ch2":
    console.log(response.number);
    break;
  default:
    runCylon();
    break;
  }
});

function runCylon() {
  Cylon.robot({
    connections: {
      leapmotion: {adaptor: "leapmotion"}
    },
    devices: {
      leapmotion: {driver: "leapmotion"}
    },
    work: function work(my) {
      new TrackingHand(my).start();
    }
  }).start();
}<|endoftext|>


<commit_before>

var loger = function exec_command2() {

    console.log('Wait!!!');

}

module.exports =  loger;<commit_msg>Delete index.js<commit_after><|endoftext|>


<commit_before>import React from 'react';
import * as monaco from 'monaco-editor';
import PropTypes from 'prop-types';
import FontAwesomeIcon from 'react-fontawesome';
import classNames from 'classnames';

import './TextEditor.css';

const SUPPORTED_LANGUAGES = ['css', 'sol', 'html', 'json'];
const DEFAULT_LANGUAGE = 'javascript';
const EDITOR_ID = 'react-monaco-editor-container';
const GUTTER_GLYPH_MARGIN = 2;

let editor;

const initMonaco = (value) => {
  let model;
  if (editor) {
    model = editor.getModel();
  }
  editor = monaco.editor.create(document.getElementById(EDITOR_ID), {
    glyphMargin: true,
    value,
    model
  });
  monaco.editor.setTheme("vs-dark");
};

class TextEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {decorations: []};
  }
  componentDidMount() {
    initMonaco();
    editor.onDidChangeModelContent((_event) => {
      const value = editor.getValue();
      this.props.onFileContentChange(value);
    });
    editor.layout();
    window.addEventListener('resize', this.handleResize);

    editor.onMouseDown((e) => {
      if (e.target.type === GUTTER_GLYPH_MARGIN){
        this.props.toggleBreakpoint(this.props.currentFile.name, e.target.position.lineNumber);
      }
    });
  }

  handleResize = () => editor.layout();

  getLanguage() {
    if (!this.props.currentFile.name) {
      return DEFAULT_LANGUAGE;
    }
    const extension = this.props.currentFile.name.split('.').pop();
    return SUPPORTED_LANGUAGES[SUPPORTED_LANGUAGES.indexOf(extension)] || DEFAULT_LANGUAGE;
  }

  extractRowCol(errorMessage) {
    const errorSplit = errorMessage.split(':');
    if (errorSplit.length >= 3) {
      return {row: parseInt(errorSplit[1], 10), col: parseInt(errorSplit[2], 10)};
    }
    return {row: 0, col: 0};
  }

  updateMarkers() {
    // TODO: Fetch Result of compilation in embark, via ws
    // const {errors, warnings} = this.props.contractCompile;
    // const markers = [].concat(errors).concat(warnings).filter((e) => e).map((e) => {
    //   const {row, col} = this.extractRowCol(e.formattedMessage);
    //   return {
    //     startLineNumber: row,
    //     startColumn: col,
    //     endLineNumber: row,
    //     endColumn: col + 1,
    //     message: e.formattedMessage,
    //     severity: e.severity
    //   };
    // });
    // monaco.editor.setModelMarkers(editor.getModel(), 'test', markers);
  }

  updateLanguage() {
    const newLanguage = this.getLanguage();
    const currentLanguage = editor.getModel().getModeId();
    if (newLanguage !== currentLanguage) {
      monaco.editor.setModelLanguage(editor.getModel(), newLanguage);
    }
  }

  updateDecorations() {
    const newDecorations = this.props.breakpoints.map(breakpoint => (
      {
        range: new monaco.Range(breakpoint,1,breakpoint,1),
        options: {
          isWholeLine: true,
          glyphMarginClassName: 'bg-primary rounded-circle'
        }
      }
    ));

    let debuggerLine = this.props.debuggerLine;
    newDecorations.push({
      range: new monaco.Range(debuggerLine,1,debuggerLine,1),
        options: {
          isWholeLine: true,
          className: 'text-editor__debuggerLine'
        }
    });
    const decorations = editor.deltaDecorations(this.state.decorations, newDecorations);
    this.setState({decorations: decorations});
  }

  componentDidUpdate(prevProps) {
    if (this.props.currentFile.content && this.props.currentFile.content !== prevProps.currentFile.content) {
      editor.setValue(this.props.currentFile.content);
    }

    this.updateMarkers();
    const expectedDecorationsLength = this.props.debuggerLine ? this.props.breakpoints.length + 1 : this.props.breakpoints.length;
    if (expectedDecorationsLength !== this.state.decorations.length || this.props.debuggerLine !== prevProps.debuggerLine) {
      this.updateDecorations();
    }
    this.updateLanguage();
    this.handleResize();
  }

  renderTabs() {
    return (

        {this.props.editorTabs.map(file => (

             this.props.addEditorTabs(file)}>{file.name}
            <FontAwesomeIcon onClick={() => this.props.removeEditorTabs(file)} className="mx-1" name="close" />

        ))}

    );
  }

  render() {
    return (

        {this.renderTabs()}

    );
  }
}

TextEditor.propTypes = {
  onFileContentChange: PropTypes.func,
  currentFile: PropTypes.object,
  toggleBreakpoint: PropTypes.func,
  breakpoints: PropTypes.array,
  debuggerLine: PropTypes.number,
  editorTabs: PropTypes.array,
  removeEditorTabs: PropTypes.func,
  addEditorTabs: PropTypes.func
};

export default TextEditor;
<commit_msg>fix tabs<commit_after>import React from 'react';
import * as monaco from 'monaco-editor';
import PropTypes from 'prop-types';
import FontAwesomeIcon from 'react-fontawesome';
import classNames from 'classnames';

import './TextEditor.css';

const SUPPORTED_LANGUAGES = ['css', 'sol', 'html', 'json'];
const DEFAULT_LANGUAGE = 'javascript';
const EDITOR_ID = 'react-monaco-editor-container';
const GUTTER_GLYPH_MARGIN = 2;

let editor;

const initMonaco = (value) => {
  let model;
  if (editor) {
    model = editor.getModel();
  }
  editor = monaco.editor.create(document.getElementById(EDITOR_ID), {
    glyphMargin: true,
    value,
    model
  });
  monaco.editor.setTheme("vs-dark");
};

class TextEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {decorations: []};
  }
  componentDidMount() {
    initMonaco();
    editor.onDidChangeModelContent((_event) => {
      const value = editor.getValue();
      this.props.onFileContentChange(value);
    });
    editor.layout();
    window.addEventListener('resize', this.handleResize);

    editor.onMouseDown((e) => {
      if (e.target.type === GUTTER_GLYPH_MARGIN){
        this.props.toggleBreakpoint(this.props.currentFile.name, e.target.position.lineNumber);
      }
    });
  }

  handleResize = () => editor.layout();

  getLanguage() {
    if (!this.props.currentFile.name) {
      return DEFAULT_LANGUAGE;
    }
    const extension = this.props.currentFile.name.split('.').pop();
    return SUPPORTED_LANGUAGES[SUPPORTED_LANGUAGES.indexOf(extension)] || DEFAULT_LANGUAGE;
  }

  extractRowCol(errorMessage) {
    const errorSplit = errorMessage.split(':');
    if (errorSplit.length >= 3) {
      return {row: parseInt(errorSplit[1], 10), col: parseInt(errorSplit[2], 10)};
    }
    return {row: 0, col: 0};
  }

  updateMarkers() {
    // TODO: Fetch Result of compilation in embark, via ws
    // const {errors, warnings} = this.props.contractCompile;
    // const markers = [].concat(errors).concat(warnings).filter((e) => e).map((e) => {
    //   const {row, col} = this.extractRowCol(e.formattedMessage);
    //   return {
    //     startLineNumber: row,
    //     startColumn: col,
    //     endLineNumber: row,
    //     endColumn: col + 1,
    //     message: e.formattedMessage,
    //     severity: e.severity
    //   };
    // });
    // monaco.editor.setModelMarkers(editor.getModel(), 'test', markers);
  }

  updateLanguage() {
    const newLanguage = this.getLanguage();
    const currentLanguage = editor.getModel().getModeId();
    if (newLanguage !== currentLanguage) {
      monaco.editor.setModelLanguage(editor.getModel(), newLanguage);
    }
  }

  updateDecorations() {
    const newDecorations = this.props.breakpoints.map(breakpoint => (
      {
        range: new monaco.Range(breakpoint,1,breakpoint,1),
        options: {
          isWholeLine: true,
          glyphMarginClassName: 'bg-primary rounded-circle'
        }
      }
    ));

    let debuggerLine = this.props.debuggerLine;
    newDecorations.push({
      range: new monaco.Range(debuggerLine,1,debuggerLine,1),
        options: {
          isWholeLine: true,
          className: 'text-editor__debuggerLine'
        }
    });
    const decorations = editor.deltaDecorations(this.state.decorations, newDecorations);
    this.setState({decorations: decorations});
  }

  componentDidUpdate(prevProps) {
    if (this.props.currentFile.content && this.props.currentFile.content !== prevProps.currentFile.content) {
      editor.setValue(this.props.currentFile.content);
    }

    this.updateMarkers();
    const expectedDecorationsLength = this.props.debuggerLine ? this.props.breakpoints.length + 1 : this.props.breakpoints.length;
    if (expectedDecorationsLength !== this.state.decorations.length || this.props.debuggerLine !== prevProps.debuggerLine) {
      this.updateDecorations();
    }
    this.updateLanguage();
    this.handleResize();
  }

  renderTabs() {
    return (

        {this.props.editorTabs.map(file => (

             this.props.addEditorTabs(file)}>
              {file.name}
               <FontAwesomeIcon onClick={() => this.props.removeEditorTabs(file)} className="mx-1" name="close"/>

        ))}

    );
  }

  render() {
    return (

        {this.renderTabs()}

    );
  }
}

TextEditor.propTypes = {
  onFileContentChange: PropTypes.func,
  currentFile: PropTypes.object,
  toggleBreakpoint: PropTypes.func,
  breakpoints: PropTypes.array,
  debuggerLine: PropTypes.number,
  editorTabs: PropTypes.array,
  removeEditorTabs: PropTypes.func,
  addEditorTabs: PropTypes.func
};

export default TextEditor;
<|endoftext|>


<commit_before>/**
 * Code
 */

const regexp = /```([\s\S]+?)```/;

module.exports = {
	test: x => new RegExp('^' + regexp.source).test(x),
	parse: text => {
		const code = text.match(new RegExp('^' + regexp.source))[0];
		return {
			type: 'code',
			content: code,
			code: code.substr(3, code.length - 6).trim(),
			codeHtml: genHtml(code.substr(3, code.length - 6).trim())
		};
	}
};

function escape(text) {
	return text
		.replace(/>/g, '>')
		.replace(/</g, '<');
}

// 文字数が多い順にソートします
// そうしないと、「function」という文字列が与えられたときに「func」が先にマッチしてしまう可能性があるためです
const keywords = [
	'true',
	'false',
	'null',
	'nil',
	'undefined',
	'void',
	'var',
	'const',
	'let',
	'mut',
	'if',
	'then',
	'else',
	'switch',
	'match',
	'case',
	'for',
	'each',
	'in',
	'while',
	'loop',
	'continue',
	'break',
	'do',
	'goto',
	'end',
	'function',
	'func',
	'fn',
	'return',
	'async',
	'await',
	'require',
	'import',
	'export',
	'new',
	'this',
	'super',
	'base',
	'class',
	'interface',
	'abstract',
	'static',
	'public',
	'private',
	'protected',
	'virtual',
	'override',
	'extends',
	'implements',
	'constructor'
].sort((a, b) => b.length - a.length);

const symbols = [
	'=',
	'+',
	'-',
	'*',
	'/',
	'%',
	'~',
	'^',
	'&',
	'|',
	'>',
	'<',
	'!',
	'?'
];

// 変数宣言
const varDef = [
	'var',
	'const',
	'let',
	'mut'
];

const elements = [
	// comment
	code => {
		if (code.substr(0, 2) != '//') return null;
		const comment = code.match(/^\/\/(.+?)\n/)[0];
		return {
			html: `<span class="comment">${escape(comment)}</span>`,
			next: comment.length
		};
	},

	// block comment
	code => {
		const match = code.match(/^\/\*([\s\S]+?)\*\//);
		if (!match) return null;
		return {
			html: `<span class="comment">${escape(match[0])}</span>`,
			next: match[0].length
		};
	},

	// string
	code => {
		if (!/^['"`]/.test(code)) return null;
		const begin = code[0];
		let str = begin;
		let thisIsNotAString = false;
		for (let i = 1; i < code.length; i++) {
			const char = code[i];
			if (char == '\\') {
				str += char;
				str += code[i + 1] || '';
				i++;
				continue;
			} else if (char == begin) {
				str += char;
				break;
			} else if (char == '\n' || i == (code.length - 1)) {
				thisIsNotAString = true;
				break;
			} else {
				str += char;
			}
		}
		if (thisIsNotAString) {
			return null;
		} else {
			return {
				html: `<span class="string">${escape(str)}</span>`,
				next: str.length
			};
		}
	},

	// regexp
	code => {
		if (code[0] != '/') return null;
		let regexp = '';
		let thisIsNotARegexp = false;
		for (let i = 1; i < code.length; i++) {
			const char = code[i];
			if (char == '\\') {
				regexp += char;
				regexp += code[i + 1] || '';
				i++;
				continue;
			} else if (char == '/') {
				break;
			} else if (char == '\n' || i == (code.length - 1)) {
				thisIsNotARegexp = true;
				break;
			} else {
				regexp += char;
			}
		}

		if (thisIsNotARegexp) return null;
		if (regexp[0] == ' ' && regexp[regexp.length - 1] == ' ') return null;

		return {
			html: `<span class="regexp">/${escape(regexp)}/</span>`,
			next: regexp.length + 2
		};
	},

	// label
	code => {
		if (code[0] != '@') return null;
		const label = code.match(/^@([a-zA-Z_-]+?)\n/)[0];
		return {
			html: `<span class="label">${label}</span>`,
			next: label.length
		};
	},

	// extract vars
	(code, i, source, vars) => {
		const prev = source[i - 1];
		if (prev && /[a-zA-Z]/.test(prev)) return null;

		const match = varDef.filter(v => code.substr(0, v.length + 1) == v + ' ')[0];

		if (match) {
			const bars = code.substr(match.length + 1).match(/^[a-zA-Z0-9_\-,\s]+/);
			if (bars) {
				bars[0].replace(/,/g, ' ').split(' ').filter(x => x != '').forEach(bar => {
					if (!keywords.some(k => k == bar)) {
						vars.push(bar);
					}
				});
			}
		}

		return null;
	},

	// vars
	(code, i, source, vars) => {
		const prev = source[i - 1];
		// プロパティは変数と認識させないために、
		// 前に . や > (PHPなどではプロパティに -> でアクセスするため) が無いかチェック
		if (prev && /[a-zA-Z\.>]/.test(prev)) return null;

		const match = vars.sort((a, b) => b.length - a.length)
			.filter(v => code.substr(0, v.length) == v)[0];

		if (match) {
			if (/^[a-zA-Z]/.test(code.substr(match.length))) return null;
			return {
				html: `<span class="var">${match}</span>`,
				next: match.length
			};
		} else {
			return null;
		}
	},

	// number
	(code, i, source) => {
		const prev = source[i - 1];
		if (prev && /[a-zA-Z]/.test(prev)) return null;
		if (!/^[\-\+]?[0-9]+/.test(code)) return null;
		const match = code.match(/^[\-\+]?[0-9-]+/)[0];
		if (match) {
			return {
				html: `<span class="number">${match}</span>`,
				next: match.length
			};
		} else {
			return null;
		}
	},

	// keyword
	(code, i, source) => {
		const prev = source[i - 1];
		if (prev && /[a-zA-Z]/.test(prev)) return null;

		const match = keywords.filter(k => code.substr(0, k.length) == k)[0];
		if (match) {
			if (/^[a-zA-Z]/.test(code.substr(match.length))) return null;
			return {
				html: `<span class="keyword ${match}">${match}</span>`,
				next: match.length
			};
		} else {
			return null;
		}
	},

	// method
	code => {
		const match = code.match(/^([a-zA-Z_-]+?)\(/);
		if (!match) return null;

		if (match[1] == '-') return null;

		return {
			html: `<span class="method">${match[1]}</span>`,
			next: match[1].length
		};
	},

	// property
	(code, i, source) => {
		const prev = source[i - 1];
		if (prev != '.') return null;

		const match = code.match(/^[a-zA-Z0-9_-]+/);
		if (!match) return null;

		return {
			html: `<span class="property">${match[0]}</span>`,
			next: match[0].length
		};
	},

	// symbol
	code => {
		const match = symbols.filter(s => code[0] == s)[0];
		if (match) {
			return {
				html: `<span class="symbol">${match}</span>`,
				next: 1
			};
		} else {
			return null;
		}
	}
];

// specify lang is todo
function genHtml(source, lang) {
	let code = source;
	let html = '';

	let vars = [];

	let i = 0;

	function push(token) {
		html += token.html;
		code = code.substr(token.next);
		i += token.next;
	}

	while (code != '') {
		const parsed = elements.some(el => {
			const e = el(code, i, source, vars);
			if (e) {
				push(e);
				return true;
			}
		});

		if (!parsed) {
			push({
				html: escape(code[0]),
				next: 1
			});
		}
	}

	return html;
}
<commit_msg>Add keyword<commit_after>/**
 * Code
 */

const regexp = /```([\s\S]+?)```/;

module.exports = {
	test: x => new RegExp('^' + regexp.source).test(x),
	parse: text => {
		const code = text.match(new RegExp('^' + regexp.source))[0];
		return {
			type: 'code',
			content: code,
			code: code.substr(3, code.length - 6).trim(),
			codeHtml: genHtml(code.substr(3, code.length - 6).trim())
		};
	}
};

function escape(text) {
	return text
		.replace(/>/g, '>')
		.replace(/</g, '<');
}

// 文字数が多い順にソートします
// そうしないと、「function」という文字列が与えられたときに「func」が先にマッチしてしまう可能性があるためです
const keywords = [
	'true',
	'false',
	'null',
	'nil',
	'undefined',
	'void',
	'var',
	'const',
	'let',
	'mut',
	'if',
	'then',
	'else',
	'switch',
	'match',
	'case',
	'for',
	'each',
	'in',
	'while',
	'loop',
	'continue',
	'break',
	'do',
	'goto',
	'end',
	'function',
	'func',
	'fn',
	'return',
	'async',
	'await',
	'require',
	'import',
	'export',
	'struct',
	'new',
	'this',
	'super',
	'base',
	'class',
	'interface',
	'abstract',
	'static',
	'public',
	'private',
	'protected',
	'virtual',
	'override',
	'extends',
	'implements',
	'constructor'
].sort((a, b) => b.length - a.length);

const symbols = [
	'=',
	'+',
	'-',
	'*',
	'/',
	'%',
	'~',
	'^',
	'&',
	'|',
	'>',
	'<',
	'!',
	'?'
];

// 変数宣言
const varDef = [
	'var',
	'const',
	'let',
	'mut'
];

const elements = [
	// comment
	code => {
		if (code.substr(0, 2) != '//') return null;
		const comment = code.match(/^\/\/(.+?)\n/)[0];
		return {
			html: `<span class="comment">${escape(comment)}</span>`,
			next: comment.length
		};
	},

	// block comment
	code => {
		const match = code.match(/^\/\*([\s\S]+?)\*\//);
		if (!match) return null;
		return {
			html: `<span class="comment">${escape(match[0])}</span>`,
			next: match[0].length
		};
	},

	// string
	code => {
		if (!/^['"`]/.test(code)) return null;
		const begin = code[0];
		let str = begin;
		let thisIsNotAString = false;
		for (let i = 1; i < code.length; i++) {
			const char = code[i];
			if (char == '\\') {
				str += char;
				str += code[i + 1] || '';
				i++;
				continue;
			} else if (char == begin) {
				str += char;
				break;
			} else if (char == '\n' || i == (code.length - 1)) {
				thisIsNotAString = true;
				break;
			} else {
				str += char;
			}
		}
		if (thisIsNotAString) {
			return null;
		} else {
			return {
				html: `<span class="string">${escape(str)}</span>`,
				next: str.length
			};
		}
	},

	// regexp
	code => {
		if (code[0] != '/') return null;
		let regexp = '';
		let thisIsNotARegexp = false;
		for (let i = 1; i < code.length; i++) {
			const char = code[i];
			if (char == '\\') {
				regexp += char;
				regexp += code[i + 1] || '';
				i++;
				continue;
			} else if (char == '/') {
				break;
			} else if (char == '\n' || i == (code.length - 1)) {
				thisIsNotARegexp = true;
				break;
			} else {
				regexp += char;
			}
		}

		if (thisIsNotARegexp) return null;
		if (regexp[0] == ' ' && regexp[regexp.length - 1] == ' ') return null;

		return {
			html: `<span class="regexp">/${escape(regexp)}/</span>`,
			next: regexp.length + 2
		};
	},

	// label
	code => {
		if (code[0] != '@') return null;
		const label = code.match(/^@([a-zA-Z_-]+?)\n/)[0];
		return {
			html: `<span class="label">${label}</span>`,
			next: label.length
		};
	},

	// extract vars
	(code, i, source, vars) => {
		const prev = source[i - 1];
		if (prev && /[a-zA-Z]/.test(prev)) return null;

		const match = varDef.filter(v => code.substr(0, v.length + 1) == v + ' ')[0];

		if (match) {
			const bars = code.substr(match.length + 1).match(/^[a-zA-Z0-9_\-,\s]+/);
			if (bars) {
				bars[0].replace(/,/g, ' ').split(' ').filter(x => x != '').forEach(bar => {
					if (!keywords.some(k => k == bar)) {
						vars.push(bar);
					}
				});
			}
		}

		return null;
	},

	// vars
	(code, i, source, vars) => {
		const prev = source[i - 1];
		// プロパティは変数と認識させないために、
		// 前に . や > (PHPなどではプロパティに -> でアクセスするため) が無いかチェック
		if (prev && /[a-zA-Z\.>]/.test(prev)) return null;

		const match = vars.sort((a, b) => b.length - a.length)
			.filter(v => code.substr(0, v.length) == v)[0];

		if (match) {
			if (/^[a-zA-Z]/.test(code.substr(match.length))) return null;
			return {
				html: `<span class="var">${match}</span>`,
				next: match.length
			};
		} else {
			return null;
		}
	},

	// number
	(code, i, source) => {
		const prev = source[i - 1];
		if (prev && /[a-zA-Z]/.test(prev)) return null;
		if (!/^[\-\+]?[0-9]+/.test(code)) return null;
		const match = code.match(/^[\-\+]?[0-9-]+/)[0];
		if (match) {
			return {
				html: `<span class="number">${match}</span>`,
				next: match.length
			};
		} else {
			return null;
		}
	},

	// keyword
	(code, i, source) => {
		const prev = source[i - 1];
		if (prev && /[a-zA-Z]/.test(prev)) return null;

		const match = keywords.filter(k => code.substr(0, k.length) == k)[0];
		if (match) {
			if (/^[a-zA-Z]/.test(code.substr(match.length))) return null;
			return {
				html: `<span class="keyword ${match}">${match}</span>`,
				next: match.length
			};
		} else {
			return null;
		}
	},

	// method
	code => {
		const match = code.match(/^([a-zA-Z_-]+?)\(/);
		if (!match) return null;

		if (match[1] == '-') return null;

		return {
			html: `<span class="method">${match[1]}</span>`,
			next: match[1].length
		};
	},

	// property
	(code, i, source) => {
		const prev = source[i - 1];
		if (prev != '.') return null;

		const match = code.match(/^[a-zA-Z0-9_-]+/);
		if (!match) return null;

		return {
			html: `<span class="property">${match[0]}</span>`,
			next: match[0].length
		};
	},

	// symbol
	code => {
		const match = symbols.filter(s => code[0] == s)[0];
		if (match) {
			return {
				html: `<span class="symbol">${match}</span>`,
				next: 1
			};
		} else {
			return null;
		}
	}
];

// specify lang is todo
function genHtml(source, lang) {
	let code = source;
	let html = '';

	let vars = [];

	let i = 0;

	function push(token) {
		html += token.html;
		code = code.substr(token.next);
		i += token.next;
	}

	while (code != '') {
		const parsed = elements.some(el => {
			const e = el(code, i, source, vars);
			if (e) {
				push(e);
				return true;
			}
		});

		if (!parsed) {
			push({
				html: escape(code[0]),
				next: 1
			});
		}
	}

	return html;
}
<|endoftext|>


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

var async = require( "async" ),
	glob = require( "glob" ),
	_ = require( "lodash" ),
	tmp = require( "tmp" ),
	childProcess = require( "child_process" ),
	fs = require( "fs" ),
	path = require( "path" ),
	uuid = require( "uuid" ),
	defaultCallbacks = require( "./lib/callbacks" );

function identityLineFilter( value ) {
	return value;
}

function spawn( interpreter, commandLine ) {
	return childProcess.spawn( interpreter, commandLine, {
		stdio: [ process.stdin, "pipe", process.stderr ]
	} );
}

var testSuite = _.extend( function OcfTestSuite( options ) {

if ( !( this instanceof OcfTestSuite ) ) {
	return new OcfTestSuite( options );
}

var QUnit,
	runningProcesses = [],
	getQUnit = function() {
		if ( !QUnit ) {
			QUnit = require( "./lib/setup" );
		}
		return QUnit;
	};

// Spawn a single child and process its stdout.
function spawnOne( assert, options ) {
	var temporary;
	var commandLine = [ options.path, options.uuid, options.location ];
	var theChild;

	if ( "preamble" in options ) {
		var temporary = tmp.fileSync();

		fs.writeSync( temporary.fd, options.preamble( options.uuid ) );
		fs.writeSync( temporary.fd, fs.readFileSync( options.path ).toString() );
		commandLine[ 0 ] = temporary.name;
	}

	theChild = options.spawn( options.interpreter, commandLine );

	runningProcesses.push( theChild );

	theChild
		.on( "exit", function( code, signal ) {
			code = ( "reportedExitStatus" in theChild ) ? theChild.reportedExitStatus : code;
			var exitCodeOK = ( code === 0 || code === null ),
				signalOK = ( signal !== "SIGSEGV" );

			assert.ok( exitCodeOK, options.name + " exited successfully (" + code + ")" );
			assert.ok( signalOK, options.name + " did not segfault" );

			var childIndex = runningProcesses.indexOf( theChild );
			if ( childIndex >= 0 ) {
				runningProcesses.splice( childIndex, 1 );
			}
			if ( temporary ) {
				temporary.removeCallback();
			}
			options.maybeQuit( theChild );
		} );

	// The stdout of the child is a sequence of \n-separated stringified JSON objects.
	theChild.stdout.on( "data", function serverStdoutData( data ) {
		_.each( data.toString().split( "\n" ), function( value ) {
			var jsonObject;

			value = options.lineFilter( value, options.path );

			if ( !value ) {
				return;
			}

			// Attempt to retrieve a JSON object from stdout.
			try {
				jsonObject = JSON.parse( value );
			} catch ( e ) {
				options.teardown( "Error parsing " + options.name + " JSON: '" + value + "'" +
					( e.message ? e.message : e ), true );
				return;
			}

			// The child is reporting the number of assertions it will be making. We add our own
			// two assertions ( 1.) successful exit and 2.) no segfault) to that count.
			if ( "assertionCount" in jsonObject ) {
				options.reportAssertions( jsonObject.assertionCount + 2 );

			// The child has requested that it and its peer(s) be killed.
			} else if ( "finished" in jsonObject ) {
				theChild.reportedExitStatus = jsonObject.finished;
				options.teardown( null, theChild );

			} else if ( jsonObject.info ) {
				console.log( "\x1b[46;30mi\x1b[0m " + jsonObject.message );

			// The child has requested a teardown.
			} else if ( jsonObject.teardown ) {
				options.teardown(
					options.name + " requested teardown: " + jsonObject.message );

			// The child is reporting that it is ready. Only servers do this.
			} else if ( jsonObject.ready ) {
				if ( options.onReady ) {
					options.onReady();
				}

			// The child is making an assertion.
			} else if ( jsonObject.assertion ) {
				assert[ jsonObject.assertion ].apply( assert, jsonObject.arguments );

			// Otherwise, we have received unknown JSON from the child - bail.
			} else {
				options.teardown( "Unkown JSON from " + options.name + ": " + value, true );
			}
		} );
	} );

	return theChild;
}

// Normalize options

// Default options for one endpoint (client/server/single)
var defaultEndpointOptions = {
	location: "ocf",
	lineFilter: identityLineFilter,
	interpreter: "node",
	spawn: spawn
};

var actualOptions = {
	client: _.extend( {}, defaultEndpointOptions, options.client || {} ),
	server: _.extend( {}, defaultEndpointOptions, options.server || {} ),
	single: _.extend( {}, defaultEndpointOptions, options.single || {} ),
	tests: ( ( options.tests && Array.isArray( options.tests ) ) ?
		_.map( options.tests, function( item ) {
			return path.join( __dirname, "tests", item );
		} ) :
		( glob.sync( path.join( __dirname, "tests", "*" ) ) ) )
};

if ( actualOptions.tests.length === 0 ) {
	console.log( "*** No tests were requested ***" );
}

_.each( actualOptions.tests, function( item ) {
	var clientPathIndex,
		clientPaths = glob.sync( path.join( item, "client*.js" ) ),
		serverPath = path.join( item, "server.js" );

	if ( fs.lstatSync( item ).isFile() && !actualOptions.single.skip ) {
		getQUnit()
			.test( path.basename( item ).replace( /\.js$/, "" ), function( assert ) {
				spawnOne( assert,
					_.extend( {}, actualOptions.single, {
						uuid: uuid.v4(),
						name: "Test",
						path: item,
						teardown: function( error, sourceProcess ) {
							sourceProcess.kill( "SIGINT" );
						},
						maybeQuit: assert.async(),
						reportAssertions: _.bind( assert.expect, assert )
					} ) );
			} );
		return;
	}

	if ( !fs.lstatSync( item ).isDirectory() ) {
		return;
	}

	for ( clientPathIndex in clientPaths ) {
		if ( !( fs.lstatSync( clientPaths[ clientPathIndex ] ).isFile() ) ) {
			throw new Error( "Cannot find client at " + clientPaths[ clientPathIndex ] );
		}
	}

	if ( !( fs.lstatSync( serverPath ).isFile() ) ) {
		throw new Error( "Cannot find server at " + serverPath );
	}

	getQUnit().test( path.basename( item ), function( assert ) {
		var totalChildren = clientPaths.length + 1,

			// Track the child processes involved in this test in this array
			children = [],

			// Turn this test async
			done = assert.async(),

			// Count assertions made by the children. Report them to assert.expect() when both
			// children have reported their number of assertions.
			totalAssertions = 0,
			childrenAssertionsReported = 0,

			commonOptions = {
				uuid: uuid.v4(),
				teardown: function( error ) {
					var index,

						// When killing child processes in a loop we have to copy the array
						// because it may become modified by the incoming notifications that a
						// process has exited.
						copyOfChildren = children.slice();

					for ( index in copyOfChildren ) {
						copyOfChildren[ index ].kill( "SIGINT" );
					}

					if ( error ) {
						throw new Error( error );
					}
				},
				maybeQuit: function( theChild ) {
					var childIndex = children.indexOf( theChild );
					if ( childIndex >= 0 ) {
						children.splice( childIndex, 1 );
					}
					if ( children.length === 0 ) {
						done();
					}
				},
				reportAssertions: function( assertionCount ) {
					childrenAssertionsReported++;
					totalAssertions += assertionCount;
					if ( childrenAssertionsReported === totalChildren ) {
						assert.expect( totalAssertions );
					}
				}
			};

		// We run the server first, because the server has to be there before the clients
		// can run. OTOH, the clients may initiate the termination of the test via a non-error
		// teardown request.
		children.push( spawnOne( assert, _.extend( {}, actualOptions.server, commonOptions, {
			name: "Server",
			path: serverPath,
			onReady: function() {
				var clientIndex = 0;
				async.eachSeries( clientPaths, function startOneChild( item, callback ) {
					children.push( spawnOne( assert,
						_.extend( {}, actualOptions.client, commonOptions, {
							name: "Client" +
								( clientPaths.length > 1 ? " " + ( ++clientIndex ) : "" ),
							path: item
						} ) ) );

					// Spawn clients at least two seconds apart to avoid message uniqueness
					// issue in iotivity: https://jira.iotivity.org/browse/IOT-724
					setTimeout( callback, 2000 );
				} );
			}
		} ) ) );
	} );
} );

process.on( "SIGINT", process.exit );

process.on( "exit", function() {
	var childIndex;

	for ( childIndex in runningProcesses ) {
		runningProcesses[ childIndex ].kill( "SIGTERM" );
	}
} );

}, { defaultCallbacks: defaultCallbacks, defaultSpawn: spawn } );

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

var async = require( "async" ),
	glob = require( "glob" ),
	_ = require( "lodash" ),
	tmp = require( "tmp" ),
	childProcess = require( "child_process" ),
	fs = require( "fs" ),
	path = require( "path" ),
	uuid = require( "uuid" ),
	defaultCallbacks = require( "./lib/callbacks" );

function identityLineFilter( value ) {
	return value;
}

function spawn( interpreter, commandLine ) {
	return childProcess.spawn( interpreter, commandLine, {
		stdio: [ process.stdin, "pipe", process.stderr ]
	} );
}

var testSuite = _.extend( function OcfTestSuite( options ) {

if ( !( this instanceof OcfTestSuite ) ) {
	return new OcfTestSuite( options );
}

var QUnit,
	runningProcesses = [],
	getQUnit = function() {
		if ( !QUnit ) {
			QUnit = require( "./lib/setup" );
		}
		return QUnit;
	};

// Spawn a single child and process its stdout.
function spawnOne( assert, options ) {
	var temporary;
	var commandLine = [ options.path, options.uuid, options.location ];
	var theChild;
	var accumulator = "";

	if ( "preamble" in options ) {
		var temporary = tmp.fileSync();

		fs.writeSync( temporary.fd, options.preamble( options.uuid ) );
		fs.writeSync( temporary.fd, fs.readFileSync( options.path ).toString() );
		commandLine[ 0 ] = temporary.name;
	}

	theChild = options.spawn( options.interpreter, commandLine );

	runningProcesses.push( theChild );

	theChild
		.on( "exit", function( code, signal ) {
			code = ( "reportedExitStatus" in theChild ) ? theChild.reportedExitStatus : code;
			var exitCodeOK = ( code === 0 || code === null ),
				signalOK = ( signal !== "SIGSEGV" );

			assert.ok( exitCodeOK, options.name + " exited successfully (" + code + ")" );
			assert.ok( signalOK, options.name + " did not segfault" );

			var childIndex = runningProcesses.indexOf( theChild );
			if ( childIndex >= 0 ) {
				runningProcesses.splice( childIndex, 1 );
			}
			if ( temporary ) {
				temporary.removeCallback();
			}
			options.maybeQuit( theChild );
		} );

	// The stdout of the child is a sequence of \n-separated stringified JSON objects.
	theChild.stdout.on( "data", function serverStdoutData( data ) {
		data = data.toString().split( "\n" );
		data[ 0 ] = accumulator + data[ 0 ];
		if ( data[ data.length - 1 ] !== "" ) {
			accumulator = data[ data.length - 1 ];
			data.splice( data.length - 1, 1 );
		} else {
			accumulator = "";
		}

		_.each( data, function( value ) {
			var jsonObject;

			value = options.lineFilter( value, options.path );

			if ( !value ) {
				return;
			}

			// Attempt to retrieve a JSON object from stdout.
			try {
				jsonObject = JSON.parse( value );
			} catch ( e ) {
				options.teardown( "Error parsing " + options.name + " JSON: '" + value + "'" +
					( e.message ? e.message : e ), true );
				return;
			}

			// The child is reporting the number of assertions it will be making. We add our own
			// two assertions ( 1.) successful exit and 2.) no segfault) to that count.
			if ( "assertionCount" in jsonObject ) {
				options.reportAssertions( jsonObject.assertionCount + 2 );

			// The child has requested that it and its peer(s) be killed.
			} else if ( "finished" in jsonObject ) {
				theChild.reportedExitStatus = jsonObject.finished;
				options.teardown( null, theChild );

			} else if ( jsonObject.info ) {
				console.log( "\x1b[46;30mi\x1b[0m " + jsonObject.message );

			// The child has requested a teardown.
			} else if ( jsonObject.teardown ) {
				options.teardown(
					options.name + " requested teardown: " + jsonObject.message );

			// The child is reporting that it is ready. Only servers do this.
			} else if ( jsonObject.ready ) {
				if ( options.onReady ) {
					options.onReady();
				}

			// The child is making an assertion.
			} else if ( jsonObject.assertion ) {
				assert[ jsonObject.assertion ].apply( assert, jsonObject.arguments );

			// Otherwise, we have received unknown JSON from the child - bail.
			} else {
				options.teardown( "Unkown JSON from " + options.name + ": " + value, true );
			}
		} );
	} );

	return theChild;
}

// Normalize options

// Default options for one endpoint (client/server/single)
var defaultEndpointOptions = {
	location: "ocf",
	lineFilter: identityLineFilter,
	interpreter: "node",
	spawn: spawn
};

var actualOptions = {
	client: _.extend( {}, defaultEndpointOptions, options.client || {} ),
	server: _.extend( {}, defaultEndpointOptions, options.server || {} ),
	single: _.extend( {}, defaultEndpointOptions, options.single || {} ),
	tests: ( ( options.tests && Array.isArray( options.tests ) ) ?
		_.map( options.tests, function( item ) {
			return path.join( __dirname, "tests", item );
		} ) :
		( glob.sync( path.join( __dirname, "tests", "*" ) ) ) )
};

if ( actualOptions.tests.length === 0 ) {
	console.log( "*** No tests were requested ***" );
}

_.each( actualOptions.tests, function( item ) {
	var clientPathIndex,
		clientPaths = glob.sync( path.join( item, "client*.js" ) ),
		serverPath = path.join( item, "server.js" );

	if ( fs.lstatSync( item ).isFile() && !actualOptions.single.skip ) {
		getQUnit()
			.test( path.basename( item ).replace( /\.js$/, "" ), function( assert ) {
				spawnOne( assert,
					_.extend( {}, actualOptions.single, {
						uuid: uuid.v4(),
						name: "Test",
						path: item,
						teardown: function( error, sourceProcess ) {
							sourceProcess.kill( "SIGINT" );
						},
						maybeQuit: assert.async(),
						reportAssertions: _.bind( assert.expect, assert )
					} ) );
			} );
		return;
	}

	if ( !fs.lstatSync( item ).isDirectory() ) {
		return;
	}

	for ( clientPathIndex in clientPaths ) {
		if ( !( fs.lstatSync( clientPaths[ clientPathIndex ] ).isFile() ) ) {
			throw new Error( "Cannot find client at " + clientPaths[ clientPathIndex ] );
		}
	}

	if ( !( fs.lstatSync( serverPath ).isFile() ) ) {
		throw new Error( "Cannot find server at " + serverPath );
	}

	getQUnit().test( path.basename( item ), function( assert ) {
		var totalChildren = clientPaths.length + 1,

			// Track the child processes involved in this test in this array
			children = [],

			// Turn this test async
			done = assert.async(),

			// Count assertions made by the children. Report them to assert.expect() when both
			// children have reported their number of assertions.
			totalAssertions = 0,
			childrenAssertionsReported = 0,

			commonOptions = {
				uuid: uuid.v4(),
				teardown: function( error ) {
					var index,

						// When killing child processes in a loop we have to copy the array
						// because it may become modified by the incoming notifications that a
						// process has exited.
						copyOfChildren = children.slice();

					for ( index in copyOfChildren ) {
						copyOfChildren[ index ].kill( "SIGINT" );
					}

					if ( error ) {
						throw new Error( error );
					}
				},
				maybeQuit: function( theChild ) {
					var childIndex = children.indexOf( theChild );
					if ( childIndex >= 0 ) {
						children.splice( childIndex, 1 );
					}
					if ( children.length === 0 ) {
						done();
					}
				},
				reportAssertions: function( assertionCount ) {
					childrenAssertionsReported++;
					totalAssertions += assertionCount;
					if ( childrenAssertionsReported === totalChildren ) {
						assert.expect( totalAssertions );
					}
				}
			};

		// We run the server first, because the server has to be there before the clients
		// can run. OTOH, the clients may initiate the termination of the test via a non-error
		// teardown request.
		children.push( spawnOne( assert, _.extend( {}, actualOptions.server, commonOptions, {
			name: "Server",
			path: serverPath,
			onReady: function() {
				var clientIndex = 0;
				async.eachSeries( clientPaths, function startOneChild( item, callback ) {
					children.push( spawnOne( assert,
						_.extend( {}, actualOptions.client, commonOptions, {
							name: "Client" +
								( clientPaths.length > 1 ? " " + ( ++clientIndex ) : "" ),
							path: item
						} ) ) );

					// Spawn clients at least two seconds apart to avoid message uniqueness
					// issue in iotivity: https://jira.iotivity.org/browse/IOT-724
					setTimeout( callback, 2000 );
				} );
			}
		} ) ) );
	} );
} );

process.on( "SIGINT", process.exit );

process.on( "exit", function() {
	var childIndex;

	for ( childIndex in runningProcesses ) {
		runningProcesses[ childIndex ].kill( "SIGTERM" );
	}
} );

}, { defaultCallbacks: defaultCallbacks, defaultSpawn: spawn } );

module.exports = testSuite;
<|endoftext|>


<commit_before>var events = require('events');
var util = require('util');
var debug = require('debug')('http-shutdown');
var Q = require('q');
/*jslint node: true */
module.exports = function () {
  var app = new App();
  return {
    middleware: function () {
      return app.middleware();
    },

    attach: function (server) {
      return app.attach(server);
    },

    destroy: function (cb) {
      return app.destroy(cb);
    }
  };
};

function Tracker() {
  if (!(this instanceof Tracker)) return new Tracker();
  events.EventEmitter.call(this);
  this.responses = [];
  this.connections = [];
}
util.inherits(Tracker, events.EventEmitter);

Tracker.prototype.createMiddleware = function createMiddleware() {
  var tracker = this;
  return function (req, res, next) {
    tracker.track(req, res, next);
  };
};

Tracker.prototype.track = function track(req, res, next) {
  this.watchForResponseToComplete(res);
  this.watchForConnectionToClose(req.socket);
  next();
};

Tracker.prototype.watchForResponseToComplete = function watchForResponseToComplete(res) {
  var tracker = this,
      responses = this.responses;

  if (responses.indexOf(res) !== -1) {
    return;
  }

  responses.push(res);

  res.on('finish', function () {
    var index = responses.indexOf(res);

    debug('A response completed');
    if (index !== -1) {
      responses.splice(index, 1);
    }

    if (responses.length === 0) {
      debug('tracker emitting finish');
      tracker.emit('finish');
    }
  });
};

Tracker.prototype.watchForConnectionToClose = function (socket) {
  var tracker = this,
      connections = this.connections;

  if (connections.indexOf(socket) !== -1) {
    return;
  }

  connections.push(socket);

  socket.on('close', function () {
    var index = connections.indexOf(socket);

    debug('A connection closed');

    if (index !== -1) {
      connections.splice(index, 1);
    }
  });
};

Tracker.prototype.pendingResponses = function () {
  return this.responses.length;
};

Tracker.prototype.closeAllConnections = function () {
  debug('Tracker closeAllConnections');
  this.connections.forEach(function (socket) {
    debug('Tracker closing a socket...');
    socket.setKeepAlive(false);
    socket.end();
    socket.unref();
  });
  this.connections.splice(0, this.connections.length);
};

function App() {
  var thisAuthApp = this,
      tracker = new Tracker();

  this.tracker = tracker;
  this.connections = [];
  tracker.on('finish', function() {
    debug('tracker finish caught');
    if (thisAuthApp.closed) {
      debug('auth app closed.  Closing all connections');
      thisAuthApp.shutdownNow();
    }
  });
}

App.prototype.shutdownNow = function() {
  this.tracker.closeAllConnections();
  this.server.unref();
  this.destroyCB();
};

App.prototype.attach = function(server) {
  this.server = server;
  thisAuthApp = this;

  server.on('connection', function (socket) {
    debug('server has a new connection', socket.remoteAddress, socket.remotePort);
    thisAuthApp.trackConnection(socket);
  });
  server.on('close', function (event) {
    debug('caught close event', event);
  });
};

App.prototype.middleware = function() {
  return this.tracker.createMiddleware();
};

App.prototype.trackConnection = function (socket) {
  this.connections.push(socket);
};

App.prototype.destroy = function (cb) {
  debug('App destroy');
  this.destroyCB = cb;
  if (!this.closed) {
    this.closed = true;
    this.server.close();
    if (this.tracker.pendingResponses() === 0) {
      this.shutdownNow();
    }
  }
};
<commit_msg>Simplify thisApp.<commit_after>var events = require('events');
var util = require('util');
var debug = require('debug')('http-shutdown');
var Q = require('q');
/*jslint node: true */
module.exports = function () {
  var app = new App();
  return {
    middleware: function () {
      return app.middleware();
    },

    attach: function (server) {
      return app.attach(server);
    },

    destroy: function (cb) {
      return app.destroy(cb);
    }
  };
};

function Tracker() {
  if (!(this instanceof Tracker)) return new Tracker();
  events.EventEmitter.call(this);
  this.responses = [];
  this.connections = [];
}
util.inherits(Tracker, events.EventEmitter);

Tracker.prototype.createMiddleware = function createMiddleware() {
  var tracker = this;
  return function (req, res, next) {
    tracker.track(req, res, next);
  };
};

Tracker.prototype.track = function track(req, res, next) {
  this.watchForResponseToComplete(res);
  this.watchForConnectionToClose(req.socket);
  next();
};

Tracker.prototype.watchForResponseToComplete = function watchForResponseToComplete(res) {
  var tracker = this,
      responses = this.responses;

  if (responses.indexOf(res) !== -1) {
    return;
  }

  responses.push(res);

  res.on('finish', function () {
    var index = responses.indexOf(res);

    debug('A response completed');
    if (index !== -1) {
      responses.splice(index, 1);
    }

    if (responses.length === 0) {
      debug('tracker emitting finish');
      tracker.emit('finish');
    }
  });
};

Tracker.prototype.watchForConnectionToClose = function (socket) {
  var tracker = this,
      connections = this.connections;

  if (connections.indexOf(socket) !== -1) {
    return;
  }

  connections.push(socket);

  socket.on('close', function () {
    var index = connections.indexOf(socket);

    debug('A connection closed');

    if (index !== -1) {
      connections.splice(index, 1);
    }
  });
};

Tracker.prototype.pendingResponses = function () {
  return this.responses.length;
};

Tracker.prototype.closeAllConnections = function () {
  debug('Tracker closeAllConnections');
  this.connections.forEach(function (socket) {
    debug('Tracker closing a socket...');
    socket.setKeepAlive(false);
    socket.end();
    socket.unref();
  });
  this.connections.splice(0, this.connections.length);
};

function App() {
  var thisApp = this,
      tracker = new Tracker();

  this.tracker = tracker;
  this.connections = [];
  tracker.on('finish', function() {
    debug('tracker finish caught');
    if (thisApp.closed) {
      debug('auth app closed.  Closing all connections');
      thisApp.shutdownNow();
    }
  });
}

App.prototype.shutdownNow = function() {
  this.tracker.closeAllConnections();
  this.server.unref();
  this.destroyCB();
};

App.prototype.attach = function(server) {
  this.server = server;
  thisApp = this;

  server.on('connection', function (socket) {
    debug('server has a new connection', socket.remoteAddress, socket.remotePort);
    thisApp.trackConnection(socket);
  });
  server.on('close', function (event) {
    debug('caught close event', event);
  });
};

App.prototype.middleware = function() {
  return this.tracker.createMiddleware();
};

App.prototype.trackConnection = function (socket) {
  this.connections.push(socket);
};

App.prototype.destroy = function (cb) {
  debug('App destroy');
  this.destroyCB = cb;
  if (!this.closed) {
    this.closed = true;
    this.server.close();
    if (this.tracker.pendingResponses() === 0) {
      this.shutdownNow();
    }
  }
};
<|endoftext|>


<commit_before>var k=require("./kernel");
var time=require("../timing");

const width = 6000;
const height = 4000;
const maxIterations = 256;
const x0 = -2;
const x1 = 1;
const y0 = -1;
const y1 = 1;

var run=() => {
    var res=k.mandel_range(x0, y0, x1, y1, width, height, 0, height, maxIterations);
    var sum=0;
    for (var i=0; i<res.length; i++) sum+=res[i];
    console.log(sum);
};
time(run, 1);
<commit_msg>add some notation<commit_after>var k=require("./kernel");
var time=require("../timing");

const width = 6000;
const height = 4000;
const maxIterations = 256;
const x0 = -2;
const x1 = 1;
const y0 = -1;
const y1 = 1;

var run=() => {
    var res=k.mandel_range(x0, y0, x1, y1, width, height, 0, height, maxIterations);
    var sum=0;
    for (var i=0; i<res.length; i++) sum+=res[i];
    console.log(sum);
};
time(run, 1);

var run2=eval("("+run.toString()+")");
<|endoftext|>


<commit_before>var nextTick = require('next-tick')
var isPromise = require('is-promise')

module.exports = Promise
function Promise(fn) {
  if (!(this instanceof Promise)) return new Promise(fn)
  if (typeof fn !== 'function') throw new TypeError('not a function')
  var state = null
    , delegating = false
    , value = null
    , deferreds = []

  this.then = function(onFulfilled, onRejected) {
    return new Promise(function(resolve, reject) {
      handle({ onFulfilled: onFulfilled, onRejected: onRejected, resolve: resolve, reject: reject })
    })
  }

  function handle(deferred) {
    if (state === null) {
      deferreds.push(deferred)
      return
    }
    nextTick(function() {
      var cb = state ? deferred.onFulfilled : deferred.onRejected
      if (typeof cb !== 'function'){
        (state ? deferred.resolve : deferred.reject)(value)
        return
      }
      var ret
      try {
        ret = cb(value)
      }
      catch (e) {
        deferred.reject(e)
        return
      }
      deferred.resolve(ret)
    })
  }

  function resolve(newValue) {
    if (delegating)
      return
    resolve_(newValue)
  }

  function resolve_(newValue) {
    if (state !== null)
      return
    if (isPromise(newValue)) {
      delegating = true
      newValue.then(resolve_, reject_)
      return
    }
    state = true
    value = newValue
    finale()
  }

  function reject(newValue) {
    if (delegating)
      return
    reject_(newValue)
  }

  function reject_(newValue) {
    if (state !== null)
      return
    state = false
    value = newValue
    finale()
  }

  function finale() {
    for (var i = 0, len = deferreds.length; i < len; i++)
      handle(deferreds[i])
    deferreds = null
  }

  try { fn(resolve, reject) }
  catch(e) { reject(e) }
}
<commit_msg>make 'deferred' objects into a class<commit_after>var nextTick = require('next-tick')
var isPromise = require('is-promise')

module.exports = Promise
function Promise(fn) {
  if (!(this instanceof Promise)) return new Promise(fn)
  if (typeof fn !== 'function') throw new TypeError('not a function')
  var state = null
    , delegating = false
    , value = null
    , deferreds = []

  this.then = function(onFulfilled, onRejected) {
    return new Promise(function(resolve, reject) {
      handle(new Handler(onFulfilled, onRejected, resolve, reject))
    })
  }

  function handle(deferred) {
    if (state === null) {
      deferreds.push(deferred)
      return
    }
    nextTick(function() {
      var cb = state ? deferred.onFulfilled : deferred.onRejected
      if (cb === null) {
        (state ? deferred.resolve : deferred.reject)(value)
        return
      }
      var ret
      try {
        ret = cb(value)
      }
      catch (e) {
        deferred.reject(e)
        return
      }
      deferred.resolve(ret)
    })
  }

  function resolve(newValue) {
    if (delegating)
      return
    resolve_(newValue)
  }

  function resolve_(newValue) {
    if (state !== null)
      return
    if (isPromise(newValue)) {
      delegating = true
      newValue.then(resolve_, reject_)
      return
    }
    state = true
    value = newValue
    finale()
  }

  function reject(newValue) {
    if (delegating)
      return
    reject_(newValue)
  }

  function reject_(newValue) {
    if (state !== null)
      return
    state = false
    value = newValue
    finale()
  }

  function finale() {
    for (var i = 0, len = deferreds.length; i < len; i++)
      handle(deferreds[i])
    deferreds = null
  }

  try { fn(resolve, reject) }
  catch(e) { reject(e) }
}

function Handler(onFulfilled, onRejected, resolve, reject){
  this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
  this.onRejected = typeof onRejected === 'function' ? onRejected : null
  this.resolve = resolve
  this.reject = reject
}
<|endoftext|>


<commit_before>import React from 'react';
import {
  ListView,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View,
} from 'react-native';

// Elements
import StockCell from './elements/stock-cell';

// 3rd party libraries
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/MaterialIcons';

// Utils
import finance from '../../utils/finance';

export default class Settings extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
      loaded: false,
      text: null,
      helpText: 'Type a company name or stock symbol.',
    };
  }

  _onTyping(text) {
    this.setState({
      text: text.text || '',
      helpText: 'Validating symbol...',
    });

    var that = this;
    finance.symbolSuggest(text.text)
      .then((response) => response.text())
      .then((result) => {
        result = result.replace(/(YAHOO\.util\.ScriptNodeDataSource\.callbacks\()(.*)(\);)/g, '$2');
        console.log(result);
        return JSON.parse(result);
      }).then((json) => {
        that.setState({
          dataSource: that.state.dataSource.cloneWithRows(json.ResultSet.Result),
          loaded: true,
          helpText: 'Type a company name or stock symbol.',
        });
      }).catch((error) => {
        console.log('Request failed', error);
      });
  }

  render() {
    return (
      <View style={styles.container}>
        {Platform.OS === 'ios' && <View style={{height: 20, backgroundColor: '#202020'}}/>}
        <View style={styles.topBlock}>
          <Text style={styles.helpText}>
            {this.state.helpText}
          </Text>
          <View style={styles.searchBar}>
            <Icon style={styles.searchIcon} name="search" size={20} color="white" />
            <TextInput
              style={styles.searchBarInput}
              autoCapitalize={'characters'}
              autoFocus={true}
              placeholder="Search"
              placeholderTextColor="gray"
              onChangeText={(text) => this._onTyping({text})}
              value={this.state.text}
            />
            {(this.state.text && this.state.text.length > 0) ?
              <Icon
                style={styles.clearIcon}
                name="cancel" size={20}
                color="white"
                onPress={() => this.setState({
                  text: '',
                  dataSource: this.state.dataSource.cloneWithRows([]),
                })}
                /> : null}
            <TouchableHighlight style={styles.cancelButton}
              underlayColor="black"
              onPress={Actions.pop}>
              <Text style={styles.cancelButtonText}>
                Cancel
              </Text>
            </TouchableHighlight>
          </View>
        </View>

        <View style={styles.suggestion}>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={(stock) => <StockCell stock={stock} watchlistCache={this.state.watchlistCache} />}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'black',
  },
  topBlock: {
    backgroundColor: '#202020',
    paddingTop: 15,
    paddingBottom: 10,
    paddingLeft: 15,
    paddingRight: 15,
  },
  helpText: {
    color: 'white',
    fontSize: 12,
    alignSelf: 'center',
  },
  searchBar: {
    marginTop: 10,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  searchIcon: {
    paddingRight: 5,
  },
  searchBarInput: {
    flex: 4,
    flexDirection: 'column',
    height: 30,
    backgroundColor: '#424242',
    borderRadius: 4,
    color: 'white',
    paddingLeft: 10,
  },
  clearIcon: {
    paddingLeft: 2,
  },
  cancelButtonText: {
    fontSize: 16,
    color: '#3CABDA',
  },
  cancelButton: {
    flex: 1,
    marginLeft: 4,
  },
  suggestion: {
    flex: 10,
    paddingHorizontal: 15,
  },
});
<commit_msg>Change font size<commit_after>import React from 'react';
import {
  ListView,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View,
} from 'react-native';

// Elements
import StockCell from './elements/stock-cell';

// 3rd party libraries
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/MaterialIcons';

// Utils
import finance from '../../utils/finance';

export default class Settings extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
      loaded: false,
      text: null,
      helpText: 'Type a company name or stock symbol.',
    };
  }

  _onTyping(text) {
    this.setState({
      text: text.text || '',
      helpText: 'Validating symbol...',
    });

    var that = this;
    finance.symbolSuggest(text.text)
      .then((response) => response.text())
      .then((result) => {
        result = result.replace(/(YAHOO\.util\.ScriptNodeDataSource\.callbacks\()(.*)(\);)/g, '$2');
        console.log(result);
        return JSON.parse(result);
      }).then((json) => {
        that.setState({
          dataSource: that.state.dataSource.cloneWithRows(json.ResultSet.Result),
          loaded: true,
          helpText: 'Type a company name or stock symbol.',
        });
      }).catch((error) => {
        console.log('Request failed', error);
      });
  }

  render() {
    return (
      <View style={styles.container}>
        {Platform.OS === 'ios' && <View style={{height: 20, backgroundColor: '#202020'}}/>}
        <View style={styles.topBlock}>
          <Text style={styles.helpText}>
            {this.state.helpText}
          </Text>
          <View style={styles.searchBar}>
            <Icon style={styles.searchIcon} name="search" size={20} color="white" />
            <TextInput
              style={styles.searchBarInput}
              autoCapitalize={'characters'}
              autoFocus={true}
              placeholder="Search"
              placeholderTextColor="gray"
              onChangeText={(text) => this._onTyping({text})}
              value={this.state.text}
            />
            {(this.state.text && this.state.text.length > 0) ?
              <Icon
                style={styles.clearIcon}
                name="cancel" size={20}
                color="white"
                onPress={() => this.setState({
                  text: '',
                  dataSource: this.state.dataSource.cloneWithRows([]),
                })}
                /> : null}
            <TouchableHighlight style={styles.cancelButton}
              underlayColor="black"
              onPress={Actions.pop}>
              <Text style={styles.cancelButtonText}>
                Cancel
              </Text>
            </TouchableHighlight>
          </View>
        </View>

        <View style={styles.suggestion}>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={(stock) => <StockCell stock={stock} watchlistCache={this.state.watchlistCache} />}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'black',
  },
  topBlock: {
    backgroundColor: '#202020',
    paddingTop: 15,
    paddingBottom: 10,
    paddingLeft: 15,
    paddingRight: 15,
  },
  helpText: {
    color: 'white',
    fontSize: 12,
    alignSelf: 'center',
  },
  searchBar: {
    marginTop: 10,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  searchIcon: {
    paddingRight: 5,
  },
  searchBarInput: {
    flex: 4,
    flexDirection: 'column',
    height: 30,
    backgroundColor: '#424242',
    borderRadius: 4,
    color: 'white',
    paddingLeft: 10,
  },
  clearIcon: {
    paddingLeft: 2,
  },
  cancelButtonText: {
    fontSize: 14,
    color: '#3CABDA',
  },
  cancelButton: {
    flex: 1,
    marginLeft: 4,
  },
  suggestion: {
    flex: 10,
    paddingHorizontal: 15,
  },
});
<|endoftext|>