<commit_before>
import API from '../classes/API'

class Epics extends API {
  static get presenter () {
    class EpicsPresenter extends API.presenter {}
    EpicsPresenter.prototype.type = 'epics'
    return EpicsPresenter
  }
}

module.exports =  Epics
<commit_msg>Implement Epics endpoint<commit_after>
import API, {
  GET,
  PUT,
  POST,
  DELETE,
  parameters,
  authenticated,
  permissions,
  required
} from '../classes/API'
import websocket from '../classes/WebSocket'
import { Epic } from '../db'
import Query from '../query'
import {NotFoundAPIError} from '../classes/APIError'

class Epics extends API {
  @GET('/epics')
  @websocket('epics', 'search')
  @authenticated
  @permissions('epic.read')
  async search (ctx) {
    let epicsQuery = new Query(ctx.query, ctx)
    let result = await Epic.findAndCountAll(epicsQuery.toSequelize)
    return Epics.presenter.render(result.rows, API.meta(result, epicsQuery))
  }

  @GET('/epics/:id')
  @websocket('epics', 'read')
  @authenticated
  @permissions('epic.read')
  @parameters('id')
  async read (ctx) {
    let epicsQuery = new Query({id: ctx.params.id}, ctx)
    let result = await Epic.findAndCountAll(epicsQuery.toSequelize)

    return Epics.presenter.render(result.rows, API.meta(result, epicsQuery))
  }

  @POST('/epics')
  @websocket('epics', 'create')
  @authenticated
  @permissions('epic.write')
  @required('notes', 'ratId')
  async create (ctx) {
    let result = await Epic.create(ctx.data)

    ctx.response.status = 201
    return Epics.presenter.render(result, API.meta(result))
  }

  @PUT('/epics/:id')
  @websocket('epics', 'update')
  @authenticated
  @permissions('epic.write')
  async update (ctx) {
    let epic = await Epic.findOne({
      where: { id: ctx.params.id }
    })

    if (!epic) {
      throw new NotFoundAPIError({ parameter: 'id' })
    }

    await Epic.update(ctx.data, {
      where: {
        id: ctx.params.id
      }
    })

    let epicsQuery = new Query({id: ctx.params.id}, ctx)
    let result = await Epic.findAndCountAll(epicsQuery.toSequelize)
    return Epics.presenter.render(result.rows, API.meta(result, epicsQuery))
  }

  @DELETE('/epics/:id')
  @websocket('epics', 'delete')
  @authenticated
  @permissions('epic.delete')
  async delete (ctx) {
    let epic = await Epic.findOne({
      where: {
        id: ctx.params.id
      }
    })

    if (!epic) {
      throw new NotFoundAPIError({ parameter: 'id' })
    }

    epic.destroy()
    ctx.status = 204
    return true
  }

  static get presenter () {
    class EpicsPresenter extends API.presenter {}
    EpicsPresenter.prototype.type = 'epics'
    return EpicsPresenter
  }
}

module.exports =  Epics
<|endoftext|>


<commit_before>const router = require('express').Router();
const uuid = require('node-uuid');
const path = require('path');
const fs = require('fs');
const db = require('../middleware/db');

var store;

if(global.config.FileStore && global.config.FileStore.Type=='S3'){
  store = require('../middleware/s3-filestore');
}
else{
  store = require('../middleware/local-filestore');
}

/**
* Saves Metadata of a file and returns a new endpoint for content upload
**/
router.put('/upload/', global.jsonParser, function(req, res){
  var body = req.body;
  if(!body || !body.Filename || !body.Size){
    return res.send({Success: false, Error: 'No filename!'});
  }
  var fileid = uuid.v4();
  db.query('Insert into `filemetadata` (`FileID`, `Filename`, `Owner`, `Size`) VALUES (?, ?, ?, ?);', [fileid, body.Filename, res.locals.user.ID, body.Size], function(err, result){
    if(err){
      console.log('Error saving file metadata', err);
      return res.send({Success: false, Error: 'Internal Server Error'});
    }
    console.log('Beginning upload of', body.Filename);
    return res.send({Success: true, EndpointID: fileid});
  });
});

router.put('/upload/:fileid', function(req, res){
  var body = req.body;
  var fileid = req.params.fileid;
  if(!body || !body.Data){
    return res.send({Success: false, Error: 'Missing File Data!'});
  }
  // get path and storage type from config
  // default to project root/files
  db.query('Select * from `filemetadata` where `Owner`=? and `FileID`=?;', [res.locals.user.ID, req.params.fileid], function(err, results){
    if(err){
      console.log('Error validating file id', err);
      return res.send({Success: false, Error: 'Internal Server Error'});
    }
    if(results.length<1){
      return res.send({Success: false, Error: 'No such file ID'});
    }
    store(results[0].Filename, results[0].Size, body.Data, function(err, currsize){
      if(err){
        console.log(err);
      }
      return res.send({Success: !(!!err), LastByte:currsize, Error: err});
    });
  });
});

module.exports = router;
<commit_msg>store and retrieve data using streams<commit_after>const router = require('express').Router();
const uuid = require('node-uuid');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const zlib = require('zlib');
const db = require('../middleware/db');

var store;

if(global.config.FileStore && global.config.FileStore.Type=='S3'){
  store = require('../middleware/s3-filestore');
}
else{
  store = require('../middleware/local-filestore');
}

/**
* Saves Metadata of a file and returns a new endpoint for content upload
**/
router.put('/upload/', global.jsonParser, function(req, res){
  var body = req.body;
  if(!body || !body.Filename || !body.Size){
    return res.send({Success: false, Error: 'No filename!'});
  }
  var fileid = uuid.v4();
  db.query('Insert into `filemetadata` (`FileID`, `Filename`, `Owner`, `Size`) VALUES (?, ?, ?, ?);', [fileid, body.Filename, res.locals.user.ID, body.Size], function(err, result){
    if(err){
      console.log('Error saving file metadata', err);
      return res.send({Success: false, Error: 'Internal Server Error'});
    }
    console.log('Beginning upload of', body.Filename);
    return res.send({Success: true, EndpointID: fileid});
  });
});

router.put('/upload/:fileid', function(req, res){
  var fileid = req.params.fileid;
  db.query('Select * from `filemetadata` where `Owner`=? and `FileID`=?;', [res.locals.user.ID, fileid], function(err, results){
    if(err){
      console.log('Error validating file id', err);
      return res.send({Success: false, Error: 'Internal Server Error'});
    }
    if(results.length<1){
      return res.send({Success: false, Error: 'No such file ID'});
    }
    const cipher = crypto.createCipher('aes256', new Buffer(global.config.StorageKey, 'base64'));
    var pl = req.pipe(zlib.createGzip()).pipe(cipher);
    store.store(fileid, pl, function(err){
      if(err){
        return res.send({Success: false, Error: err});
      }
        return res.send({Success: true});
    });
  });
});

router.get('/:fileid', function(req, res){
  var fileid = req.params.fileid;
  db.query('Select * from `filemetadata` where `Owner`=? and `FileID`=?;', [res.locals.user.ID, fileid], function(err, results){
    if(err){
      console.log('Error validating file id', err);
      return res.send({Success: false, Error: 'Internal Server Error'});
    }
    if(results.length<1){
      return res.send({Success: false, Error: 'No such file ID'});
    }
    const decipher = crypto.createDecipher('aes256', new Buffer(global.config.StorageKey, 'base64'));
    store.get(fileid).pipe(decipher).pipe(zlib.createGunzip()).pipe(res).once('close', function(){
      return res.end();
    });
  });
});

module.exports = router;
<|endoftext|>


<commit_before>import { resolve as resolvePath } from 'path';
import debug from 'debug';
import Promise from 'pinkie';
import promisifyEvent from 'promisify-event';
import mapReverse from 'map-reverse';
import { EventEmitter } from 'events';
import { flattenDeep as flatten, pull as remove } from 'lodash';
import Bootstrapper from './bootstrapper';
import Reporter from '../reporter';
import Task from './task';
import { GeneralError } from '../errors/runtime';
import MESSAGE from '../errors/runtime/message';
import { assertType, is } from '../errors/runtime/type-assertions';
import renderForbiddenCharsList from '../errors/render-forbidden-chars-list';
import detectFFMPEG from '../utils/detect-ffmpeg';
import checkFilePath from '../utils/check-file-path';
import { addRunningTest, removeRunningTest, startHandlingTestErrors, stopHandlingTestErrors } from '../utils/handle-errors';
import OPTION_NAMES from '../configuration/option-names';
import FlagList from '../utils/flag-list';
import prepareReporters from '../utils/prepare-reporters';

const DEBUG_LOGGER = debug('testcafe:runner');

export default class Runner extends EventEmitter {
    constructor (proxy, browserConnectionGateway, configuration) {
        super();

        this.proxy               = proxy;
        this.bootstrapper        = this._createBootstrapper(browserConnectionGateway);
        this.pendingTaskPromises = [];
        this.configuration       = configuration;
        this.isCli               = false;

        this.apiMethodWasCalled = new FlagList({
            initialFlagValue: false,
            flags:            [OPTION_NAMES.src, OPTION_NAMES.browsers, OPTION_NAMES.reporter]
        });
    }

    _createBootstrapper (browserConnectionGateway) {
        return new Bootstrapper(browserConnectionGateway);
    }

    _disposeBrowserSet (browserSet) {
        return browserSet.dispose().catch(e => DEBUG_LOGGER(e));
    }

    _disposeReporters (reporters) {
        return Promise.all(reporters.map(reporter => reporter.dispose().catch(e => DEBUG_LOGGER(e))));
    }

    _disposeTestedApp (testedApp) {
        return testedApp ? testedApp.kill().catch(e => DEBUG_LOGGER(e)) : Promise.resolve();
    }

    async _disposeTaskAndRelatedAssets (task, browserSet, reporters, testedApp) {
        task.abort();
        task.clearListeners();

        await this._disposeAssets(browserSet, reporters, testedApp);
    }

    _disposeAssets (browserSet, reporters, testedApp) {
        return Promise.all([
            this._disposeBrowserSet(browserSet),
            this._disposeReporters(reporters),
            this._disposeTestedApp(testedApp)
        ]);
    }

    _prepareArrayParameter (array) {
        array = flatten(array);

        if (this.isCli)
            return array.length === 0 ? void 0 : array;

        return array;
    }

    _createCancelablePromise (taskPromise) {
        const promise           = taskPromise.then(({ completionPromise }) => completionPromise);
        const removeFromPending = () => remove(this.pendingTaskPromises, promise);

        promise
            .then(removeFromPending)
            .catch(removeFromPending);

        promise.cancel = () => taskPromise
            .then(({ cancelTask }) => cancelTask())
            .then(removeFromPending);

        this.pendingTaskPromises.push(promise);
        return promise;
    }

    // Run task
    _getFailedTestCount (task, reporter) {
        let failedTestCount = reporter.testCount - reporter.passed;

        if (task.opts.stopOnFirstFail && !!failedTestCount)
            failedTestCount = 1;

        return failedTestCount;
    }

    async _getTaskResult (task, browserSet, reporters, testedApp) {
        task.on('browser-job-done', job => browserSet.releaseConnection(job.browserConnection));

        const browserSetErrorPromise = promisifyEvent(browserSet, 'error');

        const taskDonePromise = task.once('done')
            .then(() => browserSetErrorPromise.cancel());

        const promises = [
            taskDonePromise,
            browserSetErrorPromise
        ];

        if (testedApp)
            promises.push(testedApp.errorPromise);

        try {
            await Promise.race(promises);
        }
        catch (err) {
            await this._disposeTaskAndRelatedAssets(task, browserSet, reporters, testedApp);

            throw err;
        }

        await this._disposeAssets(browserSet, reporters, testedApp);

        return this._getFailedTestCount(task, reporters[0]);
    }

