<commit_before>
var gm = require('gm')
  , fs = require('fs')
  , path = require('path')
  , debug = require('debug')('flags')
  , http = require('http')

var flags = {}

var files = {}
fs.readdirSync('./flags').forEach(function(file) {
  var name = file.slice(0, -4)
  files[name] = path.resolve(__dirname, 'flags', file)
})

fs.readFileSync('./countries.txt')
  .toString()
  .split('\n')
  .forEach(function(line) {
    line = line.trim().replace(/ /g, '_').split(';')
    if (files[line[0]]) {
      flags[line[1]] = line[0]
    }
  })

flags['-'] = 'default'
files['default'] = path.resolve(__dirname, 'default.gif')

var regexp = /^\/([a-z]{2}|\-(?!\-))?(?:\-(?!\.)([0-9]{2,4})?(?:x([0-9]{2,4}))?)?\.gif$/

exports.middleware = function(options) {
  options = options || {}

  var ttl = options.ttl || (60*60*24*365)
    , cacheControl = options.cacheControl || 'max-age=' + ttl + ', public'
    , maxWidth = options.maxWidth || 3000
    , maxHeight = options.maxHeight || 3000
    , minWidth = options.minWidth || 0
    , minHeight = options.minHeight || 0
    , expiresCache

  function getExpires() {
    if (!expiresCache) {
      var d = new Date(Date.now() + ttl * 1000)
      expiresCache = d.toUTCString()
      setTimeout(function() {
        expiresCache = null
      }, 1000 - d.getMilliseconds())
    }
    return expiresCache
  }

  return function(req, res, next) {
    debug('handle request', req.url)

    if (req.url == '/') {
      res.setHeader('Content-Type', 'text/plain')
      res.end(Object.keys(flags).join('\n'))
      return
    }

    var match = regexp.exec(req.url)
    if (!match) return next()

    var code = match[1] || '-'
      , width = parseInt(match[2], 10) || null
      , height = parseInt(match[3], 10) || null
      , file = flags[code]
      , pathname = files[file]

    if (!file) return next()

    res.setHeader('Cache-Control', cacheControl)
    res.setHeader('Expires', getExpires())
    res.setHeader('Content-Type', 'image/gif')

    if (!width && !height) {
      fs.createReadStream(pathname).pipe(res)
      return
    }

    if (width > maxWidth || height > maxHeight || width < minWidth || height < minHeight) return next()

    gm(pathname)
    .resize(width, height)
    .stream(function (err, stdout, stderr, cmd) {
      if (err) return next(err)
      stdout.pipe(res)
      debug('%s', cmd, req.url)
    })

  }
}

Object.defineProperty(exports, 'handle', {
  get: exports.middleware
})

exports.listen = function() {
  var handle = exports.middleware()

  var server = http.createServer(function(req, res) {
    handle(req, res, function(err) {
      if (err) {
        res.statusCode = 500
        res.end('500 - Internal error')
        console.error(err)
        return
      }

      res.statusCode = 404
      res.end('404 - not found')
    })
  })

  server.on('listening', function() {
    var address = server.address()
    if (address.address == '0.0.0.0') address.address = '127.0.0.1'
    address = 'http://' + address.address + ':' + address.port
    console.log('Country flags service is now listening on ' + address)
  })

  server.listen.apply(server, arguments)

  return server
}
<commit_msg>dont use relative paths in fs<commit_after>
var gm = require('gm')
  , fs = require('fs')
  , path = require('path')
  , debug = require('debug')('flags')
  , http = require('http')

var flags = {}

var files = {}
fs.readdirSync(path.join(__dirname, 'flags')).forEach(function(file) {
  var name = file.slice(0, -4)
  files[name] = path.join(__dirname, 'flags', file)
})

fs.readFileSync(path.join(__dirname, 'countries.txt'))
  .toString()
  .split('\n')
  .forEach(function(line) {
    line = line.trim().replace(/ /g, '_').split(';')
    if (files[line[0]]) {
      flags[line[1]] = line[0]
    }
  })

flags['-'] = 'default'
files['default'] = path.resolve(__dirname, 'default.gif')

var regexp = /^\/([a-z]{2}|\-(?!\-))?(?:\-(?!\.)([0-9]{2,4})?(?:x([0-9]{2,4}))?)?\.gif$/

exports.middleware = function(options) {
  options = options || {}

  var ttl = options.ttl || (60*60*24*365)
    , cacheControl = options.cacheControl || 'max-age=' + ttl + ', public'
    , maxWidth = options.maxWidth || 3000
    , maxHeight = options.maxHeight || 3000
    , minWidth = options.minWidth || 0
    , minHeight = options.minHeight || 0
    , expiresCache

  function getExpires() {
    if (!expiresCache) {
      var d = new Date(Date.now() + ttl * 1000)
      expiresCache = d.toUTCString()
      setTimeout(function() {
        expiresCache = null
      }, 1000 - d.getMilliseconds())
    }
    return expiresCache
  }

  return function(req, res, next) {
    debug('handle request', req.url)

    if (req.url == '/') {
      res.setHeader('Content-Type', 'text/plain')
      res.end(Object.keys(flags).join('\n'))
      return
    }

    var match = regexp.exec(req.url)
    if (!match) return next()

    var code = match[1] || '-'
      , width = parseInt(match[2], 10) || null
      , height = parseInt(match[3], 10) || null
      , file = flags[code]
      , pathname = files[file]

    if (!file) return next()

    res.setHeader('Cache-Control', cacheControl)
    res.setHeader('Expires', getExpires())
    res.setHeader('Content-Type', 'image/gif')

    if (!width && !height) {
      fs.createReadStream(pathname).pipe(res)
      return
    }

    if (width > maxWidth || height > maxHeight || width < minWidth || height < minHeight) return next()

    gm(pathname)
    .resize(width, height)
    .stream(function (err, stdout, stderr, cmd) {
      if (err) return next(err)
      stdout.pipe(res)
      debug('%s', cmd, req.url)
    })

  }
}

Object.defineProperty(exports, 'handle', {
  get: exports.middleware
})

exports.listen = function() {
  var handle = exports.middleware()

  var server = http.createServer(function(req, res) {
    handle(req, res, function(err) {
      if (err) {
        res.statusCode = 500
        res.end('500 - Internal error')
        console.error(err)
        return
      }

      res.statusCode = 404
      res.end('404 - not found')
    })
  })

  server.on('listening', function() {
    var address = server.address()
    if (address.address == '0.0.0.0') address.address = '127.0.0.1'
    address = 'http://' + address.address + ':' + address.port
    console.log('Country flags service is now listening on ' + address)
  })

  server.listen.apply(server, arguments)

  return server
}
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');

var coveralls = require('gulp-coveralls');
var gutil = require('gulp-util');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var runsequence = require('run-sequence');
var shell = require('gulp-shell');
var uglify = require('gulp-uglify');
var bump = require('gulp-bump');
var git = require('gulp-git');

function ignoreerror() {
  /* jshint ignore:start */ // using `this` in this context is weird
  this.emit('end');
  /* jshint ignore:end */
}

/**
 * @file gulpfile.js
 *
 * Defines tasks that can be run on gulp.
 *
 * Summary:

 *
 `test` - runs all the tests on node and the browser (mocha and karma)
 *

 *
 `test:node`
 *
 `test:node:nofail` - internally used for watching (due to bug on gulp-mocha)
 *
 `test:browser`
 *
`
 *
 `watch:test` - watch for file changes and run tests
 *

 *
 `watch:test:node`
 *
 `watch:test:browser`
 *
`
 *
 `browser` - generate files needed for browser (browserify)
 *

 *
 `browser:uncompressed` - build uncomprssed browser bundle (`bitcore-*.js`)
 *
 `browser:compressed` - build compressed browser bundle (`bitcore-*.min.js`)
 *
 `browser:maketests` - build `tests.js`, needed for testing without karma
 *
`
 *
 `lint` - run `jshint`
 *
 `coverage` - run `istanbul` with mocha to generate a report of test coverage
 *
 `coveralls` - updates coveralls info
 *
 `release` - automates release process (only for maintainers)
 *

 */
