<commit_before>(function () {

  const app = angular.module('app');

  app.controller('TaskListsController', function ($scope,
    TaskListsService,
    TaskListWithTasksFactory,
    $rootScope) {

    const listFeature = $rootScope.appData.flags.find(function(elem) {
      return elem.name == 'list';
    });

    $scope.featureEnabled = {}
    $scope.featureEnabled.list = listFeature && listFeature.value === 'enabled'

    $scope.formData = {};

    $scope.pageFns = {};

    var refreshTaskLists = function () {
      TaskListsService.readAll().then(function (response) {
        const data = response.data;
        if (data) {
          const taskListsWithTasks = TaskListWithTasksFactory.buildFromJsonCollection(data);
          $scope.pageData.taskListWithTasks = taskListsWithTasks
        }
      }, function () {});
    }

    $scope.pageFns.createTaskList = function () {
      TaskListsService.create($scope.formData.name).then(function (response) {
        if (response.data) {
          refreshTaskLists();
          $scope.formData.name = '';
        }
      }, function () {});
    }

    $scope.pageFns.syncList = function (list) {
      TaskListsService.read(list.listId).then(function (response) {
        const data = response.data;
        if (data) {
          TaskListWithTasksFactory.updateFromJson(list, data);
        }
      }, function () {});
    }

    $scope.pageData = {};
    $scope.pageData.taskListWithTasks = [];

    refreshTaskLists();

    // TODO consider refactoring this as this is moved to a directive
    $scope.pageFns.undoDeleteTaskList = function (list) {
      // TODO for now, will only focus on deleting and undeleting
      //      a task list
      //      won't touch tasks
      //      because that branches the undo here to two possibilities:
      //        1. undelete that taskList + bulk undelete all associated tasks
      //        2. only undelete the taskList
      TaskListsService.update(list.listId, {name: list.listName, isDeleted: false})
        .then(function (response) {
          const data = response.data;
          if (data) {
            TaskListWithTasksFactory.updateFromJson(list, data);
          }
        }, {})
    }
  });

})();
<commit_msg>fixed a bug I hope (#335)<commit_after>(function () {

  const app = angular.module('app');

  app.controller('TaskListsController', function ($scope,
    TaskListsService,
    TaskListWithTasksFactory,
    $rootScope) {

    const listFeature = $rootScope.appData.flags.find(function(elem) {
      return elem.name == 'list';
    });

    $scope.featureEnabled = {}
    $scope.featureEnabled.list = listFeature && listFeature.value === 'enabled'

    $scope.formData = {};

    $scope.pageFns = {};

    var refreshTaskLists = function () {
      TaskListsService.readAll().then(function (response) {
        const data = response.data;
        if (data) {
          const taskListsWithTasks = TaskListWithTasksFactory.buildFromJsonCollection(data);
          $scope.pageData.taskListWithTasks = taskListsWithTasks
        }
      }, function () {});
    }

    $scope.pageFns.createTaskList = function () {
      TaskListsService.create($scope.formData.name).then(function (response) {
        const data = response.data;
        if (data) {
          // add the new taskList
          const taskListWithTasks = TaskListWithTasksFactory.buildFromJsonCollection(data);
          $scope.pageData.taskListWithTasks.push(taskListWithTasks);

          // reset the form
          $scope.formData.name = '';
        }
      }, function () {});
    }

    $scope.pageFns.syncList = function (list) {
      TaskListsService.read(list.listId).then(function (response) {
        const data = response.data;
        if (data) {
          TaskListWithTasksFactory.updateFromJson(list, data);
        }
      }, function () {});
    }

    $scope.pageData = {};
    $scope.pageData.taskListWithTasks = [];

    refreshTaskLists();

    // TODO consider refactoring this as this is moved to a directive
    $scope.pageFns.undoDeleteTaskList = function (list) {
      // TODO for now, will only focus on deleting and undeleting
      //      a task list
      //      won't touch tasks
      //      because that branches the undo here to two possibilities:
      //        1. undelete that taskList + bulk undelete all associated tasks
      //        2. only undelete the taskList
      TaskListsService.update(list.listId, {name: list.listName, isDeleted: false})
        .then(function (response) {
          const data = response.data;
          if (data) {
            TaskListWithTasksFactory.updateFromJson(list, data);
          }
        }, {})
    }
  });

})();
<|endoftext|>


<commit_before>'use strict'

var test = require('tape').test
var persistence = require('./')
var Redis = require('ioredis')
var mqemitterRedis = require('mqemitter-redis')
var abs = require('aedes-cached-persistence/abstract')
var db = new Redis()

db.on('connect', unref)

function unref () {
  this.connector.stream.unref()
}

abs({
  test: test,
  buildEmitter: function () {
    var emitter = mqemitterRedis()

    emitter.subConn.on('connect', unref)
    emitter.pubConn.on('connect', unref)

    return emitter
  },
  persistence: function () {
    db.flushall()
    return persistence()
  },
  waitForReady: true
})

function toBroker (id, emitter) {
  return {
    id: id,
    publish: emitter.emit.bind(emitter),
    subscribe: emitter.on.bind(emitter),
    unsubscribe: emitter.removeListener.bind(emitter)
  }
}

test('multiple persistences', function (t) {
  t.plan(7)
  db.flushall()
  var emitter = mqemitterRedis()
  var emitter2 = mqemitterRedis()
  var instance = persistence()
  var instance2 = persistence()
  instance.broker = toBroker('1', emitter)
  instance2.broker = toBroker('2', emitter2)

  var client = { id: 'multipleTest' }
  var subs = [{
    topic: 'hello',
    qos: 1
  }, {
    topic: 'hello/#',
    qos: 1
  }, {
    topic: 'matteo',
    qos: 1
  }]

  instance2._waitFor(client, 'sub', function () {
    instance2.subscriptionsByTopic('hello', function (err, resubs) {
      t.notOk(err, 'no error')
      t.deepEqual(resubs, [{
        clientId: client.id,
        topic: 'hello/#',
        qos: 1
      }, {
        clientId: client.id,
        topic: 'hello',
        qos: 1
      }])
      instance.destroy(t.pass.bind(t, 'first dies'))
      instance2.destroy(t.pass.bind(t, 'second dies'))
      emitter.close(t.pass.bind(t, 'first emitter dies'))
      emitter2.close(t.pass.bind(t, 'second emitter dies'))
    })
  })

  var ready = false
  var ready2 = false

  function check () {
    if (ready && ready2) {
      instance.addSubscriptions(client, subs, function (err) {
        t.notOk(err, 'no error')
      })
    }
  }

  instance.on('ready', function () {
    ready = true
    check()
  })

  instance2.on('ready', function () {
    ready2 = true
    check()
  })
})
<commit_msg>Disambiguate error message<commit_after>'use strict'

var test = require('tape').test
var persistence = require('./')
var Redis = require('ioredis')
var mqemitterRedis = require('mqemitter-redis')
var abs = require('aedes-cached-persistence/abstract')
var db = new Redis()

db.on('connect', unref)

function unref () {
  this.connector.stream.unref()
}

abs({
  test: test,
  buildEmitter: function () {
    var emitter = mqemitterRedis()

    emitter.subConn.on('connect', unref)
    emitter.pubConn.on('connect', unref)

    return emitter
  },
  persistence: function () {
    db.flushall()
    return persistence()
  },
  waitForReady: true
})

function toBroker (id, emitter) {
  return {
    id: id,
    publish: emitter.emit.bind(emitter),
    subscribe: emitter.on.bind(emitter),
    unsubscribe: emitter.removeListener.bind(emitter)
  }
}

test('multiple persistences', function (t) {
  t.plan(7)
  db.flushall()
  var emitter = mqemitterRedis()
  var emitter2 = mqemitterRedis()
  var instance = persistence()
  var instance2 = persistence()
  instance.broker = toBroker('1', emitter)
  instance2.broker = toBroker('2', emitter2)

  var client = { id: 'multipleTest' }
  var subs = [{
    topic: 'hello',
    qos: 1
  }, {
    topic: 'hello/#',
    qos: 1
  }, {
    topic: 'matteo',
    qos: 1
  }]

  instance2._waitFor(client, 'sub', function () {
    instance2.subscriptionsByTopic('hello', function (err, resubs) {
      t.notOk(err, 'subs by topic no error')
      t.deepEqual(resubs, [{
        clientId: client.id,
        topic: 'hello/#',
        qos: 1
      }, {
        clientId: client.id,
        topic: 'hello',
        qos: 1
      }])
      instance.destroy(t.pass.bind(t, 'first dies'))
      instance2.destroy(t.pass.bind(t, 'second dies'))
      emitter.close(t.pass.bind(t, 'first emitter dies'))
      emitter2.close(t.pass.bind(t, 'second emitter dies'))
    })
  })

  var ready = false
  var ready2 = false

  function check () {
    if (ready && ready2) {
      instance.addSubscriptions(client, subs, function (err) {
        t.notOk(err, 'add subs no error')
      })
    }
  }

  instance.on('ready', function () {
    ready = true
    check()
  })

  instance2.on('ready', function () {
    ready2 = true
    check()
  })
})
<|endoftext|>


<commit_before>'use strict';

var server = require('nachos-server-api');
var packages = require('nachos-packages');
var path = require('path');
var fs = require('fs');
var exec = require('child_process').exec;
var rimraf = require('rimraf');
var Q = require('q');
var debug = require('debug')('nachosPackageManager:install');
var mkdirp = require('mkdirp');
var os = require('os');
var zlib = require('zlib');
var tarFs = require('tar-fs');

/**
 * Build an installer
 *
 * @param {string} command Command to execute
 * @param {string} filePath Full path to file to read install info from
 * @private
 */