    _createTask (tests, browserConnectionGroups, proxy, opts) {
        return new Task(tests, browserConnectionGroups, proxy, opts);
    }

    _runTask (reporterPlugins, browserSet, tests, testedApp) {
        let completed           = false;
        const task              = this._createTask(tests, browserSet.browserConnectionGroups, this.proxy, this.configuration.getOptions());
        const reporters         = reporterPlugins.map(reporter => new Reporter(reporter.plugin, task, reporter.outStream));
        const completionPromise = this._getTaskResult(task, browserSet, reporters, testedApp);

        task.on('start', startHandlingTestErrors);

        if (!this.configuration.getOption(OPTION_NAMES.skipUncaughtErrors)) {
            task.once('test-run-start', addRunningTest);
            task.once('test-run-done', removeRunningTest);
        }

        task.on('done', stopHandlingTestErrors);

        const setCompleted = () => {
            completed = true;
        };

        completionPromise
            .then(setCompleted)
            .catch(setCompleted);

        const cancelTask = async () => {
            if (!completed)
                await this._disposeTaskAndRelatedAssets(task, browserSet, reporters, testedApp);
        };

        return { completionPromise, cancelTask };
    }

    _registerAssets (assets) {
        assets.forEach(asset => this.proxy.GET(asset.path, asset.info));
    }

    _validateSpeedOption () {
        const speed = this.configuration.getOption(OPTION_NAMES.speed);

        if (speed === void 0)
            return;

        if (typeof speed !== 'number' || isNaN(speed) || speed < 0.01 || speed > 1)
            throw new GeneralError(MESSAGE.invalidSpeedValue);
    }

    _validateConcurrencyOption () {
        const concurrency = this.configuration.getOption(OPTION_NAMES.concurrency);

        if (concurrency === void 0)
            return;

        if (typeof concurrency !== 'number' || isNaN(concurrency) || concurrency < 1)
            throw new GeneralError(MESSAGE.invalidConcurrencyFactor);
    }

    _validateProxyBypassOption () {
        let proxyBypass = this.configuration.getOption(OPTION_NAMES.proxyBypass);

        if (proxyBypass === void 0)
            return;

        assertType([ is.string, is.array ], null, '"proxyBypass" argument', proxyBypass);

        if (typeof proxyBypass === 'string')
            proxyBypass = [proxyBypass];

        proxyBypass = proxyBypass.reduce((arr, rules) => {
            assertType(is.string, null, '"proxyBypass" argument', rules);

            return arr.concat(rules.split(','));
        }, []);

        this.configuration.mergeOptions({ proxyBypass });
    }

    _validateScreenshotOptions () {
        const screenshotPath        = this.configuration.getOption(OPTION_NAMES.screenshotPath);
        const screenshotPathPattern = this.configuration.getOption(OPTION_NAMES.screenshotPathPattern);

        if (screenshotPath) {
            this._validateScreenshotPath(screenshotPath, 'screenshots base directory path');

            this.configuration.mergeOptions({ [OPTION_NAMES.screenshotPath]: resolvePath(screenshotPath) });
        }

        if (screenshotPathPattern)
            this._validateScreenshotPath(screenshotPathPattern, 'screenshots path pattern');

        if (!screenshotPath && screenshotPathPattern)
            throw new GeneralError(MESSAGE.cantUseScreenshotPathPatternWithoutBaseScreenshotPathSpecified);
    }

    async _validateVideoOptions () {
        const videoPath            = this.configuration.getOption(OPTION_NAMES.videoPath);
        const videoEncodingOptions = this.configuration.getOption(OPTION_NAMES.videoEncodingOptions);

        let videoOptions = this.configuration.getOption(OPTION_NAMES.videoOptions);

        if (!videoPath) {
            if (videoOptions || videoEncodingOptions)
                throw new GeneralError(MESSAGE.cannotSetVideoOptionsWithoutBaseVideoPathSpecified);

            return;
        }

        this.configuration.mergeOptions({ [OPTION_NAMES.videoPath]: resolvePath(videoPath) });

        if (!videoOptions) {
            videoOptions = {};

            this.configuration.mergeOptions({ [OPTION_NAMES.videoOptions]: videoOptions });
        }

        if (videoOptions.ffmpegPath)
            videoOptions.ffmpegPath = resolvePath(videoOptions.ffmpegPath);
        else
            videoOptions.ffmpegPath = await detectFFMPEG();

        if (!videoOptions.ffmpegPath)
            throw new GeneralError(MESSAGE.cannotFindFFMPEG);
    }

    async _validateRunOptions () {
        this._validateScreenshotOptions();
        await this._validateVideoOptions();
        this._validateSpeedOption();
        this._validateConcurrencyOption();
        this._validateProxyBypassOption();
    }

    _createRunnableConfiguration () {
        return this.bootstrapper.createRunnableConfiguration();
    }

    _validateScreenshotPath (screenshotPath, pathType) {
        const forbiddenCharsList = checkFilePath(screenshotPath);

        if (forbiddenCharsList.length)
            throw new GeneralError(MESSAGE.forbiddenCharatersInScreenshotPath, screenshotPath, pathType, renderForbiddenCharsList(forbiddenCharsList));
    }

    _setBootstrapperOptions () {
        this.bootstrapper.sources      = this.configuration.getOption(OPTION_NAMES.src) || this.bootstrapper.sources;
        this.bootstrapper.browsers     = this.configuration.getOption(OPTION_NAMES.browsers) || this.bootstrapper.browsers;
        this.bootstrapper.concurrency  = this.configuration.getOption(OPTION_NAMES.concurrency);
        this.bootstrapper.appCommand   = this.configuration.getOption(OPTION_NAMES.appCommand) || this.bootstrapper.appCommand;
        this.bootstrapper.appInitDelay = this.configuration.getOption(OPTION_NAMES.appInitDelay);
        this.bootstrapper.filter       = this.configuration.getOption(OPTION_NAMES.filter) || this.bootstrapper.filter;
        this.bootstrapper.reporters    = this.configuration.getOption(OPTION_NAMES.reporter) || this.bootstrapper.reporters;
    }

    // API
    embeddingOptions (opts) {
        const { assets, TestRunCtor } = opts;

        this._registerAssets(assets);
        this.configuration.mergeOptions({ TestRunCtor });

        return this;
    }

    src (...sources) {
        if (this.apiMethodWasCalled.src)
            throw new GeneralError(MESSAGE.multipleAPIMethodCallForbidden, OPTION_NAMES.src);

        sources = this._prepareArrayParameter(sources);
        this.configuration.mergeOptions({ [OPTION_NAMES.src]: sources });

        this.apiMethodWasCalled.src = true;

        return this;
    }

    browsers (...browsers) {
        if (this.apiMethodWasCalled.browsers)
            throw new GeneralError(MESSAGE.multipleAPIMethodCallForbidden, OPTION_NAMES.browsers);

        browsers = this._prepareArrayParameter(browsers);
        this.configuration.mergeOptions({ browsers });

        this.apiMethodWasCalled.browsers = true;

        return this;
    }

    concurrency (concurrency) {
        this.configuration.mergeOptions({ concurrency });

        return this;
    }

    reporter (name, fileOrStream) {
        if (this.apiMethodWasCalled.reporter)
            throw new GeneralError(MESSAGE.multipleAPIMethodCallForbidden, OPTION_NAMES.reporter);

        let reporters = prepareReporters(name, fileOrStream);

        reporters = this._prepareArrayParameter(reporters);

        this.configuration.mergeOptions({ [OPTION_NAMES.reporter]: reporters });

        this.apiMethodWasCalled.reporter = true;

        return this;
    }

    filter (filter) {
        this.configuration.mergeOptions({ filter });

        return this;
    }

    useProxy (proxy, proxyBypass) {
        this.configuration.mergeOptions({ proxy, proxyBypass });

        return this;
    }

    screenshots (path, takeOnFails, pattern) {
        this.configuration.mergeOptions({
            [OPTION_NAMES.screenshotPath]:         path,
            [OPTION_NAMES.takeScreenshotsOnFails]: takeOnFails,
            [OPTION_NAMES.screenshotPathPattern]:  pattern
        });

        return this;
    }

    video (path, options, encodingOptions) {
        this.configuration.mergeOptions({
            [OPTION_NAMES.videoPath]:            path,
            [OPTION_NAMES.videoOptions]:         options,
            [OPTION_NAMES.videoEncodingOptions]: encodingOptions
        });

        return this;
    }

    startApp (command, initDelay) {
        this.configuration.mergeOptions({
            [OPTION_NAMES.appCommand]:   command,
            [OPTION_NAMES.appInitDelay]: initDelay
        });

        return this;
    }

    run (options = {}) {
        this.apiMethodWasCalled.reset();

        const {
            skipJsErrors,
            disablePageReloads,
            quarantineMode,
            debugMode,
            selectorTimeout,
            assertionTimeout,
            pageLoadTimeout,
            speed,
            debugOnFail,
            skipUncaughtErrors,
            stopOnFirstFail
        } = options;

        this.configuration.mergeOptions({
            skipJsErrors:       skipJsErrors,
            disablePageReloads: disablePageReloads,
            quarantineMode:     quarantineMode,
            debugMode:          debugMode,
            debugOnFail:        debugOnFail,
            selectorTimeout:    selectorTimeout,
            assertionTimeout:   assertionTimeout,
            pageLoadTimeout:    pageLoadTimeout,
            speed:              speed,
            skipUncaughtErrors: skipUncaughtErrors,
            stopOnFirstFail:    stopOnFirstFail
        });

        this.configuration.prepare();
        this.configuration.notifyAboutOverridenOptions();

        this._setBootstrapperOptions();

        const runTaskPromise = Promise.resolve()
            .then(() => this._validateRunOptions())
            .then(() => this._createRunnableConfiguration())
            .then(({ reporterPlugins, browserSet, tests, testedApp }) => {
                this.emit('done-bootstrapping');

                return this._runTask(reporterPlugins, browserSet, tests, testedApp);
            });

        return this._createCancelablePromise(runTaskPromise);
    }