function startGulp(name, opts) {

  opts = opts || {};
  var browser = !opts.skipBrowser;
  var isSubmodule = name ? true : false;
  var fullname = name ? 'bitcore-' + name : 'bitcore';
  var files = ['lib/**/*.js'];
  var tests = ['test/**/*.js'];
  var alljs = files.concat(tests);

  /**
   * testing
   */
  var testmocha = function() {
    return gulp.src(tests).pipe(new mocha({
      reporter: 'spec'
    }));
  };

  var testkarma = shell.task([
    './node_modules/gulp-bitcore/node_modules/karma/bin/karma start ./node_modules/gulp-bitcore/karma.conf.js'
  ]);

  gulp.task('test:node', testmocha);

  gulp.task('test:node:nofail', function() {
    return testmocha().on('error', ignoreerror);
  });

  gulp.task('test:browser', ['browser:uncompressed', 'browser:maketests'], testkarma);

  if (browser) {
    gulp.task('test', function(callback) {
      runsequence(['test:node'], ['test:browser'], callback);
    });
  } else {
    gulp.task('test', ['test:node']);
  }

  /**
   * file generation
   */
  if (browser) {

    var browserifyCommand;

    if (isSubmodule) {
      browserifyCommand = './node_modules/.bin/browserify --require ./index.js:' + fullname + ' --external bitcore -o ' + fullname + '.js';
    } else {
      browserifyCommand = './node_modules/.bin/browserify --require ./index.js:bitcore -o bitcore.js';
    }

    gulp.task('browser:uncompressed', shell.task([
      browserifyCommand
    ]));

    gulp.task('browser:compressed', ['browser:uncompressed'], function() {
      return gulp.src(fullname + '.js')
        .pipe(uglify({
          mangle: true,
          compress: true
        }))
        .pipe(rename(fullname + '.min.js'))
        .pipe(gulp.dest('.'))
        .on('error', gutil.log);
    });

    gulp.task('browser:maketests', shell.task([
      'find test/ -type f -name "*.js" | xargs ./node_modules/.bin/browserify -t brfs -o tests.js'
    ]));

    gulp.task('browser', function(callback) {
      runsequence(['browser:compressed'], ['browser:maketests'], callback);
    });
  }

  /**
   * code quality and documentation
   */

  gulp.task('lint', function() {
    return gulp.src(alljs)
      .pipe(jshint())
      .pipe(jshint.reporter('default'));
  });

  gulp.task('plato', shell.task(['plato -d report -r -l .jshintrc -t ' + fullname + ' lib']));

  gulp.task('coverage', shell.task(['node_modules/.bin/./istanbul cover node_modules/.bin/_mocha -- --recursive']));

  gulp.task('coveralls', ['coverage'], function() {
    gulp.src('coverage/lcov.info').pipe(coveralls());
  });

  /**
   * watch tasks
   */

  gulp.task('watch:test', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['test']);
  });

  gulp.task('watch:test:node', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['test:node']);
  });

  if (browser) {
    gulp.task('watch:test:browser', function() {
      // todo: only run tests that are linked to file changes by doing
      // something smart like reading through the require statements
      return gulp.watch(alljs, ['test:browser']);
    });
  }

  gulp.task('watch:jsdoc', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['jsdoc']);
  });

  gulp.task('watch:coverage', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['coverage']);
  });

  gulp.task('watch:lint', function() {
    // todo: only lint files that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['lint']);
  });

  if (browser) {
    gulp.task('watch:browser', function() {
      return gulp.watch(alljs, ['browser']);
    });
  }

  /**
   * Release automation
   */

  gulp.task('release:install', function() {
    return shell.task([
      'npm install',
    ]);
  });

  var releaseFiles = ['./package.json'];
  if (browser) {
    releaseFiles.push('./bower.json');
  }

  gulp.task('release:bump', function() {
    return gulp.src(releaseFiles)
      .pipe(bump({
        type: 'patch'
      }))
      .pipe(gulp.dest('./'));
  });

  gulp.task('release:checkout-releases', function(cb) {
    git.checkout('releases', {
      args: ''
    }, cb);
  });

  gulp.task('release:merge-master', function(cb) {
    git.merge('master', {
      args: ''
    }, cb);
  });

  gulp.task('release:checkout-master', function(cb) {
    git.checkout('master', {
      args: ''
    }, cb);
  });

  var buildFiles = ['./package.json'];
  if (browser) {
    buildFiles.push(fullname + '.js');
    buildFiles.push(fullname + '.min.js');
    buildFiles.push('./bower.json');
  }
  gulp.task('release:add-built-files', function() {
    return gulp.src(buildFiles)
      .pipe(git.add({
        args: '-f'
      }));
  });

  gulp.task('release:build-commit', ['release:add-built-files'], function() {
    var pjson = require('../../package.json');
    return gulp.src(buildFiles)
      .pipe(git.commit('Build: ' + pjson.version, {
        args: ''
      }));
  });

  gulp.task('release:version-commit', function() {
    var pjson = require('../../package.json');
    return gulp.src(releaseFiles)
      .pipe(git.commit('Bump package version to ' + pjson.version, {
        args: ''
      }));
  });

  gulp.task('release:push-releases', function(cb) {
    git.push('bitpay', 'releases', {
      args: ''
    }, cb);
  });

  gulp.task('release:push', function(cb) {
    git.push('bitpay', 'master', {
      args: ''
    }, cb);
  });

  gulp.task('release:push-tag', function(cb) {
    var pjson = require('../../package.json');
    var name = 'v' + pjson.version;
    git.tag(name, 'Release ' + name, function() {
      git.push('bitpay', name, cb);
    });
  });

  gulp.task('release:publish', shell.task([
    'npm publish'
  ]));

  // requires https://hub.github.com/
  gulp.task('release', function(cb) {
    runsequence(
      // Checkout the `releases` branch
      ['release:checkout-releases'],
      // Merge the master branch
      ['release:merge-master'],
      // Run npm install
      ['release:install'],
      // Run tests with gulp test
      ['test'],
      // Update package.json and bower.json
      ['release:bump'],
      // Commit
      ['release:build-commit'],
      // Run git push bitpay $VERSION
      ['release:push-tag'],
      // Push to releases branch
      ['release:push-releases'],
      // Run npm publish
      ['release:publish'],
      // Checkout the `master` branch
      ['release:checkout-master'],
      // Bump package.json and bower.json, again
      ['release:bump'],
      // Version commit with no binary files to master
      ['release:version-commit'],
      // Push to master
      ['release:push'],
      cb);
  });

}

module.exports = startGulp;
<commit_msg>Rename module to bitcore-build<commit_after>'use strict';

var gulp = require('gulp');

var coveralls = require('gulp-coveralls');
var gutil = require('gulp-util');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var runsequence = require('run-sequence');
var shell = require('gulp-shell');
var uglify = require('gulp-uglify');
var bump = require('gulp-bump');
var git = require('gulp-git');

function ignoreerror() {
  /* jshint ignore:start */ // using `this` in this context is weird
  this.emit('end');
  /* jshint ignore:end */
}

/**
 * @file gulpfile.js
 *
 * Defines tasks that can be run on gulp.
 *
 * Summary:

 *
 `test` - runs all the tests on node and the browser (mocha and karma)
 *

 *
 `test:node`
 *
 `test:node:nofail` - internally used for watching (due to bug on gulp-mocha)
 *
 `test:browser`
 *
`
 *
 `watch:test` - watch for file changes and run tests
 *

 *
 `watch:test:node`
 *
 `watch:test:browser`
 *
`
 *
 `browser` - generate files needed for browser (browserify)
 *

 *
 `browser:uncompressed` - build uncomprssed browser bundle (`bitcore-*.js`)
 *
 `browser:compressed` - build compressed browser bundle (`bitcore-*.min.js`)
 *
 `browser:maketests` - build `tests.js`, needed for testing without karma
 *
`
 *
 `lint` - run `jshint`
 *
 `coverage` - run `istanbul` with mocha to generate a report of test coverage
 *
 `coveralls` - updates coveralls info
 *
 `release` - automates release process (only for maintainers)
 *

 */
function startGulp(name, opts) {

  opts = opts || {};
  var browser = !opts.skipBrowser;
  var isSubmodule = name ? true : false;
  var fullname = name ? 'bitcore-' + name : 'bitcore';
  var files = ['lib/**/*.js'];
  var tests = ['test/**/*.js'];
  var alljs = files.concat(tests);

  /**
   * testing
   */
  var testmocha = function() {
    return gulp.src(tests).pipe(new mocha({
      reporter: 'spec'
    }));
  };

  var testkarma = shell.task([
    './node_modules/bitcore-build/node_modules/karma/bin/karma start ./node_modules/bitcore-build/karma.conf.js'
  ]);

  gulp.task('test:node', testmocha);

  gulp.task('test:node:nofail', function() {
    return testmocha().on('error', ignoreerror);
  });

  gulp.task('test:browser', ['browser:uncompressed', 'browser:maketests'], testkarma);

  if (browser) {
    gulp.task('test', function(callback) {
      runsequence(['test:node'], ['test:browser'], callback);
    });
  } else {
    gulp.task('test', ['test:node']);
  }

  /**
   * file generation
   */
  if (browser) {

    var browserifyCommand;

    if (isSubmodule) {
      browserifyCommand = './node_modules/.bin/browserify --require ./index.js:' + fullname + ' --external bitcore -o ' + fullname + '.js';
    } else {
      browserifyCommand = './node_modules/.bin/browserify --require ./index.js:bitcore -o bitcore.js';
    }

    gulp.task('browser:uncompressed', shell.task([
      browserifyCommand
    ]));

    gulp.task('browser:compressed', ['browser:uncompressed'], function() {
      return gulp.src(fullname + '.js')
        .pipe(uglify({
          mangle: true,
          compress: true
        }))
        .pipe(rename(fullname + '.min.js'))
        .pipe(gulp.dest('.'))
        .on('error', gutil.log);
    });

    gulp.task('browser:maketests', shell.task([
      'find test/ -type f -name "*.js" | xargs ./node_modules/.bin/browserify -t brfs -o tests.js'
    ]));

    gulp.task('browser', function(callback) {
      runsequence(['browser:compressed'], ['browser:maketests'], callback);
    });
  }

  /**
   * code quality and documentation
   */

  gulp.task('lint', function() {
    return gulp.src(alljs)
      .pipe(jshint())
      .pipe(jshint.reporter('default'));
  });

  gulp.task('plato', shell.task(['plato -d report -r -l .jshintrc -t ' + fullname + ' lib']));

  gulp.task('coverage', shell.task(['node_modules/.bin/./istanbul cover node_modules/.bin/_mocha -- --recursive']));

  gulp.task('coveralls', ['coverage'], function() {
    gulp.src('coverage/lcov.info').pipe(coveralls());
  });

  /**
   * watch tasks
   */

  gulp.task('watch:test', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['test']);
  });

  gulp.task('watch:test:node', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['test:node']);
  });

  if (browser) {
    gulp.task('watch:test:browser', function() {
      // todo: only run tests that are linked to file changes by doing
      // something smart like reading through the require statements
      return gulp.watch(alljs, ['test:browser']);
    });
  }

  gulp.task('watch:jsdoc', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['jsdoc']);
  });

  gulp.task('watch:coverage', function() {
    // todo: only run tests that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['coverage']);
  });

  gulp.task('watch:lint', function() {
    // todo: only lint files that are linked to file changes by doing
    // something smart like reading through the require statements
    return gulp.watch(alljs, ['lint']);
  });

  if (browser) {
    gulp.task('watch:browser', function() {
      return gulp.watch(alljs, ['browser']);
    });
  }

  /**
   * Release automation
   */

  gulp.task('release:install', function() {
    return shell.task([
      'npm install',
    ]);
  });

  var releaseFiles = ['./package.json'];
  if (browser) {
    releaseFiles.push('./bower.json');
  }

  gulp.task('release:bump', function() {
    return gulp.src(releaseFiles)
      .pipe(bump({
        type: 'patch'
      }))
      .pipe(gulp.dest('./'));
  });

  gulp.task('release:checkout-releases', function(cb) {
    git.checkout('releases', {
      args: ''
    }, cb);
  });

  gulp.task('release:merge-master', function(cb) {
    git.merge('master', {
      args: ''
    }, cb);
  });

  gulp.task('release:checkout-master', function(cb) {
    git.checkout('master', {
      args: ''
    }, cb);
  });

  var buildFiles = ['./package.json'];
  if (browser) {
    buildFiles.push(fullname + '.js');
    buildFiles.push(fullname + '.min.js');
    buildFiles.push('./bower.json');
  }
  gulp.task('release:add-built-files', function() {
    return gulp.src(buildFiles)
      .pipe(git.add({
        args: '-f'
      }));
  });

  gulp.task('release:build-commit', ['release:add-built-files'], function() {
    var pjson = require('../../package.json');
    return gulp.src(buildFiles)
      .pipe(git.commit('Build: ' + pjson.version, {
        args: ''
      }));
  });

  gulp.task('release:version-commit', function() {
    var pjson = require('../../package.json');
    return gulp.src(releaseFiles)
      .pipe(git.commit('Bump package version to ' + pjson.version, {
        args: ''
      }));
  });

  gulp.task('release:push-releases', function(cb) {
    git.push('bitpay', 'releases', {
      args: ''
    }, cb);
  });

  gulp.task('release:push', function(cb) {
    git.push('bitpay', 'master', {
      args: ''
    }, cb);
  });

  gulp.task('release:push-tag', function(cb) {
    var pjson = require('../../package.json');
    var name = 'v' + pjson.version;
    git.tag(name, 'Release ' + name, function() {
      git.push('bitpay', name, cb);
    });
  });

  gulp.task('release:publish', shell.task([
    'npm publish'
  ]));

  // requires https://hub.github.com/
  gulp.task('release', function(cb) {
    runsequence(
      // Checkout the `releases` branch
      ['release:checkout-releases'],
      // Merge the master branch
      ['release:merge-master'],
      // Run npm install
      ['release:install'],
      // Run tests with gulp test
      ['test'],
      // Update package.json and bower.json
      ['release:bump'],
      // Commit
      ['release:build-commit'],
      // Run git push bitpay $VERSION
      ['release:push-tag'],
      // Push to releases branch
      ['release:push-releases'],
      // Run npm publish
      ['release:publish'],
      // Checkout the `master` branch
      ['release:checkout-master'],
      // Bump package.json and bower.json, again
      ['release:bump'],
      // Version commit with no binary files to master
      ['release:version-commit'],
      // Push to master
      ['release:push'],
      cb);
  });

}