var _buildInstaller = function (command, filePath) {
  return Q.nfcall(fs.access, filePath)
    .then(function () {
      debug('running %s', command);

      return Q.nfcall(exec, command, {cwd: path.dirname(filePath)});
    }, function () {
      debug('no %s', path.basename(filePath));

      return Q.resolve();
    });
};

/**
 * Install a package
 *
 * @param {string} packageName package name to install
 * @returns {Q.promise} Destination directory
 */
module.exports = function (packageName) {
  if (!packageName) {
    return Q.reject(new TypeError('nachos-package-manager install: Package name must be provided'));
  }

  var client = server();
  var tmpDir = path.join(os.tmpDir(), packageName + '-tmp-download-' + Date.now());
  var tgzPath = path.join(tmpDir, packageName + '.tgz');

  return client.packages.byName({}, {package: packageName})
    .then(function (data) {
      debug('package details: %j', data);

      return packages.getFolderByType(data.type)
        .then(function (folderPath) {
          data.dest = path.join(folderPath, data.name);
          debug('destination path: %s', data.dest);

          return data;
        });
    })
    .then(function (data) {
      debug('Deleting existing package in %s', data.dest);

      return Q.nfcall(rimraf, data.dest)
        .then(function () {
          debug('Package deleted');

          return data;
        });
    })
    .then(function (data) {
      debug('Creating folder %s', tmpDir);

      return Q.nfcall(mkdirp, tmpDir)
        .then(function () {
          return data;
        });
    })
    .then(function (data) {
      debug('tgz path: %s', tgzPath);

      var file = fs.createWriteStream(tgzPath);

      debug('Downloading %s from server', packageName);

      return client.packages.download({}, {package: packageName})
        .then(function (tarball) {
          var deferred = Q.defer();

          tarball.pipe(file)
            .on('error', function (err) {
              deferred.reject(err);
            }).on('finish', function () {
              deferred.resolve(data);
            });

          return deferred.promise;
        });
    })
    .then(function (data) {
      var deferred = Q.defer();

      debug('Extracting tarball to %s', data.dest);

      fs.createReadStream(tgzPath)
        .pipe(zlib.Unzip())
        .pipe(tarFs.extract(data.dest))
        .on('finish', function () {
          deferred.resolve(data);
        })
        .on('error', function (err) {
          console.log('error: ', err);
        });

      return deferred.promise;
    })
    .then(function (data) {
      var dir = data.type === 'dip' || data.type === 'burrito' ? data.dest : path.join(data.dest, 'resources', 'app');

      debug('Executing npm install and bower install in %s', dir);

      return Q.all([
        _buildInstaller('npm install --production', path.join(dir, 'package.json'))
      ])
        .then(function () {
          return data.dest;
        });
    })
    .finally(function () {
      debug('Deleting temp directory %s', tmpDir);
      Q.nfcall(rimraf, tmpDir)
        .then(function () {
          debug('Temp directory %s deleted', tmpDir);
        });
    });
};<commit_msg>Npm install both on root and in root/resources/app<commit_after>'use strict';

var server = require('nachos-server-api');
var packages = require('nachos-packages');
var path = require('path');
var fs = require('fs');
var exec = require('child_process').exec;
var rimraf = require('rimraf');
var Q = require('q');
var debug = require('debug')('nachosPackageManager:install');
var mkdirp = require('mkdirp');
var os = require('os');
var zlib = require('zlib');
var tarFs = require('tar-fs');
var _ = require('lodash');

/**
 * Build an installer
 *
 * @param {string} command Command to execute
 * @param {string} filePath Full path to file to read install info from
 * @private
 */
var _buildInstaller = function (command, filePath) {
  return Q.nfcall(fs.access, filePath)
    .then(function () {
      debug('running %s', command);

      return Q.nfcall(exec, command, {cwd: path.dirname(filePath)});
    }, function () {
      debug('no %s', path.basename(filePath));

      return Q.resolve();
    });
};

/**
 * Install a package
 *
 * @param {string} packageName package name to install
 * @returns {Q.promise} Destination directory
 */
module.exports = function (packageName) {
  if (!packageName) {
    return Q.reject(new TypeError('nachos-package-manager install: Package name must be provided'));
  }

  var client = server();
  var tmpDir = path.join(os.tmpDir(), packageName + '-tmp-download-' + Date.now());
  var tgzPath = path.join(tmpDir, packageName + '.tgz');

  return client.packages.byName({}, {package: packageName})
    .then(function (data) {
      debug('package details: %j', data);

      return packages.getFolderByType(data.type)
        .then(function (folderPath) {
          data.dest = path.join(folderPath, data.name);
          debug('destination path: %s', data.dest);

          return data;
        });
    })
    .then(function (data) {
      debug('Deleting existing package in %s', data.dest);

      return Q.nfcall(rimraf, data.dest)
        .then(function () {
          debug('Package deleted');

          return data;
        });
    })
    .then(function (data) {
      debug('Creating folder %s', tmpDir);

      return Q.nfcall(mkdirp, tmpDir)
        .then(function () {
          return data;
        });
    })
    .then(function (data) {
      debug('tgz path: %s', tgzPath);

      var file = fs.createWriteStream(tgzPath);

      debug('Downloading %s from server', packageName);

      return client.packages.download({}, {package: packageName})
        .then(function (tarball) {
          var deferred = Q.defer();

          tarball.pipe(file)
            .on('error', function (err) {
              deferred.reject(err);
            }).on('finish', function () {
              deferred.resolve(data);
            });

          return deferred.promise;
        });
    })
    .then(function (data) {
      var deferred = Q.defer();

      debug('Extracting tarball to %s', data.dest);

      fs.createReadStream(tgzPath)
        .pipe(zlib.Unzip())
        .pipe(tarFs.extract(data.dest))
        .on('finish', function () {
          deferred.resolve(data);
        })
        .on('error', function (err) {
          console.log('error: ', err);
        });

      return deferred.promise;
    })
    .then(function (data) {
      return Q.all(
        _.map([data.dest, path.join(data.dest, 'resources', 'app')], function (dir) {
          debug('Executing npm install in %s', dir);

          return _buildInstaller('npm install --production', path.join(dir, 'package.json'));
        }))
        .then(function () {
          return data.dest;
        });
    })
    .finally(function () {
      debug('Deleting temp directory %s', tmpDir);
      Q.nfcall(rimraf, tmpDir)
        .then(function () {
          debug('Temp directory %s deleted', tmpDir);
        });
    });
};<|endoftext|>


<commit_before>'use strict';

const Command = require('ember-cli/lib/models/command'),
      childProcess = require('child_process'),
      options = require('../utils/publish-options'),
      publisher = require('electron-simple-publisher/lib/publisher'),
      path = require('path'),
      fs = require('fs');

module.exports = Command.extend({
  name: 'khartis:release',
  description: 'Publish khartis electron release',
  availableOptions: options,
  run: function(options) {
    return new Promise((res, rej) => {
      process.on('SIGINT', function() {
        rej();
        process.exit();
      });
      if (!(options.make === false || options.make === "false")) {
        let buildPipeline = [];
        if (!(options.skipbuild === "true" || options.skipbuild === true)) {
          buildPipeline.push('ember electron:build --output-path electron-out/ember');
        }
        if (!(options.skipassemble === "true" || options.skipassemble === true)) {
          buildPipeline.push('ember electron:assemble --build-path electron-out/ember --output-path electron-out/project');
        }
        if (!(options.skippackage === "true" || options.skippackage === true)) {
          buildPipeline.push('ember electron:package --project-path electron-out/project --platform=darwin,win32,linux');
        }
        buildPipeline = buildPipeline.concat([
          'ember electron:make --skip-package --platform=darwin',
          'ember electron:make --skip-package --platform=win32',
          'ember electron:make --skip-package --platform=linux'
        ]);
        let proc = childProcess.exec(buildPipeline.join(' && '));
        proc.stdout.pipe(process.stdout);
        proc.stderr.pipe(process.stderr);
        proc.on("exit", () => {
            console.log("Realease : ok");
            res();
          });
      } else {
        res();
      }
    }).then( () => {
      if (!(options.publish === false || options.publish === "false")) {
        return new Promise((res, rej) => {
          let publisherJsonFile = path.join(__dirname, "..", "..", "publisher.json");
          if (!fs.existsSync(publisherJsonFile) || options.configure === true || options.configure === "true") {
            console.log("Configuring publisher");
            console.log("Enter your github API token :");
            process.stdin.resume();
            process.stdin.setEncoding('utf8');
            process.stdin.on('data', function (text) {
              process.stdin.pause();
              generatePublisherJson(text.replace(/\n$/, ''));
              publish(publisherJsonFile).then( () => res() ).catch((e) => rej(e));
            });
          } else {
            publish(publisherJsonFile).then( () => res() ).catch((e) => rej(e));
          }
        });
      } else {
        return Promise.resolve();
      }
    });
  }
});

function generatePublisherJson(token) {
  let publisherJsonFile = path.join(__dirname, "..", "..", "publisher.json"),
      publisherJsonFileTpl = path.join(__dirname, "..", "..", "publisher.json.tpl");
  let json = JSON.parse(fs.readFileSync(publisherJsonFileTpl, "utf8"));
  json.transport.token = token;
  fs.writeFileSync(publisherJsonFile, JSON.stringify(json), "utf8");
}

function publish(publisherJsonFile) {
  return publisher.run({
    command: "publish",
    config: publisherJsonFile,
    path: "electron-out/make",
    builds: [
      'darwin-x64',
      'winSquirrel-x64'
    ]
  });
}
<commit_msg>correction<commit_after>'use strict';