    async stop () {
        // NOTE: When taskPromise is cancelled, it is removed from
        // the pendingTaskPromises array, which leads to shifting indexes
        // towards the beginning. So, we must copy the array in order to iterate it,
        // or we can perform iteration from the end to the beginning.
        const cancellationPromises = mapReverse(this.pendingTaskPromises, taskPromise => taskPromise.cancel());

        await Promise.all(cancellationPromises);
    }
}
<commit_msg>fix live (closes #3366) (#3367)<commit_after>import { resolve as resolvePath } from 'path';
import debug from 'debug';
import Promise from 'pinkie';
import promisifyEvent from 'promisify-event';
import mapReverse from 'map-reverse';
import { EventEmitter } from 'events';
import { flattenDeep as flatten, pull as remove } from 'lodash';
import Bootstrapper from './bootstrapper';
import Reporter from '../reporter';
import Task from './task';
import { GeneralError } from '../errors/runtime';
import MESSAGE from '../errors/runtime/message';
import { assertType, is } from '../errors/runtime/type-assertions';
import renderForbiddenCharsList from '../errors/render-forbidden-chars-list';
import detectFFMPEG from '../utils/detect-ffmpeg';
import checkFilePath from '../utils/check-file-path';
import { addRunningTest, removeRunningTest, startHandlingTestErrors, stopHandlingTestErrors } from '../utils/handle-errors';
import OPTION_NAMES from '../configuration/option-names';
import FlagList from '../utils/flag-list';
import prepareReporters from '../utils/prepare-reporters';

const DEBUG_LOGGER = debug('testcafe:runner');

export default class Runner extends EventEmitter {
    constructor (proxy, browserConnectionGateway, configuration) {
        super();

        this.proxy               = proxy;
        this.bootstrapper        = this._createBootstrapper(browserConnectionGateway);
        this.pendingTaskPromises = [];
        this.configuration       = configuration;
        this.isCli               = false;

        this.apiMethodWasCalled = new FlagList({
            initialFlagValue: false,
            flags:            [OPTION_NAMES.src, OPTION_NAMES.browsers, OPTION_NAMES.reporter]
        });
    }

    _createBootstrapper (browserConnectionGateway) {
        return new Bootstrapper(browserConnectionGateway);
    }

    _disposeBrowserSet (browserSet) {
        return browserSet.dispose().catch(e => DEBUG_LOGGER(e));
    }

    _disposeReporters (reporters) {
        return Promise.all(reporters.map(reporter => reporter.dispose().catch(e => DEBUG_LOGGER(e))));
    }

    _disposeTestedApp (testedApp) {
        return testedApp ? testedApp.kill().catch(e => DEBUG_LOGGER(e)) : Promise.resolve();
    }

    async _disposeTaskAndRelatedAssets (task, browserSet, reporters, testedApp) {
        task.abort();
        task.clearListeners();

        await this._disposeAssets(browserSet, reporters, testedApp);
    }

    _disposeAssets (browserSet, reporters, testedApp) {
        return Promise.all([
            this._disposeBrowserSet(browserSet),
            this._disposeReporters(reporters),
            this._disposeTestedApp(testedApp)
        ]);
    }

    _prepareArrayParameter (array) {
        array = flatten(array);

        if (this.isCli)
            return array.length === 0 ? void 0 : array;

        return array;
    }

    _createCancelablePromise (taskPromise) {
        const promise           = taskPromise.then(({ completionPromise }) => completionPromise);
        const removeFromPending = () => remove(this.pendingTaskPromises, promise);

        promise
            .then(removeFromPending)
            .catch(removeFromPending);

        promise.cancel = () => taskPromise
            .then(({ cancelTask }) => cancelTask())
            .then(removeFromPending);

        this.pendingTaskPromises.push(promise);
        return promise;
    }

    // Run task
    _getFailedTestCount (task, reporter) {
        let failedTestCount = reporter.testCount - reporter.passed;

        if (task.opts.stopOnFirstFail && !!failedTestCount)
            failedTestCount = 1;

        return failedTestCount;
    }

    async _getTaskResult (task, browserSet, reporters, testedApp) {
        task.on('browser-job-done', job => browserSet.releaseConnection(job.browserConnection));

        const browserSetErrorPromise = promisifyEvent(browserSet, 'error');

        const taskDonePromise = task.once('done')
            .then(() => browserSetErrorPromise.cancel());

        const promises = [
            taskDonePromise,
            browserSetErrorPromise
        ];

        if (testedApp)
            promises.push(testedApp.errorPromise);

        try {
            await Promise.race(promises);
        }
        catch (err) {
            await this._disposeTaskAndRelatedAssets(task, browserSet, reporters, testedApp);

            throw err;
        }

        await this._disposeAssets(browserSet, reporters, testedApp);

        return this._getFailedTestCount(task, reporters[0]);
    }

    _createTask (tests, browserConnectionGroups, proxy, opts) {
        return new Task(tests, browserConnectionGroups, proxy, opts);
    }

    _runTask (reporterPlugins, browserSet, tests, testedApp) {
        let completed           = false;
        const task              = this._createTask(tests, browserSet.browserConnectionGroups, this.proxy, this.configuration.getOptions());
        const reporters         = reporterPlugins.map(reporter => new Reporter(reporter.plugin, task, reporter.outStream));
        const completionPromise = this._getTaskResult(task, browserSet, reporters, testedApp);

        task.on('start', startHandlingTestErrors);

        if (!this.configuration.getOption(OPTION_NAMES.skipUncaughtErrors)) {
            task.once('test-run-start', addRunningTest);
            task.once('test-run-done', removeRunningTest);
        }

        task.on('done', stopHandlingTestErrors);

        const setCompleted = () => {
            completed = true;
        };

        completionPromise
            .then(setCompleted)
            .catch(setCompleted);

        const cancelTask = async () => {
            if (!completed)
                await this._disposeTaskAndRelatedAssets(task, browserSet, reporters, testedApp);
        };

        return { completionPromise, cancelTask };
    }

    _registerAssets (assets) {
        assets.forEach(asset => this.proxy.GET(asset.path, asset.info));
    }

    _validateSpeedOption () {
        const speed = this.configuration.getOption(OPTION_NAMES.speed);

        if (speed === void 0)
            return;

        if (typeof speed !== 'number' || isNaN(speed) || speed < 0.01 || speed > 1)
            throw new GeneralError(MESSAGE.invalidSpeedValue);
    }

    _validateConcurrencyOption () {
        const concurrency = this.configuration.getOption(OPTION_NAMES.concurrency);

        if (concurrency === void 0)
            return;

        if (typeof concurrency !== 'number' || isNaN(concurrency) || concurrency < 1)
            throw new GeneralError(MESSAGE.invalidConcurrencyFactor);
    }

    _validateProxyBypassOption () {
        let proxyBypass = this.configuration.getOption(OPTION_NAMES.proxyBypass);

        if (proxyBypass === void 0)
            return;

        assertType([ is.string, is.array ], null, '"proxyBypass" argument', proxyBypass);

        if (typeof proxyBypass === 'string')
            proxyBypass = [proxyBypass];

        proxyBypass = proxyBypass.reduce((arr, rules) => {
            assertType(is.string, null, '"proxyBypass" argument', rules);

            return arr.concat(rules.split(','));
        }, []);

        this.configuration.mergeOptions({ proxyBypass });
    }

    _validateScreenshotOptions () {
        const screenshotPath        = this.configuration.getOption(OPTION_NAMES.screenshotPath);
        const screenshotPathPattern = this.configuration.getOption(OPTION_NAMES.screenshotPathPattern);

        if (screenshotPath) {
            this._validateScreenshotPath(screenshotPath, 'screenshots base directory path');

            this.configuration.mergeOptions({ [OPTION_NAMES.screenshotPath]: resolvePath(screenshotPath) });
        }

        if (screenshotPathPattern)
            this._validateScreenshotPath(screenshotPathPattern, 'screenshots path pattern');

        if (!screenshotPath && screenshotPathPattern)
            throw new GeneralError(MESSAGE.cantUseScreenshotPathPatternWithoutBaseScreenshotPathSpecified);
    }

    async _validateVideoOptions () {
        const videoPath            = this.configuration.getOption(OPTION_NAMES.videoPath);
        const videoEncodingOptions = this.configuration.getOption(OPTION_NAMES.videoEncodingOptions);

        let videoOptions = this.configuration.getOption(OPTION_NAMES.videoOptions);

        if (!videoPath) {
            if (videoOptions || videoEncodingOptions)
                throw new GeneralError(MESSAGE.cannotSetVideoOptionsWithoutBaseVideoPathSpecified);

            return;
        }

        this.configuration.mergeOptions({ [OPTION_NAMES.videoPath]: resolvePath(videoPath) });

        if (!videoOptions) {
            videoOptions = {};

            this.configuration.mergeOptions({ [OPTION_NAMES.videoOptions]: videoOptions });
        }

        if (videoOptions.ffmpegPath)
            videoOptions.ffmpegPath = resolvePath(videoOptions.ffmpegPath);
        else
            videoOptions.ffmpegPath = await detectFFMPEG();

        if (!videoOptions.ffmpegPath)
            throw new GeneralError(MESSAGE.cannotFindFFMPEG);
    }

    async _validateRunOptions () {
        this._validateScreenshotOptions();
        await this._validateVideoOptions();
        this._validateSpeedOption();
        this._validateConcurrencyOption();
        this._validateProxyBypassOption();
    }

    _createRunnableConfiguration () {
        return this.bootstrapper.createRunnableConfiguration();
    }

    _validateScreenshotPath (screenshotPath, pathType) {
        const forbiddenCharsList = checkFilePath(screenshotPath);

        if (forbiddenCharsList.length)
            throw new GeneralError(MESSAGE.forbiddenCharatersInScreenshotPath, screenshotPath, pathType, renderForbiddenCharsList(forbiddenCharsList));
    }

    _setBootstrapperOptions () {
        this.configuration.prepare();
        this.configuration.notifyAboutOverridenOptions();

        this.bootstrapper.sources      = this.configuration.getOption(OPTION_NAMES.src) || this.bootstrapper.sources;
        this.bootstrapper.browsers     = this.configuration.getOption(OPTION_NAMES.browsers) || this.bootstrapper.browsers;
        this.bootstrapper.concurrency  = this.configuration.getOption(OPTION_NAMES.concurrency);
        this.bootstrapper.appCommand   = this.configuration.getOption(OPTION_NAMES.appCommand) || this.bootstrapper.appCommand;
        this.bootstrapper.appInitDelay = this.configuration.getOption(OPTION_NAMES.appInitDelay);
        this.bootstrapper.filter       = this.configuration.getOption(OPTION_NAMES.filter) || this.bootstrapper.filter;
        this.bootstrapper.reporters    = this.configuration.getOption(OPTION_NAMES.reporter) || this.bootstrapper.reporters;
    }

    // API
    embeddingOptions (opts) {
        const { assets, TestRunCtor } = opts;

        this._registerAssets(assets);
        this.configuration.mergeOptions({ TestRunCtor });

        return this;
    }

    src (...sources) {
        if (this.apiMethodWasCalled.src)
            throw new GeneralError(MESSAGE.multipleAPIMethodCallForbidden, OPTION_NAMES.src);

        sources = this._prepareArrayParameter(sources);
        this.configuration.mergeOptions({ [OPTION_NAMES.src]: sources });

        this.apiMethodWasCalled.src = true;

        return this;
    }

    browsers (...browsers) {
        if (this.apiMethodWasCalled.browsers)
            throw new GeneralError(MESSAGE.multipleAPIMethodCallForbidden, OPTION_NAMES.browsers);

        browsers = this._prepareArrayParameter(browsers);
        this.configuration.mergeOptions({ browsers });

        this.apiMethodWasCalled.browsers = true;

        return this;
    }

    concurrency (concurrency) {
        this.configuration.mergeOptions({ concurrency });

        return this;
    }

    reporter (name, fileOrStream) {
        if (this.apiMethodWasCalled.reporter)
            throw new GeneralError(MESSAGE.multipleAPIMethodCallForbidden, OPTION_NAMES.reporter);

        let reporters = prepareReporters(name, fileOrStream);

        reporters = this._prepareArrayParameter(reporters);

        this.configuration.mergeOptions({ [OPTION_NAMES.reporter]: reporters });

        this.apiMethodWasCalled.reporter = true;

        return this;
    }

    filter (filter) {
        this.configuration.mergeOptions({ filter });

        return this;
    }

    useProxy (proxy, proxyBypass) {
        this.configuration.mergeOptions({ proxy, proxyBypass });

        return this;
    }

    screenshots (path, takeOnFails, pattern) {
        this.configuration.mergeOptions({
            [OPTION_NAMES.screenshotPath]:         path,
            [OPTION_NAMES.takeScreenshotsOnFails]: takeOnFails,
            [OPTION_NAMES.screenshotPathPattern]:  pattern
        });

        return this;
    }

    video (path, options, encodingOptions) {
        this.configuration.mergeOptions({
            [OPTION_NAMES.videoPath]:            path,
            [OPTION_NAMES.videoOptions]:         options,
            [OPTION_NAMES.videoEncodingOptions]: encodingOptions
        });

        return this;
    }

    startApp (command, initDelay) {
        this.configuration.mergeOptions({
            [OPTION_NAMES.appCommand]:   command,
            [OPTION_NAMES.appInitDelay]: initDelay
        });

        return this;
    }

    run (options = {}) {
        this.apiMethodWasCalled.reset();

        const {
            skipJsErrors,
            disablePageReloads,
            quarantineMode,
            debugMode,
            selectorTimeout,
            assertionTimeout,
            pageLoadTimeout,
            speed,
            debugOnFail,
            skipUncaughtErrors,
            stopOnFirstFail
        } = options;

        this.configuration.mergeOptions({
            skipJsErrors:       skipJsErrors,
            disablePageReloads: disablePageReloads,
            quarantineMode:     quarantineMode,
            debugMode:          debugMode,
            debugOnFail:        debugOnFail,
            selectorTimeout:    selectorTimeout,
            assertionTimeout:   assertionTimeout,
            pageLoadTimeout:    pageLoadTimeout,
            speed:              speed,
            skipUncaughtErrors: skipUncaughtErrors,
            stopOnFirstFail:    stopOnFirstFail
        });

        this._setBootstrapperOptions();

        const runTaskPromise = Promise.resolve()
            .then(() => this._validateRunOptions())
            .then(() => this._createRunnableConfiguration())
            .then(({ reporterPlugins, browserSet, tests, testedApp }) => {
                this.emit('done-bootstrapping');

                return this._runTask(reporterPlugins, browserSet, tests, testedApp);
            });

        return this._createCancelablePromise(runTaskPromise);
    }

    async stop () {
        // NOTE: When taskPromise is cancelled, it is removed from
        // the pendingTaskPromises array, which leads to shifting indexes
        // towards the beginning. So, we must copy the array in order to iterate it,
        // or we can perform iteration from the end to the beginning.
        const cancellationPromises = mapReverse(this.pendingTaskPromises, taskPromise => taskPromise.cancel());

        await Promise.all(cancellationPromises);
    }
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var np = require('named-parameters');
var MovementIterator = require('./movement_iterator.js');
var Move = require('./move.js');

module.exports = function(args) {
  var parsedArgs = np.parse(args).
    require('directions', 'array').
    default('limit', Infinity).
    require('limit', 'positive integer').
    default('moveOnly', false).
    require('moveOnly', 'boolean').
    values();

  var moveLimit = parsedArgs.limit;
  var moveOnly = parsedArgs.moveOnly;

  var advanceFunction = _.compose.apply(this,
    _.map(parsedArgs.directions, function(direction) {
      return directionAdvanceFunction(direction);
    })
  );

  return {
    getMoves: getMoves
  };

  function getMoves(args) {
    var parsedArgs = np.parse(args).
      require('piece').
      require('board').
      values();

    var board = parsedArgs.board;
    var piece = parsedArgs.piece;

    var currentLocation = board.pieceLocation(piece);

    var movementIterator = new MovementIterator({
      location: currentLocation,
      bounds: board.bounds(),
      advanceFunction: advanceFunction,
      limit: moveLimit
    });

    var moves = [];

    while(movementIterator.inBounds()) {
      if (board.canMoveIntoSpace({ piece: piece, location: movementIterator.location() })){
        moves.push(
          new Move({
            piece: piece,
            board: board,
            destination: movementIterator.location(),
            attacked: moveOnly
          })
        );
      } else if (!moveOnly && board.couldTake({ piece: piece, location: movementIterator.location() })){
        moves.push(
          new Move({
            piece: piece,
            board: board,
            destination: movementIterator.location(),
            attacked: true
          })
        );
      } else {
        break;
      }
      movementIterator.advanceLocation();
    }

    return moves;
  }

  function directionAdvanceFunction(direction) {
    var func;

    if(direction == 'up') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row - 1,
          col: currentLocation.col
        };
      };
    } else if (direction == 'down') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row + 1,
          col: currentLocation.col
        };
      };

    } else if (direction == 'left') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row,
          col: currentLocation.col - 1
        };
      };
    } else if (direction == 'right') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row,
          col: currentLocation.col + 1
        };
      };
    } else {
      throw('unsupported direction');
    }

    return func;
  }
};
<commit_msg>State type of args for MoveDeginitions.getMoves()<commit_after>var _ = require('lodash');
var np = require('named-parameters');
var MovementIterator = require('./movement_iterator.js');
var Move = require('./move.js');