module.exports = startGulp;
<|endoftext|>


<commit_before>/*
 * mockserver
 * http://mock-server.com
 *
 * Copyright (c) 2014 James Bloom
 * Licensed under the Apache License, Version 2.0
 */

module.exports = (function () {

    var mockServer;
    var artifactoryHost = 'oss.sonatype.org';
    var artifactoryPath = '/content/repositories/releases/org/mock-server/mockserver-netty/';
    var mockServerVersion = '5.6.1';

    var Q = require('q');
    var http = require('http');

    function defer() {
        var promise = (global.protractor && protractor.promise.USE_PROMISE_MANAGER !== false)
            ? protractor.promise
            : Q;
        var deferred = promise.defer();

        if (deferred.fulfill && !deferred.resolve) {
            deferred.resolve = deferred.fulfill;
        }
        return deferred;
    }

    function checkStarted(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);
        req.setTimeout(2000);

        req.once('response', function (response) {
            var body = '';

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

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    body: body
                });
            });
        });

        req.once('error', function (error) {
            if (retries > 0) {
                setTimeout(function () {
                    verbose && console.log("waiting for MockServer to start retries remaining: " + retries);
                    checkStarted(request, retries - 1, promise, verbose);
                }, 100);
            } else {
                verbose && console.log("MockServer failed to start");
                deferred.reject(error);
            }
        });

        req.end();

        return deferred.promise;
    }

    function checkStopped(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);

        req.once('response', function (response) {
            var body = '';

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

            response.on('end', function () {
                if (retries > 0) {
                    verbose && console.log("waiting for MockServer to stop retries remaining: " + retries);
                    setTimeout(function () {
                        checkStopped(request, retries - 1, promise, verbose)
                    }, 100);
                } else {
                    verbose && console.log("MockServer failed to stop");
                    deferred.reject();
                }
            });
        });

        req.once('error', function () {
            deferred.resolve();
        });

        req.end();

        return deferred.promise;
    }

    function sendRequest(request) {
        var deferred = defer();

        var callback = function (response) {
            var body = '';

            if (response.statusCode === 400 || response.statusCode === 404) {
                deferred.reject(response.statusCode);
            }

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

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    headers: response.headers,
                    body: body
                });
            });
        };

        var req = http.request(request, callback);

        req.once('error', function (err) {
            deferred.reject(err);
        });

        req.end();

        return deferred.promise;
    }

    function start_mockserver(options) {
        var port;
        var deferred = defer();

        if (!(options && options.serverPort)) {
            deferred.reject('Please specify "serverPort", for example: "start_mockserver({ serverPort: 1080 })"');
            return deferred.promise;
        }

        if ((options.systemProperties)) {
            deferred.reject('The option "systemProperties" was renamed to "jvmOptions" in 5.4.1. Please migrate to the new option name');
            return deferred.promise;
        }

        if (options.artifactoryHost) {
            artifactoryHost = options.artifactoryHost;
        }

        if (options.artifactoryPath) {
            artifactoryPath = options.artifactoryPath;
        }

        if (options.mockServerVersion) {
            mockServerVersion = options.mockServerVersion;
        }

        var startupRetries = options.startupRetries || options.javaDebugPort ? 500 : 110;

        // double check the jar has already been downloaded
        require('./downloadJar').downloadJar(mockServerVersion, artifactoryHost, artifactoryPath).then(function () {

            var spawn = require('child_process').spawn;
            var glob = require('glob');
            var commandLineOptions = ['-Dfile.encoding=UTF-8'];
            if (options.trace) {
                commandLineOptions.push('-Dmockserver.logLevel=TRACE');
            } else if (options.verbose) {
                commandLineOptions.push('-Dmockserver.logLevel=INFO');
            } else {
                commandLineOptions.push('-Dmockserver.logLevel=WARN');
            }
            if (options.initializationJsonPath) {
                commandLineOptions.push('-Dmockserver.initializationJsonPath=' + options.initializationJsonPath);
            }
            if (options.javaDebugPort) {
                commandLineOptions.push('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=' + options.javaDebugPort);
            }

            if (options.jvmOptions) {
                commandLineOptions.push(options.jvmOptions);
            }
            commandLineOptions.push('-jar');
            commandLineOptions.push(glob.sync('**/mockserver-netty-*-jar-with-dependencies.jar'));
            if (options.serverPort) {
                commandLineOptions.push("-serverPort");
                commandLineOptions.push(options.serverPort);
                port = port || options.serverPort;
            }
            if (options.proxyRemotePort) {
                commandLineOptions.push("-proxyRemotePort");
                commandLineOptions.push(options.proxyRemotePort);
            }
            if (options.proxyRemoteHost) {
                commandLineOptions.push("-proxyRemoteHost");
                commandLineOptions.push(options.proxyRemoteHost);
            }
            if (options.logLevel) {
                commandLineOptions.push("-logLevel");
                commandLineOptions.push(options.logLevel);
            }
            if (options.verbose) {
                console.log('Running \'java ' + commandLineOptions.join(' ') + '\'');
            }
            if (!options.runForked) {
                function exitHandler(config, err) {
                    return stop_mockserver(config.options).then(function () {
                        if (config.exit) process.exit();
                        if (err) console.log(err.stack);
                    });
                }

                // stop mockserver when ctrl+c event fired
                process.on('SIGINT', exitHandler.bind(null, {exit: false, options: options}));

                // stop mockserver when kill used
                process.on('SIGTERM', exitHandler.bind(null, {exit: true, options: options}));

                // stop mockserver for uncaught exceptions
                process.on('uncaughtException', exitHandler.bind(null, {exit: false, options: options}));
            }
            mockServer = spawn('java', commandLineOptions, {
                stdio: ['ignore', (options.verbose ? process.stdout : 'ignore'), process.stderr]
            });

        }).then(function () {
            return checkStarted({
                method: 'PUT',
                host: "localhost",
                path: "/mockserver/retrieve?type=ACTIVE_EXPECTATIONS",
                port: port
            }, startupRetries, deferred, options.verbose);
        }, function (error) {
            deferred.reject(error);
        });

        return deferred.promise;
    }

    function stop_mockserver(options) {
        var port;
        var deferred = defer();

        if (options && options.serverPort) {
            if (options.serverPort) {
                port = port || options.serverPort;
            }
            if (options.verbose) {
                console.log('Using port \'' + port + '\' to stop MockServer and MockServer Proxy');
            }
            sendRequest({
                method: 'PUT',
                host: "localhost",
                path: "/stop",
                port: port
            }).then(
                function () {
                    mockServer && mockServer.kill();
                    checkStopped({
                        method: 'PUT',
                        host: "localhost",
                        path: "/reset",
                        port: port
                    }, 100, deferred, options && options.verbose); // wait for 10 seconds
                },
                function (err) {
                    if (err && err.code === "ECONNREFUSED") {
                        deferred.resolve();
                    } else {
                        deferred.reject(err);
                    }
                }
            );

        } else {
            deferred.reject("Please specify \"serverPort\", for example: \"stop_mockserver({ serverPort: 1080 })\"");
        }
        return deferred.promise;
    }

    return {
        start_mockserver: start_mockserver,
        stop_mockserver: stop_mockserver
    };
})();
<commit_msg>cleaned up code and linting errors<commit_after>/*
 * mockserver
 * http://mock-server.com
 *
 * Copyright (c) 2014 James Bloom
 * Licensed under the Apache License, Version 2.0
 */