const Command = require('ember-cli/lib/models/command'),
      childProcess = require('child_process'),
      options = require('../utils/publish-options'),
      publisher = require('electron-simple-publisher/lib/publisher'),
      path = require('path'),
      fs = require('fs');

module.exports = Command.extend({
  name: 'khartis:release',
  description: 'Publish khartis electron release',
  availableOptions: options,
  run: function(options) {
    return new Promise((res, rej) => {
      process.on('SIGINT', function() {
        rej();
        process.exit();
      });
      if (!(options.make === false || options.make === "false")) {
        let buildPipeline = [];
        if (!(options.skipbuild === "true" || options.skipbuild === true)) {
          buildPipeline.push('ember electron:build --output-path electron-out/ember');
        }
        if (!(options.skipassemble === "true" || options.skipassemble === true)) {
          buildPipeline.push('ember electron:assemble --build-path electron-out/ember --output-path electron-out/project');
        }
        if (!(options.skippackage === "true" || options.skippackage === true)) {
          buildPipeline.push('ember electron:package --project-path electron-out/project --platform=darwin,win32,linux');
        }
        buildPipeline = buildPipeline.concat([
          'ember electron:make --skip-package --platform=darwin',
          'ember electron:make --skip-package --platform=win32',
          'ember electron:make --skip-package --platform=linux'
        ]);
        let proc = childProcess.exec(buildPipeline.join(' && '));
        proc.stdout.pipe(process.stdout);
        proc.stderr.pipe(process.stderr);
        proc.on("exit", () => {
            console.log("Realease : ok");
            res();
          });
      } else {
        res();
      }
    }).then( () => {
      if (!(options.publish === false || options.publish === "false")) {
        return new Promise((res, rej) => {
          let publisherJsonFile = path.join(__dirname, "..", "..", "publisher.json");
          if (!fs.existsSync(publisherJsonFile) || options.configure === true || options.configure === "true") {
            console.log("Configuring publisher");
            console.log("Enter your github API token :");
            process.stdin.resume();
            process.stdin.setEncoding('utf8');
            process.stdin.on('data', function (text) {
              process.stdin.pause();
              generatePublisherJson(text.replace(/\n$/, ''));
              publish(publisherJsonFile).then( () => res() ).catch((e) => rej(e));
            });
          } else {
            publish(publisherJsonFile).then( () => res() ).catch((e) => rej(e));
          }
        });
      } else {
        return Promise.resolve();
      }
    });
  }
});

function generatePublisherJson(token) {
  let publisherJsonFile = path.join(__dirname, "..", "..", "publisher.json"),
      publisherJsonFileTpl = path.join(__dirname, "..", "..", "publisher.json.tpl");
  let json = JSON.parse(fs.readFileSync(publisherJsonFileTpl, "utf8"));
  json.transport.token = token;
  fs.writeFileSync(publisherJsonFile, JSON.stringify(json), "utf8");
}

function publish(publisherJsonFile) {
  return publisher.run({
    command: "publish",
    config: publisherJsonFile,
    path: "electron-out/make",
    builds: [
      'darwin-x64',
      'win32-x64'
    ]
  });
}
<|endoftext|>


<commit_before>var dotest = require ('dotest');
var app = require ('./');

var config = {
  hostname: process.env.MFC_HOSTNAME || null,
  timeout: process.env.MFC_TIMEOUT || 5000
};

var cacheSleep = null;

var mfc = app (config);

dotest.add ('Configuration', function (test) {
  if (!config.hostname) {
    test ()
      .fail ('MFC_HOSTNAME not set')
      .exit ();
  } else {
    test ()
      .good ('MFC_HOSTNAME is set')
      .info ('MFC_TIMEOUT:  ' + config.timeout)
      .done ();
  }
});

dotest.add ('Module', function (test) {
  var general = mfc && mfc.general;

  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', mfc)
    .isFunction ('fail', '.current', mfc && mfc.current)
    .isFunction ('fail', '.sleep', mfc && mfc.sleep)
    .isObject ('fail', '.general', general)
    .isFunction ('fail', '.general.status', general && general.status)
    .isFunction ('fail', '.general.information', general && general.information)
    .done ();
});

dotest.add ('Method .sleep - get value', function (test) {
  mfc.sleep (function (err, data) {
    var value = data && data.value;

    if (value && value.key) {
      cacheSleep = value.key;
    }

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.presets', data && data.presets)
      .isObject ('fail', 'data.value', value)
      .isNumber ('fail', 'data.value.key', value && value.key)
      .isNumber ('fail', 'data.presets[1]', data && data.presets && data.presets[1])
      .done ();
  });
});

dotest.add ('Method .sleep - set value', function (test) {
  mfc.sleep (cacheSleep, function (err, data) {
    test (err)
      .isExactly ('fail', 'data', data, true)
      .done ();
  });
});

dotest.add ('Method .current', function (test) {
  mfc.current (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isString ('fail', 'data.state', data && data.state)
      .isString ('fail', 'data.stateReasons', data && data.stateReasons)
      .isNumber ('fail', 'data.jobs', data && data.jobs)
      .isNumber ('fail', 'data.uptime', data && data.uptime)
      .isDate ('fail', 'data.uptimeDate', data && data.uptimeDate)
      .isObject ('fail', 'data.ink', data && data.ink)
      .info (data && data.ink)
      .done ();
  });
});

dotest.add ('Method general.status', function (test) {
  mfc.general.status (function (err, data) {
    var i;

    test (err)
      .isObject ('fail', 'data', data)
      .isString ('fail', 'data.model', data && data.model)
      .isString ('fail', 'data.status', data && data.status)
      .isString ('fail', 'data.message', data && data.message)
      .isObject ('fail', 'data.ink', data && data.ink)
      .isNotEmpty ('fail', 'data.ink', data && data.ink);

    for (i in data && data.ink) {
      test () .isNumber ('fail', 'data.ink.' + i, data.ink [i]);
    }

    test () .done ();
  });
});

dotest.run ();
<commit_msg>Test: added method general.information test<commit_after>var dotest = require ('dotest');
var app = require ('./');

var config = {
  hostname: process.env.MFC_HOSTNAME || null,
  timeout: process.env.MFC_TIMEOUT || 5000
};

var cacheSleep = null;

var mfc = app (config);

dotest.add ('Configuration', function (test) {
  if (!config.hostname) {
    test ()
      .fail ('MFC_HOSTNAME not set')
      .exit ();
  } else {
    test ()
      .good ('MFC_HOSTNAME is set')
      .info ('MFC_TIMEOUT:  ' + config.timeout)
      .done ();
  }
});

dotest.add ('Module', function (test) {
  var general = mfc && mfc.general;

  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', mfc)
    .isFunction ('fail', '.current', mfc && mfc.current)
    .isFunction ('fail', '.sleep', mfc && mfc.sleep)
    .isObject ('fail', '.general', general)
    .isFunction ('fail', '.general.status', general && general.status)
    .isFunction ('fail', '.general.information', general && general.information)
    .done ();
});

dotest.add ('Method .sleep - get value', function (test) {
  mfc.sleep (function (err, data) {
    var value = data && data.value;

    if (value && value.key) {
      cacheSleep = value.key;
    }

    test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.presets', data && data.presets)
      .isObject ('fail', 'data.value', value)
      .isNumber ('fail', 'data.value.key', value && value.key)
      .isNumber ('fail', 'data.presets[1]', data && data.presets && data.presets[1])
      .done ();
  });
});

dotest.add ('Method .sleep - set value', function (test) {
  mfc.sleep (cacheSleep, function (err, data) {
    test (err)
      .isExactly ('fail', 'data', data, true)
      .done ();
  });
});

dotest.add ('Method .current', function (test) {
  mfc.current (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isString ('fail', 'data.state', data && data.state)
      .isString ('fail', 'data.stateReasons', data && data.stateReasons)
      .isNumber ('fail', 'data.jobs', data && data.jobs)
      .isNumber ('fail', 'data.uptime', data && data.uptime)
      .isDate ('fail', 'data.uptimeDate', data && data.uptimeDate)
      .isObject ('fail', 'data.ink', data && data.ink)
      .info (data && data.ink)
      .done ();
  });
});

dotest.add ('Method general.status', function (test) {
  mfc.general.status (function (err, data) {
    var i;

    test (err)
      .isObject ('fail', 'data', data)
      .isString ('fail', 'data.model', data && data.model)
      .isString ('fail', 'data.status', data && data.status)
      .isString ('fail', 'data.message', data && data.message)
      .isObject ('fail', 'data.ink', data && data.ink)
      .isNotEmpty ('fail', 'data.ink', data && data.ink);

    for (i in data && data.ink) {
      test () .isNumber ('fail', 'data.ink.' + i, data.ink [i]);
    }

    test () .done ();
  });
});

dotest.add ('Method general.information', function (test) {
  mfc.general.information (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isString ('fail', 'data.ip_address', data && data.ip_address)
      .isNumber ('fail', 'data.page_counter', data && data.page_counter)
      .done ();
  });
});

dotest.run ();
<|endoftext|>


<commit_before>// Copyright (c) 2021, Marc Poulhiès
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

import path from 'path';

import { BaseCompiler } from '../base-compiler';

import { MrustcParser } from './argument-parsers';

export class MrustcCompiler extends BaseCompiler {
    static get key() { return 'mrustc'; }

    optionsForFilter(filters, outputFilename) {
        // mrustc always dumps the C code for <baseout> target in the <baseout>.c file.
        // In our case, the actual file in -o is not even created because we are
        // faking the last step (C compilation).
        // Craft the 'outname' to have the intermediate .c file writen in outputFilename.
        let outname = path.join(path.dirname(this.filename(outputFilename)),
            path.basename(this.filename(outputFilename), '.c'));
        return ['-o', outname, '-L', path.join(path.dirname(this.compiler.exe), '..', 'output')];
    }