module.exports = function(args) {
  var parsedArgs = np.parse(args).
    require('directions', 'array').
    default('limit', Infinity).
    require('limit', 'positive integer').
    default('moveOnly', false).
    require('moveOnly', 'boolean').
    values();

  var moveLimit = parsedArgs.limit;
  var moveOnly = parsedArgs.moveOnly;

  var advanceFunction = _.compose.apply(this,
    _.map(parsedArgs.directions, function(direction) {
      return directionAdvanceFunction(direction);
    })
  );

  return {
    getMoves: getMoves
  };

  function getMoves(args) {
    var parsedArgs = np.parse(args).
      require('piece', 'object').
      require('board', 'object').
      values();

    var board = parsedArgs.board;
    var piece = parsedArgs.piece;

    var currentLocation = board.pieceLocation(piece);

    var movementIterator = new MovementIterator({
      location: currentLocation,
      bounds: board.bounds(),
      advanceFunction: advanceFunction,
      limit: moveLimit
    });

    var moves = [];

    while(movementIterator.inBounds()) {
      if (board.canMoveIntoSpace({ piece: piece, location: movementIterator.location() })){
        moves.push(
          new Move({
            piece: piece,
            board: board,
            destination: movementIterator.location(),
            attacked: moveOnly
          })
        );
      } else if (!moveOnly && board.couldTake({ piece: piece, location: movementIterator.location() })){
        moves.push(
          new Move({
            piece: piece,
            board: board,
            destination: movementIterator.location(),
            attacked: true
          })
        );
      } else {
        break;
      }
      movementIterator.advanceLocation();
    }

    return moves;
  }

  function directionAdvanceFunction(direction) {
    var func;

    if(direction == 'up') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row - 1,
          col: currentLocation.col
        };
      };
    } else if (direction == 'down') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row + 1,
          col: currentLocation.col
        };
      };

    } else if (direction == 'left') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row,
          col: currentLocation.col - 1
        };
      };
    } else if (direction == 'right') {
      func = function(currentLocation) {
        return {
          row: currentLocation.row,
          col: currentLocation.col + 1
        };
      };
    } else {
      throw('unsupported direction');
    }

    return func;
  }
};
<|endoftext|>


<commit_before>// Copyright 2013 Joyent, Inc.  All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

var path = require('path');

var nfs = require('nfs');
var vasync = require('vasync');

var common = require('./common');
var crc32 = require('sse4_crc32');

///--- Helpers

function rand() {
    return (Math.floor((Math.random() * Math.pow(2, 31)) + 1));
}

///-- API

function readdirplus(call, reply, next) {
    var log = call.log;
    log.debug('readdirplus(%s): entered', call._filename);

    var barrier = vasync.barrier();
    var error = null;

    barrier.once('drain', function () {
        if (error) {
            nfs.handle_error(error, call, reply, next);
        } else {
            call.fs.stat(call._filename, function (err, stats) {
                if (err) {
                    log.warn(err, 'readdirplus(%s): dir stat failed',
                         call._filename);
                    reply.error(nfs.NFS3ERR_SERVERFAULT);
                    next(false);
                } else {
                    log.debug('readdirplus(%s): done', call._filename);
                    reply.setDirAttributes(stats);
                    reply.send();
                    next();
                }
            });
        }
    });

    barrier.start('readdir: ' + call._filename);
    call.fs.readdir(call._filename, function (err1, files) {
        if (err1) {
            log.warn(err1, 'readdirplus(%s): rd failed', call._filename);
            error = error || (err1.code === 'ENOTDIR' ?
                        nfs.NFS3ERR_NOTDIR :
                        nfs.NFS3ERR_IO);
            barrier.done('readdir: ' + call._filename);
            return;
        }

        // XXX
        // Need to handle call.dircount and call.maxcount correctly for
        // returning data. Also need to handle reading more directory info
        // based on the cookie if we couldn't return all data in one call.
        // reply.eof = (files.length < call.count);
        reply.eof = true;

        // XXX is cookie handling ok?
        var cook = 1;
        files.forEach(function (f) {
            var p = path.join(call._filename, f);
            barrier.start('file: ' + p);
            call.fs.stat(p, function (err2, stats) {
                if (err2) {
                    log.warn(err2, 'readdirplus(%s): stat failed', p);
                    error = error || err2;
                } else {
                    call.fs.lookup(p, function (err3, fhandle) {
                        if (err3) {
                            log.warn(err3, 'readdirplus(%s): lu failed', p);
                            error = error || err3;
                        } else {
                            reply.addEntry({
                                fileid: crc32.calculate(p),
                                name: f,
                                cookie: cook++,
                                name_attributes: nfs.create_fattr3(stats),
                                name_handle: fhandle
                            });
                        }
                    });
                }
                barrier.done('file: ' + p);
            });
        });

        barrier.done('readdir: ' + call._filename);
    });
}

///--- Exports

module.exports = function chain() {
    return ([
        common.fhandle_to_filename,
        readdirplus
    ]);
};
<commit_msg>MANTA-1844 fix readdirplus error handling<commit_after>// Copyright 2013 Joyent, Inc.  All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

var path = require('path');

var nfs = require('nfs');
var vasync = require('vasync');

var common = require('./common');
var crc32 = require('sse4_crc32');

///--- Helpers

function rand() {
    return (Math.floor((Math.random() * Math.pow(2, 31)) + 1));
}

///-- API