module.exports = (function () {

    var mockServer;
    var artifactoryHost = 'oss.sonatype.org';
    var artifactoryPath = '/content/repositories/releases/org/mock-server/mockserver-netty/';
    var mockServerVersion = '5.6.1';

    var Q = require('q');
    var http = require('http');

    function defer() {
        var promise = (global.protractor && protractor.promise.USE_PROMISE_MANAGER !== false)
            ? protractor.promise
            : Q;
        var deferred = promise.defer();

        if (deferred.fulfill && !deferred.resolve) {
            deferred.resolve = deferred.fulfill;
        }
        return deferred;
    }

    function checkStarted(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);
        req.setTimeout(2000);

        req.once('response', function (response) {
            var body = '';

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

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    body: body
                });
            });
        });

        req.once('error', function (error) {
            if (retries > 0) {
                setTimeout(function () {
                    if (verbose) {
                        console.log("waiting for MockServer to start retries remaining: " + retries);
                    }
                    checkStarted(request, retries - 1, promise, verbose);
                }, 100);
            } else {
                if (verbose) {
                    console.log("MockServer failed to start");
                }
                deferred.reject(error);
            }
        });

        req.end();

        return deferred.promise;
    }

    function checkStopped(request, retries, promise, verbose) {
        var deferred = promise || defer();

        var req = http.request(request);

        req.once('response', function (response) {
            var body = '';

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

            response.on('end', function () {
                if (retries > 0) {
                    if (verbose) {
                        console.log("waiting for MockServer to stop retries remaining: " + retries);
                    }
                    setTimeout(function () {
                        checkStopped(request, retries - 1, promise, verbose);
                    }, 100);
                } else {
                    if (verbose) {
                        console.log("MockServer failed to stop");
                    }
                    deferred.reject();
                }
            });
        });

        req.once('error', function () {
            deferred.resolve();
        });

        req.end();

        return deferred.promise;
    }

    function sendRequest(request) {
        var deferred = defer();

        var callback = function (response) {
            var body = '';

            if (response.statusCode === 400 || response.statusCode === 404) {
                deferred.reject(response.statusCode);
            }

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

            response.on('end', function () {
                deferred.resolve({
                    statusCode: response.statusCode,
                    headers: response.headers,
                    body: body
                });
            });
        };

        var req = http.request(request, callback);

        req.once('error', function (err) {
            deferred.reject(err);
        });

        req.end();

        return deferred.promise;
    }

    function stop_mockserver(options) {
        var port;
        var deferred = defer();

        if (options && options.serverPort) {
            if (options.serverPort) {
                port = port || options.serverPort;
            }
            if (options.verbose) {
                console.log('Using port \'' + port + '\' to stop MockServer and MockServer Proxy');
            }
            sendRequest({
                method: 'PUT',
                host: "localhost",
                path: "/stop",
                port: port
            }).then(
                function () {
                    if (mockServer) {
                        mockServer.kill();
                    }
                    checkStopped({
                        method: 'PUT',
                        host: "localhost",
                        path: "/reset",
                        port: port
                    }, 100, deferred, options && options.verbose); // wait for 10 seconds
                },
                function (err) {
                    if (err && err.code === "ECONNREFUSED") {
                        deferred.resolve();
                    } else {
                        deferred.reject(err);
                    }
                }
            );

        } else {
            deferred.reject("Please specify \"serverPort\", for example: \"stop_mockserver({ serverPort: 1080 })\"");
        }
        return deferred.promise;
    }

    function start_mockserver(options) {
        var port;
        var deferred = defer();

        if (!(options && options.serverPort)) {
            deferred.reject('Please specify "serverPort", for example: "start_mockserver({ serverPort: 1080 })"');
            return deferred.promise;
        }

        if ((options.systemProperties)) {
            deferred.reject('The option "systemProperties" was renamed to "jvmOptions" in 5.4.1. Please migrate to the new option name');
            return deferred.promise;
        }

        if (options.artifactoryHost) {
            artifactoryHost = options.artifactoryHost;
        }

        if (options.artifactoryPath) {
            artifactoryPath = options.artifactoryPath;
        }

        if (options.mockServerVersion) {
            mockServerVersion = options.mockServerVersion;
        }

        var startupRetries = options.startupRetries || options.javaDebugPort ? 500 : 110;

        // double check the jar has already been downloaded
        require('./downloadJar').downloadJar(mockServerVersion, artifactoryHost, artifactoryPath).then(function () {

            var spawn = require('child_process').spawn;
            var glob = require('glob');
            var commandLineOptions = ['-Dfile.encoding=UTF-8'];
            if (options.trace) {
                options.logLevel = 'TRACE';
            } else if (options.verbose) {
                options.logLevel = 'DEBUG';
            }
            if (options.initializationJsonPath) {
                commandLineOptions.push('-Dmockserver.initializationJsonPath=' + options.initializationJsonPath);
            }
            if (options.javaDebugPort) {
                commandLineOptions.push('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=' + options.javaDebugPort);
            }

            if (options.jvmOptions) {
                commandLineOptions.push(options.jvmOptions);
            }
            commandLineOptions.push('-jar');
            commandLineOptions.push(glob.sync('**/mockserver-netty-*-jar-with-dependencies.jar'));
            if (options.serverPort) {
                commandLineOptions.push("-serverPort");
                commandLineOptions.push(options.serverPort);
                port = port || options.serverPort;
            }
            if (options.proxyRemotePort) {
                commandLineOptions.push("-proxyRemotePort");
                commandLineOptions.push(options.proxyRemotePort);
            }
            if (options.proxyRemoteHost) {
                commandLineOptions.push("-proxyRemoteHost");
                commandLineOptions.push(options.proxyRemoteHost);
            }
            if (options.logLevel) {
                commandLineOptions.push("-logLevel");
                commandLineOptions.push(options.logLevel);
            }
            if (options.verbose) {
                console.log('Running \'java ' + commandLineOptions.join(' ') + '\'');
            }
            if (!options.runForked) {
                var exitHandler = function(config, err) {
                    return stop_mockserver(config.options).then(function () {
                        if (config.exit) {
                            process.exit();
                        }
                        if (err) {
                            console.log(err.stack);
                        }
                    });
                };

                // stop mockserver when ctrl+c event fired
                process.on('SIGINT', exitHandler.bind(null, {exit: false, options: options}));

                // stop mockserver when kill used
                process.on('SIGTERM', exitHandler.bind(null, {exit: true, options: options}));

                // stop mockserver for uncaught exceptions
                process.on('uncaughtException', exitHandler.bind(null, {exit: false, options: options}));
            }
            mockServer = spawn('java', commandLineOptions, {
                stdio: ['ignore', (options.verbose ? process.stdout : 'ignore'), process.stderr]
            });

        }).then(function () {
            return checkStarted({
                method: 'PUT',
                host: "localhost",
                path: "/mockserver/retrieve?type=ACTIVE_EXPECTATIONS",
                port: port
            }, startupRetries, deferred, options.verbose);
        }, function (error) {
            deferred.reject(error);
        });

        return deferred.promise;
    }

    return {
        start_mockserver: start_mockserver,
        stop_mockserver: stop_mockserver
    };
})();
<|endoftext|>


<commit_before>var bitwise = require('./bitwise.js')

// Use Hilbert curve point generation to map 2D data to 1D space and vice-versa.
// Will later expand to allow `n` dimensions.

function Point(x, y, z) {
    this.rotations = {
        x: 0,
        y: 0,
        z: 0
    }

    this.init = function (x, y, z) {
        this.x = Math.round(x) || 0
        this.y = Math.round(y) || 0
        if (z != null) {
            this.z = Math.round(z) || 0
            this.d = 3
            this.n = 4 * this.z + 2 * this.y  + this.x
        } else {
            this.z = null
            this.d = 2
        }
    }
    if (x instanceof Array) {
        this.init(x[0], x[1], x[2])
    } else {
        this.init(x, y, z)
    }
}

Point.prototype.rotate = function (p, n) { // :: Point -> Int -> Point
    // record rotations
    if (p.n == 0) return new Point(this.z, this.x, this.y)
    if (p.n == 1 || p.n == 3) return new Point(this.y, this.z, this.x)
    if (p.n == 2 || p.n == 6) return new Point(n - this.x, n - this.y, this.z)
    return new Point(n - this.z, this.x, n - this.y)
}

Point.prototype.rotate2d = function (n, xbit, ybit) { // : Int -> Int -> Int -> Point
    return new Point(rotate2d(n, this.x, this.y, xbit, ybit))
}

Point.prototype.rotate3d = function (level) { // :: Int -> Point
    return new Point(rotate3d(level, this.x, this.y, this.z))
}

Point.prototype.rotateLeft = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.y, this.z, this.x)
    return new Point(this.z, this.x, this.y)
}

Point.prototype.rotateRight = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.z, this.x, this.y)
    return new Point(this.y, this.z, this.x)
}

Point.prototype.toArray = function () { // :: -> [Int, Int]
        if (this.d == 3) { return [this.x, this.y, this.z] }
        return [this.x, this.y]
}

Point.prototype.mod = function (n) { // :: Int -> Point
    return new Point(this.x % n, this.y % n, this.z % n)
}

Point.prototype.unrotate = function (n) {
    // read this.rotations and undo
}

// Accepts the height or width of a square/graph, and the coordinates to
// convert.
function convert2dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int
    var xbit, ybit, level, d = 0
    var forHeight = p.x > p.y ? p.x : p.y

    // needs some tests to make sure height is compatible
    // What keeps the user from putting 54 down as the height
    while (forHeight >= height) {
            height *=2
    }
    // For each Hilbert level, we want to add an amount to
    // `d` based on which region we are in
    for (level = height / 2; level > 0; level = Math.floor(level / 2)) {
        // Determine what region we're in
        xbit = (p.x & level) > 0
        ybit = (p.y & level) > 0
        // increase distance based on region
        d += level * level * ((3 * xbit) ^ ybit)
        // rotate so that we'll be in sync with the next
        // region.
        p = p.rotate2d(level, xbit, ybit)
        // HEAD
        // p = p.rotate2d(height, xbit, ybit)
    }

    return d
}

// height and coordinates.
function convert3dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int -> Int
    var s = 1, level = 0
    var max = Math.max.apply(Math, p.toArray())
    for (; 2 * s <= max; s *= 2) {
        level = (level + 1) % 3
    }

    // shuffle axes
    // rotate based on parity
}

// Accepts height or width of a square/graph and distance
function convertDistanceTo2dPoint (distance, height) { // :: Int -> Int -> [Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, level, p = new Point(0, 0)

    if (height <= Math.sqrt(distance))  {
        height = 2
        while (height <= Math.sqrt(distance)) {
            height *=2
        }
    }

    for (level = 1; level < height; level *= 2) {
        xbit = 1 & (distance / 2)
        ybit = 1 & (distance ^ xbit)

        p = p.rotate2d(level, xbit, ybit)
        p.x += level * xbit
        p.y += level * ybit
        distance = Math.floor(distance / 4)
    }

    return p.toArray()
}

// height/width of a square/graph and distance
function convertDistanceTo3dPoint (distance, height) { // Int -> Int -> [Int, Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, zbit, level, parity
    var iter = 2, log = 0, p = new Point(0, 0, 0)

    height = height || 2

    // vvv this is interesting.
    for (parity = 1; parity < height; parity *= 2, ++log) {}
    parity = log % 3;

    // the `|| distance` was removed from 2d version
    for (level = 1; level < height || distance > 0; level *=2) {
        xbit = distance & 1;
        ybit = (distance / 2) & 1;
        zbit = (distance / 4) & 1;

        var temp = rotate3d(level - 1, xbit ^ ybit, ybit ^ zbit, zbit)
        p.x = temp[0] * level + level - 1
        p.y = temp[1] * level + level - 1
        p.z = temp[2] * level + level - 1

        distance = Math.floor(distance / 8)
        level *= 2;
        iter++;
    }

    return p.rotateLeft(iter - parity + 1).toArray();
}