    async runCompiler(compiler, options, inputFilename, execOptions) {
        // mrustc will always invoke a C compiler on its C output to create a final exec/object.
        // There's no easy way to disable this last step, so simply faking it with 'true' works.
        execOptions.env.CC = 'true';

        return super.runCompiler(compiler, options, inputFilename, execOptions);
    }

    getOutputFilename(dirPath) {
        return path.join(dirPath, `${path.basename(this.compileFilename, this.lang.extensions[0])}.c`);
    }

    getArgumentParser() {
        return MrustcParser;
    }

}
<commit_msg>mrustc: force crate_type to rlib (#2691)<commit_after>// Copyright (c) 2021, Marc Poulhiès
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

import path from 'path';

import { BaseCompiler } from '../base-compiler';

import { MrustcParser } from './argument-parsers';

export class MrustcCompiler extends BaseCompiler {
    static get key() { return 'mrustc'; }

    optionsForFilter(filters, outputFilename) {
        // mrustc always dumps the C code for <baseout> target in the <baseout>.c file.
        // In our case, the actual file in -o is not even created because we are
        // faking the last step (C compilation).
        // Craft the 'outname' to have the intermediate .c file writen in outputFilename.
        let outname = path.join(path.dirname(this.filename(outputFilename)),
            path.basename(this.filename(outputFilename), '.c'));

        // Currently always targets a rlib, no binary support at the moment.
        return ['--crate-type', 'rlib',
            '-o', outname, '-L', path.join(path.dirname(this.compiler.exe), '..', 'output')];
    }

    async runCompiler(compiler, options, inputFilename, execOptions) {
        // mrustc will always invoke a C compiler on its C output to create a final exec/object.
        // There's no easy way to disable this last step, so simply faking it with 'true' works.
        execOptions.env.CC = 'true';

        return super.runCompiler(compiler, options, inputFilename, execOptions);
    }

    getOutputFilename(dirPath) {
        return path.join(dirPath, `${path.basename(this.compileFilename, this.lang.extensions[0])}.c`);
    }

    getArgumentParser() {
        return MrustcParser;
    }

}
<|endoftext|>


<commit_before>var assert = require('assert');
var LevelQueue = require('./index.js');
var level = require('memdb');
var SubLevel = require('level-sublevel');

describe('level-queue', function () {
    describe('enqueue', function () {
        it('Should add an item to the queue', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'task'];
            var follow = queue.follow(key);
            follow.on('data', function data(msg) {
                if (msg.value.indexOf('hello world') !== -1)
                    done()
                else done(new Error)
            });
            queue.enqueue(key, 'hello world');

        });
        it('Should retain order', function(done) {
            var msg1 = 'Hello';
            var msg2 = 'World';

            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];

            queue.enqueue(key, msg1);
            queue.enqueue(key, msg2);

            queue.toArray(key, function(err, res) {
                assert(res[0].key[2] < res[1].key[2]);
                done();
            });
        });
    });

    describe('toArray', function () {
        it('Should return an array', function(done) {
            var msg1 = 'Hello';
            var msg2 = 'World';

            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];

            queue.enqueue(key, msg1);
            queue.enqueue(key, msg2);

            queue.toArray(key, function(err, res) {
                assert(Array.isArray(res));
                done();
            });
        });
    });

    describe('follow', function () {
        it('Should return a stream', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];
            var follow = queue.follow(key);
            follow.on('data', function data(msg) {
                done();
            });

            queue.enqueue(key, 'hello world');
        });

        describe('- stream', function() {
            it('Should not be writable', function (done) {
                var db = SubLevel(level());
                var queue = LevelQueue(db);
                var key = ['worker', 'tasks'];
                var follow = queue.follow(key);
                assert(follow.writable === false);
                done();
            });
        });

        it('Should use keys properly', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];
            var key2 = ['worker-1', 'tasks'];
            var follow = queue.follow(key2);

            queue.enqueue(key, 'hello world');

            follow.on('data', function() {
                var err = new Error('There should be no data event');
                done(err);
                done = function () {};
            });
            follow.on('end', function () {
                done();
            });
        });
    });

    describe('dequeue', function () {
        it('Should remove 1 item from the queue', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];

            queue.enqueue(key, 'hello');
            queue.enqueue(key, 'world');
            queue.dequeue(key, function (err, res) {
                if (err) done(err);

                if (res) {
                    queue.toArray(key, function (err, arr) {
                        assert(arr.length === 1);
                        done();
                    });
                }
            });
        });
    });
});
<commit_msg>Made dequeu tests more comprehensive<commit_after>var assert = require('assert');
var LevelQueue = require('./index.js');
var level = require('memdb');
var SubLevel = require('level-sublevel');

describe('level-queue', function () {
    describe('enqueue', function () {
        it('Should add an item to the queue', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'task'];
            var follow = queue.follow(key);
            follow.on('data', function data(msg) {
                if (msg.value.indexOf('hello world') !== -1)
                    done()
                else done(new Error)
            });
            queue.enqueue(key, 'hello world');

        });
        it('Should retain order', function(done) {
            var msg1 = 'Hello';
            var msg2 = 'World';

            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];

            queue.enqueue(key, msg1);
            queue.enqueue(key, msg2);

            queue.toArray(key, function(err, res) {
                assert(res[0].key[2] < res[1].key[2]);
                done();
            });
        });
    });

    describe('toArray', function () {
        it('Should return an array', function(done) {
            var msg1 = 'Hello';
            var msg2 = 'World';

            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];

            queue.enqueue(key, msg1);
            queue.enqueue(key, msg2);

            queue.toArray(key, function(err, res) {
                assert(Array.isArray(res));
                done();
            });
        });
    });

    describe('follow', function () {
        it('Should return a stream', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];
            var follow = queue.follow(key);
            follow.on('data', function data(msg) {
                done();
            });

            queue.enqueue(key, 'hello world');
        });

        describe('- stream', function() {
            it('Should not be writable', function (done) {
                var db = SubLevel(level());
                var queue = LevelQueue(db);
                var key = ['worker', 'tasks'];
                var follow = queue.follow(key);
                assert(follow.writable === false);
                done();
            });
        });

        it('Should use keys properly', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];
            var key2 = ['worker-1', 'tasks'];
            var follow = queue.follow(key2);

            queue.enqueue(key, 'hello world');

            follow.on('data', function() {
                var err = new Error('There should be no data event');
                done(err);
                done = function () {};
            });
            follow.on('end', function () {
                done();
            });
        });
    });

    describe('dequeue', function () {
        it('Should remove 1 item from the queue retaining order', function (done) {
            var db = SubLevel(level());
            var queue = LevelQueue(db);
            var key = ['worker', 'tasks'];

            queue.enqueue(key, 'hello');
            queue.enqueue(key, 'world');
            queue.dequeue(key, function (err, res) {
                if (err) done(err);

                if (res) {
                    queue.toArray(key, function (err, arr) {
                        assert(arr.length === 1);
                        assert(arr[0].value === 'hello');
                        done();
                    });
                }
            });
        });
    });
});
<|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');
var ExecutionEnvironment = require('exenv');
var ModalPortal = React.createFactory(require('./ModalPortal'));
var ariaAppHider = require('../helpers/ariaAppHider');
var elementClass = require('element-class');
var renderSubtreeIntoContainer = require("react-dom").unstable_renderSubtreeIntoContainer;
var Assign = require('lodash.assign');

var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var AppElement = ExecutionEnvironment.canUseDOM ? document.body : {appendChild: function() {}};

var Modal = React.createClass({

  displayName: 'Modal',
  statics: {
    setAppElement: function(element) {
        AppElement = ariaAppHider.setElement(element);
    },
    injectCSS: function() {
      "production" !== process.env.NODE_ENV
        && console.warn('React-Modal: injectCSS has been deprecated ' +
                        'and no longer has any effect. It will be removed in a later version');
    }
  },

  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    style: React.PropTypes.shape({
      content: React.PropTypes.object,
      overlay: React.PropTypes.object
    }),
    appElement: React.PropTypes.instanceOf(SafeHTMLElement),
    onAfterOpen: React.PropTypes.func,
    onRequestClose: React.PropTypes.func,
    closeTimeoutMS: React.PropTypes.number,
    ariaHideApp: React.PropTypes.bool,
    shouldCloseOnOverlayClick: React.PropTypes.bool
  },

  getDefaultProps: function () {
    return {
      isOpen: false,
      ariaHideApp: true,
      closeTimeoutMS: 0,
      shouldCloseOnOverlayClick: true
    };
  },

  componentDidMount: function() {
    this.node = document.createElement('div');
    this.node.className = 'ReactModalPortal';
    AppElement.appendChild(this.node);
    this.renderPortal(this.props);
  },

  componentWillReceiveProps: function(newProps) {
    this.renderPortal(newProps);
  },

  componentWillUnmount: function() {
    ReactDOM.unmountComponentAtNode(this.node);
    AppElement.removeChild(this.node);
    elementClass(document.body).remove('ReactModal__Body--open');
  },

  renderPortal: function(props) {
    if (props.isOpen) {
      elementClass(document.body).add('ReactModal__Body--open');
    } else {
      elementClass(document.body).remove('ReactModal__Body--open');
    }

    if (props.ariaHideApp) {
      ariaAppHider.toggle(props.isOpen, props.appElement);
    }

    sanitizeProps(props);
    this.portal = renderSubtreeIntoContainer(this, ModalPortal(Assign({}, props, {defaultStyles: Modal.defaultStyles})), this.node);
  },

  render: function () {
    return React.DOM.noscript();
  }
});