function readdirplus(call, reply, next) {
    var log = call.log;
    log.debug('readdirplus(%s): entered', call._filename);

    var barrier = vasync.barrier();
    var error = null;

    barrier.once('drain', function () {
        if (error) {
            reply.error(error);
            next(false);
        } else {
            call.fs.stat(call._filename, function (err, stats) {
                if (err) {
                    log.warn(err, 'readdirplus(%s): dir stat failed',
                         call._filename);
                    reply.error(nfs.NFS3ERR_SERVERFAULT);
                    next(false);
                } else {
                    log.debug('readdirplus(%s): done', call._filename);
                    reply.setDirAttributes(stats);
                    reply.send();
                    next();
                }
            });
        }
    });

    barrier.start('readdir: ' + call._filename);
    call.fs.readdir(call._filename, function (err1, files) {
        barrier.done('readdir: ' + call._filename);
        if (err1) {
            log.warn(err1, 'readdirplus(%s): rd failed', call._filename);
            error = error || (err1.code === 'ENOTDIR' ?
                        nfs.NFS3ERR_NOTDIR :
                        nfs.NFS3ERR_IO);
            return;
        }

        // XXX
        // Need to handle call.dircount and call.maxcount correctly for
        // returning data. Also need to handle reading more directory info
        // based on the cookie if we couldn't return all data in one call.
        // reply.eof = (files.length < call.count);
        reply.eof = true;

        // XXX is cookie handling ok?
        var cook = 1;
        files.forEach(function (f) {
            var p = path.join(call._filename, f);
            barrier.start('file: ' + p);
            call.fs.stat(p, function (err2, stats) {
                if (err2) {
                    log.warn(err2, 'readdirplus(%s): stat failed', p);
                    error = error || nfs.NFS3ERR_SERVERFAULT;
                    barrier.done('file: ' + p);
                } else {
                    call.fs.lookup(p, function (err3, fhandle) {
                        if (err3) {
                            log.warn(err3, 'readdirplus(%s): lu failed', p);
                            error = error || nfs.NFS3ERR_SERVERFAULT;
                        } else {
                            reply.addEntry({
                                fileid: crc32.calculate(p),
                                name: f,
                                cookie: cook++,
                                name_attributes: nfs.create_fattr3(stats),
                                name_handle: fhandle
                            });
                        }
                        barrier.done('file: ' + p);
                    });
                }
            });
        });
    });
}

///--- Exports

module.exports = function chain() {
    return ([
        common.fhandle_to_filename,
        readdirplus
    ]);
};
<|endoftext|>


<commit_before>var oBuffer=Buffer;

var _ArrayBuffer_=true;

Buffer.prototype.readUInt=function() {
	switch (this.length) {
		case 1 : return this[0];
		case 2 : return this.readUInt16BE(0);
		case 4 : return this.readUInt32BE(0);
		return 0;
	};
};

//node.js buffer.js
//modified not to throw - see #3159
Buffer.prototype.slice = function(start, end) {
	if (end === undefined) end = this.length;
	if (end > this.length) {
		end = this.length;
		console.log('BUFFER : slice - bad formatted buffer ')
	};
	if (start > end) {
		start=end;
		console.log('BUFFER : slice - bad formatted buffer ')
	};

	return new oBuffer(this.parent, end - start, +start + this.offset);
};

Buffer.prototype.writeUInt=function(val) {
	switch (this.length) {
		case 1 : this.writeUInt8(val,0);break;
		case 2 : this.writeUInt16BE(val,0);break;
		case 4 : this.writeUInt32BE(val,0);break;
	};
	return this;
};

Buffer.prototype.map=function(buff) {
	var l=buff.length;
	for (var i=0;i<l;i++) {
		this[i]=buff[i];
	};
	this.fill(0,l);
};

Array.prototype.concatBuffers = function() {
	var str=[];
	this.forEach(function(val) {
		str.push(val.toString('hex'));
	});
	return new Buffer(str.join(''),'hex');
};

if (_ArrayBuffer_) {
	Buffer=function(a,e) {
		if ((!e)&&(typeof(a)==='string')) {
			e='utf8';
		};
		if ((a instanceof Array) || ((!isNaN(a))&&(!e))) {
			return new Uint8Array(a);
		};
		if (e==='utf8') {
			return (new TextEncoder('utf-8')).encode(a);
		};
		if (e==='hex') {
			var b=new Uint8Array(a.length/2);
			var l=a.length;
			for (var i=0;i<l;i+=2) {
				b[i/2]=parseInt(a[i]+a[i+1],16);
			};
		};
		if (e==='binary') {
			var b=new Uint8Array(a.length);
			var l=b.length;
			for (var i=0;i<l;i++) {
				b[i]=a.charCodeAt(i);
			};
		};
		return b;
	};

	oBuffer.isBuffer=function(b) {
		return b instanceof oBuffer;
	};

	/* See V8 note below */
	Uint8Array.prototype.slice=function(start,end) {
		return this.subarray(start,end);
	};

	Uint8Array.prototype.isBuffer=function(b) {
		return b instanceof Uint8Array;
	};

	Uint8Array.prototype.map=oBuffer.prototype.map;

	Uint8Array.prototype.readUInt=oBuffer.prototype.readUInt;

	Uint8Array.prototype.writeUInt=oBuffer.prototype.writeUInt;

	Uint8Array.prototype.fill=function(val,offset) {
		var l=this.length;
		for (var i=offset;i<l;i++) {
			this[i]=val;
		};
	};
	/*
	previous V8 versions do not implement slice for ArrayBuffers but for Typed Arrays
	replace below this.byteOffset+o by o
	and change above in the slice method : return this.buffer.slice(start,end);
	*/
	Uint8Array.prototype.readUInt16BE=function(o) {
		var a=new DataView(this.buffer);
		return a.getUint16(this.byteOffset+o);
	};

	Uint8Array.prototype.readUInt32BE=function(o) {
		var a=new DataView(this.buffer);
		return a.getUint32(this.byteOffset+o);
	};

	Uint8Array.prototype.writeUInt8=function(val,o) {
		this[o]=val;
	};

	Uint8Array.prototype.writeUInt16BE=function(val,o) {
		var a=new DataView(this.buffer);
		a.setUint16(this.byteOffset+o,val);
	};

	Uint8Array.prototype.writeUInt32BE=function(val,o) {
		var a=new DataView(this.buffer);
		a.setUint32(this.byteOffset+o,val);
	};

	Uint8Array.prototype.readUInt=oBuffer.prototype.readUInt;

	Uint8Array.prototype.writeUInt=oBuffer.prototype.writeUInt;

	Uint8Array.prototype.toString=function(enc) {
		var l=this.length;
		var r=[];
		if (enc==='utf8') {
			return (new TextDecoder('utf-8')).decode(this);
		};
		for (var i=0;i<l;i++) {
			switch (enc) {
				case 'hex' : var tmp=this[i].toString(16);r.push(tmp.length===1?('0'+tmp):tmp);break;
				case 'binary' : r.push(String.fromCharCode(this[i]));break;
			};
		};
		return r.join('');
	};

};

/*
These two functions below are not mandatory if your are in an environment that understands both Buffers and ArrayBuffers (ie node.js)
As long as node.js's Buffers have the same properties as ArrayBuffers and Typed Arrays, you can use both without any conversion
(example : var a buf=Buffer_based_on_typed_array;socket.write(buf);)
They can be usefull in an environment that does not understand Buffers (browsers for example) or ArrayBuffers
*/
var ArrayBufferToBuffer= function(data) {
	if (data instanceof Uint8Array) {
		var a=new oBuffer(data.length);
		a.map(data);
		data=a;
	};
	return data;
};

var BufferToArrayBuffer= function(data) {
	if (!(data instanceof Uint8Array)) {
		var a=new Buffer(data.length);
		a.map(data);
		data=a;
	};
	return data;
};

/* Examples - note that 'new' is not required for ArrayBuffer/Typed Array here but used for compatibility reasons with Buffers or if you want to construct Typed Arrays differently

	var a=new Buffer('aabbcc','hex');

	var b=a.toString('hex');

	console.log(b);

	a=new Buffer('','utf8');

	console.log(a.toString('utf8'));

	console.log(a.toString('hex'));

	console.log(a.toString('binary'));

	console.log((new Buffer('c3a9c3a8c3a0c3af','hex')).toString('binary'));

	a=new Buffer('10','hex');

	console.log(a.length);

	console.log(a.readUInt());

	a.writeUInt(0x20);

	console.log(a.readUInt());

	a=new Buffer('1020','hex');

	console.log((a.readUInt()).toString(16));

	a.writeUInt(0x2030);

	console.log((a.readUInt()).toString(16));

	a=new Buffer('10203040','hex');

	console.log((a.readUInt()).toString(16));

	a.writeUInt(0x20304050);

	console.log((a.readUInt()).toString(16));

	a=new Buffer(10);

	a[0]=0x10;
	a[1]=0x20;

	console.log(a.toString('hex'));

	a.fill(0x50,3);

	console.log(a.toString('hex'));

	b=a.slice(2);

	console.log(b.toString('hex'));

	b=a.slice(2,4);

	console.log(b.toString('hex'));

	console.log(b.readUInt);

	b=new Buffer(20);

	b.map(a);

	console.log(b.toString('hex'));

	console.log(b instanceof Uint8Array);

	var b=new Buffer('000007000200030000','hex');

	//var b=new Uint8Array([0x000007000200030000]);

	console.log(b instanceof Uint8Array);

	//b.slice=function(start,end) {return this.buffer.slice(start,end);};

	var c=b.slice(5,7);

	//console.log(c);

	console.log(c instanceof Uint8Array);

	console.log(c.readUInt());

*/<commit_msg>modif concat<commit_after>var oBuffer=Buffer;

var _ArrayBuffer_=true;

Buffer.prototype.readUInt=function() {
	switch (this.length) {
		case 1 : return this[0];
		case 2 : return this.readUInt16BE(0);
		case 4 : return this.readUInt32BE(0);
		return 0;
	};
};

//node.js buffer.js
//modified not to throw - see #3159
Buffer.prototype.slice = function(start, end) {
	if (end === undefined) end = this.length;
	if (end > this.length) {
		end = this.length;
		console.log('BUFFER : slice - bad formatted buffer ')
	};
	if (start > end) {
		start=end;
		console.log('BUFFER : slice - bad formatted buffer ')
	};

	return new oBuffer(this.parent, end - start, +start + this.offset);
};

Buffer.prototype.writeUInt=function(val) {
	switch (this.length) {
		case 1 : this.writeUInt8(val,0);break;
		case 2 : this.writeUInt16BE(val,0);break;
		case 4 : this.writeUInt32BE(val,0);break;
	};
	return this;
};

Buffer.prototype.map=function(buff) {
	var l=buff.length;
	for (var i=0;i<l;i++) {
		this[i]=buff[i];
	};
	this.fill(0,l);
};

//Array.prototype.concatBuffers = function() {
//	var str=[];
//	this.forEach(function(val) {
//		str.push(val.toString('hex'));
//	});
//	return new Buffer(str.join(''),'hex');
//};

Array.prototype.concatBuffers = function() {
	var str=[];
	var n=0;
	this.forEach(function(val) {
		n +=val.length;
	});
	var buff=new Buffer(n);
	var index=0;
	this.forEach(function(val) {
		var l=val.length;
		for (var i=0;i<l;i++) {
			buff[index]=val[i];
			index++;
		};
	});
	return buff;
};