// Rotate the coordinate plane and (x,y)
function rotate2d (n, x, y, xbit, ybit) { // :: Int -> Int -> Int -> Int -> Int -> [Int, Int]
    if (ybit == 0  ) {
        if (xbit == 1) {
            x = n - 1 - x
            y = n - 1 - y
        }

        var temp = x
        x = y
        y = temp
    }

    return [x, y]
}

// Rotate the coordinate plane and (x,y, z)
function rotate3d(level, x, y, z) { // :: Int -> Int -> Int -> Int -> [Int, Int, Int]
    var index = 4 * z + 2 * y + x
    if (index == 0) {
        return [z, x, y]
    } else if (index == 1 || index == 3) {
        return [y, z, x]
    } else if (index == 2 || index == 6) {
        return [level - x, level - y, z]
    } else if (index == 5 || index == 7) {
        return [y, level - z, level - x]
    } else {
        return [level - z, x, level - y]
    }
}

function grayCode (sequence) {
    return sequence ^ (sequence >> 1)
}

// returns a non-negative int 'inverse' such that graycode(inverse) = g
function grayInverse (g) { // : Int -> Int
    var m = precision(g), inverse = g, j = 1
    while (j < m) {
        inverse = inverse ^ (g >> j)
        j++
    }
    return inverse
}

// Returns the number of bits required to store an integer
function precision (n) { // :: Int > Int
    var ret = 0
    while (n > 0) {
        ret++
        n = n >> 1
    }
    return ret
}

function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1)
}

function grayInverseTransform (entry, direction, x, dim) {
    return grayTransform(bitwise.rotateRight(entry, dim, 0, direction + 1), dim - direction - 1)
}

function hilbertIndex(dim, point) {
    var index = 0, entry = 0, direction = 0, arr = point.toArray(), code,
        i = precision(Math.max.apply(null, arr)) - 1

    while (i >= 0) {
        // l = [bit(p sub n-1 ; i), bit(p sub n 0 ; i)]
        var bits = 0
        var mask = 1 << dim - 1

        for (var k = 0; k < arr.length; k++) {
            if (arr[arr.length - (k+1)] & (1 << i)) {
                bits |= mask
            }
            mask >>>= 1
        }

        bits = grayTransform(entry, direction, bits, dim)
        code = grayInverse(bits)

        entry = entry ^ bitwise.rotateLeft((entry * code), dim, 0, direction + 1)
        direction = direction + ((direction * code) + 1) % dim
        index = (index << dim) | code

        i--
    }

    return index
}

exports.xy2d = function (x, y, height) {
    height = height || 2
    return convert2dPointToDistance(new Point(x, y), height)
}

exports.xyz2d = function(x, y, z, height) {
    height = height || 2
    return convert3dPointToDistance(new Point(x, y, z), height)
}
exports.d2xy = convertDistanceTo2dPoint
exports.d2xyz = convertDistanceTo3dPoint
exports.hilbert = function (dim, x, y, z) {
    return hilbertIndex(dim, new Point(x, y, z))
}
exports.grayInverse = grayInverse
exports.grayCode = grayCode
<commit_msg>Shift parens in direction calculation.<commit_after>var bitwise = require('./bitwise.js')

// Use Hilbert curve point generation to map 2D data to 1D space and vice-versa.
// Will later expand to allow `n` dimensions.

function Point(x, y, z) {
    this.rotations = {
        x: 0,
        y: 0,
        z: 0
    }

    this.init = function (x, y, z) {
        this.x = Math.round(x) || 0
        this.y = Math.round(y) || 0
        if (z != null) {
            this.z = Math.round(z) || 0
            this.d = 3
            this.n = 4 * this.z + 2 * this.y  + this.x
        } else {
            this.z = null
            this.d = 2
        }
    }
    if (x instanceof Array) {
        this.init(x[0], x[1], x[2])
    } else {
        this.init(x, y, z)
    }
}

Point.prototype.rotate = function (p, n) { // :: Point -> Int -> Point
    // record rotations
    if (p.n == 0) return new Point(this.z, this.x, this.y)
    if (p.n == 1 || p.n == 3) return new Point(this.y, this.z, this.x)
    if (p.n == 2 || p.n == 6) return new Point(n - this.x, n - this.y, this.z)
    return new Point(n - this.z, this.x, n - this.y)
}

Point.prototype.rotate2d = function (n, xbit, ybit) { // : Int -> Int -> Int -> Point
    return new Point(rotate2d(n, this.x, this.y, xbit, ybit))
}

Point.prototype.rotate3d = function (level) { // :: Int -> Point
    return new Point(rotate3d(level, this.x, this.y, this.z))
}

Point.prototype.rotateLeft = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.y, this.z, this.x)
    return new Point(this.z, this.x, this.y)
}

Point.prototype.rotateRight = function (n) { // :: Int -> Point
    if (n % 3 == 0) return this
    if (n % 3 == 1) return new Point(this.z, this.x, this.y)
    return new Point(this.y, this.z, this.x)
}

Point.prototype.toArray = function () { // :: -> [Int, Int]
        if (this.d == 3) { return [this.x, this.y, this.z] }
        return [this.x, this.y]
}

Point.prototype.mod = function (n) { // :: Int -> Point
    return new Point(this.x % n, this.y % n, this.z % n)
}

Point.prototype.unrotate = function (n) {
    // read this.rotations and undo
}

// Accepts the height or width of a square/graph, and the coordinates to
// convert.
function convert2dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int
    var xbit, ybit, level, d = 0
    var forHeight = p.x > p.y ? p.x : p.y

    // needs some tests to make sure height is compatible
    // What keeps the user from putting 54 down as the height
    while (forHeight >= height) {
            height *=2
    }
    // For each Hilbert level, we want to add an amount to
    // `d` based on which region we are in
    for (level = height / 2; level > 0; level = Math.floor(level / 2)) {
        // Determine what region we're in
        xbit = (p.x & level) > 0
        ybit = (p.y & level) > 0
        // increase distance based on region
        d += level * level * ((3 * xbit) ^ ybit)
        // rotate so that we'll be in sync with the next
        // region.
        p = p.rotate2d(level, xbit, ybit)
        // HEAD
        // p = p.rotate2d(height, xbit, ybit)
    }

    return d
}

// height and coordinates.
function convert3dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int -> Int
    var s = 1, level = 0
    var max = Math.max.apply(Math, p.toArray())
    for (; 2 * s <= max; s *= 2) {
        level = (level + 1) % 3
    }

    // shuffle axes
    // rotate based on parity
}

// Accepts height or width of a square/graph and distance
function convertDistanceTo2dPoint (distance, height) { // :: Int -> Int -> [Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, level, p = new Point(0, 0)

    if (height <= Math.sqrt(distance))  {
        height = 2
        while (height <= Math.sqrt(distance)) {
            height *=2
        }
    }

    for (level = 1; level < height; level *= 2) {
        xbit = 1 & (distance / 2)
        ybit = 1 & (distance ^ xbit)

        p = p.rotate2d(level, xbit, ybit)
        p.x += level * xbit
        p.y += level * ybit
        distance = Math.floor(distance / 4)
    }

    return p.toArray()
}

// height/width of a square/graph and distance
function convertDistanceTo3dPoint (distance, height) { // Int -> Int -> [Int, Int, Int]
    distance = Math.floor(distance)
    var xbit, ybit, zbit, level, parity
    var iter = 2, log = 0, p = new Point(0, 0, 0)

    height = height || 2

    // vvv this is interesting.
    for (parity = 1; parity < height; parity *= 2, ++log) {}
    parity = log % 3;

    // the `|| distance` was removed from 2d version
    for (level = 1; level < height || distance > 0; level *=2) {
        xbit = distance & 1;
        ybit = (distance / 2) & 1;
        zbit = (distance / 4) & 1;

        var temp = rotate3d(level - 1, xbit ^ ybit, ybit ^ zbit, zbit)
        p.x = temp[0] * level + level - 1
        p.y = temp[1] * level + level - 1
        p.z = temp[2] * level + level - 1

        distance = Math.floor(distance / 8)
        level *= 2;
        iter++;
    }

    return p.rotateLeft(iter - parity + 1).toArray();
}

// Rotate the coordinate plane and (x,y)
function rotate2d (n, x, y, xbit, ybit) { // :: Int -> Int -> Int -> Int -> Int -> [Int, Int]
    if (ybit == 0  ) {
        if (xbit == 1) {
            x = n - 1 - x
            y = n - 1 - y
        }

        var temp = x
        x = y
        y = temp
    }

    return [x, y]
}

// Rotate the coordinate plane and (x,y, z)
function rotate3d(level, x, y, z) { // :: Int -> Int -> Int -> Int -> [Int, Int, Int]
    var index = 4 * z + 2 * y + x
    if (index == 0) {
        return [z, x, y]
    } else if (index == 1 || index == 3) {
        return [y, z, x]
    } else if (index == 2 || index == 6) {
        return [level - x, level - y, z]
    } else if (index == 5 || index == 7) {
        return [y, level - z, level - x]
    } else {
        return [level - z, x, level - y]
    }
}

function grayCode (sequence) {
    return sequence ^ (sequence >> 1)
}

// returns a non-negative int 'inverse' such that graycode(inverse) = g
function grayInverse (g) { // : Int -> Int
    var m = precision(g), inverse = g, j = 1
    while (j < m) {
        inverse = inverse ^ (g >> j)
        j++
    }
    return inverse
}

// Returns the number of bits required to store an integer
function precision (n) { // :: Int > Int
    var ret = 0
    while (n > 0) {
        ret++
        n = n >> 1
    }
    return ret
}

function grayTransform (entry, direction, x, dim) { // :: Int -> Int -> Int -> Int
    return bitwise.rotateRight((x ^ entry), dim, 0, direction + 1)
}

function grayInverseTransform (entry, direction, x, dim) {
    return grayTransform(bitwise.rotateRight(entry, dim, 0, direction + 1), dim - direction - 1)
}

function hilbertIndex(dim, point) {
    var index = 0, entry = 0, direction = 0, arr = point.toArray(), code,
        i = precision(Math.max.apply(null, arr)) - 1

    while (i >= 0) {
        var bits = 0
        var mask = 1 << dim - 1

        for (var k = 0; k < arr.length; k++) {
            if (arr[arr.length - (k+1)] & (1 << i)) {
                bits |= mask
            }
            mask >>>= 1
        }

        bits = grayTransform(entry, direction, bits, dim)
        code = grayInverse(bits)

        entry = entry ^ bitwise.rotateLeft((entry * code), dim, 0, direction + 1)
        direction = (direction + (direction * code) + 1) % dim
        index = (index << dim) | code

        console.log('bits: ' + bits)
        console.log('entry: ' + entry)
        console.log('direction: ' + direction)
        console.log('code: ' + code)
        console.log('index: ' + index)

        i--
    }

    return index
}