Modal.defaultStyles = {
  overlay: {
    position        : 'fixed',
    top             : 0,
    left            : 0,
    right           : 0,
    bottom          : 0,
    backgroundColor : 'rgba(255, 255, 255, 0.75)'
  },
  content: {
    position                : 'absolute',
    top                     : '40px',
    left                    : '40px',
    right                   : '40px',
    bottom                  : '40px',
    border                  : '1px solid #ccc',
    background              : '#fff',
    overflow                : 'auto',
    WebkitOverflowScrolling : 'touch',
    borderRadius            : '4px',
    outline                 : 'none',
    padding                 : '20px'
  }
}

module.exports = Modal

function sanitizeProps(props) {
  delete props.ref;
}
<commit_msg>[fixed] moved sanitizeProps out of the render calls. (#162)<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
var ExecutionEnvironment = require('exenv');
var ModalPortal = React.createFactory(require('./ModalPortal'));
var ariaAppHider = require('../helpers/ariaAppHider');
var elementClass = require('element-class');
var renderSubtreeIntoContainer = require("react-dom").unstable_renderSubtreeIntoContainer;
var Assign = require('lodash.assign');

var SafeHTMLElement = ExecutionEnvironment.canUseDOM ? window.HTMLElement : {};
var AppElement = ExecutionEnvironment.canUseDOM ? document.body : {appendChild: function() {}};

var Modal = React.createClass({

  displayName: 'Modal',
  statics: {
    setAppElement: function(element) {
        AppElement = ariaAppHider.setElement(element);
    },
    injectCSS: function() {
      "production" !== process.env.NODE_ENV
        && console.warn('React-Modal: injectCSS has been deprecated ' +
                        'and no longer has any effect. It will be removed in a later version');
    }
  },

  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    style: React.PropTypes.shape({
      content: React.PropTypes.object,
      overlay: React.PropTypes.object
    }),
    appElement: React.PropTypes.instanceOf(SafeHTMLElement),
    onAfterOpen: React.PropTypes.func,
    onRequestClose: React.PropTypes.func,
    closeTimeoutMS: React.PropTypes.number,
    ariaHideApp: React.PropTypes.bool,
    shouldCloseOnOverlayClick: React.PropTypes.bool
  },

  getDefaultProps: function () {
    return {
      isOpen: false,
      ariaHideApp: true,
      closeTimeoutMS: 0,
      shouldCloseOnOverlayClick: true
    };
  },

  componentDidMount: function() {
    this.node = document.createElement('div');
    this.node.className = 'ReactModalPortal';
    AppElement.appendChild(this.node);
    this.renderPortal(this.props);
  },

  componentWillReceiveProps: function(newProps) {
    sanitizeProps(newProps);
    this.renderPortal(newProps);
  },

  componentWillUnmount: function() {
    ReactDOM.unmountComponentAtNode(this.node);
    AppElement.removeChild(this.node);
    elementClass(document.body).remove('ReactModal__Body--open');
  },

  renderPortal: function(props) {
    if (props.isOpen) {
      elementClass(document.body).add('ReactModal__Body--open');
    } else {
      elementClass(document.body).remove('ReactModal__Body--open');
    }

    if (props.ariaHideApp) {
      ariaAppHider.toggle(props.isOpen, props.appElement);
    }

    this.portal = renderSubtreeIntoContainer(this, ModalPortal(Assign({}, props, {defaultStyles: Modal.defaultStyles})), this.node);
  },

  render: function () {
    return React.DOM.noscript();
  }
});

Modal.defaultStyles = {
  overlay: {
    position        : 'fixed',
    top             : 0,
    left            : 0,
    right           : 0,
    bottom          : 0,
    backgroundColor : 'rgba(255, 255, 255, 0.75)'
  },
  content: {
    position                : 'absolute',
    top                     : '40px',
    left                    : '40px',
    right                   : '40px',
    bottom                  : '40px',
    border                  : '1px solid #ccc',
    background              : '#fff',
    overflow                : 'auto',
    WebkitOverflowScrolling : 'touch',
    borderRadius            : '4px',
    outline                 : 'none',
    padding                 : '20px'
  }
}

module.exports = Modal

function sanitizeProps(props) {
  delete props.ref;
}
<|endoftext|>


<commit_before>var request = require('request');
var cheerio = require('cheerio');
var searchTerm = 'screen+scraping';
//var url = 'http://www.bing.com/search?q=' + searchTerm;
var url = "https://medium.com/"
request(url, function(err, resp, body){
  $ = cheerio.load(body);
  links = $('a'); //jquery get all hyperlinks
  $(links).each(function(i, link){
    console.log($(link).text() + ':\n  ' + $(link).attr('href'));
  });
});
<commit_msg>added max pool sockets to request<commit_after>var request = require('request');
var cheerio = require('cheerio');
var searchTerm = 'screen+scraping';
//var url = 'http://www.bing.com/search?q=' + searchTerm;
var url = "https://medium.com/"
request({'url':url, 'method':'GET', 'pool.maxSockets': 5}, function(err, resp, body){
  $ = cheerio.load(body);
  links = $('a'); //jquery get all hyperlinks
  $(links).each(function(i, link){
    console.log($(link).text() + ':\n  ' + $(link).attr('href'));
  });
});
<|endoftext|>


<commit_before>import React from 'react';

import focusTrap from 'focus-trap';

import { whichAnimationEvent } from './utils';

const bodyActiveClass = 'u-body-modal-active';
const animationEvent = whichAnimationEvent();

function stopPropagation(event) {
    event.stopPropagation();
}

export default React.createClass({

    displayName: 'Modal',

    propTypes: {
        children: React.PropTypes.node.isRequired,
        isOpen: React.PropTypes.bool.isRequired,
        onRequestClose: React.PropTypes.func,
        onAfterOpen: React.PropTypes.func,
        onAfterClose: React.PropTypes.func,
        overlayClick: React.PropTypes.bool,
        label: React.PropTypes.string,
        className: React.PropTypes.string,
        controls: React.PropTypes.object,
        insideControls: React.PropTypes.bool,
        ariaHideApp: React.PropTypes.bool,
    },

    getDefaultProps() {
        return {
            ariaHideApp: true,
            onRequestClose: null,
            onAfterOpen: null,
            onAfterClose: null,
            overlayClick: true,
            className: '',
            label: null,
            controls: null,
            insideControls: false,
        };
    },

    getInitialState() {
        return {
            // afterOpen: false,
            beforeClose: false,
        };
    },

    componentDidMount() {
        // Focus needs to be set when mounting and already open
        if (this.props.isOpen) {
            this.open();
        }
    },

    componentWillReceiveProps(newProps) {
        if (this.props.isOpen && !newProps.isOpen) {
            this.handleClose();
        }
    },

    componentDidUpdate(prevProps) {
        // Focus only needs to be set once when the modal is being opened
        if (!prevProps.isOpen && this.props.isOpen) {
            this.open();
        }
    },

    componentWillUnmount() {
        if (this.props.isOpen) {
            this.cleanup();
        }
    },

    open() {
        document.body.classList.add(bodyActiveClass);

        if (animationEvent) {
            const modal = this.refs.modal;
            modal.addEventListener(animationEvent, this.afterOpen );
            return;
        }

        this.afterOpen();
    },

    afterOpen(e) {
        const { modal } = this.refs;

        // make sure we're listening to the modals animationEvent
        if (e) {
            const target = e.target || e.srcElement;
            if (target !== modal) {
                return;
            }
        }

        this.setAriaHidden(false);
        this.setFocusTrap();

        if (animationEvent) {
            modal.removeEventListener(animationEvent, this.afterOpen);
        }

        this.setState({afterOpen: true}, function() {
            window.addEventListener('keydown', this.handleKeyDown);
            if (this.props.onAfterOpen) {
                this.props.onAfterOpen();
            }
        });
    },

    requestClose() {
        const { onRequestClose } = this.props;

        if (onRequestClose) {
            onRequestClose();
        }
    },

    handleClose() {
        const { onRequestClose } = this.props;

        document.body.classList.remove(bodyActiveClass);

        if (!onRequestClose) {
            return;
        }

        if (animationEvent) {
            const modal = this.refs.modal;
            modal.addEventListener(animationEvent, this.close );
            modal.classList.remove('modal--active');
            modal.classList.add('modal--exit');
            this.setState({
                beforeClose: true
            });
            return;
        }

        this.close();
    },

    close(e) {
        const { modal } = this.refs;

        // make sure we're listening to the modals animationEvent
        if (e) {
            const target = e.target || e.srcElement;
            if (target !== modal) {
                return;
            }
        }

        this.setAriaHidden(true);

        if (animationEvent) {
            modal.removeEventListener(animationEvent, this.close);
        }

        this.setState({
            afterOpen: false,
            beforeClose: false,
        }, this.afterClose);
    },

    cleanup() {
        document.body.classList.remove(bodyActiveClass);
        focusTrap.deactivate(this.refs.modal);
        window.removeEventListener('keydown', this.handleKeyDown);
    },

    afterClose() {
        const { onAfterClose } = this.props;
        this.cleanup();

        if (onAfterClose) {
            onAfterClose();
        }
    },

    handleKeyDown(e) {
        // ESC key
        if (e.keyCode === 27) {
            this.requestClose();
        }
    },

    handleOverlayClick() {
        const { overlayClick } = this.props;
        if (!overlayClick) {
            return;
        }

        this.requestClose();
    },

    shouldBeClosed() {
        return !this.props.isOpen && !this.state.beforeClose;
    },

    setAriaHidden(isHidden) {
        const { ariaHideApp } = this.props;
        const { content } = this.refs;

        if (!ariaHideApp) {
            return;
        }

        if (!content) {
            return;
        }

        content.setAttribute('aria-hidden', isHidden);

        const mainContent = document.querySelector('[data-main-content]');
        if (mainContent) {
            mainContent.setAttribute('aria-hidden', !isHidden);
        }
    },

    setFocusTrap() {
        const { modal, content } = this.refs;

        if (!content) {
            return;
        }

        focusTrap.activate(modal, {
            clickOutsideDeactivates: true,
            returnFocusOnDeactivate: true,
        });
    },

    render() {
        const { className, children, controls, label, insideControls } = this.props;

        const classList = ['modal', 'modal--active'];

        let controlsMarkup;

        if (controls) {
            controlsMarkup = controls;
        } else {
            controlsMarkup = (
                <div className={`modal__control${insideControls ? ' modal__control--inside' : ''}`}>

×

            );
        }

        if (className) {
            classList.push(className);
        }

        return this.shouldBeClosed() ? null : (

                            {children}

                            {insideControls && controlsMarkup}

                {!insideControls && controlsMarkup}

        );
    },
});