if (_ArrayBuffer_) {
	Buffer=function(a,e) {
		if ((!e)&&(typeof(a)==='string')) {
			e='utf8';
		};
		if ((a instanceof Array) || ((!isNaN(a))&&(!e))) {
			return new Uint8Array(a);
		};
		if (e==='utf8') {
			return (new TextEncoder('utf-8')).encode(a);
		};
		if (e==='hex') {
			var b=new Uint8Array(a.length/2);
			var l=a.length;
			for (var i=0;i<l;i+=2) {
				b[i/2]=parseInt(a[i]+a[i+1],16);
			};
		};
		if (e==='binary') {
			var b=new Uint8Array(a.length);
			var l=b.length;
			for (var i=0;i<l;i++) {
				b[i]=a.charCodeAt(i);
			};
		};
		return b;
	};

	oBuffer.isBuffer=function(b) {
		return b instanceof oBuffer;
	};

	Uint8Array.prototype.slice=function(start,end) {
		return this.subarray(start,end);
	};

	Uint8Array.prototype.isBuffer=function(b) {
		return b instanceof Uint8Array;
	};

	Uint8Array.prototype.map=oBuffer.prototype.map;

	Uint8Array.prototype.readUInt=oBuffer.prototype.readUInt;

	Uint8Array.prototype.writeUInt=oBuffer.prototype.writeUInt;

	Uint8Array.prototype.fill=function(val,offset) {
		var l=this.length;
		for (var i=offset;i<l;i++) {
			this[i]=val;
		};
	};
	Uint8Array.prototype.readUInt16BE=function(o) {
		var a=new DataView(this.buffer);
		return a.getUint16(this.byteOffset+o);
	};

	Uint8Array.prototype.readUInt32BE=function(o) {
		var a=new DataView(this.buffer);
		return a.getUint32(this.byteOffset+o);
	};

	Uint8Array.prototype.writeUInt8=function(val,o) {
		this[o]=val;
	};

	Uint8Array.prototype.writeUInt16BE=function(val,o) {
		var a=new DataView(this.buffer);
		a.setUint16(this.byteOffset+o,val);
	};

	Uint8Array.prototype.writeUInt32BE=function(val,o) {
		var a=new DataView(this.buffer);
		a.setUint32(this.byteOffset+o,val);
	};

	Uint8Array.prototype.readUInt=oBuffer.prototype.readUInt;

	Uint8Array.prototype.writeUInt=oBuffer.prototype.writeUInt;

	Uint8Array.prototype.toString=function(enc) {
		var l=this.length;
		var r=[];
		if (enc==='utf8') {
			return (new TextDecoder('utf-8')).decode(this);
		};
		for (var i=0;i<l;i++) {
			switch (enc) {
				case 'hex' : var tmp=this[i].toString(16);r.push(tmp.length===1?('0'+tmp):tmp);break;
				case 'binary' : r.push(String.fromCharCode(this[i]));break;
			};
		};
		return r.join('');
	};

};

/*
These two functions below are not mandatory if your are in an environment that understands both Buffers and ArrayBuffers (ie node.js)
As long as node.js's Buffers have the same properties as ArrayBuffers and Typed Arrays, you can use both without any conversion
(example : var a buf=Buffer_based_on_typed_array;socket.write(buf);)
They can be usefull in an environment that does not understand Buffers (browsers for example) or ArrayBuffers
*/
var ArrayBufferToBuffer= function(data) {
	if (data instanceof Uint8Array) {
		var a=new oBuffer(data.length);
		a.map(data);
		data=a;
	};
	return data;
};

var BufferToArrayBuffer= function(data) {
	if (!(data instanceof Uint8Array)) {
		var a=new Buffer(data.length);
		a.map(data);
		data=a;
	};
	return data;
};

/* Examples - note that 'new' is not required for ArrayBuffer/Typed Array here but used for compatibility reasons with Buffers or if you want to construct Typed Arrays differently

	var a=new Buffer('aabbcc','hex');

	var b=a.toString('hex');

	console.log(b);

	a=new Buffer('','utf8');

	console.log(a.toString('utf8'));

	console.log(a.toString('hex'));

	console.log(a.toString('binary'));

	console.log((new Buffer('c3a9c3a8c3a0c3af','hex')).toString('binary'));

	a=new Buffer('10','hex');

	console.log(a.length);

	console.log(a.readUInt());

	a.writeUInt(0x20);

	console.log(a.readUInt());

	a=new Buffer('1020','hex');

	console.log((a.readUInt()).toString(16));

	a.writeUInt(0x2030);

	console.log((a.readUInt()).toString(16));

	a=new Buffer('10203040','hex');

	console.log((a.readUInt()).toString(16));

	a.writeUInt(0x20304050);

	console.log((a.readUInt()).toString(16));

	a=new Buffer(10);

	a[0]=0x10;
	a[1]=0x20;

	console.log(a.toString('hex'));

	a.fill(0x50,3);

	console.log(a.toString('hex'));

	b=a.slice(2);

	console.log(b.toString('hex'));

	b=a.slice(2,4);

	console.log(b.toString('hex'));

	console.log(b.readUInt);

	b=new Buffer(20);

	b.map(a);

	console.log(b.toString('hex'));

	console.log(b instanceof Uint8Array);

	var b=new Buffer('000007000200030000','hex');

	//var b=new Uint8Array([0x000007000200030000]);

	console.log(b instanceof Uint8Array);

	//b.slice=function(start,end) {return this.buffer.slice(start,end);};

	var c=b.slice(5,7);

	//console.log(c);

	console.log(c instanceof Uint8Array);

	console.log(c.readUInt());

*/<|endoftext|>


<commit_before>/**
 * Choices object
 * Collection of multiple `choice` object
 */

var _ = require("lodash");
var Separator = require("./separator");
var Choice = require("./choice");

/**
 * Module exports
 */

module.exports = Choices;

/**
 * Choices collection
 * @constructor
 * @param {Array} choices  All `choice` to keep in the collection
 */

function Choices( choices ) {
  this.choices = _.map( choices, function( val ) {
    if ( val instanceof Separator ) {
      return val;
    }
    return new Choice( val );
  });

  this.realChoices = this.choices.filter(Separator.exclude);

  Object.defineProperty( this, "length", {
    get: function() {
      return this.choices.length;
    },
    set: function( val ) {
      this.choices.length = val;
    }
  });

  Object.defineProperty( this, "realLength", {
    get: function() {
      return this.realChoices.length;
    },
    set: function() {
      throw new Error("Cannot set `realLength` of a Choices collection");
    }
  });
}

/**
 * Get a valid choice from the collection
 * @param  {Number} selector  The selected choice index
 * @return {Choice|Undefined} Return the matched choice or undefined
 */

Choices.prototype.getChoice = function( selector ) {
  if ( _.isNumber(selector) ) {
    return this.realChoices[ selector ];
  }
  return undefined;
};

/**
 * Get a raw element from the collection
 * @param  {Number} selector  The selected index value
 * @return {Choice|Undefined} Return the matched choice or undefined
 */

Choices.prototype.get = function( selector ) {
  if ( _.isNumber(selector) ) {
    return this.choices[ selector ];
  }
  return undefined;
};

/**
 * Match the valid choices against a where clause
 * @param  {Object} whereClause Lodash `where` clause
 * @return {Array}              Matching choices or empty array
 */

Choices.prototype.where = function( whereClause ) {
  return _.where( this.realChoices, whereClause );
};

/**
 * Pluck a particular key from the choices
 * @param  {String} propertyName Property name to select
 * @return {Array}               Selected properties
 */

Choices.prototype.pluck = function( propertyName ) {
  return _.pluck( this.realChoices, propertyName );
};

// Propagate usual Array methods
Choices.prototype.forEach = function() {
  return this.choices.forEach.apply( this.choices, arguments );
};
Choices.prototype.filter = function() {
  return this.choices.filter.apply( this.choices, arguments );
};
Choices.prototype.push = function() {
  var objs = _.map( arguments, function( val ) { return new Choice( val ); });
  this.choices.push.apply( this.choices, objs );
  this.realChoices = this.choices.filter(Separator.exclude);
  return this.choices;
};

/**
 * Render the choices as formatted string
 * @return {String}  formatted content
 */

Choices.prototype.render = function() {
  return this.renderingMethod.apply( this, arguments );
};

/**
 * Set the rendering method
 * @param {Function} render  Function to be use when rendering
 * @param {Object}   opt     Option object, pass `paginated: true` to paginate to output
 */

Choices.prototype.setRender = function( render, opt ) {
  this.renderingMethod = (opt && opt.paginated) ? this.paginateOutput(render) : render;
};

/**
 * Paginate the output of a render function
 * @param  {Function} render Render function whose content must be paginated
 * @return {Function}        Wrapped render function
 */

Choices.prototype.paginateOutput = function( render ) {
  var pageSize = 7;

  return function( pointer ) {
    var output = render.apply( this, arguments );
    var lines = output.split("\n");

    // Make sure there's enough line to paginate
    if ( lines.length <= pageSize ) return output;

    // Duplicate the lines so it give an infinite list look
    var infinite = _.flatten([ lines, lines, lines ]);
    var topIndex = Math.max( 0, pointer + lines.length - 3 );

    return infinite.splice( topIndex, pageSize ).join("\n");
  }.bind(this);
};
<commit_msg>Add text notification when choices are paginated<commit_after>/**
 * Choices object
 * Collection of multiple `choice` object
 */

var _ = require("lodash");
var clc = require("cli-color");
var Separator = require("./separator");
var Choice = require("./choice");

/**
 * Module exports
 */

module.exports = Choices;

/**
 * Choices collection
 * @constructor
 * @param {Array} choices  All `choice` to keep in the collection
 */

function Choices( choices ) {
  this.choices = _.map( choices, function( val ) {
    if ( val instanceof Separator ) {
      return val;
    }
    return new Choice( val );
  });

  this.realChoices = this.choices.filter(Separator.exclude);

  Object.defineProperty( this, "length", {
    get: function() {
      return this.choices.length;
    },
    set: function( val ) {
      this.choices.length = val;
    }
  });

  Object.defineProperty( this, "realLength", {
    get: function() {
      return this.realChoices.length;
    },
    set: function() {
      throw new Error("Cannot set `realLength` of a Choices collection");
    }
  });
}

/**
 * Get a valid choice from the collection
 * @param  {Number} selector  The selected choice index
 * @return {Choice|Undefined} Return the matched choice or undefined
 */

Choices.prototype.getChoice = function( selector ) {
  if ( _.isNumber(selector) ) {
    return this.realChoices[ selector ];
  }
  return undefined;
};

/**
 * Get a raw element from the collection
 * @param  {Number} selector  The selected index value
 * @return {Choice|Undefined} Return the matched choice or undefined
 */

Choices.prototype.get = function( selector ) {
  if ( _.isNumber(selector) ) {
    return this.choices[ selector ];
  }
  return undefined;
};

/**
 * Match the valid choices against a where clause
 * @param  {Object} whereClause Lodash `where` clause
 * @return {Array}              Matching choices or empty array
 */

Choices.prototype.where = function( whereClause ) {
  return _.where( this.realChoices, whereClause );
};

/**
 * Pluck a particular key from the choices
 * @param  {String} propertyName Property name to select
 * @return {Array}               Selected properties
 */

Choices.prototype.pluck = function( propertyName ) {
  return _.pluck( this.realChoices, propertyName );
};

// Propagate usual Array methods
Choices.prototype.forEach = function() {
  return this.choices.forEach.apply( this.choices, arguments );
};
Choices.prototype.filter = function() {
  return this.choices.filter.apply( this.choices, arguments );
};
Choices.prototype.push = function() {
  var objs = _.map( arguments, function( val ) { return new Choice( val ); });
  this.choices.push.apply( this.choices, objs );
  this.realChoices = this.choices.filter(Separator.exclude);
  return this.choices;
};

/**
 * Render the choices as formatted string
 * @return {String}  formatted content
 */

Choices.prototype.render = function() {
  return this.renderingMethod.apply( this, arguments );
};

/**
 * Set the rendering method
 * @param {Function} render  Function to be use when rendering
 * @param {Object}   opt     Option object, pass `paginated: true` to paginate to output
 */

Choices.prototype.setRender = function( render, opt ) {
  this.renderingMethod = (opt && opt.paginated) ? this.paginateOutput(render) : render;
};