exports.xy2d = function (x, y, height) {
    height = height || 2
    return convert2dPointToDistance(new Point(x, y), height)
}

exports.xyz2d = function(x, y, z, height) {
    height = height || 2
    return convert3dPointToDistance(new Point(x, y, z), height)
}
exports.d2xy = convertDistanceTo2dPoint
exports.d2xyz = convertDistanceTo3dPoint
exports.hilbert = function (dim, x, y, z) {
    return hilbertIndex(dim, new Point(x, y, z))
}
exports.grayInverse = grayInverse
exports.grayCode = grayCode
<|endoftext|>


<commit_before>var net = require('net'),
    protobuf = require('protobuf.js'),
    butils = require('butils');

var messageCodes = {
    '0': 'RpbErrorResp',
    '1': 'RpbPingReq',
    '2': 'RpbPingResp',
    '3': 'RpbGetClientIdReq',
    '4': 'RpbGetClientIdResp',
    '5': 'RpbSetClientIdReq',
    '6': 'RpbSetClientIdResp',
    '7': 'RpbGetServerInfoReq',
    '8': 'RpbGetServerInfoResp',
    '9': 'RpbGetReq',
    '10': 'RpbGetResp',
    '11': 'RpbPutReq',
    '12': 'RpbPutResp',
    '13': 'RpbDelReq',
    '14': 'RpbDelResp',
    '15': 'RpbListBucketsReq',
    '16': 'RpbListBucketsResp',
    '17': 'RpbListKeysReq',
    '18': 'RpbListKeysResp',
    '19': 'RpbGetBucketReq',
    '20': 'RpbGetBucketResp',
    '21': 'RpbSetBucketReq',
    '22': 'RpbSetBucketResp',
    '23': 'RpbMapRedReq',
    '24': 'RpbMapRedResp',
    '25': 'RpbIndexReq',
    '26': 'RpbIndexResp',
    '27': 'RpbSearchQueryReq',
    '28': 'RpbSearchQueryResp'
};
Object.keys(messageCodes).forEach(function (key) {
    messageCodes[messageCodes[key]] = Number(key);
});

function RiakPBC(options) {
    var self = this;
    options = options || {};
    self.host = options.host || '127.0.0.1';
    self.port = options.port || 8087;
    self.bucket = options.bucket || undefined;
    self.translator = protobuf.loadSchema('./spec/riak_kv.proto');
    self.client = new net.Socket();
    self.connected = false;
    self.client.on('end', self.disconnect);
    self.client.on('error', self.disconnect);
    self.paused = false;
    self.queue = [];
    var mc, reply = {};

    function splitPacket(pkt) {
        var ret = [], len, pos = 0, end = pkt.length;
        while (pos < end) {
            len = butils.readInt32(pkt, pos);
            ret.push(pkt.slice(pos + 4, pos + len + 4));
            pos += len + 4;
        }
        return ret;
    }

    self.client.on('data', function (chunk) {
        splitPacket(chunk).forEach(function (packet) {
            mc = messageCodes['' + packet[0]];
            reply = _merge(reply, self.translator.decode(mc, packet.slice(1)));
            if (!self.task.expectMultiple || reply.done || mc === 'RpbErrorResp') {
                self.task.callback(reply);
                mc = undefined;
                self.task = undefined;
                reply = {};
                self.paused = false;
                self.processNext();
            }
        });
    });

    self.processNext = function () {
        if (self.queue.length && !self.paused) {
            self.paused = true;
            self.connect(function () {
                self.task = self.queue.shift();
                self.client.write(self.task.message);
            });
        }
    };
}

function _merge(obj1, obj2) {
    var obj = {};
    if (obj2.hasOwnProperty('phase')) {
        obj = obj1;
        if (obj[obj2.phase] === undefined) obj[obj2.phase] = [];
        obj[obj2.phase] = obj[obj2.phase].concat(JSON.parse(obj2.response));
    } else {
        [obj1, obj2].forEach(function (old) {
            Object.keys(old).forEach(function (key) {
                if (!old.hasOwnProperty(key)) return;
                if (Array.isArray(old[key])) {
                    if (!obj[key]) obj[key] = [];
                    obj[key] = obj[key].concat(old[key]);
                } else {
                    obj[key] = old[key];
                }
            });
        });
    }
    return obj;
}

RiakPBC.prototype.makeRequest = function (type, data, callback, expectMultiple) {
    var self = this,
        reply = {},
        buffer = this.translator.encode(type, data),
        message = [];

    butils.writeInt32(message, buffer.length + 1);
    butils.writeInt(message, messageCodes[type], 4);
    message = message.concat(buffer);
    self.queue.push({ message: new Buffer(message), callback: callback, expectMultiple: expectMultiple });
    process.nextTick(self.processNext);
};

RiakPBC.prototype.getBuckets = function (callback) {
    this.makeRequest('RpbListBucketsReq', null, callback);
};

RiakPBC.prototype.getBucket = function (params, callback) {
    this.makeRequest('RpbGetBucketReq', params, callback);
};

RiakPBC.prototype.setBucket = function (params, callback) {
    this.makeRequest('RpbSetBucketReq', params, callback);
};

RiakPBC.prototype.getKeys = function (params, callback) {
    this.makeRequest('RpbListKeysReq', params, callback, true);
};

RiakPBC.prototype.put = function (params, callback) {
    this.makeRequest('RpbPutReq', params, callback);
};

RiakPBC.prototype.get = function (params, callback) {
    this.makeRequest('RpbGetReq', params, callback);
};

RiakPBC.prototype.del = function (params, callback) {
    this.makeRequest('RpbDelReq', params, callback);
};

RiakPBC.prototype.mapred = function (params, callback) {
    this.makeRequest('RpbMapRedReq', params, callback, true);
};

RiakPBC.prototype.getIndex = function (params, callback) {
    this.makeRequest('RpbIndexReq', params, callback);
};

RiakPBC.prototype.search = function (params, callback) {
    this.makeRequest('RpbSearchQueryReq', params, callback);
};

RiakPBC.prototype.getClientId = function (callback) {
    this.makeRequest('RpbGetClientIdReq', null, callback);
};

RiakPBC.prototype.setClientId = function (params, callback) {
    this.makeRequest('RpbSetClientIdReq', params, callback);
};

RiakPBC.prototype.getServerInfo = function (callback) {
    this.makeRequest('RpbGetServerInfoReq', null, callback);
};

RiakPBC.prototype.ping = function (callback) {
    this.makeRequest('RpbPingReq', null, callback);
};

RiakPBC.prototype.connect = function (callback) {
    if (this.connected) return callback();
    var self = this;
    self.client.connect(self.port, self.host, function () {
        self.connected = true;
        callback();
    });
};

RiakPBC.prototype.disconnect = function () {
    if (!this.connected) return;
    this.client.end();
    this.connected = false;
    if (this.task) {
        this.queue.unshift(this.task);
        this.task = undefined;
    }
};

exports.createClient = function (options) {
    return new RiakPBC(options);
};
<commit_msg>Allow tasks to be streaming, for mapred and keys.<commit_after>var net = require('net'),
    protobuf = require('protobuf.js'),
    butils = require('butils');

var messageCodes = {
    '0': 'RpbErrorResp',
    '1': 'RpbPingReq',
    '2': 'RpbPingResp',
    '3': 'RpbGetClientIdReq',
    '4': 'RpbGetClientIdResp',
    '5': 'RpbSetClientIdReq',
    '6': 'RpbSetClientIdResp',
    '7': 'RpbGetServerInfoReq',
    '8': 'RpbGetServerInfoResp',
    '9': 'RpbGetReq',
    '10': 'RpbGetResp',
    '11': 'RpbPutReq',
    '12': 'RpbPutResp',
    '13': 'RpbDelReq',
    '14': 'RpbDelResp',
    '15': 'RpbListBucketsReq',
    '16': 'RpbListBucketsResp',
    '17': 'RpbListKeysReq',
    '18': 'RpbListKeysResp',
    '19': 'RpbGetBucketReq',
    '20': 'RpbGetBucketResp',
    '21': 'RpbSetBucketReq',
    '22': 'RpbSetBucketResp',
    '23': 'RpbMapRedReq',
    '24': 'RpbMapRedResp',
    '25': 'RpbIndexReq',
    '26': 'RpbIndexResp',
    '27': 'RpbSearchQueryReq',
    '28': 'RpbSearchQueryResp'
};
Object.keys(messageCodes).forEach(function (key) {
    messageCodes[messageCodes[key]] = Number(key);
});

function RiakPBC(options) {
    var self = this;
    options = options || {};
    self.host = options.host || '127.0.0.1';
    self.port = options.port || 8087;
    self.bucket = options.bucket || undefined;
    self.translator = protobuf.loadSchema('./spec/riak_kv.proto');
    self.client = new net.Socket();
    self.connected = false;
    self.client.on('end', self.disconnect);
    self.client.on('error', self.disconnect);
    self.paused = false;
    self.queue = [];
    var mc, reply = {};

    function splitPacket(pkt) {
        var ret = [], len, pos = 0, end = pkt.length;
        while (pos < end) {
            len = butils.readInt32(pkt, pos);
            ret.push(pkt.slice(pos + 4, pos + len + 4));
            pos += len + 4;
        }
        return ret;
    }

    self.client.on('data', function (chunk) {
        splitPacket(chunk).forEach(function (packet) {
            mc = messageCodes['' + packet[0]];

            if (self.task.streaming && !reply.done) {
                self.task.callback(reply);
                return;
            }

            reply = _merge(reply, self.translator.decode(mc, packet.slice(1)));
            if (!self.task.expectMultiple || reply.done || mc === 'RpbErrorResp') {
                self.task.callback(reply);
                mc = undefined;
                self.task = undefined;
                reply = {};
                self.paused = false;
                self.processNext();
            }
        });
    });

    self.processNext = function () {
        if (self.queue.length && !self.paused) {
            self.paused = true;
            self.connect(function () {
                self.task = self.queue.shift();
                self.client.write(self.task.message);
            });
        }
    };
}