<commit_msg>Shuffle DOM order of close buttton when inside content<commit_after>import React from 'react';

import focusTrap from 'focus-trap';

import { whichAnimationEvent } from './utils';

const bodyActiveClass = 'u-body-modal-active';
const animationEvent = whichAnimationEvent();

function stopPropagation(event) {
    event.stopPropagation();
}

export default React.createClass({

    displayName: 'Modal',

    propTypes: {
        children: React.PropTypes.node.isRequired,
        isOpen: React.PropTypes.bool.isRequired,
        onRequestClose: React.PropTypes.func,
        onAfterOpen: React.PropTypes.func,
        onAfterClose: React.PropTypes.func,
        overlayClick: React.PropTypes.bool,
        label: React.PropTypes.string,
        className: React.PropTypes.string,
        controls: React.PropTypes.object,
        insideControls: React.PropTypes.bool,
        ariaHideApp: React.PropTypes.bool,
    },

    getDefaultProps() {
        return {
            ariaHideApp: true,
            onRequestClose: null,
            onAfterOpen: null,
            onAfterClose: null,
            overlayClick: true,
            className: '',
            label: null,
            controls: null,
            insideControls: false,
        };
    },

    getInitialState() {
        return {
            // afterOpen: false,
            beforeClose: false,
        };
    },

    componentDidMount() {
        // Focus needs to be set when mounting and already open
        if (this.props.isOpen) {
            this.open();
        }
    },

    componentWillReceiveProps(newProps) {
        if (this.props.isOpen && !newProps.isOpen) {
            this.handleClose();
        }
    },

    componentDidUpdate(prevProps) {
        // Focus only needs to be set once when the modal is being opened
        if (!prevProps.isOpen && this.props.isOpen) {
            this.open();
        }
    },

    componentWillUnmount() {
        if (this.props.isOpen) {
            this.cleanup();
        }
    },

    open() {
        document.body.classList.add(bodyActiveClass);

        if (animationEvent) {
            const modal = this.refs.modal;
            modal.addEventListener(animationEvent, this.afterOpen );
            return;
        }

        this.afterOpen();
    },

    afterOpen(e) {
        const { modal } = this.refs;

        // make sure we're listening to the modals animationEvent
        if (e) {
            const target = e.target || e.srcElement;
            if (target !== modal) {
                return;
            }
        }

        this.setAriaHidden(false);
        this.setFocusTrap();

        if (animationEvent) {
            modal.removeEventListener(animationEvent, this.afterOpen);
        }

        this.setState({afterOpen: true}, function() {
            window.addEventListener('keydown', this.handleKeyDown);
            if (this.props.onAfterOpen) {
                this.props.onAfterOpen();
            }
        });
    },

    requestClose() {
        const { onRequestClose } = this.props;

        if (onRequestClose) {
            onRequestClose();
        }
    },

    handleClose() {
        const { onRequestClose } = this.props;

        document.body.classList.remove(bodyActiveClass);

        if (!onRequestClose) {
            return;
        }

        if (animationEvent) {
            const modal = this.refs.modal;
            modal.addEventListener(animationEvent, this.close );
            modal.classList.remove('modal--active');
            modal.classList.add('modal--exit');
            this.setState({
                beforeClose: true
            });
            return;
        }

        this.close();
    },

    close(e) {
        const { modal } = this.refs;

        // make sure we're listening to the modals animationEvent
        if (e) {
            const target = e.target || e.srcElement;
            if (target !== modal) {
                return;
            }
        }

        this.setAriaHidden(true);

        if (animationEvent) {
            modal.removeEventListener(animationEvent, this.close);
        }

        this.setState({
            afterOpen: false,
            beforeClose: false,
        }, this.afterClose);
    },

    cleanup() {
        document.body.classList.remove(bodyActiveClass);
        focusTrap.deactivate(this.refs.modal);
        window.removeEventListener('keydown', this.handleKeyDown);
    },

    afterClose() {
        const { onAfterClose } = this.props;
        this.cleanup();

        if (onAfterClose) {
            onAfterClose();
        }
    },

    handleKeyDown(e) {
        // ESC key
        if (e.keyCode === 27) {
            this.requestClose();
        }
    },

    handleOverlayClick() {
        const { overlayClick } = this.props;
        if (!overlayClick) {
            return;
        }

        this.requestClose();
    },

    shouldBeClosed() {
        return !this.props.isOpen && !this.state.beforeClose;
    },

    setAriaHidden(isHidden) {
        const { ariaHideApp } = this.props;
        const { content } = this.refs;

        if (!ariaHideApp) {
            return;
        }

        if (!content) {
            return;
        }

        content.setAttribute('aria-hidden', isHidden);

        const mainContent = document.querySelector('[data-main-content]');
        if (mainContent) {
            mainContent.setAttribute('aria-hidden', !isHidden);
        }
    },

    setFocusTrap() {
        const { modal, content } = this.refs;

        if (!content) {
            return;
        }

        focusTrap.activate(modal, {
            clickOutsideDeactivates: true,
            returnFocusOnDeactivate: true,
        });
    },

    render() {
        const { className, children, controls, label, insideControls } = this.props;

        const classList = ['modal', 'modal--active'];

        let controlsMarkup;

        if (controls) {
            controlsMarkup = controls;
        } else {
            controlsMarkup = (
                <div className={`modal__control${insideControls ? ' modal__control--inside' : ''}`}>

×

            );
        }

        if (className) {
            classList.push(className);
        }

        return this.shouldBeClosed() ? null : (

                            {insideControls && controlsMarkup}

                            {children}

                {!insideControls && controlsMarkup}

        );
    },
});

<|endoftext|>


<commit_before>var test = require('tape')
var spawn = require('child_process').spawn
var bl = require('bl')

test('nsqd listens on port 4150', function (t) {
  testPort(t, 4150)
})

test('nsqd listens on port 4151', function (t) {
  testPort(t, 4151)
})

function testPort (t, port) {
  t.plan(2)
  var regexp = new RegExp(":" + port)
  spawn('lsof', [ '-i', ':' + port ])
    .on('exit', function (code) {
      t.equal(code, 0, 'lsof exited without error')
    })
    .stdout.pipe(bl(function (err, data) {
      t.equal(regexp.test(data.toString()), true, 'should match port')
    }))
}
<commit_msg>use environment from current process<commit_after>var test = require('tape')
var spawn = require('child_process').spawn
var bl = require('bl')

test('nsqd listens on port 4150', function (t) {
  testPort(t, 4150)
})

test('nsqd listens on port 4151', function (t) {
  testPort(t, 4151)
})

function testPort (t, port) {
  t.plan(2)
  var regexp = new RegExp(":" + port)
  spawn('lsof', [ '-i', ':' + port ], { env: process.env })
    .on('exit', function (code) {
      t.equal(code, 0, 'lsof exited without error')
    })
    .stdout.pipe(bl(function (err, data) {
      t.equal(regexp.test(data.toString()), true, 'should match port')
    }))
}
<|endoftext|>


<commit_before>'use strict';

var direction,
    assert,
    fixtures;

/**
 * Module dependencies.
 */

direction = require('./');
assert = require('assert');

/**
 * Test data.
 */

fixtures = {
    'a' : 'ltr',
    '\u05e0' : 'rtl',
    '\u0000' : 'neutral',
    '\u0020' : 'neutral',
    '!' : 'neutral',
    '@' : 'neutral',
    '[' : 'neutral',
    '`' : 'neutral',
    '0' : 'neutral',
    '123' : 'neutral',
    'A' : 'ltr',
    'english' : 'ltr',
    'sentence' : 'ltr',
    'Un' : 'ltr',
    'simple' : 'ltr',
    'anglais' : 'ltr',
    'phrase' : 'ltr',
    'أ' : 'rtl',
    'الجملة' : 'rtl',
    'الانجليزية' : 'rtl',
    'بسيطة' : 'rtl'
};

/**
 * Unit tests.
 */

describe('direction(value)', function () {
    it('should be of type `function`', function () {
        assert(typeof direction === 'function');
    });

    Object.keys(fixtures).forEach(function (fixture) {
        var result;

        result = fixtures[fixture];

        it('should classify `' + fixture + '` as `' + result + '` ',
            function () {
                assert(direction(fixture) === result);
            }
        );
    });
});
<commit_msg>Refactor test<commit_after>'use strict';

/**
 * Dependencies.
 */

var direction,
    assert;

direction = require('./');
assert = require('assert');

/**
 * Fixtures
 */

var fixtures;