/**
 * Paginate the output of a render function
 * @param  {Function} render Render function whose content must be paginated
 * @return {Function}        Wrapped render function
 */

Choices.prototype.paginateOutput = function( render ) {
  var pageSize = 7;

  return function( pointer ) {
    var output = render.apply( this, arguments );
    var lines = output.split("\n");

    // Make sure there's enough line to paginate
    if ( lines.length <= pageSize ) return output;

    // Duplicate the lines so it give an infinite list look
    var infinite = _.flatten([ lines, lines, lines ]);
    var topIndex = Math.max( 0, pointer + lines.length - 3 );

    var section = infinite.splice( topIndex, pageSize ).join("\n");
    return section + "\n" + clc.blackBright("(Move up and down to reveal more choices)");
  }.bind(this);
};
<|endoftext|>


<commit_before>const express = require("express")
const passport = require("passport")
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser")
const jwt = require("jsonwebtoken")
const cors = require("cors")
const {graphqlExpress, graphiqlExpress} = require("graphql-server-express")
const history = require("connect-history-api-fallback")

const baseUrl = require("./middlewares/baseUrl")
const setupFbStrategy = require("./middlewares/setupFbStrategy")
const {secret} = require("../config")
const knex = require("./knex.js")

const schema = require("./schema")

const app = express()
app.use(baseUrl)
app.use(cors())
app.use(cookieParser())

app.use((req, res, next) => {
  try {
    if (req.cookies.jwt_token) {
      const {id} = jwt.verify(req.cookies.jwt_token, secret)
      knex("users").where("id", id).then(rows => {
        if (rows.length) {
          req.user = rows[0]
        }
      })
    }
  } finally {
    next()
  }
})

// Authentication routes
app.get("/auth/facebook", setupFbStrategy, passport.authenticate("facebook"))
app.get(
  "/auth/facebook/callback",
  passport.authenticate("facebook", {session: false}),
  (req, res) => {
    const token = jwt.sign({id: req.user.id}, secret)
    res.cookie("jwt_token", token, {httpOnly: true}).redirect("/")
  },
)
app.get("/disconnect", (req, res) => res.clearCookie("jwt_token").redirect("/"))

// Graphql routes
app.use(
  "/graphql",
  bodyParser.json(),
  graphqlExpress((req, res) => ({
    schema,
    context: {me: req.user},
  })),
)

// graphiql endpoint only for developement
if (process.env.NODE_ENV !== "production") {
  app.use(
    "/graphiql",
    graphiqlExpress({
      endpointURL: "/graphql",
    }),
  )
}

app.use(history())
app.use(express.static(process.env.RAZZLE_PUBLIC_DIR))

const assets = require(process.env.RAZZLE_ASSETS_MANIFEST)
app.get("*", (req, res) => {
  res.send(`
<!doctype html>

    <meta charset="utf-8">
    <title>Friends Radio 📻</title>
    <link
      href="https://fonts.googleapis.com/css?family=Open+Sans"
      rel="stylesheet"
    >
    ${assets.client.css
      ? `<link rel="stylesheet" href="${assets.client.css}">`
      : ""}

  `)
})

export default app
<commit_msg>clearCookie on fail<commit_after>const express = require("express")
const passport = require("passport")
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser")
const jwt = require("jsonwebtoken")
const cors = require("cors")
const {graphqlExpress, graphiqlExpress} = require("graphql-server-express")
const history = require("connect-history-api-fallback")

const baseUrl = require("./middlewares/baseUrl")
const setupFbStrategy = require("./middlewares/setupFbStrategy")
const {secret} = require("../config")
const knex = require("./knex.js")

const schema = require("./schema")

const app = express()
app.use(baseUrl)
app.use(cors())
app.use(cookieParser())

app.use((req, res, next) => {
  try {
    if (req.cookies.jwt_token) {
      const {id} = jwt.verify(req.cookies.jwt_token, secret)
      knex("users").where("id", id).then(rows => {
        if (rows.length) {
          req.user = rows[0]
        }
      })
    }
  } catch (err) {
    console.error(err)
  } finally {
    if (!req.user) {
      res.clearCookie("jwt_token")
    }
    next()
  }
})

// Authentication routes
app.get("/auth/facebook", setupFbStrategy, passport.authenticate("facebook"))
app.get(
  "/auth/facebook/callback",
  passport.authenticate("facebook", {session: false}),
  (req, res) => {
    const token = jwt.sign({id: req.user.id}, secret)
    res.cookie("jwt_token", token, {httpOnly: true}).redirect("/")
  },
)
app.get("/disconnect", (req, res) => res.clearCookie("jwt_token").redirect("/"))

// Graphql routes
app.use(
  "/graphql",
  bodyParser.json(),
  graphqlExpress((req, res) => ({
    schema,
    context: {me: req.user},
  })),
)

// graphiql endpoint only for developement
if (process.env.NODE_ENV !== "production") {
  app.use(
    "/graphiql",
    graphiqlExpress({
      endpointURL: "/graphql",
    }),
  )
}

app.use(history())
app.use(express.static(process.env.RAZZLE_PUBLIC_DIR))

const assets = require(process.env.RAZZLE_ASSETS_MANIFEST)
app.get("*", (req, res) => {
  res.send(`
<!doctype html>

    <meta charset="utf-8">
    <title>Friends Radio 📻</title>
    <link
      href="https://fonts.googleapis.com/css?family=Open+Sans"
      rel="stylesheet"
    >
    ${assets.client.css
      ? `<link rel="stylesheet" href="${assets.client.css}">`
      : ""}

  `)
})

export default app
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

export default class FileInput extends React.Component {
    static onDragOver(e) {
        e.dataTransfer.dropEffect = 'copy';
        e.preventDefault();  // indicate we are going to handle the drop
    }