function _merge(obj1, obj2) {
    var obj = {};
    if (obj2.hasOwnProperty('phase')) {
        obj = obj1;
        if (obj[obj2.phase] === undefined) obj[obj2.phase] = [];
        obj[obj2.phase] = obj[obj2.phase].concat(JSON.parse(obj2.response));
    } else {
        [obj1, obj2].forEach(function (old) {
            Object.keys(old).forEach(function (key) {
                if (!old.hasOwnProperty(key)) return;
                if (Array.isArray(old[key])) {
                    if (!obj[key]) obj[key] = [];
                    obj[key] = obj[key].concat(old[key]);
                } else {
                    obj[key] = old[key];
                }
            });
        });
    }
    return obj;
}

RiakPBC.prototype.makeRequest = function (type, data, callback, expectMultiple, streaming) {
    var self = this,
        reply = {},
        buffer = this.translator.encode(type, data),
        message = [];

    butils.writeInt32(message, buffer.length + 1);
    butils.writeInt(message, messageCodes[type], 4);
    message = message.concat(buffer);
    self.queue.push({ message: new Buffer(message), callback: callback, expectMultiple: expectMultiple, streaming: streaming });
    process.nextTick(self.processNext);
};

RiakPBC.prototype.getBuckets = function (callback) {
    this.makeRequest('RpbListBucketsReq', null, callback);
};

RiakPBC.prototype.getBucket = function (params, callback) {
    this.makeRequest('RpbGetBucketReq', params, callback);
};

RiakPBC.prototype.setBucket = function (params, callback) {
    this.makeRequest('RpbSetBucketReq', params, callback);
};