fixtures = {
    'a' : 'ltr',
    '\u05e0' : 'rtl',
    '\u0000' : 'neutral',
    '\u0020' : 'neutral',
    '!' : 'neutral',
    '@' : 'neutral',
    '[' : 'neutral',
    '`' : 'neutral',
    '0' : 'neutral',
    '123' : 'neutral',
    'A' : 'ltr',
    'english' : 'ltr',
    'sentence' : 'ltr',
    'Un' : 'ltr',
    'simple' : 'ltr',
    'anglais' : 'ltr',
    'phrase' : 'ltr',
    'أ' : 'rtl',
    'الجملة' : 'rtl',
    'الانجليزية' : 'rtl',
    'بسيطة' : 'rtl'
};

/**
 * Tests.
 */

describe('direction(value)', function () {
    it('should be of type `function`', function () {
        assert(typeof direction === 'function');
    });

    Object.keys(fixtures).forEach(function (fixture) {
        var result;

        result = fixtures[fixture];

        it('should classify `' + fixture + '` as `' + result + '` ',
            function () {
                assert(direction(fixture) === result);
            }
        );
    });
});
<|endoftext|>


<commit_before>"use strict";

const oui = require(".");
const nock = require("nock");
const {join} = require("path");
const {test, expect} = global;

nock("https://linuxnet.ca").persist().get("/ieee/oui.txt").replyWithFile(200, join(__dirname, "fixtures/sanitized.txt"));
nock("http://standards.ieee.org").persist().get("/develop/regauth/oui/oui.txt").replyWithFile(200, join(__dirname, "fixtures/sanitized.txt"));

test("oui", () => {
  expect(oui("203706")).toMatch(/cisco/i);
  expect(oui("20:37:06")).toMatch(/cisco/i);
  expect(oui("20:37:6")).toMatch(/cisco/i);
  expect(oui("20:37:06:11:22:33")).toMatch(/cisco/i);
  expect(oui("20:37:6:11:22:33")).toMatch(/cisco/i);
  expect(oui("20370")).toEqual(null);

  expect(() => {oui(null)}).toThrow();
  expect(() => {oui(undefined)}).toThrow();
  expect(() => {oui([])}).toThrow();
  expect(() => {oui("20370", {strict: true})}).toThrow();
  expect(() => {oui("abcd", {strict: true})}).toThrow();
  expect(() => {oui(null, {strict: true})}).toThrow();
  expect(() => {oui(undefined, {strict: true})}).toThrow();
});

test("oui.search", () => {
  expect(oui.search("*Juniper Systems*").length >= 1).toBeTruthy();
  expect(oui.search(["*Juniper Systems*"]).length >= 1).toBeTruthy();
  expect(oui.search(["*Juniper*", "*Systems*"]).length >= 1).toBeTruthy();
});

test("oui.update", async () => {
  expect(await Promise.all([
    oui.update(),
    oui.update({url: "https://linuxnet.ca/ieee/oui.txt"}),
    oui.update({url: "http://standards.ieee.org/develop/regauth/oui/oui.txt"}),
  ])).toEqual([undefined, undefined, undefined]);
});
<commit_msg>try different nock init<commit_after>"use strict";

const oui = require(".");
const nock = require("nock");
const {join} = require("path");
const {test, expect, beforeAll, afterAll} = global;

beforeAll(() => {
  nock("https://linuxnet.ca").persist().get("/ieee/oui.txt").replyWithFile(200, join(__dirname, "fixtures/sanitized.txt"));
  nock("http://standards.ieee.org").persist().get("/develop/regauth/oui/oui.txt").replyWithFile(200, join(__dirname, "fixtures/sanitized.txt"));
});

test("oui", () => {
  expect(oui("203706")).toMatch(/cisco/i);
  expect(oui("20:37:06")).toMatch(/cisco/i);
  expect(oui("20:37:6")).toMatch(/cisco/i);
  expect(oui("20:37:06:11:22:33")).toMatch(/cisco/i);
  expect(oui("20:37:6:11:22:33")).toMatch(/cisco/i);
  expect(oui("20370")).toEqual(null);

  expect(() => {oui(null)}).toThrow();
  expect(() => {oui(undefined)}).toThrow();
  expect(() => {oui([])}).toThrow();
  expect(() => {oui("20370", {strict: true})}).toThrow();
  expect(() => {oui("abcd", {strict: true})}).toThrow();
  expect(() => {oui(null, {strict: true})}).toThrow();
  expect(() => {oui(undefined, {strict: true})}).toThrow();
});

test("oui.search", () => {
  expect(oui.search("*Juniper Systems*").length >= 1).toBeTruthy();
  expect(oui.search(["*Juniper Systems*"]).length >= 1).toBeTruthy();
  expect(oui.search(["*Juniper*", "*Systems*"]).length >= 1).toBeTruthy();
});

test("oui.update", async () => {
  expect(await Promise.all([
    oui.update(),
    oui.update({url: "https://linuxnet.ca/ieee/oui.txt"}),
    oui.update({url: "http://standards.ieee.org/develop/regauth/oui/oui.txt"}),
  ])).toEqual([undefined, undefined, undefined]);
});

afterAll(() => {
  nock.cleanAll();
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var sceneRelease = require('./');

describe('sceneRelease', function(){
  it('should parse Citizenfour example correctly', function() {
    var result = sceneRelease('Citizenfour.2014.720p.WEB-DL.AAC2.0.H.264-NOGRP');

    assert.equal(result.title, 'Citizenfour');
    assert.equal(result.original, 'Citizenfour.2014.720p.WEB-DL.AAC2.0.H.264-NOGRP');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'NOGRP');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'WEB-DL');

    assert.equal(result.video, 'H.264');
    assert.equal(result.audio, 'AAC2.0');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse The Raid 2 example correctly', function() {
    var result = sceneRelease('The.Raid.2.2014.BluRay.720p.DTS.x264-CHD');

    assert.equal(result.title, 'The Raid 2');
    assert.equal(result.original, 'The.Raid.2.2014.BluRay.720p.DTS.x264-CHD');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'CHD');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, 'DTS');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse Gravity example correctly', function() {
    var result = sceneRelease('Gravity.2013.1080p.BluRay.x264-SPARKS');

    assert.equal(result.title, 'Gravity');
    assert.equal(result.original, 'Gravity.2013.1080p.BluRay.x264-SPARKS');
    assert.equal(result.year, '2013');
    assert.equal(result.group, 'SPARKS');

    assert.equal(result.resolution, '1080p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse The Lego Movie example correctly', function() {
    var result = sceneRelease('The.Lego.Movie.2014.3D.COMPLETE.BLURAY-BAKED');

    assert.equal(result.title, 'The Lego Movie');
    assert.equal(result.original, 'The.Lego.Movie.2014.3D.COMPLETE.BLURAY-BAKED');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'BAKED');

    assert.equal(result.resolution, void 0);
    assert.equal(result.type, 'BLURAY');

    assert.equal(result.video, void 0);
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags[0], 'COMPLETE');
    assert.equal(result.edition, '3D');
    assert.equal(result.release, void 0);
  });

  it('should parse Thor: The Dark World example correctly', function() {
    var result = sceneRelease('Thor.The.Dark.World.3D.2013.MULTi.COMPLETE.BLURAY-iND');

    assert.equal(result.title, 'Thor The Dark World');
    assert.equal(result.original, 'Thor.The.Dark.World.3D.2013.MULTi.COMPLETE.BLURAY-iND');
    assert.equal(result.year, '2013');
    assert.equal(result.group, 'iND');

    assert.equal(result.resolution, void 0);
    assert.equal(result.type, 'BLURAY');

    assert.equal(result.video, void 0);
    assert.equal(result.audio, void 0);

    assert.equal(result.language, 'MULTi');
    assert.equal(result.tags[0], 'COMPLETE');
    assert.equal(result.edition, '3D');
    assert.equal(result.release, void 0);
  });

  it('should parse Veronica Mars french language example correctly', function() {
    var result = sceneRelease('Veronica.Mars.2014.LIMITED.FRENCH.720p.BluRay.x264-PRiDEHD');

    assert.equal(result.title, 'Veronica Mars');
    assert.equal(result.original, 'Veronica.Mars.2014.LIMITED.FRENCH.720p.BluRay.x264-PRiDEHD');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'PRiDEHD');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, 'FRENCH');
    assert.equal(result.tags[0], 'LIMITED');
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse long title with The 100-Year-Old Man example correctly', function() {
    var result = sceneRelease('Hundraaringen.Som.Klev.Ut.Genom.Fonstret.Och.Forsvann.2013.DiRFiX.SWEDiSH.1080p.BluRay.x264-GNiSTOR');

    assert.equal(result.title, 'Hundraaringen Som Klev Ut Genom Fonstret Och Forsvann');
    assert.equal(result.original, 'Hundraaringen.Som.Klev.Ut.Genom.Fonstret.Och.Forsvann.2013.DiRFiX.SWEDiSH.1080p.BluRay.x264-GNiSTOR');
    assert.equal(result.year, '2013');
    assert.equal(result.group, 'GNiSTOR');

    assert.equal(result.resolution, '1080p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, 'SWEDiSH');
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, 'DiRFiX');
  });

  it('should parse title with a year in the beginning, like 2001: A Space Odyssey', function() {
    var result = sceneRelease('2001.A.Space.Odyssey.1968.iNTERNAL.1080p.BluRay.x264-MANNEKEPiS');

    assert.equal(result.title, '2001 A Space Odyssey');
    assert.equal(result.original, '2001.A.Space.Odyssey.1968.iNTERNAL.1080p.BluRay.x264-MANNEKEPiS');
    assert.equal(result.year, '1968');
    assert.equal(result.group, 'MANNEKEPiS');

    assert.equal(result.resolution, '1080p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags[0], 'iNTERNAL');
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse Greys Anatomy TV episode example with whitespace correctly', function() {
    var result = sceneRelease('Greys Anatomy S11E12 720p WEB-DL DD5 1 H 264-NTb');

    assert.equal(result.title, 'Greys Anatomy S11E12');
    assert.equal(result.original, 'Greys Anatomy S11E12 720p WEB-DL DD5 1 H 264-NTb');
    assert.equal(result.year, void 0);
    assert.equal(result.group, 'NTb');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'WEB-DL');

    assert.equal(result.video, 'H 264');
    assert.equal(result.audio, 'DD5 1');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse House of Cards TV episode example with NF tag correctly', function() {
    var result = sceneRelease('House.of.Cards.2013.S03E01.720p.NF.WEBRip.DD5.1.x264-NTb');

    assert.equal(result.title, 'House of Cards S03E01');
    assert.equal(result.original, 'House.of.Cards.2013.S03E01.720p.NF.WEBRip.DD5.1.x264-NTb');
    assert.equal(result.year, "2013");
    assert.equal(result.group, 'NTb');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'WEBRip');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, 'DD5.1');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, 'NF');
    assert.equal(result.release, void 0);
  });

  it('should parse What If movie example with EXTENDED CUT tag', function() {
    var result = sceneRelease('What.If.2013.Extended.Cut.DVDRip.x264-EXViD');

    assert.equal(result.title, 'What If');
    assert.equal(result.original, 'What.If.2013.Extended.Cut.DVDRip.x264-EXViD');
    assert.equal(result.year, "2013");
    assert.equal(result.group, 'EXViD');

    assert.equal(result.resolution, void 0);
    assert.equal(result.type, 'DVDRip');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, 'Extended Cut');
    assert.equal(result.release, void 0);
  });
});
<commit_msg>Create unit test spec example with READ.NFO and NTSC tags<commit_after>'use strict';