    constructor() {
        super();

        // Bind this to non-React methods
        this.onDrop = this.onDrop.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onDrop(e) {
        const file = e.dataTransfer.files[0];
        this.onChange(null, file);
        e.preventDefault();
    }

    onChange(e, file) {
        let rFile = file;
        if (rFile === undefined) {
            const input = this.refs.input;
            rFile = input.files[0];
        }
        const reader = new FileReader();
        reader.onloadend = () => {
            const value = {
                download: rFile.name,
                type: rFile.type || undefined,
                href: reader.result,
            };
            this.props.onChange(value);
        };
        if (file) {
            reader.readAsDataURL(file);
        }
    }

    render() {
        const value = this.props.value || {};
        const mimetype = value.type;
        const preview = (mimetype && mimetype.indexOf('image/') === 0) ?  : '';
        const filename = value.download;
        return (
            <div className={`dropzone${this.props.disabled ? ' disabled' : ''}`} onDragOver={FileInput.onDragOver} onDrop={this.onDrop}>

                    {filename ?

                        {filename}

 : ''}

{preview}

Drop a {filename ? 'replacement' : ''} file here.
                    Or <input ref="input" type="file" onChange={this.onChange} disabled={this.props.disabled} />

        );
    }
}

FileInput.propTypes = {
    value: PropTypes.object.isRequired,
    disabled: PropTypes.bool,
    onChange: PropTypes.func.isRequired,
};

FileInput.defaultProps = {
    disabled: false,
};
<commit_msg>ENCD-3566 Fix JS FileInput add document (#2076)<commit_after>import React from 'react';
import PropTypes from 'prop-types';

export default class FileInput extends React.Component {
    static onDragOver(e) {
        e.dataTransfer.dropEffect = 'copy';
        e.preventDefault();  // indicate we are going to handle the drop
    }

    constructor() {
        super();

        // Bind this to non-React methods
        this.onDrop = this.onDrop.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onDrop(e) {
        const file = e.dataTransfer.files[0];
        this.onChange(null, file);
        e.preventDefault();
    }

    onChange(e, file) {
        let rFile = file;
        if (rFile === undefined) {
            const input = this.refs.input;
            rFile = input.files[0];
        }
        const reader = new FileReader();
        reader.onloadend = () => {
            const value = {
                download: rFile.name,
                type: rFile.type || undefined,
                href: reader.result,
            };
            this.props.onChange(value);
        };
        if (rFile) {
            reader.readAsDataURL(rFile);
        }
    }

    render() {
        const value = this.props.value || {};
        const mimetype = value.type;
        const preview = (mimetype && mimetype.indexOf('image/') === 0) ?  : '';
        const filename = value.download;
        return (
            <div className={`dropzone${this.props.disabled ? ' disabled' : ''}`} onDragOver={FileInput.onDragOver} onDrop={this.onDrop}>

                    {filename ?

                        {filename}

 : ''}

{preview}

Drop a {filename ? 'replacement' : ''} file here.
                    Or <input ref="input" type="file" onChange={this.onChange} disabled={this.props.disabled} />

        );
    }
}

FileInput.propTypes = {
    value: PropTypes.object.isRequired,
    disabled: PropTypes.bool,
    onChange: PropTypes.func.isRequired,
};

FileInput.defaultProps = {
    disabled: false,
};
<|endoftext|>


<commit_before>"use strict";

const cpp = require("child-process-promise");

const Verda = require("./verda");
const Plugin = require("../plugin");
const messages = require("../messages");

class Command extends Plugin {
	constructor() {
		super();
	}
	load(context, targeted) {
		if (!context.resources.verda) Verda.singleton.load(context, targeted);
		context.command = async function(cmd, args, options) {
			const t = this;
			return await context.resources.verda.mutex(function() {
				t.message(messages.kind("Command"), cmd, args.join(" "));
				let prom = cpp.spawn(cmd, args, options);
				let proc = prom.childProcess;
				proc.stdout.on("data", function(data) {
					process.stdout.write(data);
				});
				proc.stderr.on("data", function(data) {
					process.stderr.write(data);
				});
				return prom;
			});
		};
		context.run = async function(cmd, ...args) {
			return await this.command(cmd, args);
		};
	}
}

module.exports = Command;
<commit_msg>added <cd> directive<commit_after>"use strict";

const cpp = require("child-process-promise");

const Verda = require("./verda");
const Plugin = require("../plugin");
const messages = require("../messages");

class Command extends Plugin {
	constructor() {
		super();
	}
	load(context, targeted) {
		if (!context.resources.verda) Verda.singleton.load(context, targeted);
		context.command = async function(cmd, args, options, interactive) {
			const t = this;
			return await context.resources.verda.mutex(function() {
				t.message(
					messages.kind("Command"),
					cmd,
					args.join(" "),
					options.cwd ? messages.kind("in") + " " + options.cwd : ""
				);
				let prom = cpp.spawn(cmd, args, options);
				let proc = prom.childProcess;
				if (!interactive) {
					proc.stdout.on("data", function(data) {
						process.stdout.write(data);
					});
					proc.stderr.on("data", function(data) {
						process.stderr.write(data);
					});
				}
				return prom;
			});
		};
		context.cd = function(dir) {
			return {
				run: function(cmd, ...args) {
					return context.command(cmd, args, { cwd: dir });
				},
				runInteractive: function(cmd, ...args) {
					return context.command(cmd, args, { cwd: dir, stdio: "inherit" }, true);
				}
			};
		};
		context.run = function(cmd, ...args) {
			return this.command(cmd, args);
		};
		context.runInteractive = function(cmd, ...args) {
			return context.command(cmd, args, { stdio: "inherit" }, true);
		};
	}
}

module.exports = Command;
<|endoftext|>


<commit_before>module.exports = {
    'attr-bans': [
        'align',
        'background',
        'bgcolor',
        'border',
        'frameborder',
        'longdesc',
        'marginwidth',
        'marginheight',
        'scrolling',
        'style',
        'width'
    ],
    'indent-style': 'nonmixed',
    'indent-width': 4,
    'indent-width-cont': false,
    'text-escape-spec-char': true,
    'tag-bans': ['style', 'b', 'i'],
    'tag-close': true,
    'tag-limit-top-level': false,
    'tag-name-lowercase': true,
    'tag-name-match': true,
    'tag-self-close': false,
    'doctype-first': false,
    'doctype-html5': false,
    'attr-name-style': 'lowercase',
    'attr-name-ignore-regex': false,
    'attr-no-dup': true,
    'attr-no-unsafe-chars': true,
    'attr-order': false,
    'attr-quote-style': 'double',
    'attr-req-value': true,
    'id-no-dup': true,
    'id-class-no-ad': true,
    'id-class-style': 'underscore',
    'class-no-dup': true,
    'class-style': false,
    'id-class-ignore-regex': false,
    'img-req-alt': true,
    'img-req-src': true,
    'href-style': false,
    'csslint': false,
    'label-req-for': true,
    'line-end-style': 'lf',
    'line-max-len': false,
    'line-max-len-ignore-regex': false,
    'head-req-title': true,
    'title-no-dup': true,
    'title-max-len': 60,
    'html-req-lang': false,
    'lang-style': 'case'
};
<commit_msg>Correct default preset: attr-no-unsafe-chars -> char<commit_after>module.exports = {
    'attr-bans': [
        'align',
        'background',
        'bgcolor',
        'border',
        'frameborder',
        'longdesc',
        'marginwidth',
        'marginheight',
        'scrolling',
        'style',
        'width'
    ],
    'indent-style': 'nonmixed',
    'indent-width': 4,
    'indent-width-cont': false,
    'text-escape-spec-char': true,
    'tag-bans': ['style', 'b', 'i'],
    'tag-close': true,
    'tag-limit-top-level': false,
    'tag-name-lowercase': true,
    'tag-name-match': true,
    'tag-self-close': false,
    'doctype-first': false,
    'doctype-html5': false,
    'attr-name-style': 'lowercase',
    'attr-name-ignore-regex': false,
    'attr-no-dup': true,
    'attr-no-unsafe-char': true,
    'attr-order': false,
    'attr-quote-style': 'double',
    'attr-req-value': true,
    'id-no-dup': true,
    'id-class-no-ad': true,
    'id-class-style': 'underscore',
    'class-no-dup': true,
    'class-style': false,
    'id-class-ignore-regex': false,
    'img-req-alt': true,
    'img-req-src': true,
    'href-style': false,
    'csslint': false,
    'label-req-for': true,
    'line-end-style': 'lf',
    'line-max-len': false,
    'line-max-len-ignore-regex': false,
    'head-req-title': true,
    'title-no-dup': true,
    'title-max-len': 60,
    'html-req-lang': false,
    'lang-style': 'case'
};
<|endoftext|>


<commit_before>import { config, configure } from "./config";
import { objectOrFunction, isFunction, now } from './utils';
import { cast } from "./cast";
import { all } from "./all";
import { race } from "./race";
import { resolve as staticResolve } from "./resolve";
import { reject as staticReject } from "./reject";
import { asap } from "./asap";

var guidKey = 'rsvp_' + now() + '-';
var counter = 0;

config.async = asap; // default async is asap;

function Promise(resolver) {
  if (!isFunction(resolver)) {
    throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  }

  if (!(this instanceof Promise)) {
    throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  }

  this._id = counter++;
  this._subscribers = [];

  invokeResolver(resolver, this);
}

function invokeResolver(resolver, promise) {
  function resolvePromise(value) {
    resolve(promise, value);
  }

  function rejectPromise(reason) {
    reject(promise, reason);
  }

  try {
    resolver(resolvePromise, rejectPromise);
  } catch(e) {
    rejectPromise(e);
  }
}

function invokeCallback(settled, promise, callback, detail) {
  var hasCallback = isFunction(callback),
      value, error, succeeded, failed;

  if (hasCallback) {
    try {
      value = callback(detail);
      succeeded = true;
    } catch(e) {
      failed = true;
      error = e;
    }
  } else {
    value = detail;
    succeeded = true;
  }

  if (handleThenable(promise, value)) {
    return;
  } else if (hasCallback && succeeded) {
    resolve(promise, value);
  } else if (failed) {
    reject(promise, error);
  } else if (settled === FULFILLED) {
    resolve(promise, value);
  } else if (settled === REJECTED) {
    reject(promise, value);
  }
}

var PENDING   = void 0;
var SEALED    = 0;
var FULFILLED = 1;
var REJECTED  = 2;

function subscribe(parent, child, onFulfillment, onRejection) {
  var subscribers = parent._subscribers;
  var length = subscribers.length;

  subscribers[length] = child;
  subscribers[length + FULFILLED] = onFulfillment;
  subscribers[length + REJECTED]  = onRejection;
}

function publish(promise, settled) {
  var child, callback, subscribers = promise._subscribers, detail = promise._detail;

  for (var i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    invokeCallback(settled, child, callback, detail);
  }

  promise._subscribers = null;
}

Promise.prototype = {
  constructor: Promise,

  _id: undefined,
  _guidKey: guidKey,

  _state: undefined,
  _detail: undefined,
  _subscribers: undefined,

  then: function(onFulfillment, onRejection) {
    var promise = this;

    var thenPromise = new this.constructor(function() {});

    if (this._state) {
      var callbacks = arguments;
      config.async(function invokePromiseCallback() {
        invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
      });
    } else {
      subscribe(this, thenPromise, onFulfillment, onRejection);
    }

    return thenPromise;
  },

  'catch': function(onRejection) {
    return this.then(null, onRejection);
  }
};

Promise.all = all;
Promise.cast = cast;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;

function handleThenable(promise, value) {
  var then = null,
  resolved;

  try {
    if (promise === value) {
      throw new TypeError("A promises callback cannot return that same promise.");
    }

    if (objectOrFunction(value)) {
      then = value.then;

      if (isFunction(then)) {
        then.call(value, function(val) {
          if (resolved) { return true; }
          resolved = true;

          if (value !== val) {
            resolve(promise, val);
          } else {
            fulfill(promise, val);
          }
        }, function(val) {
          if (resolved) { return true; }
          resolved = true;

          reject(promise, val);
        });

        return true;
      }
    }
  } catch (error) {
    if (resolved) { return true; }
    reject(promise, error);
    return true;
  }

  return false;
}

function resolve(promise, value) {
  if (promise === value) {
    fulfill(promise, value);
  } else if (!handleThenable(promise, value)) {
    fulfill(promise, value);
  }
}

function fulfill(promise, value) {
  if (promise._state !== PENDING) { return; }
  promise._state = SEALED;
  promise._detail = value;

  config.async(publishFulfillment, promise);
}

function reject(promise, reason) {
  if (promise._state !== PENDING) { return; }
  promise._state = SEALED;
  promise._detail = reason;

  config.async(publishRejection, promise);
}

function publishFulfillment(promise) {
  publish(promise, promise._state = FULFILLED);
}

function publishRejection(promise) {
  publish(promise, promise._state = REJECTED);
}

export { Promise };
<commit_msg>No-longer needed private vars<commit_after>import { config, configure } from "./config";
import { objectOrFunction, isFunction, now } from './utils';
import { cast } from "./cast";
import { all } from "./all";
import { race } from "./race";
import { resolve as staticResolve } from "./resolve";
import { reject as staticReject } from "./reject";
import { asap } from "./asap";

var counter = 0;

config.async = asap; // default async is asap;

function Promise(resolver) {
  if (!isFunction(resolver)) {
    throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  }

  if (!(this instanceof Promise)) {
    throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  }

  this._subscribers = [];

  invokeResolver(resolver, this);
}

function invokeResolver(resolver, promise) {
  function resolvePromise(value) {
    resolve(promise, value);
  }

  function rejectPromise(reason) {
    reject(promise, reason);
  }

  try {
    resolver(resolvePromise, rejectPromise);
  } catch(e) {
    rejectPromise(e);
  }
}

function invokeCallback(settled, promise, callback, detail) {
  var hasCallback = isFunction(callback),
      value, error, succeeded, failed;

  if (hasCallback) {
    try {
      value = callback(detail);
      succeeded = true;
    } catch(e) {
      failed = true;
      error = e;
    }
  } else {
    value = detail;
    succeeded = true;
  }

  if (handleThenable(promise, value)) {
    return;
  } else if (hasCallback && succeeded) {
    resolve(promise, value);
  } else if (failed) {
    reject(promise, error);
  } else if (settled === FULFILLED) {
    resolve(promise, value);
  } else if (settled === REJECTED) {
    reject(promise, value);
  }
}

var PENDING   = void 0;
var SEALED    = 0;
var FULFILLED = 1;
var REJECTED  = 2;

function subscribe(parent, child, onFulfillment, onRejection) {
  var subscribers = parent._subscribers;
  var length = subscribers.length;

  subscribers[length] = child;
  subscribers[length + FULFILLED] = onFulfillment;
  subscribers[length + REJECTED]  = onRejection;
}

function publish(promise, settled) {
  var child, callback, subscribers = promise._subscribers, detail = promise._detail;

  for (var i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    invokeCallback(settled, child, callback, detail);
  }

  promise._subscribers = null;
}

Promise.prototype = {
  constructor: Promise,

  _state: undefined,
  _detail: undefined,
  _subscribers: undefined,

  then: function(onFulfillment, onRejection) {
    var promise = this;

    var thenPromise = new this.constructor(function() {});

    if (this._state) {
      var callbacks = arguments;
      config.async(function invokePromiseCallback() {
        invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
      });
    } else {
      subscribe(this, thenPromise, onFulfillment, onRejection);
    }

    return thenPromise;
  },

  'catch': function(onRejection) {
    return this.then(null, onRejection);
  }
};

Promise.all = all;
Promise.cast = cast;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;

function handleThenable(promise, value) {
  var then = null,
  resolved;

  try {
    if (promise === value) {
      throw new TypeError("A promises callback cannot return that same promise.");
    }

    if (objectOrFunction(value)) {
      then = value.then;

      if (isFunction(then)) {
        then.call(value, function(val) {
          if (resolved) { return true; }
          resolved = true;

          if (value !== val) {
            resolve(promise, val);
          } else {
            fulfill(promise, val);
          }
        }, function(val) {
          if (resolved) { return true; }
          resolved = true;

          reject(promise, val);
        });

        return true;
      }
    }
  } catch (error) {
    if (resolved) { return true; }
    reject(promise, error);
    return true;
  }

  return false;
}

function resolve(promise, value) {
  if (promise === value) {
    fulfill(promise, value);
  } else if (!handleThenable(promise, value)) {
    fulfill(promise, value);
  }
}

function fulfill(promise, value) {
  if (promise._state !== PENDING) { return; }
  promise._state = SEALED;
  promise._detail = value;

  config.async(publishFulfillment, promise);
}

function reject(promise, reason) {
  if (promise._state !== PENDING) { return; }
  promise._state = SEALED;
  promise._detail = reason;

  config.async(publishRejection, promise);
}

function publishFulfillment(promise) {
  publish(promise, promise._state = FULFILLED);
}

function publishRejection(promise) {
  publish(promise, promise._state = REJECTED);
}

export { Promise };
<|endoftext|>