RiakPBC.prototype.getKeys = function (params, callback, streaming) {
    this.makeRequest('RpbListKeysReq', params, callback, true, streaming;
};

RiakPBC.prototype.put = function (params, callback) {
    this.makeRequest('RpbPutReq', params, callback);
};

RiakPBC.prototype.get = function (params, callback) {
    this.makeRequest('RpbGetReq', params, callback);
};

RiakPBC.prototype.del = function (params, callback) {
    this.makeRequest('RpbDelReq', params, callback);
};

RiakPBC.prototype.mapred = function (params, callback, streaming) {
    this.makeRequest('RpbMapRedReq', params, callback, true, streaming);
};

RiakPBC.prototype.getIndex = function (params, callback) {
    this.makeRequest('RpbIndexReq', params, callback);
};

RiakPBC.prototype.search = function (params, callback) {
    this.makeRequest('RpbSearchQueryReq', params, callback);
};

RiakPBC.prototype.getClientId = function (callback) {
    this.makeRequest('RpbGetClientIdReq', null, callback);
};

RiakPBC.prototype.setClientId = function (params, callback) {
    this.makeRequest('RpbSetClientIdReq', params, callback);
};

RiakPBC.prototype.getServerInfo = function (callback) {
    this.makeRequest('RpbGetServerInfoReq', null, callback);
};

RiakPBC.prototype.ping = function (callback) {
    this.makeRequest('RpbPingReq', null, callback);
};

RiakPBC.prototype.connect = function (callback) {
    if (this.connected) return callback();
    var self = this;
    self.client.connect(self.port, self.host, function () {
        self.connected = true;
        callback();
    });
};

RiakPBC.prototype.disconnect = function () {
    if (!this.connected) return;
    this.client.end();
    this.connected = false;
    if (this.task) {
        this.queue.unshift(this.task);
        this.task = undefined;
    }
};

exports.createClient = function (options) {
    return new RiakPBC(options);
};
<|endoftext|>


<commit_before>var concat = require('concat-stream')

var get_dependencies = require('./lib/get-dependencies')
  , get_description = require('./lib/get-description')

module.exports = setup

function setup(unpm) {
  var dependents = {}

  unpm.backend.createMetaStream().pipe(concat(build_initial))
  unpm.router.add('get', '/-/_view/dependedUpon', serve_dependents)

  function build_initial(data) {
    var deps = {}

    var module_deps
      , current
      , module
      , dep

    for(var i = 0, l = data.length; i < l; ++i) {
      module = data[i]
      module_deps = get_dependencies(module)

      for(var j = 0, k = module_deps.length; j < k; ++j) {
        dep = module_deps[j]
        deps[dep] = deps[dep] || []
        deps[dep].push({
            name: module.key
          , description: get_description(module)
        })
      }
    }

    unpm.backend.set('unpm-dependents', deps)
    unpm.backend.on('setMeta', update_deps)

    function update_deps(name, data, old_data) {
      var old_deps = get_dependencies(old_data)
        , new_deps = get_dependencies(data)

      for(var i = 0, l = old_deps.length; i < l; ++i) {
        if(new_deps.indexOf(old_deps[i]) === -1) {
          if(!deps[old_deps[i]]) continue
          deps[old_deps[i]].splice(deps[old_deps[i]].indexOf(name), 1)
        }
      }

      for(var i = 0, l = new_deps.length; i < l; ++i) {
        deps[new_deps[i]] = deps[new_deps[i]] || []
        if(deps[new_deps[i]].indexOf(name) === -1) {
          deps[new_deps[i]].push(name)
        }
      }

      unpm.backend.set('unpm-dependents', deps)
    }
  }

  function serve_dependents(context, route, respond) {
    var start = route.query.startkey
      , module

    // to mirror official npm query of `["modulename"]`
    module = start.slice(2, -2)

    if(!module) return respond.not_found()

    unpm.backend.get('unpm-dependents', serve_deps)

    function serve_deps(err, data) {
      if(err || !data || !data[module]) return respond.not_found()

      respond(null, 200, {rows: data[module].map(to_output)})
    }

    function to_output(el) {
      return {key: [module, el.name, el.description], value: 1}
    }
  }
}

<commit_msg>remove unnecessary newline<commit_after>var concat = require('concat-stream')

var get_dependencies = require('./lib/get-dependencies')
  , get_description = require('./lib/get-description')

module.exports = setup

function setup(unpm) {
  var dependents = {}

  unpm.backend.createMetaStream().pipe(concat(build_initial))
  unpm.router.add('get', '/-/_view/dependedUpon', serve_dependents)

  function build_initial(data) {
    var deps = {}

    var module_deps
      , current
      , module
      , dep

    for(var i = 0, l = data.length; i < l; ++i) {
      module = data[i]
      module_deps = get_dependencies(module)

      for(var j = 0, k = module_deps.length; j < k; ++j) {
        dep = module_deps[j]
        deps[dep] = deps[dep] || []
        deps[dep].push({
            name: module.key
          , description: get_description(module)
        })
      }
    }

    unpm.backend.set('unpm-dependents', deps)
    unpm.backend.on('setMeta', update_deps)

    function update_deps(name, data, old_data) {
      var old_deps = get_dependencies(old_data)
        , new_deps = get_dependencies(data)

      for(var i = 0, l = old_deps.length; i < l; ++i) {
        if(new_deps.indexOf(old_deps[i]) === -1) {
          if(!deps[old_deps[i]]) continue
          deps[old_deps[i]].splice(deps[old_deps[i]].indexOf(name), 1)
        }
      }

      for(var i = 0, l = new_deps.length; i < l; ++i) {
        deps[new_deps[i]] = deps[new_deps[i]] || []
        if(deps[new_deps[i]].indexOf(name) === -1) {
          deps[new_deps[i]].push(name)
        }
      }

      unpm.backend.set('unpm-dependents', deps)
    }
  }

  function serve_dependents(context, route, respond) {
    var start = route.query.startkey
      , module

    // to mirror official npm query of `["modulename"]`
    module = start.slice(2, -2)

    if(!module) return respond.not_found()

    unpm.backend.get('unpm-dependents', serve_deps)

    function serve_deps(err, data) {
      if(err || !data || !data[module]) return respond.not_found()

      respond(null, 200, {rows: data[module].map(to_output)})
    }

    function to_output(el) {
      return {key: [module, el.name, el.description], value: 1}
    }
  }
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Matteo Collina <hello@matteocollina.com>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

'use strict';

var Duplex    = require('readable-stream').Duplex
  , Writable  = require('readable-stream').Writable
  , inherits  = require('inherits')

function ReaDuplexer(writable, readable, options) {
  if (!(this instanceof ReaDuplexer))
    return new ReaDuplexer(writable, readable, options)

  this._options   = options

  Duplex.call(this, options)

  this.hook(writable, readable)

  this.on('finish', function() {
    if (this._writable)
      this._writable.end()
  })

  this._lastReadCallback = null
}

inherits(ReaDuplexer, Duplex)

function callWrite2Args(chunk, enc, cb) {
  this._writable.write(chunk, enc)
  cb()
  return true
}

function callWrite3Args(chunk, enc, cb) {
  return this._writable.write(chunk, enc, cb)
}

ReaDuplexer.prototype.hookWritable = function hookWritable(writable) {
  var that = this

  if (this._writable)
    throw new Error('already hooked to a Writable')

  if (!writable)
    throw new Error('missing writable')

  this._writable = writable

  writable.on('drain', function() {
    that.emit('drain')
  })

  writable.on('error', function(err) {
    that.emit('error', err)
  })

  if (this._writable.write.length === 3) {
    this._callWrite = callWrite3Args
  } else {
    this._callWrite = callWrite2Args
  }

  if (this._firstPayload) {
    this._callWrite(
      this._firstPayload.chunk
    , this._firstPayload.enc
    , this._firstPayload.cb)

    delete this._firstPayload
  }

  return this
}

ReaDuplexer.prototype.hookReadable = function hookReadable(readable) {
  var that          = this
    , dummyWritable = new Writable(this._options)

  if (this._readable)
    throw new Error('already hooked to a Readable')

  if (!readable)
    throw new Error('missing readable')

  this._readable  = readable

  dummyWritable._write = function dummyWrite(chunk, enc, cb) {
    if (that.push(chunk, enc))
      cb()
    else
      that._lastReadCallback = cb
  }

  dummyWritable.on('finish', function() {
    that.push(null)
  })

  ;[readable, dummyWritable].forEach(function(stream) {
    stream.on('error', function(err) {
      that.emit('error', err)
    })
  })

  readable.pipe(dummyWritable)

  return this
}

ReaDuplexer.prototype.hook = function hook(writable, readable) {
  if (writable)
    this.hookWritable(writable)

  if (readable)
    this.hookReadable(readable)

  return this
}

ReaDuplexer.prototype._read = function read(n) {
  if (this._lastReadCallback)
    this._lastReadCallback()

  this._lastReadCallback = null
}

ReaDuplexer.prototype._callWrite = function nop() {
  throw new Error('hook Writable to use')
}

ReaDuplexer.prototype._write = function write(chunk, enc, cb) {
  if (this._writable)
    this._callWrite(chunk, enc, cb)

  // we are in delayed open
  this._firstPayload = {
      chunk: chunk
    , enc: enc
    , cb: cb
  }
}

module.exports = ReaDuplexer
<commit_msg>Stop enqueuing after hookWritable.<commit_after>/*
Copyright (c) 2014, Matteo Collina <hello@matteocollina.com>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

'use strict';

var Duplex    = require('readable-stream').Duplex
  , Writable  = require('readable-stream').Writable
  , inherits  = require('inherits')

function ReaDuplexer(writable, readable, options) {
  if (!(this instanceof ReaDuplexer))
    return new ReaDuplexer(writable, readable, options)

  this._options   = options

  Duplex.call(this, options)

  this.hook(writable, readable)

  this.on('finish', function() {
    if (this._writable)
      this._writable.end()
  })

  this._lastReadCallback = null
}

inherits(ReaDuplexer, Duplex)

function callWrite2Args(chunk, enc, cb) {
  this._writable.write(chunk, enc)
  cb()
  return true
}

function callWrite3Args(chunk, enc, cb) {
  return this._writable.write(chunk, enc, cb)
}

ReaDuplexer.prototype.hookWritable = function hookWritable(writable) {
  var that = this

  if (this._writable)
    throw new Error('already hooked to a Writable')

  if (!writable)
    throw new Error('missing writable')

  this._writable = writable

  writable.on('drain', function() {
    that.emit('drain')
  })

  writable.on('error', function(err) {
    that.emit('error', err)
  })

  if (this._writable.write.length === 3) {
    this._callWrite = callWrite3Args
  } else {
    this._callWrite = callWrite2Args
  }

  if (this._firstPayload) {
    this._callWrite(
      this._firstPayload.chunk
    , this._firstPayload.enc
    , this._firstPayload.cb)

    delete this._firstPayload
  }

  return this
}

ReaDuplexer.prototype.hookReadable = function hookReadable(readable) {
  var that          = this
    , dummyWritable = new Writable(this._options)

  if (this._readable)
    throw new Error('already hooked to a Readable')

  if (!readable)
    throw new Error('missing readable')

  this._readable  = readable

  dummyWritable._write = function dummyWrite(chunk, enc, cb) {
    if (that.push(chunk, enc))
      cb()
    else
      that._lastReadCallback = cb
  }

  dummyWritable.on('finish', function() {
    that.push(null)
  })

  ;[readable, dummyWritable].forEach(function(stream) {
    stream.on('error', function(err) {
      that.emit('error', err)
    })
  })

  readable.pipe(dummyWritable)

  return this
}

ReaDuplexer.prototype.hook = function hook(writable, readable) {
  if (writable)
    this.hookWritable(writable)

  if (readable)
    this.hookReadable(readable)

  return this
}

ReaDuplexer.prototype._read = function read(n) {
  if (this._lastReadCallback)
    this._lastReadCallback()

  this._lastReadCallback = null
}

ReaDuplexer.prototype._callWrite = function nop() {
  throw new Error('hook Writable to use')
}

ReaDuplexer.prototype._write = function write(chunk, enc, cb) {
  if (this._writable)
    return this._callWrite(chunk, enc, cb)

  // we are in delayed open
  this._firstPayload = {
      chunk: chunk
    , enc: enc
    , cb: cb
  }
}

module.exports = ReaDuplexer
<|endoftext|>


<commit_before>'use strict';
//a version from scratch built using Actions on Google Client Library

process.env.DEBUG = 'actions-on-google:*';
const ApiAiApp = require('actions-on-google').ApiAiApp;
const https = require('https');
const http = require('http');

// API.AI actions
const UNRECOGNIZED_DEEP_LINK = 'deeplink.unknown';
const FETCH_INFO = 'fetch.info';

// API.AI parameter names
const CATEGORY_ARGUMENT = 'category';

// API.AI Contexts/lifespans
const SOLAR = 'solar';
const INFORMATION_GIVEN = 'information-given';
const DEFAULT_LIFESPAN = 5;
const END_LIFESPAN = 0;

const PVoutputParameter = {
  // consider adding more like 'peak'
  POWER: 'power',
  ENERGY: 'energy',
  EFFICIENCY: 'efficiency'
};

const LINK_OUT_TEXT = 'Learn more';
const PVOUTPUT_LINK = 'https://pvoutput.org/';
const NEXT_INFO_DIRECTIVE = 'Would you like to know anything else?';
const CONFIRMATION_SUGGESTIONS = ['Sure', 'No thanks'];

const NO_INPUTS = [
  'I didn\'t hear that.',
  'If you\'re still there, say that again.',
  'We can stop here. See you soon.'
];

exports.PVoutputFullfilment = (request, response) => {
  const app = new ApiAiApp({ request, response });

  //let requestHeader = JSON.stringify(request.headers);
  //console.log('Request headers: ' + requestHeader);
  //let requestBody = JSON.stringify(request.body);
  //console.log('Request body: ' + requestBody);

  function unrecognised (app) {

  }

  function handler (app){

    function fetchInfo (app, service, d="", t="", df="", dt="" ){
      var PVdict = {"date":"","time":"","energy":"","power":"","efficiency":""};
      var PVmessagesDict = {};
      https.get('https://pvoutput.org/service/r2/'+service+'.jsp?sid='+request.body.result.parameters.SID.SID+'&key='+request.body.result.parameters.readOnlyAPIKey, function(PVres){
        PVres.setEncoding('utf8');
        PVres.on('data', function(chunk) {
          let PVoutput = chunk.split(',');
          PVdict.date = PVoutput[0];
          PVdict.time = PVoutput[1];
          PVdict.energy = (PVoutput[2]/1000).toString();
          PVdict.power = (PVoutput[3]/1000).toString();
          PVdict.efficiency = (PVoutput[6]*100).toString();

          PVmessagesDict = {
              "":"I am sorry please ask again but specify if you want information about power, energy or efficiency. ",
              "date":"",
              "time":"",
              "energy": PVdict.energy + " kilowatt hours have been produced so far today. ",
              "power":"The current power output is " + PVdict.power + " kilowatts. ",
              "efficiency":"The solar array is currently outputting at  " + PVdict.efficiency + " percent of capacity. "};

          //makes dataIntent equal to the parameters made but removes duplicates
          let dataIntent = [...new Set(request.body.result.parameters.PVoutputParameter)];

          var speech = "";
          for (var i = 0; i < dataIntent.length; i++) {
              speech += PVmessagesDict[dataIntent[i]];
          }
          app.ask(speech);
        });
      });
    }

    switch (request.body.result.parameters.time.length) {
      case 0:
        fetchInfo(app, 'getstatus')
        break;
      default:

  }

  }
  let actionMap = new Map();
  actionMap.set(UNRECOGNIZED_DEEP_LINK, unrecognised);
  actionMap.set(FETCH_INFO, handler);

  app.handleRequest(actionMap);

};
<commit_msg>expands switch<commit_after>'use strict';
//a version from scratch built using Actions on Google Client Library

process.env.DEBUG = 'actions-on-google:*';
const ApiAiApp = require('actions-on-google').ApiAiApp;
const https = require('https');
const http = require('http');

// API.AI actions
const UNRECOGNIZED_DEEP_LINK = 'deeplink.unknown';
const FETCH_INFO = 'fetch.info';

// API.AI parameter names
const CATEGORY_ARGUMENT = 'category';

// API.AI Contexts/lifespans
const SOLAR = 'solar';
const INFORMATION_GIVEN = 'information-given';
const DEFAULT_LIFESPAN = 5;
const END_LIFESPAN = 0;

const PVoutputParameter = {
  // consider adding more like 'peak'
  POWER: 'power',
  ENERGY: 'energy',
  EFFICIENCY: 'efficiency'
};

const LINK_OUT_TEXT = 'Learn more';
const PVOUTPUT_LINK = 'https://pvoutput.org/';
const NEXT_INFO_DIRECTIVE = 'Would you like to know anything else?';
const CONFIRMATION_SUGGESTIONS = ['Sure', 'No thanks'];

const NO_INPUTS = [
  'I didn\'t hear that.',
  'If you\'re still there, say that again.',
  'We can stop here. See you soon.'
];

exports.PVoutputFullfilment = (request, response) => {
  const app = new ApiAiApp({ request, response });

  //let requestHeader = JSON.stringify(request.headers);
  //console.log('Request headers: ' + requestHeader);
  //let requestBody = JSON.stringify(request.body);
  //console.log('Request body: ' + requestBody);

  function unrecognised (app) {

  }

  function handler (app){

    function fetchInfo (app, service, d="", t="", df="", dt="" ){
      var PVdict = {"date":"","time":"","energy":"","power":"","efficiency":""};
      var PVmessagesDict = {};
      https.get('https://pvoutput.org/service/r2/'+service+'.jsp?sid='+request.body.result.parameters.SID.SID+'&key='+request.body.result.parameters.readOnlyAPIKey, function(PVres){
        PVres.setEncoding('utf8');
        PVres.on('data', function(chunk) {
          let PVoutput = chunk.split(',');
          PVdict.date = PVoutput[0];
          PVdict.time = PVoutput[1];
          PVdict.energy = (PVoutput[2]/1000).toString();
          PVdict.power = (PVoutput[3]/1000).toString();
          PVdict.efficiency = (PVoutput[6]*100).toString();

          PVmessagesDict = {
              "":"I am sorry please ask again but specify if you want information about power, energy or efficiency. ",
              "date":"",
              "time":"",
              "energy": PVdict.energy + " kilowatt hours have been produced so far today. ",
              "power":"The current power output is " + PVdict.power + " kilowatts. ",
              "efficiency":"The solar array is currently outputting at  " + PVdict.efficiency + " percent of capacity. "};

          //makes dataIntent equal to the parameters made but removes duplicates
          let dataIntent = [...new Set(request.body.result.parameters.PVoutputParameter)];

          var speech = "";
          for (var i = 0; i < dataIntent.length; i++) {
              speech += PVmessagesDict[dataIntent[i]];
          }
          app.ask(speech);
        });
      });
    }

    switch (request.body.result.parameters.time.length) {
      case 0:
        fetchInfo(app, 'getstatus');
        break;
      case 8:

        break;
      case 10:

        break;
      case 17:

        break;
      case 20:

        break;
      case 21:

        break;
      case 41:

        break;
      default:
        fetchInfo(app, 'getstatus');
        break;

  }

  }
  let actionMap = new Map();
  actionMap.set(UNRECOGNIZED_DEEP_LINK, unrecognised);
  actionMap.set(FETCH_INFO, handler);

  app.handleRequest(actionMap);

};
<|endoftext|>