var assert = require('assert');
var sceneRelease = require('./');

describe('sceneRelease', function(){
  it('should parse Citizenfour example correctly', function() {
    var result = sceneRelease('Citizenfour.2014.720p.WEB-DL.AAC2.0.H.264-NOGRP');

    assert.equal(result.title, 'Citizenfour');
    assert.equal(result.original, 'Citizenfour.2014.720p.WEB-DL.AAC2.0.H.264-NOGRP');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'NOGRP');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'WEB-DL');

    assert.equal(result.video, 'H.264');
    assert.equal(result.audio, 'AAC2.0');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse The Raid 2 example correctly', function() {
    var result = sceneRelease('The.Raid.2.2014.BluRay.720p.DTS.x264-CHD');

    assert.equal(result.title, 'The Raid 2');
    assert.equal(result.original, 'The.Raid.2.2014.BluRay.720p.DTS.x264-CHD');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'CHD');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, 'DTS');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse Gravity example correctly', function() {
    var result = sceneRelease('Gravity.2013.1080p.BluRay.x264-SPARKS');

    assert.equal(result.title, 'Gravity');
    assert.equal(result.original, 'Gravity.2013.1080p.BluRay.x264-SPARKS');
    assert.equal(result.year, '2013');
    assert.equal(result.group, 'SPARKS');

    assert.equal(result.resolution, '1080p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse The Lego Movie example correctly', function() {
    var result = sceneRelease('The.Lego.Movie.2014.3D.COMPLETE.BLURAY-BAKED');

    assert.equal(result.title, 'The Lego Movie');
    assert.equal(result.original, 'The.Lego.Movie.2014.3D.COMPLETE.BLURAY-BAKED');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'BAKED');

    assert.equal(result.resolution, void 0);
    assert.equal(result.type, 'BLURAY');

    assert.equal(result.video, void 0);
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags[0], 'COMPLETE');
    assert.equal(result.edition, '3D');
    assert.equal(result.release, void 0);
  });

  it('should parse Thor: The Dark World example correctly', function() {
    var result = sceneRelease('Thor.The.Dark.World.3D.2013.MULTi.COMPLETE.BLURAY-iND');

    assert.equal(result.title, 'Thor The Dark World');
    assert.equal(result.original, 'Thor.The.Dark.World.3D.2013.MULTi.COMPLETE.BLURAY-iND');
    assert.equal(result.year, '2013');
    assert.equal(result.group, 'iND');

    assert.equal(result.resolution, void 0);
    assert.equal(result.type, 'BLURAY');

    assert.equal(result.video, void 0);
    assert.equal(result.audio, void 0);

    assert.equal(result.language, 'MULTi');
    assert.equal(result.tags[0], 'COMPLETE');
    assert.equal(result.edition, '3D');
    assert.equal(result.release, void 0);
  });

  it('should parse Veronica Mars french language example correctly', function() {
    var result = sceneRelease('Veronica.Mars.2014.LIMITED.FRENCH.720p.BluRay.x264-PRiDEHD');

    assert.equal(result.title, 'Veronica Mars');
    assert.equal(result.original, 'Veronica.Mars.2014.LIMITED.FRENCH.720p.BluRay.x264-PRiDEHD');
    assert.equal(result.year, '2014');
    assert.equal(result.group, 'PRiDEHD');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, 'FRENCH');
    assert.equal(result.tags[0], 'LIMITED');
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse long title with The 100-Year-Old Man example correctly', function() {
    var result = sceneRelease('Hundraaringen.Som.Klev.Ut.Genom.Fonstret.Och.Forsvann.2013.DiRFiX.SWEDiSH.1080p.BluRay.x264-GNiSTOR');

    assert.equal(result.title, 'Hundraaringen Som Klev Ut Genom Fonstret Och Forsvann');
    assert.equal(result.original, 'Hundraaringen.Som.Klev.Ut.Genom.Fonstret.Och.Forsvann.2013.DiRFiX.SWEDiSH.1080p.BluRay.x264-GNiSTOR');
    assert.equal(result.year, '2013');
    assert.equal(result.group, 'GNiSTOR');

    assert.equal(result.resolution, '1080p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, 'SWEDiSH');
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, 'DiRFiX');
  });

  it('should parse title with a year in the beginning, like 2001: A Space Odyssey', function() {
    var result = sceneRelease('2001.A.Space.Odyssey.1968.iNTERNAL.1080p.BluRay.x264-MANNEKEPiS');

    assert.equal(result.title, '2001 A Space Odyssey');
    assert.equal(result.original, '2001.A.Space.Odyssey.1968.iNTERNAL.1080p.BluRay.x264-MANNEKEPiS');
    assert.equal(result.year, '1968');
    assert.equal(result.group, 'MANNEKEPiS');

    assert.equal(result.resolution, '1080p');
    assert.equal(result.type, 'BluRay');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags[0], 'iNTERNAL');
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse Greys Anatomy TV episode example with whitespace correctly', function() {
    var result = sceneRelease('Greys Anatomy S11E12 720p WEB-DL DD5 1 H 264-NTb');

    assert.equal(result.title, 'Greys Anatomy S11E12');
    assert.equal(result.original, 'Greys Anatomy S11E12 720p WEB-DL DD5 1 H 264-NTb');
    assert.equal(result.year, void 0);
    assert.equal(result.group, 'NTb');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'WEB-DL');

    assert.equal(result.video, 'H 264');
    assert.equal(result.audio, 'DD5 1');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, void 0);
  });

  it('should parse House of Cards TV episode example with NF tag correctly', function() {
    var result = sceneRelease('House.of.Cards.2013.S03E01.720p.NF.WEBRip.DD5.1.x264-NTb');

    assert.equal(result.title, 'House of Cards S03E01');
    assert.equal(result.original, 'House.of.Cards.2013.S03E01.720p.NF.WEBRip.DD5.1.x264-NTb');
    assert.equal(result.year, "2013");
    assert.equal(result.group, 'NTb');

    assert.equal(result.resolution, '720p');
    assert.equal(result.type, 'WEBRip');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, 'DD5.1');

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, 'NF');
    assert.equal(result.release, void 0);
  });

  it('should parse What If movie example with EXTENDED CUT tag', function() {
    var result = sceneRelease('What.If.2013.Extended.Cut.DVDRip.x264-EXViD');

    assert.equal(result.title, 'What If');
    assert.equal(result.original, 'What.If.2013.Extended.Cut.DVDRip.x264-EXViD');
    assert.equal(result.year, "2013");
    assert.equal(result.group, 'EXViD');

    assert.equal(result.resolution, void 0);
    assert.equal(result.type, 'DVDRip');

    assert.equal(result.video, 'x264');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, 'Extended Cut');
    assert.equal(result.release, void 0);
  });

  it('should parse example with READ.NFO tag', function() {
    var result = sceneRelease('The.Hobbit.The.Battle.Of.The.Five.Armies.2014.READ.NFO.NTSC.DVDR-KART3LDVD');

    assert.equal(result.title, 'The Hobbit The Battle Of The Five Armies');
    assert.equal(result.original, 'The.Hobbit.The.Battle.Of.The.Five.Armies.2014.READ.NFO.NTSC.DVDR-KART3LDVD');
    assert.equal(result.year, "2014");
    assert.equal(result.group, 'KART3LDVD');

    assert.equal(result.resolution, void 0);
    assert.equal(result.type, 'DVDR');

    assert.equal(result.video, 'NTSC');
    assert.equal(result.audio, void 0);

    assert.equal(result.language, void 0);
    assert.equal(result.tags, null);
    assert.equal(result.edition, void 0);
    assert.equal(result.release, 'READ NFO');
  });
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-17 10:13:31<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>