<commit_before>
'use strict';

const Promise = require('bluebird');
const Sanitizer = require('./strig-sanitize');
const URL = require('url');
const randomWords = require('random-words');

/**
 * Proxy Function of String Sanitzing
 * @param  {String} raw_string Raw String, such as from user input
 * @return {String}            Sanitzed String
 */
const sanitize = (raw_string) => {
  return Sanitizer.sanitize(raw_string);
};

/**
 * Validate if the incomping UUID is valid or not. (Callback)
 * The type of uuid used on xenserver is not-really-standard, fallback to regex
 * @param  {String} raw_uuid UUID String to be checked
 * @return {Boolean}         Is this UUID Correct?
 */
const check_uuid_base = (raw_uuid) => {
  return /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.test(raw_uuid);
};

/**
 * Validate if the incomping UUID is valid or not. (Promise)
 * @param  {String} raw_uuid UUID String to be checked
 * @return {Promise}         Is this UUID Correct?
 */
const check_uuid_promise = (raw_uuid) => {
  let promise = new Promise((fulfill, reject) => {
    if (check_uuid_base(raw_uuid)) {
      fulfill(raw_uuid);
    } else {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
  });
  return promise;
};

/**
 * generate meaningful Name, For various stuffs
 * @return {String} generated string
 */
const generate_name = () => {
  return randomWords({ exactly: 2, join: '-' });
};

/**
 * Check if the given installation is within allowed distro
 * @return {Boolean} Accept?
 */
const accpted_distro = ['debianlike', 'rhlike', 'sleslike'];
const check_distro = (input) => {
  // Human-Readable: http://manpages.ubuntu.com/manpages/precise/man1/eliloader.1.html
  // Currently supported values are 'rhlike', 'sleslike', and 'debianlike'.
  return accpted_distro.indexOf(sanitize(input.toLowerCase())) > -1;
};

/**
 * Check if the given installation is within allowed distro
 * @return {Boolean} Accept?
 */
const accepted_unit = ['M', 'G'];
const check_unit = (input) => {
  // Human-Readable: http://manpages.ubuntu.com/manpages/precise/man1/eliloader.1.html
  // Currently supported values are 'rhlike', 'sleslike', and 'debianlike'.
  return accepted_unit.indexOf(sanitize(input)) > -1;
};

/**
 * Create a new VM from a Template
 * @param  {Object} incoming_object No Description
 * @return {Promise}
 */
const vm_clone_from_template = (incoming) => {
  let parsed_repo = URL.parse(incoming.repo);
  let parsed_kick = URL.parse(incoming.ks);
  let normalized  = {};
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(incoming.src) || !check_uuid_base(incoming.network)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (incoming.repo === '' || incoming.ks === '') {
      reject({
        status: 400,
        error: 'REPO_OR_KS_File_Missing'
      });
    }
    if (parsed_repo.protocol === 'https:' || parsed_kick.protocol === 'https:') {
      reject({
        status: 400,
        error: 'HTTPS_NOT_SUPPORTED_ON_REPO_OR_KICKSTART_URL'
      });
    }
    if (!check_distro(incoming.distro)) {
      reject({
        status: 400,
        error: 'DISTRO_NOT_SUPPORTED',
        info: accpted_distro
      });
    }
    if (!check_unit(incoming.disk_unit) || !check_unit(incoming.ram_unit)) {
      reject({
        status: 400,
        error: 'INCORRECT_UNIT',
        info: accepted_unit
      });
    }
    fulfill({
      src_vm: sanitize(incoming.src),
      new_vm_name: incoming.vm_name === '' ? generate_name() : sanitize(incoming.vm_name),
      ks_url: incoming.ks,
      repo_url: incoming.repo,
      distro: sanitize(incoming.distro),
      deb_distro_release: sanitize(incoming.debian_distro),
      network_ref: sanitize(incoming.network),
      disk_size: incoming.disk_size,
      disk_unit: sanitize(incoming.disk_unit),
      ram_size: incoming.ram_size,
      ram_unit: sanitize(incoming.ram_unit),
      userid: incoming.userid
    });
  });
  return promise;
};

/**
 * Clone VM From Template
 * @param  {String} src_uuid Source VM UUID
 * @param  {Object} incoming express.js post body
 * @return {Promise}
 */
const vm_clone = (src_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(src_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    fulfill({
      src_vm: uuid,
      new_vm_name: (incoming.hasOwnProperty('vm_name') || incoming.vm_name === '') ? generate_name() : sanitize(incoming.vm_name),
      userid: incoming.userid
    });
  });
  return promise;
};

/**
 * Tag // Untag an object
 * @param  {String} target_uuid Target Object UUID
 * @param  {Object} incoming    express.js post body
 * @return {Promise}
 */
const tag = (target_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(target_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (!incoming.hasOwnProperty('tag') || incoming.tag === '') {
      reject({
        status: 400,
        error: 'TAG_MISSING'
      });
    }
    fulfill({
      ref: target_uuid,
      tag: sanitize(incoming.tag)
    });
  });
  return promise;
};

/**
 * Generate VIF Creation
 * @param  {Object} incoming    express.js post body
 * @return {Promise}
 */
const vif = (target_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(target_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (!incoming.hasOwnProperty('vm_slot') || isNaN(parseInt(incoming.vm_slot, 10)) || parseInt(incoming.vm_slot, 10) <= 0) {
      reject({
        status: 400,
        error: 'INVALID_SLOT'
      });
    }
    fulfill({
      vm: incoming.vm_uuid,
      net: incoming.vnet_uuid,
      slot: incoming.vm_slot
    });
  });
  return promise;
};

/**
 * Generate Payload for resizing VDI
 * @param  {String} incoming_uuid UUID Value in URL.
 * @param  {Object} incoming      express.js req.body
 * @return {Promise}
 */
const vdi_resize = (incoming_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!incoming.hasOwnProperty('vnet_uuid') || !incoming.hasOwnProperty('vm_uuid') || !check_uuid_base(incoming.vnet_uuid) || !check_uuid_base(incoming.vm_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (!check_unit(incoming.disk_unit)) {
      reject({
        status: 400,
        error: 'INCORRECT_UNIT',
        info: accepted_unit
      });
    }
    fulfill({
      vdi_ref: incoming.vm_uuid,
      vdi_size: incoming.vdi_size,
      vdi_unit: incoming.vdi_unit
    });
  });
  return promise;
};

/**
 * Generate Payload for Creating Network
 * @param {Object} incoming
 * @return {Promise}
 */
const vnet = (incoming) => {
  let promise = new Promise((fulfill, reject) => {
    fulfill({
      network_name: (incoming.hasOwnProperty('net_name') || incoming.net_name === '') ? generate_name() : sanitize(incoming.net_name),
      userid: incoming.userid
    });
  });
  return promise;
};

/**
 * Route Preprocessor: Check if Userid is included.
 * @param {Object}  req     express.js request
 * @param {Object}  res     express.js response
 * @param {*}       next    express.js callback to next middleware
 */
const pp_userid = (req, res, next) => {
  if (req.body.hasOwnProperty('userid') && !isNaN(parseInt(req.body.userid, 10))) {
    return next();
  } else {
    res.status(403).json({
      status: 403,
      error: 'FORBIDDEN_USERID_MISSING'
    });
  }
};

module.exports = {
  uuid: check_uuid_promise,
  sanitize: sanitize,
  generate: {
    vm_clone_from_tpl: vm_clone_from_template,
    vm_clone: vm_clone,
    tag: tag,
    net: vnet,
    vif: vif,
    vdi_resize: vdi_resize
  },
  pp: {
    userid: pp_userid
  }
};
<commit_msg>Fix an error on referencing uuid<commit_after>
'use strict';

const Promise = require('bluebird');
const Sanitizer = require('./strig-sanitize');
const URL = require('url');
const randomWords = require('random-words');

/**
 * Proxy Function of String Sanitzing
 * @param  {String} raw_string Raw String, such as from user input
 * @return {String}            Sanitzed String
 */
const sanitize = (raw_string) => {
  return Sanitizer.sanitize(raw_string);
};

/**
 * Validate if the incomping UUID is valid or not. (Callback)
 * The type of uuid used on xenserver is not-really-standard, fallback to regex
 * @param  {String} raw_uuid UUID String to be checked
 * @return {Boolean}         Is this UUID Correct?
 */
const check_uuid_base = (raw_uuid) => {
  return /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/.test(raw_uuid);
};

/**
 * Validate if the incomping UUID is valid or not. (Promise)
 * @param  {String} raw_uuid UUID String to be checked
 * @return {Promise}         Is this UUID Correct?
 */
const check_uuid_promise = (raw_uuid) => {
  let promise = new Promise((fulfill, reject) => {
    if (check_uuid_base(raw_uuid)) {
      fulfill(raw_uuid);
    } else {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
  });
  return promise;
};

/**
 * generate meaningful Name, For various stuffs
 * @return {String} generated string
 */
const generate_name = () => {
  return randomWords({ exactly: 2, join: '-' });
};

/**
 * Check if the given installation is within allowed distro
 * @return {Boolean} Accept?
 */
const accpted_distro = ['debianlike', 'rhlike', 'sleslike'];
const check_distro = (input) => {
  // Human-Readable: http://manpages.ubuntu.com/manpages/precise/man1/eliloader.1.html
  // Currently supported values are 'rhlike', 'sleslike', and 'debianlike'.
  return accpted_distro.indexOf(sanitize(input.toLowerCase())) > -1;
};

/**
 * Check if the given installation is within allowed distro
 * @return {Boolean} Accept?
 */
const accepted_unit = ['M', 'G'];
const check_unit = (input) => {
  // Human-Readable: http://manpages.ubuntu.com/manpages/precise/man1/eliloader.1.html
  // Currently supported values are 'rhlike', 'sleslike', and 'debianlike'.
  return accepted_unit.indexOf(sanitize(input)) > -1;
};

/**
 * Create a new VM from a Template
 * @param  {Object} incoming_object No Description
 * @return {Promise}
 */
const vm_clone_from_template = (incoming) => {
  let parsed_repo = URL.parse(incoming.repo);
  let parsed_kick = URL.parse(incoming.ks);
  let normalized  = {};
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(incoming.src) || !check_uuid_base(incoming.network)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (incoming.repo === '' || incoming.ks === '') {
      reject({
        status: 400,
        error: 'REPO_OR_KS_File_Missing'
      });
    }
    if (parsed_repo.protocol === 'https:' || parsed_kick.protocol === 'https:') {
      reject({
        status: 400,
        error: 'HTTPS_NOT_SUPPORTED_ON_REPO_OR_KICKSTART_URL'
      });
    }
    if (!check_distro(incoming.distro)) {
      reject({
        status: 400,
        error: 'DISTRO_NOT_SUPPORTED',
        info: accpted_distro
      });
    }
    if (!check_unit(incoming.disk_unit) || !check_unit(incoming.ram_unit)) {
      reject({
        status: 400,
        error: 'INCORRECT_UNIT',
        info: accepted_unit
      });
    }
    fulfill({
      src_vm: sanitize(incoming.src),
      new_vm_name: incoming.vm_name === '' ? generate_name() : sanitize(incoming.vm_name),
      ks_url: incoming.ks,
      repo_url: incoming.repo,
      distro: sanitize(incoming.distro),
      deb_distro_release: sanitize(incoming.debian_distro),
      network_ref: sanitize(incoming.network),
      disk_size: incoming.disk_size,
      disk_unit: sanitize(incoming.disk_unit),
      ram_size: incoming.ram_size,
      ram_unit: sanitize(incoming.ram_unit),
      userid: incoming.userid
    });
  });
  return promise;
};

/**
 * Clone VM From Template
 * @param  {String} src_uuid Source VM UUID
 * @param  {Object} incoming express.js post body
 * @return {Promise}
 */
const vm_clone = (src_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(src_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    fulfill({
      src_vm: src_uuid,
      new_vm_name: (incoming.hasOwnProperty('vm_name') || incoming.vm_name === '') ? generate_name() : sanitize(incoming.vm_name),
      userid: incoming.userid
    });
  });
  return promise;
};

/**
 * Tag // Untag an object
 * @param  {String} target_uuid Target Object UUID
 * @param  {Object} incoming    express.js post body
 * @return {Promise}
 */
const tag = (target_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(target_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (!incoming.hasOwnProperty('tag') || incoming.tag === '') {
      reject({
        status: 400,
        error: 'TAG_MISSING'
      });
    }
    fulfill({
      ref: target_uuid,
      tag: sanitize(incoming.tag)
    });
  });
  return promise;
};

/**
 * Generate VIF Creation
 * @param  {Object} incoming    express.js post body
 * @return {Promise}
 */
const vif = (target_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!check_uuid_base(target_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (!incoming.hasOwnProperty('vm_slot') || isNaN(parseInt(incoming.vm_slot, 10)) || parseInt(incoming.vm_slot, 10) <= 0) {
      reject({
        status: 400,
        error: 'INVALID_SLOT'
      });
    }
    fulfill({
      vm: incoming.vm_uuid,
      net: incoming.vnet_uuid,
      slot: incoming.vm_slot
    });
  });
  return promise;
};

/**
 * Generate Payload for resizing VDI
 * @param  {String} incoming_uuid UUID Value in URL.
 * @param  {Object} incoming      express.js req.body
 * @return {Promise}
 */
const vdi_resize = (incoming_uuid, incoming) => {
  let promise = new Promise((fulfill, reject) => {
    if (!incoming.hasOwnProperty('vnet_uuid') || !incoming.hasOwnProperty('vm_uuid') || !check_uuid_base(incoming.vnet_uuid) || !check_uuid_base(incoming.vm_uuid)) {
      reject({
        status: 400,
        error: 'INVALID_UUID'
      });
    }
    if (!check_unit(incoming.disk_unit)) {
      reject({
        status: 400,
        error: 'INCORRECT_UNIT',
        info: accepted_unit
      });
    }
    fulfill({
      vdi_ref: incoming.vm_uuid,
      vdi_size: incoming.vdi_size,
      vdi_unit: incoming.vdi_unit
    });
  });
  return promise;
};

/**
 * Generate Payload for Creating Network
 * @param {Object} incoming
 * @return {Promise}
 */
const vnet = (incoming) => {
  let promise = new Promise((fulfill, reject) => {
    fulfill({
      network_name: (incoming.hasOwnProperty('net_name') || incoming.net_name === '') ? generate_name() : sanitize(incoming.net_name),
      userid: incoming.userid
    });
  });
  return promise;
};

/**
 * Route Preprocessor: Check if Userid is included.
 * @param {Object}  req     express.js request
 * @param {Object}  res     express.js response
 * @param {*}       next    express.js callback to next middleware
 */
const pp_userid = (req, res, next) => {
  if (req.body.hasOwnProperty('userid') && !isNaN(parseInt(req.body.userid, 10))) {
    return next();
  } else {
    res.status(403).json({
      status: 403,
      error: 'FORBIDDEN_USERID_MISSING'
    });
  }
};

module.exports = {
  uuid: check_uuid_promise,
  sanitize: sanitize,
  generate: {
    vm_clone_from_tpl: vm_clone_from_template,
    vm_clone: vm_clone,
    tag: tag,
    net: vnet,
    vif: vif,
    vdi_resize: vdi_resize
  },
  pp: {
    userid: pp_userid
  }
};
<|endoftext|>


<commit_before>import React from "react";
import { Switch, Route } from "react-router";
import Map from "./containers/Map";
import SearchResults from "./containers/SearchResults";
import { injectIntl } from "react-intl";
import "./Home.css";
import MediaQuery from "react-responsive";

class Home extends React.Component {
  render() {
    return (

        <MediaQuery query="(min-device-width: 992px)">
          <Map />
        </MediaQuery>
        <Switch>
          <Route
            exact
            path="/"
            component={() => <SearchResults {...this.props} />}
          />
          <Route
            exact
            path="/search"
            component={() => <SearchResults {...this.props} />}
          />
          <Route
            path="/cases"
            component={() =>
              <SearchResults selectedCategory="Cases" {...this.props} />}
          />
          <Route
            path="/methods"
            component={() =>
              <SearchResults selectedCategory="Methods" {...this.props} />}
          />
          <Route
            path="/organizations"
            component={() =>
              <SearchResults
                selectedCategory="Organizations"
                {...this.props}
              />}
          />
        </Switch>

    );
  }
}

export default injectIntl(Home);
<commit_msg>Cleaning up unnecessary complexity<commit_after>import React from "react";
import { Switch, Route } from "react-router";
import Map from "./containers/Map";
import SearchResults from "./containers/SearchResults";
import { injectIntl } from "react-intl";
import "./Home.css";
import MediaQuery from "react-responsive";

class Home extends React.Component {
  render() {
    return (

        <MediaQuery query="(min-device-width: 992px)">
          <Map />
        </MediaQuery>
        <Switch>
          <Route exact path="/" component={SearchResults} />
          <Route exact path="/search" component={SearchResults} />
          <Route
            path="/cases"
            component={() => (
              <SearchResults selectedCategory="Cases" {...this.props} />
            )}
          />
          <Route
            path="/methods"
            component={() => (
              <SearchResults selectedCategory="Methods" {...this.props} />
            )}
          />
          <Route
            path="/organizations"
            component={() => (
              <SearchResults selectedCategory="Organizations" {...this.props} />
            )}
          />
        </Switch>

    );
  }
}

export default injectIntl(Home);
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 GochoMugo <mugo@forfuture.co.ke>
 * Copyright (c) 2017 Forfuture LLC <we@forfuture.co.ke>
 */

// built-in modules
const assert = require("assert");

// own modules
const SessionStore = require("../../../store/base");
const RedisStore = require("../../../store/redis");

describe("RedisStore", function() {
    const sid = "SID";
    const session = { key: "value" };
    const options = { ttl: +Infinity };
    let store;

    beforeEach(function() {
        store = new RedisStore({
            prefix: "test:mau:",
        });
    });

    it("is exported as a Function/constructor", function() {
        assert.equal(typeof RedisStore, "function");
    });
    it("sub-classes SessionStore", function() {
        assert.ok(store instanceof SessionStore);
    });

    describe("#put()", function() {
        it("[#get()] saves key-value pair", function(done) {
            store.put(sid, session, options, function(error) {
                assert.ifError(error);
                store.get(sid, function(error, sess) {
                    assert.ifError(error);
                    assert.deepEqual(sess, session, "Incorrect session returned.");
                    return done();
                });
            });
        });
    });

    describe("#del()", function() {
        it("deletes session", function(done) {
            store.del(sid, function(error) {
                assert.ifError(error);
                store.get(sid, function(error, sess) {
                    assert.ifError(error);
                    assert.ok(!sess, "Session not destroyed.");
                    return done();
                });
            });
        });
    });
});
<commit_msg>test: Clean redis session data before test<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 GochoMugo <mugo@forfuture.co.ke>
 * Copyright (c) 2017 Forfuture LLC <we@forfuture.co.ke>
 */

// built-in modules
const assert = require("assert");

// own modules
const SessionStore = require("../../../store/base");
const RedisStore = require("../../../store/redis");

describe("RedisStore", function() {
    const prefix = "test:mau:";
    const sid = "SID";
    const session = { key: "value" };
    const options = { ttl: +Infinity };
    let store;

    beforeEach(function(done) {
        store = new RedisStore({
            prefix,
        });
        store.del(sid, done);
    });

    it("is exported as a Function/constructor", function() {
        assert.equal(typeof RedisStore, "function");
    });
    it("sub-classes SessionStore", function() {
        assert.ok(store instanceof SessionStore);
    });

    describe("#put()", function() {
        it("[#get()] saves key-value pair", function(done) {
            store.put(sid, session, options, function(error) {
                assert.ifError(error);
                store.get(sid, function(error, sess) {
                    assert.ifError(error);
                    assert.deepEqual(sess, session, "Incorrect session returned.");
                    return done();
                });
            });
        });
    });

    describe("#del()", function() {
        it("[#put()] deletes session", function(done) {
            store.put(sid, session, options, function(error) {
                assert.ifError(error);
                store.del(sid, function(error) {
                    assert.ifError(error);
                    store.get(sid, function(error, sess) {
                        assert.ifError(error);
                        assert.ok(!sess, "Session not destroyed.");
                        return done();
                    });
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

describe('stream', function() {
  beforeEach(function() {
    this.addMatchers({
      toMatchTypedArray: function(expected) {
        var actual = this.actual;
        if (actual.length != expected.length)
          return false;
        for (var i = 0, ii = expected.length; i < ii; i++) {
          var a = actual[i], b = expected[i];
          if (a !== b)
            return false;
        }
        return true;
      }
    });
  });
  describe('PredictorStream', function() {
    it('should decode simple predictor data', function() {
      var dict = new Dict();
      dict.set('Predictor', 12);
      dict.set('Colors', 1);
      dict.set('BitsPerComponent', 8);
      dict.set('Columns', 2);

      var input = new Stream(new Uint8Array([2, 100, 3, 2, 1, 255, 2, 1, 255]),
        0, 9, dict);
      var predictor = new PredictorStream(input, dict);
      var result = predictor.getBytes(6);

      expect(result).toMatchTypedArray(new Uint8Array([100, 3, 101, 2, 102, 1]));
    });
  });
});

<commit_msg>Fix nit.<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

'use strict';

describe('stream', function() {
  beforeEach(function() {
    this.addMatchers({
      toMatchTypedArray: function(expected) {
        var actual = this.actual;
        if (actual.length != expected.length)
          return false;
        for (var i = 0, ii = expected.length; i < ii; i++) {
          var a = actual[i], b = expected[i];
          if (a !== b)
            return false;
        }
        return true;
      }
    });
  });
  describe('PredictorStream', function() {
    it('should decode simple predictor data', function() {
      var dict = new Dict();
      dict.set('Predictor', 12);
      dict.set('Colors', 1);
      dict.set('BitsPerComponent', 8);
      dict.set('Columns', 2);

      var input = new Stream(new Uint8Array([2, 100, 3, 2, 1, 255, 2, 1, 255]),
        0, 9, dict);
      var predictor = new PredictorStream(input, dict);
      var result = predictor.getBytes(6);

      expect(result).toMatchTypedArray(
        new Uint8Array([100, 3, 101, 2, 102, 1])
      );
    });
  });
});

<|endoftext|>


<commit_before>var Kiwi = (function ($) {
	var TRANSPOSE_CHAR = '%';

	var interpolate_general = function(text, array){
		var stringToReturn = ""
		 	,length = text.length
		 	,index = 0
		 	,array_length = array.length;

		for(var i = 0; i < length; i++){
			var currentChar = text[i];
			var nextChar = null;
			if(i + 1 < length) nextChar = text[i+1];

			if(currentChar === '`' && nextChar === TRANSPOSE_CHAR){
				stringToReturn += TRANSPOSE_CHAR;
				i += 1;
			}else{
				if(currentChar === TRANSPOSE_CHAR){
					if(index < array_length){
						stringToReturn += array[index++];
					}else{
						stringToReturn += '';
					}
				}
				else{
					stringToReturn += currentChar;
				}
			}
		}
		return stringToReturn;
	}

	var get_key_length = function(text, index){
		var length = text.length;

		var key = "";

		var i = index;
		while(i < length && text[i] !== '}'){
			key += text[i];
			i++;
		}

		if(text[i] === '}') key += '}';
		else throw Error("Syntax error.");

		return [key.slice(2, key.length - 1), key.length];
	}

	var interpolate_key_value = function(text, json){
		var stringToReturn = ""
		 	,length = text.length
		 	,index = 0;

		for(var i = 0; i < length; i++){
			var currentChar = text[i];
			var nextChar = null;
			if(i + 1 < length) nextChar = text[i+1];

			if(currentChar === '%' && nextChar === '{'){
				var result = get_key_length(text, i);
				var key = result[0];
				var key_length = result[1];

				stringToReturn += (json[key] === undefined ? "" : json[key]);
				i += key_length - 1 ;

			}else{
				stringToReturn += currentChar;
			}
		}

		return stringToReturn;
	}

	var interpolate = function(text, input){
		if(input === undefined) return text;

		if(Object.prototype.toString.call(input) === "[object Array]"){
			return interpolate_general(text, input);
		}else{
			return interpolate_key_value(text, input);
		}
	};

	return {
		"compose": interpolate
	};

}(Kiwi));<commit_msg>Updated the error name.<commit_after>var Kiwi = (function ($) {
	var TRANSPOSE_CHAR = '%';

	var interpolate_general = function(text, array){
		var stringToReturn = ""
		 	,length = text.length
		 	,index = 0
		 	,array_length = array.length;

		for(var i = 0; i < length; i++){
			var currentChar = text[i];
			var nextChar = null;
			if(i + 1 < length) nextChar = text[i+1];

			if(currentChar === '`' && nextChar === TRANSPOSE_CHAR){
				stringToReturn += TRANSPOSE_CHAR;
				i += 1;
			}else{
				if(currentChar === TRANSPOSE_CHAR){
					if(index < array_length){
						stringToReturn += array[index++];
					}else{
						stringToReturn += '';
					}
				}
				else{
					stringToReturn += currentChar;
				}
			}
		}
		return stringToReturn;
	}

	var get_key_length = function(text, index){
		var length = text.length;

		var key = "";

		var i = index;
		while(i < length && text[i] !== '}'){
			key += text[i];
			i++;
		}

		if(text[i] === '}') key += '}';
		else throw Error("SYNTAX ERROR");

		return [key.slice(2, key.length - 1), key.length];
	}

	var interpolate_key_value = function(text, json){
		var stringToReturn = ""
		 	,length = text.length
		 	,index = 0;

		for(var i = 0; i < length; i++){
			var currentChar = text[i];
			var nextChar = null;
			if(i + 1 < length) nextChar = text[i+1];

			if(currentChar === '%' && nextChar === '{'){
				var result = get_key_length(text, i);
				var key = result[0];
				var key_length = result[1];

				stringToReturn += (json[key] === undefined ? "" : json[key]);
				i += key_length - 1 ;

			}else{
				stringToReturn += currentChar;
			}
		}

		return stringToReturn;
	}

	var interpolate = function(text, input){
		if(input === undefined) return text;

		if(Object.prototype.toString.call(input) === "[object Array]"){
			return interpolate_general(text, input);
		}else{
			return interpolate_key_value(text, input);
		}
	};

	return {
		"compose": interpolate
	};

}(Kiwi));<|endoftext|>


<commit_before>import wrapper from '../../src/pdftotext-wrapper';
import {expect} from 'chai';

describe('pdftotext-wrapper', () => {
  it('should abort on non-exist PDF files', () => {
    return expect(wrapper('not-exist.pdf')).to.be.rejected;
  });

  it('should invoke pdftotext', () => {
    return expect(wrapper('test/fixture/oneword.pdf')).to.eventually.include('FOO_BAR');
  });

  it('should handle large PDF files', () => {
    return wrapper('test/fixture/large.pdf').then(html => {
      expect(html).to.be.a('string');
    });
  });

});
<commit_msg>wrapper should pass commands through to pdftotext<commit_after>import wrapper from '../../src/pdftotext-wrapper';
import {expect} from 'chai';

describe('pdftotext-wrapper', () => {
  it('should abort on non-exist PDF files', () => {
    return expect(wrapper('not-exist.pdf')).to.be.rejected;
  });

  it('should invoke pdftotext', () => {
    return expect(wrapper('test/fixture/oneword.pdf')).to.eventually.include('FOO_BAR');
  });

  it('should handle large PDF files', () => {
    return wrapper('test/fixture/large.pdf').then(html => {
      expect(html).to.be.a('string');
    });
  });

  it('should pass command through', () => {
    return wrapper('test/fixture/large.pdf', '-l 1').then(html => {
      expect(html.match(/<page/gi).length).to.equal(1);
    });
  });

});
<|endoftext|>


<commit_before>var util = require('../util.test');

module.exports = function() {
  if (/^v0\.10\./.test(process.version)) { //node 0.10不支持socksv5这个模块，暂时屏蔽掉
    return;
  }
  util.request('http://socks1.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks1.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks2.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks2.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks3.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks3.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks4.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks4.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks5.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks5.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks6.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks6.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks7.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks7.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks8.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks8.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });
};
<commit_msg>test: socks<commit_after>var util = require('../util.test');

module.exports = function() {
  if (/^v0\.10\./.test(process.version) ||  process.versions.modules >= 64) { //node 0.10不支持socksv5这个模块，暂时屏蔽掉
    return;
  }
  util.request('http://socks1.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks1.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks2.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks2.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks3.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks3.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks4.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks4.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks5.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks5.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks6.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks6.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks7.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1080);
  });
  util.request('https://socks7.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });

  util.request('http://socks8.w2.org/index.html', function(res, data) {
    data.port.should.be.equal(1118);
  });
  util.request('https://socks8.w2.org/index.html', function(res, data) {
    data.body.should.be.equal('test');
  });
};
<|endoftext|>


<commit_before>var chai = require('chai');
var expect = chai.expect;
var Label = require('../../lib/utils/label');

describe('lib/utils/label', function () {
    var label;
    var scale;
    before(function () {
        label = new Label();
        scale = { min: { '0': 30, '1': 24 },
          max: { '0': 300, '1': 600 },
          maxSet: [],
          len: 10,
          rows: 2,
          ySecs: { 0: 3, 1: 3 },
          color: [ 'red', 'blue' ],
          scattered: false,
          line: true,
          'font-family': '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',
          height: 500,
          width: 1200,
          pHeight: 460,
          paddingY: 20,
          paddingX: 30 };
    });

    it('describeYAxis (scale, multi : true ) should return a yaxis border', function () {
        var result = label.describeYAxis(scale, {multi: true});
        expect(result)
            .to.be.a('array')
            .to.have.length(2)
            .to.satisfy(function (arr) {
                return /text/.test(arr[0]) && /text/.test(arr[1]);
            });
    });

    it('describeYAxis (scale, true) should return a yaxis label set', function () {
        scale.ySecs = 3;
        scale.max = 300;
        var result = label.describeYAxis(scale, true);
        expect(result)
            .to.be.a('array')
            .to.have.length(1)
            .to.satisfy(function (arr) {
                return /text/.test(arr[0]);
            });
    });

    it('describeXAxis (scale, opts) should return a xaxis label set', function () {
        var scale = { min: { '0': 68, '1': 30 },
          max: { '0': 600, '1': 500 },
          maxSet: [],
          len: 10,
          rows: 2,
          ySecs: { '0': 3, '1': 5 },
          color: [ 'red', 'blue' ],
          scattered: false,
          line: true,
          'font-family': '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',
          height: 500,
          width: 1200,
          pHeight: 460,
          paddingY: 20,
          paddingX: 30,
          heightRatio: NaN,
          gap: 125.55556 };

        var opts = { dateTimeLabelFormat: 'MM/DD hh ap',
          minUTC: 1378512000000,
          interval: '4h',
          format: 'dateTime' };

        var result = label.describeXAxis(scale, opts);
        expect(result)
            .to.be.a('array')
            .to.have.length(1)
            .to.satisfy(function (arr) {
                return /text/.test(arr[0]);
            });
    });

    it('_utcMultiplier should return utc', function () {
        expect(label._utcMultiplier('1s'))
            .to.equal(1000);
        expect(label._utcMultiplier('1m'))
            .to.equal(6e4);
        expect(label._utcMultiplier('1h'))
            .to.equal(3600000);
        expect(label._utcMultiplier('1D'))
            .to.equal(86400000);
        expect(label._utcMultiplier('1M'))
            .to.equal(2592000000);
        expect(label._utcMultiplier('1Y'))
            .to.equal(31104000000);
    });

    it('_formatTimeStamp should return the desired time format', function () {
        var base = 1378512000000;
        expect(label._formatTimeStamp('YY/MM/DD', base + 3600000))
            .to.equal('13/9/6');
        expect(label._formatTimeStamp('YYYY', base + 3600000))
            .to.equal('2013');
        expect(label._formatTimeStamp('mm.ss', base + 3600000))
            .to.equal('00.00');
    });
});<commit_msg>updated test to avoid timezone<commit_after>var chai = require('chai');
var expect = chai.expect;
var Label = require('../../lib/utils/label');

describe('lib/utils/label', function () {
    var label;
    var scale;
    before(function () {
        label = new Label();
        scale = { min: { '0': 30, '1': 24 },
          max: { '0': 300, '1': 600 },
          maxSet: [],
          len: 10,
          rows: 2,
          ySecs: { 0: 3, 1: 3 },
          color: [ 'red', 'blue' ],
          scattered: false,
          line: true,
          'font-family': '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',
          height: 500,
          width: 1200,
          pHeight: 460,
          paddingY: 20,
          paddingX: 30 };
    });

    it('describeYAxis (scale, multi : true ) should return a yaxis border', function () {
        var result = label.describeYAxis(scale, {multi: true});
        expect(result)
            .to.be.a('array')
            .to.have.length(2)
            .to.satisfy(function (arr) {
                return /text/.test(arr[0]) && /text/.test(arr[1]);
            });
    });

    it('describeYAxis (scale, true) should return a yaxis label set', function () {
        scale.ySecs = 3;
        scale.max = 300;
        var result = label.describeYAxis(scale, true);
        expect(result)
            .to.be.a('array')
            .to.have.length(1)
            .to.satisfy(function (arr) {
                return /text/.test(arr[0]);
            });
    });

    it('describeXAxis (scale, opts) should return a xaxis label set', function () {
        var scale = { min: { '0': 68, '1': 30 },
          max: { '0': 600, '1': 500 },
          maxSet: [],
          len: 10,
          rows: 2,
          ySecs: { '0': 3, '1': 5 },
          color: [ 'red', 'blue' ],
          scattered: false,
          line: true,
          'font-family': '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',
          height: 500,
          width: 1200,
          pHeight: 460,
          paddingY: 20,
          paddingX: 30,
          heightRatio: NaN,
          gap: 125.55556 };

        var opts = { dateTimeLabelFormat: 'MM/DD hh ap',
          minUTC: 1378512000000,
          interval: '4h',
          format: 'dateTime' };

        var result = label.describeXAxis(scale, opts);
        expect(result)
            .to.be.a('array')
            .to.have.length(1)
            .to.satisfy(function (arr) {
                return /text/.test(arr[0]);
            });
    });

    it('_utcMultiplier should return utc', function () {
        expect(label._utcMultiplier('1s'))
            .to.equal(1000);
        expect(label._utcMultiplier('1m'))
            .to.equal(6e4);
        expect(label._utcMultiplier('1h'))
            .to.equal(3600000);
        expect(label._utcMultiplier('1D'))
            .to.equal(86400000);
        expect(label._utcMultiplier('1M'))
            .to.equal(2592000000);
        expect(label._utcMultiplier('1Y'))
            .to.equal(31104000000);
    });

    it('_formatTimeStamp should return the desired time format', function () {
        var base = 1378512000000;
        expect(label._formatTimeStamp('YY/MM', base + 3600000))
            .to.equal('13/9');
        expect(label._formatTimeStamp('YYYY', base + 3600000))
            .to.equal('2013');
        expect(label._formatTimeStamp('mm.ss', base + 3600000))
            .to.equal('00.00');
    });
});<|endoftext|>


<commit_before>/*
 * tests requiring DOM manipulation for punchcards.WeekdayRect from dist/punchcards.js
 */

describe('punchcards WeekdayRect class...', function() {

    var fixtures, cf;

    beforeEach(function() {

        var data;

        // set the base directory for loading of fixtures
        fixture.setBase('test');

        // load the html and json fixtures
        fixtures = fixture.load('weekday-rect.fixture.html',
            'cityofchicago-police-data.fixture.json');

        data = fixtures[1];
        cf = crossfilter(data);

    });

    afterEach(function(){
        // clean up the DOM
        fixture.cleanup();
        cf = undefined;
    });

    it('...html fixture should have loaded correctly', function() {
        var actual, expected;
        actual = fixtures[0][0].outerHTML;
        expected = '

';
        expect(actual).toEqual(expected);
    });

    it('...json fixture should have loaded correctly', function() {
        var actual, expected;
        actual = Object.keys(fixtures[1][0]).sort();
        expected = ["casenumber", "datestr", "description", "latitude", "longitude", "primary"];
        expect(actual).toEqual(expected);
    });

    it('...json fixture should have 5000 records', function() {
        var actual, expected;
        actual = cf.size();
        expected = 5000;
        expect(actual).toEqual(expected);
    });

    it('...constructor should return an instance of punchcards.WeekdayRect when called with valid arguments', function() {
        var actual, weekdayrect;
        weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
        actual = weekdayrect instanceof punchcards.WeekdayRect;
        expect(actual).toBe(true);
    });

    it('...after calling .drawHorizontalAxis(), the chart should have an ' +
        'SVG g element of class "horizontal-axis" attached to it', function() {
        var actual, weekdayrect;
        weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
        weekdayrect.defineDimensions();
        weekdayrect.drawSvg();
        weekdayrect.drawHorizontalAxis();
        actual = weekdayrect.svg.select('g.horizontal-axis')[0][0];
        expect(actual).not.toBe(null);
    });

    it('...after calling .drawSymbols(), the chart should have an ' +
        'SVG g element of class "symbol" attached to it', function() {
        var actual, weekdayrect;
        weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
        weekdayrect.defineDimensions();
        weekdayrect.drawSvg();
        weekdayrect.drawHorizontalAxis();
        weekdayrect.drawVerticalAxis();
        weekdayrect.drawSymbols();
        actual = weekdayrect.svg.select('g.symbol')[0][0];
        expect(actual).not.toBe(null);
    });

    it('...after calling .drawSymbols(), the chart should have an ' +
        'SVG g element of class "symbol" with 139 SVG rects of class ' +
        '"symbol" attached to it', function() {
        var actual, weekdayrect, symbols;
        weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
        weekdayrect.defineDimensions();
        weekdayrect.drawSvg();
        weekdayrect.drawHorizontalAxis();
        weekdayrect.drawVerticalAxis();
        weekdayrect.drawSymbols();
        symbols = weekdayrect.svg.select('g.symbol').selectAll('rect.symbol')[0];
        actual = symbols.length;;
        expect(actual).toEqual(139);
    });

})

<commit_msg>fixed all jslint and jshint errors<commit_after>/*
 * tests requiring DOM manipulation for punchcards.WeekdayRect from dist/punchcards.js
 */

/*global describe, beforeEach, fixture, crossfilter, afterEach, it, expect, punchcards*/

describe('punchcards WeekdayRect class...', function () {

    'use strict';

    var fixtures, cf;

    beforeEach(function () {

        var data;

        // set the base directory for loading of fixtures
        fixture.setBase('test');

        // load the html and json fixtures
        fixtures = fixture.load('weekday-rect.fixture.html',
            'cityofchicago-police-data.fixture.json');

        data = fixtures[1];
        cf = crossfilter(data);

    });

    afterEach(function () {
        // clean up the DOM
        fixture.cleanup();
        cf = undefined;
    });

    it('...html fixture should have loaded correctly', function () {
        var actual, expected;
        actual = fixtures[0][0].outerHTML;
        expected = '

';
        expect(actual).toEqual(expected);
    });

    it('...json fixture should have loaded correctly', function () {
        var actual, expected;
        actual = Object.keys(fixtures[1][0]).sort();
        expected = ["casenumber", "datestr", "description", "latitude", "longitude", "primary"];
        expect(actual).toEqual(expected);
    });

    it('...json fixture should have 5000 records', function () {
        var actual, expected;
        actual = cf.size();
        expected = 5000;
        expect(actual).toEqual(expected);
    });

    it('...constructor should return an instance of punchcards.WeekdayRect when called with valid arguments', function () {
        var actual, weekdayrect;
        weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
        actual = weekdayrect instanceof punchcards.WeekdayRect;
        expect(actual).toBe(true);
    });

    it('...after calling .drawHorizontalAxis(), the chart should have an ' +
        'SVG g element of class "horizontal-axis" attached to it', function () {
            var actual, weekdayrect;
            weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
            weekdayrect.defineDimensions();
            weekdayrect.drawSvg();
            weekdayrect.drawHorizontalAxis();
            actual = weekdayrect.svg.select('g.horizontal-axis')[0][0];
            expect(actual).not.toBe(null);
        });

    it('...after calling .drawSymbols(), the chart should have an ' +
        'SVG g element of class "symbol" attached to it', function () {
            var actual, weekdayrect;
            weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
            weekdayrect.defineDimensions();
            weekdayrect.drawSvg();
            weekdayrect.drawHorizontalAxis();
            weekdayrect.drawVerticalAxis();
            weekdayrect.drawSymbols();
            actual = weekdayrect.svg.select('g.symbol')[0][0];
            expect(actual).not.toBe(null);
        });

    it('...after calling .drawSymbols(), the chart should have an ' +
        'SVG g element of class "symbol" with 139 SVG rects of class ' +
        '"symbol" attached to it', function () {
            var actual, weekdayrect, symbols;
            weekdayrect = new punchcards.WeekdayRect(cf, 'punchcard-weekday-rect');
            weekdayrect.defineDimensions();
            weekdayrect.drawSvg();
            weekdayrect.drawHorizontalAxis();
            weekdayrect.drawVerticalAxis();
            weekdayrect.drawSymbols();
            symbols = weekdayrect.svg.select('g.symbol').selectAll('rect.symbol')[0];
            actual = symbols.length;
            expect(actual).toEqual(139);
        });

});

<|endoftext|>


<commit_before>'use strict';
/**
 * Unit tests for Configuration.
 */

const chai = require('chai');
const Configuration = require('./Configuration');

const expect = chai.expect;

describe('Configuration', () => {
  describe('defaults', () => {
    let expectedDefaults;

    before(() => {
      expectedDefaults = {
        webpackConfig: 'webpack.config.js',
        includeModules: false,
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        serializedCompile: false
      };
    });

    it('should set default configuration without custom', () => {
      const config = new Configuration();
      expect(config).to.have.a.property('_config').that.deep.equals(expectedDefaults);
      expect(config).to.have.a.property('hasLegacyConfig').that.is.false;
    });

    it('should set default configuration without webpack property', () => {
      const config = new Configuration({});
      expect(config).to.have.a.property('_config').that.deep.equals(expectedDefaults);
      expect(config).to.have.a.property('hasLegacyConfig').that.is.false;
    });
  });

  describe('with legacy configuration', () => {
    it('should use custom.webpackIncludeModules', () => {
      const testCustom = { webpackIncludeModules: { forceInclude: ['mod1'] } };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('includeModules').that.deep.equals(testCustom.webpackIncludeModules);
    });

    it('should use custom.webpack as string', () => {
      const testCustom = { webpack: 'myWebpackFile.js' };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('webpackConfig').that.equals('myWebpackFile.js');
    });

    it('should detect it', () => {
      const testCustom = { webpack: 'myWebpackFile.js' };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('hasLegacyConfig').that.is.true;
    });

    it('should add defaults', () => {
      const testCustom = {
        webpackIncludeModules: { forceInclude: ['mod1'] },
        webpack: 'myWebpackFile.js'
      };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('includeModules').that.deep.equals(testCustom.webpackIncludeModules);
      expect(config._config).to.deep.equal({
        webpackConfig: 'myWebpackFile.js',
        includeModules: { forceInclude: ['mod1'] },
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        serializedCompile: false
      });
    });
  });

  describe('with a configuration object', () => {
    it('should use it and add any defaults', () => {
      const testCustom = {
        webpack: {
          includeModules: { forceInclude: ['mod1'] },
          webpackConfig: 'myWebpackFile.js'
        }
      };
      const config = new Configuration(testCustom);
      expect(config._config).to.deep.equal({
        webpackConfig: 'myWebpackFile.js',
        includeModules: { forceInclude: ['mod1'] },
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        serializedCompile: false
      });
    });

    it('should favor new configuration', () => {
      const testCustom = {
        webpackIncludeModules: { forceExclude: ['mod2'] },
        webpack: {
          includeModules: { forceInclude: ['mod1'] },
          webpackConfig: 'myWebpackFile.js'
        }
      };
      const config = new Configuration(testCustom);
      expect(config._config).to.deep.equal({
        webpackConfig: 'myWebpackFile.js',
        includeModules: { forceInclude: ['mod1'] },
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        serializedCompile: false
      });
    });
  });
});
<commit_msg>Update Configuration.test.js<commit_after>'use strict';
/**
 * Unit tests for Configuration.
 */

const chai = require('chai');
const Configuration = require('./Configuration');

const expect = chai.expect;

describe('Configuration', () => {
  describe('defaults', () => {
    let expectedDefaults;

    before(() => {
      expectedDefaults = {
        webpackConfig: 'webpack.config.js',
        includeModules: false,
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        concurrency: undefined
      };
    });

    it('should set default configuration without custom', () => {
      const config = new Configuration();
      expect(config).to.have.a.property('_config').that.deep.equals(expectedDefaults);
      expect(config).to.have.a.property('hasLegacyConfig').that.is.false;
    });

    it('should set default configuration without webpack property', () => {
      const config = new Configuration({});
      expect(config).to.have.a.property('_config').that.deep.equals(expectedDefaults);
      expect(config).to.have.a.property('hasLegacyConfig').that.is.false;
    });
  });

  describe('with legacy configuration', () => {
    it('should use custom.webpackIncludeModules', () => {
      const testCustom = { webpackIncludeModules: { forceInclude: ['mod1'] } };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('includeModules').that.deep.equals(testCustom.webpackIncludeModules);
    });

    it('should use custom.webpack as string', () => {
      const testCustom = { webpack: 'myWebpackFile.js' };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('webpackConfig').that.equals('myWebpackFile.js');
    });

    it('should detect it', () => {
      const testCustom = { webpack: 'myWebpackFile.js' };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('hasLegacyConfig').that.is.true;
    });

    it('should add defaults', () => {
      const testCustom = {
        webpackIncludeModules: { forceInclude: ['mod1'] },
        webpack: 'myWebpackFile.js'
      };
      const config = new Configuration(testCustom);
      expect(config).to.have.a.property('includeModules').that.deep.equals(testCustom.webpackIncludeModules);
      expect(config._config).to.deep.equal({
        webpackConfig: 'myWebpackFile.js',
        includeModules: { forceInclude: ['mod1'] },
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        concurrency: undefined
      });
    });
  });

  describe('with a configuration object', () => {
    it('should use it and add any defaults', () => {
      const testCustom = {
        webpack: {
          includeModules: { forceInclude: ['mod1'] },
          webpackConfig: 'myWebpackFile.js'
        }
      };
      const config = new Configuration(testCustom);
      expect(config._config).to.deep.equal({
        webpackConfig: 'myWebpackFile.js',
        includeModules: { forceInclude: ['mod1'] },
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        concurrency: undefined
      });
    });

    it('should favor new configuration', () => {
      const testCustom = {
        webpackIncludeModules: { forceExclude: ['mod2'] },
        webpack: {
          includeModules: { forceInclude: ['mod1'] },
          webpackConfig: 'myWebpackFile.js'
        }
      };
      const config = new Configuration(testCustom);
      expect(config._config).to.deep.equal({
        webpackConfig: 'myWebpackFile.js',
        includeModules: { forceInclude: ['mod1'] },
        packager: 'npm',
        packagerOptions: {},
        keepOutputDirectory: false,
        config: null,
        concurrency: undefined
      });
    });
  });
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Slider from '../src/slider'

var SampleNextArrow = React.createClass({
  render: function() {
    return

;
  }
});

var SamplePrevArrow = React.createClass({
  render: function() {
    return (

    );
  }
});

export default class CustomArrows extends Component {
  render() {
    const settings = {
      dots: true,
      infinite: true,
      slidesToShow: 3,
      slidesToScroll: 1,
      nextArrow: <SampleNextArrow />,
      prevArrow: <SamplePrevArrow />
    };
    return (

Custom Arrows

        <Slider {...settings}>

1

2

3

4

5

6

        </Slider>

    );
  }
}<commit_msg>Fix for custom arrows issue https://github.com/akiran/react-slick/issues/671<commit_after>import React, { Component } from 'react'
import Slider from '../src/slider'

class CarouselArrow extends Component {

  render() {
    let style = {
      ...this.props.style,
      display: 'block',
      background: '#d8e4e8',
      'paddingLeft': '6px',
    };

    return (

    );
  }
}

export default class CustomArrows extends Component {
  render() {
    const settings = {
      dots: true,
      infinite: true,
      slidesToShow: 3,
      slidesToScroll: 1,
      nextArrow: <CarouselArrow />,
      prevArrow: <CarouselArrow />
    };
    return (

Custom Arrows

        <Slider {...settings}>

1

2

3

4

5

6

        </Slider>

    );
  }
}<|endoftext|>


<commit_before>// =================================== MAIN ===================================

/**
 * JSUtils main object
 * @module JSUtils
 */
(function (global) {
  "use strict";

  // Check that JSUtils is not already defined.
  if (global.JSUtils) {
    return;
  }

  // Private variables
  var internal = {
    global: global,
  };

  global.JSUtils = {

    /**
     * Returns the global object.
     * @memberOf JSUtils.Main
     * @return {Object} The global object.
     */
    getGlobal : function() {
      return internal.global;
    },

    /**
     * Checks if the given object is equal to the global object.
     * @memberOf JSUtils.Main
     * @param  {Any} elem A given element.
     * @return {Boolean}  True if the given element is equal to the global object,
     *                    false otherwise.
     */
    isGlobal : function(elem) {
      return elem === internal.global;
    },

    /**
     * Stores a private variable to JSUtils.
     * If the variable was already defined, it will be overridden.
     * This variable can be used through the getVariable method.
     * @param  {String} name  The variable's name.
     * @param  {Any}    value Value stored in the given variable.
     * @return {Bool}         True if the variable was successfully stored,
     *                        false otherwise.
     */
    storeVariable : function(name, value) {
      // TODO: Test
      if (JSUtils.isString(name)) {
        internal[name] = value;
        return internal[name];
      }
      return false;
    },

    /**
     * Given its name, returns the value stored in a private variable of the JSUtils module.
     * Returns undefined if the variable was not defined previously.
     * @param  {String} name Internal variable name.
     * @return {Any}         Value stored in the private variable, if found.
     */
    getVariable : function(name) {
      // TODO: Test
      if (JSUtils.isString(name)) {
        return internal[name];
      }
      return undefined;
    },

    /**
     * Returns an array with the property names for the given object.
     * If obj is not an object, then an exception is thrown.
     * @memberOf JSUtils.Main
     * @param  {Object} obj The given object.
     * @return {Array}      Array of property names.
     */
    getKeys : function(obj) {
      var keys = [],
          key;
      if (!JSUtils.isObject(obj)) {
        throw new TypeError('Invalid object');
      }
      for (key in obj) {
        if (obj.hasOwnProperty(key)) {
          keys.push(key);
        }
      }
      return keys;
    },

    /**
     * Concise and efficient forEach implementation.
     * @memberOf JSUtils.Main
     * @param  {Object} obj     Elements to be iterated.
     * @param  {Function} func  Function applied to the elements in obj.
     * @param  {Object} context Context for func.
     */
    forEach : function(obj, func, context) {
      var i, len, keys;
      if (JSUtils.isObject(obj)) {
        keys = JSUtils.getKeys(obj);
        for (i=0, len=keys.length; i<len; i+=1) {
          func.call(context, obj[keys[i]], keys[i], obj);
        }
      } else {
        for (i=0, len=obj.length; i<len; i+=1) {
          func.call(context, obj[i], i, obj);
        }
      }
    },

    isArray : function(arr) {
      // TODO: Tests and doc
      return toString.call(arr) == '[object Array]';
    },

    isObject : function(obj) {
      // TODO: Tests and doc
      return obj === Object(obj);
    },

    isBoolean : function(bool) {
      // TODO: Tests and doc
      return bool === true || bool === false;
    },

    isString : function(str) {
      // TODO: Tests and doc
      return toString.call(str) == '[object String]';
    },

    isUndefined : function(obj) {
      // TODO: Tests and doc
      return typeof obj === "undefined";
    },

    isNumber : function(num){
      // TODO: Tests and doc
      return !isNaN(parseFloat(n)) && isFinite(n);
    },
  };

}(this));<commit_msg>Updated to avoid JSHint conflicts<commit_after>// =================================== MAIN ===================================

/**
 * JSUtils main object
 * @module JSUtils
 */
(function (global) {
  "use strict";

  var JSUtils = global.JSUtils,
      // Private variables
      internal = {
        global: global,
      };

  // Check that JSUtils is not already defined.
  if (global.JSUtils) {
    return;
  }

  JSUtils = {

    /**
     * Returns the global object.
     * @memberOf JSUtils.Main
     * @return {Object} The global object.
     */
    getGlobal : function() {
      return internal.global;
    },

    /**
     * Checks if the given object is equal to the global object.
     * @memberOf JSUtils.Main
     * @param  {Any} elem A given element.
     * @return {Boolean}  True if the given element is equal to the global object,
     *                    false otherwise.
     */
    isGlobal : function(elem) {
      return elem === internal.global;
    },

    /**
     * Stores a private variable to JSUtils.
     * If the variable was already defined, it will be overridden.
     * This variable can be used through the getVariable method.
     * @param  {String} name  The variable's name.
     * @param  {Any}    value Value stored in the given variable.
     * @return {Bool}         True if the variable was successfully stored,
     *                        false otherwise.
     */
    storeVariable : function(name, value) {
      // TODO: Test
      if (JSUtils.isString(name)) {
        internal[name] = value;
        return internal[name];
      }
      return false;
    },

    /**
     * Given its name, returns the value stored in a private variable of the JSUtils module.
     * Returns undefined if the variable was not defined previously.
     * @param  {String} name Internal variable name.
     * @return {Any}         Value stored in the private variable, if found.
     */
    getVariable : function(name) {
      // TODO: Test
      if (JSUtils.isString(name)) {
        return internal[name];
      }
      return undefined;
    },

    /**
     * Returns an array with the property names for the given object.
     * If obj is not an object, then an exception is thrown.
     * @memberOf JSUtils.Main
     * @param  {Object} obj The given object.
     * @return {Array}      Array of property names.
     */
    getKeys : function(obj) {
      var keys = [],
          key;
      if (!JSUtils.isObject(obj)) {
        throw new TypeError('Invalid object');
      }
      for (key in obj) {
        if (obj.hasOwnProperty(key)) {
          keys.push(key);
        }
      }
      return keys;
    },

    /**
     * Concise and efficient forEach implementation.
     * @memberOf JSUtils.Main
     * @param  {Object} obj     Elements to be iterated.
     * @param  {Function} func  Function applied to the elements in obj.
     * @param  {Object} context Context for func.
     */
    forEach : function(obj, func, context) {
      var i, len, keys;
      if (JSUtils.isObject(obj)) {
        keys = JSUtils.getKeys(obj);
        for (i=0, len=keys.length; i<len; i+=1) {
          func.call(context, obj[keys[i]], keys[i], obj);
        }
      } else {
        for (i=0, len=obj.length; i<len; i+=1) {
          func.call(context, obj[i], i, obj);
        }
      }
    },

    isArray : function(arr) {
      // TODO: Tests and doc
      return Object.prototype.toString.call(arr) == '[object Array]';
    },

    isObject : function(obj) {
      // TODO: Tests and doc
      return obj === Object(obj);
    },

    isBoolean : function(bool) {
      // TODO: Tests and doc
      return bool === true || bool === false;
    },

    isString : function(str) {
      // TODO: Tests and doc
      return Object.prototype.toString.call(str) == '[object String]';
    },

    isUndefined : function(obj) {
      // TODO: Tests and doc
      return typeof obj === "undefined";
    },

    isNumber : function(num){
      // TODO: Tests and doc
      return !isNaN(parseFloat(num)) && isFinite(num);
    },
  };

  global.JSUtils = JSUtils;

}(this));<|endoftext|>


<commit_before>(function(root, factory) {
    if (typeof exports !== "undefined") {
        var React = require("react");
        var PropTypes = require("prop-types");
        var createReactClass = require("create-react-class");
        module.exports = factory(React, PropTypes, createReactClass);
    }
    else if (typeof define === "function" && define.amd) {
        define(["react", "prop-types", "create-react-class"], function(React, PropTypes, createReactClass) {
            return factory(React, PropTypes, createReactClass);
        });
    }
    else {
        factory(root.React, root.PropTypes, root.createReactClass);
    }
}(this, function(React, PropTypes, createReactClass) {

    var FileDrop = createReactClass({
        displayName: "FileDrop",

        propTypes: {
            onDrop: PropTypes.func,
            onDragOver: PropTypes.func,
            onDragLeave: PropTypes.func,
            dropEffect: PropTypes.oneOf(["copy", "move", "link", "none"]),
            targetAlwaysVisible: PropTypes.bool,
            frame: function (props, propName, componentName) {
                var prop = props[propName];
                if (prop == null) {
                    return new Error("Warning: Required prop `" + propName + "` was not specified in `" + componentName + "`");
                }
                if (prop !== document && prop !== window && !(prop instanceof HTMLElement)) {
                    return new Error("Warning: Prop `" + propName + "` must be one of the following: document, window, or an HTMLElement!");
                }
            },
            onFrameDragEnter: PropTypes.func,
            onFrameDragLeave: PropTypes.func,
            onFrameDrop: PropTypes.func
        },

        getDefaultProps: function () {
            return {
                dropEffect: "copy",
                frame: document,
                targetAlwaysVisible: false
            };
        },

        // getInitialState: in componentWillMount, we call this.resetDragging();

        resetDragging: function () {
            this._dragCount = 0;
            this.setState({draggingOverFrame: false, draggingOverTarget: false});
        },

        _handleDrop: function (event) {
            event.preventDefault();
            if (this.props.onDrop) {
                var files = (event.dataTransfer) ? event.dataTransfer.files : (event.frame) ? event.frame.files : undefined;
                this.props.onDrop(files, event);
                this.resetDragging();
            }
        },

        _handleDragOver: function (event) {
            event.preventDefault();
            event.stopPropagation();
            event.dataTransfer.dropEffect = this.props.dropEffect;

            // set active drag state only when file is dragged into
            // (in mozilla when file is dragged effect is "uninitialized")
            var effectAllowed = event.dataTransfer.effectAllowed;
            if (effectAllowed === "all" || effectAllowed === "uninitialized") {
                this.setState({draggingOverTarget: true});
            }

            if (this.props.onDragOver) this.props.onDragOver(event);
        },

        _handleDragLeave: function (event) {
            this.setState({draggingOverTarget: false});
            if (this.props.onDragLeave) this.props.onDragLeave(event);
        },

        _handleFrameDrag: function (event) {
            // We are listening for events on the 'frame', so every time the user drags over any element in the frame's tree,
            // the event bubbles up to the frame. By keeping count of how many "dragenters" we get, we can tell if they are still
            // "draggingOverFrame" (b/c you get one "dragenter" initially, and one "dragenter"/one "dragleave" for every bubble)
            this._dragCount += (event.type === "dragenter" ? 1 : -1);
            if (this._dragCount === 1) {
                if (this.props.onFrameDragEnter) {
					if (this.props.onFrameDragEnter(event) === false) {
						return;
					}
				}
                this.setState({draggingOverFrame: true});
            } else if (this._dragCount === 0) {
                if (this.props.onFrameDragLeave) this.props.onFrameDragLeave(event);
                this.setState({draggingOverFrame: false});
            }
        },

        _handleFrameDrop: function(event) {
            if (!this.state.draggingOverTarget) {
                this.resetDragging();
                if (this.props.onFrameDrop) this.props.onFrameDrop(event);
            }
        },

        render: function () {
            var fileDropTarget;
            var fileDropTargetClassName = "file-drop-target";
            if (this.props.targetAlwaysVisible || this.state.draggingOverFrame) {
                if (this.state.draggingOverFrame) fileDropTargetClassName += " file-drop-dragging-over-frame";
                if (this.state.draggingOverTarget) fileDropTargetClassName += " file-drop-dragging-over-target";
                fileDropTarget = (
                    React.createElement("div", {className: fileDropTargetClassName},
                        this.props.children
                    )
                );
            }
            var className = "file-drop";
            if (this.props.className) {
                className += " " + this.props.className;
            }
            return (
                React.createElement("div", {className: className, onDrop: this._handleDrop, onDragLeave: this._handleDragLeave, onDragOver: this._handleDragOver},
                    fileDropTarget
                )
            );
        },

        _handleWindowDragOverOrDrop: function(event) {
            event.preventDefault();
        },

        componentWillReceiveProps: function(nextProps) {
            if (nextProps.frame !== this.props.frame) {
                this.resetDragging();
                this.stopFrameListeners(this.props.frame);
                this.startFrameListeners(nextProps.frame);
            }
        },

        componentWillMount: function() {
            this.startFrameListeners();
            this.resetDragging();
            window.addEventListener("dragover", this._handleWindowDragOverOrDrop);
            window.addEventListener("drop", this._handleWindowDragOverOrDrop);
        },

        componentWillUnmount: function() {
            this.stopFrameListeners();
            window.removeEventListener("dragover", this._handleWindowDragOverOrDrop);
            window.removeEventListener("drop", this._handleWindowDragOverOrDrop);
        },

        stopFrameListeners: function(frame) {
            frame = frame || this.props.frame;
            frame.removeEventListener("dragenter", this._handleFrameDrag);
            frame.removeEventListener("dragleave", this._handleFrameDrag);
            frame.removeEventListener("drop", this._handleFrameDrop);
        },

        startFrameListeners: function(frame) {
            frame = frame || this.props.frame;
            frame.addEventListener("dragenter", this._handleFrameDrag);
            frame.addEventListener("dragleave", this._handleFrameDrag);
            frame.addEventListener("drop", this._handleFrameDrop);
        }
    });

    if (typeof exports === "undefined" && typeof define !== "function" && !this.ReactFileDrop) {
        this.ReactFileDrop = FileDrop;
    }

    return FileDrop;
}));
<commit_msg>Added prop disableDoubleDrop to conditionally fix #20<commit_after>(function(root, factory) {
    if (typeof exports !== "undefined") {
        var React = require("react");
        var PropTypes = require("prop-types");
        var createReactClass = require("create-react-class");
        module.exports = factory(React, PropTypes, createReactClass);
    }
    else if (typeof define === "function" && define.amd) {
        define(["react", "prop-types", "create-react-class"], function(React, PropTypes, createReactClass) {
            return factory(React, PropTypes, createReactClass);
        });
    }
    else {
        factory(root.React, root.PropTypes, root.createReactClass);
    }
}(this, function(React, PropTypes, createReactClass) {

    var FileDrop = createReactClass({
        displayName: "FileDrop",

        propTypes: {
            onDrop: PropTypes.func,
            onDragOver: PropTypes.func,
            onDragLeave: PropTypes.func,
            dropEffect: PropTypes.oneOf(["copy", "move", "link", "none"]),
            targetAlwaysVisible: PropTypes.bool,
            disableDoubleDrop: PropTypes.bool,
            frame: function (props, propName, componentName) {
                var prop = props[propName];
                if (prop == null) {
                    return new Error("Warning: Required prop `" + propName + "` was not specified in `" + componentName + "`");
                }
                if (prop !== document && prop !== window && !(prop instanceof HTMLElement)) {
                    return new Error("Warning: Prop `" + propName + "` must be one of the following: document, window, or an HTMLElement!");
                }
            },
            onFrameDragEnter: PropTypes.func,
            onFrameDragLeave: PropTypes.func,
            onFrameDrop: PropTypes.func
        },

        getDefaultProps: function () {
            return {
                dropEffect: "copy",
                frame: document,
                targetAlwaysVisible: false,
                disableDoubleDrop: false
            };
        },

        // getInitialState: in componentWillMount, we call this.resetDragging();

        resetDragging: function () {
            this._dragCount = 0;
            this.setState({draggingOverFrame: false, draggingOverTarget: false});
        },

        _handleDrop: function (event) {
            event.preventDefault();
            if (this.props.onDrop) {
                var files = (event.dataTransfer) ? event.dataTransfer.files : (event.frame) ? event.frame.files : undefined;
                this.props.onDrop(files, event);
                this.resetDragging();
            }
        },

        _handleDragOver: function (event) {
            event.preventDefault();
            event.stopPropagation();
            event.dataTransfer.dropEffect = this.props.dropEffect;

            // set active drag state only when file is dragged into
            // (in mozilla when file is dragged effect is "uninitialized")
            var effectAllowed = event.dataTransfer.effectAllowed;
            if (effectAllowed === "all" || effectAllowed === "uninitialized") {
                this.setState({draggingOverTarget: true});
            }

            if (this.props.onDragOver) this.props.onDragOver(event);
        },

        _handleDragLeave: function (event) {
            this.setState({draggingOverTarget: false});
            if (this.props.onDragLeave) this.props.onDragLeave(event);
        },

        _handleFrameDrag: function (event) {
            // We are listening for events on the 'frame', so every time the user drags over any element in the frame's tree,
            // the event bubbles up to the frame. By keeping count of how many "dragenters" we get, we can tell if they are still
            // "draggingOverFrame" (b/c you get one "dragenter" initially, and one "dragenter"/one "dragleave" for every bubble)
            this._dragCount += (event.type === "dragenter" ? 1 : -1);
            if (this._dragCount === 1) {
                if (this.props.onFrameDragEnter) {
					if (this.props.onFrameDragEnter(event) === false) {
						return;
					}
				}
                this.setState({draggingOverFrame: true});
            } else if (this._dragCount === 0) {
                if (this.props.onFrameDragLeave) this.props.onFrameDragLeave(event);
                this.setState({draggingOverFrame: false});
            }
        },

        _handleFrameDrop: function(event) {
            if (!this.state.draggingOverTarget) {
                this.resetDragging();
                if (this.props.onFrameDrop) this.props.onFrameDrop(event);
            }
            if(!this.props.disableDoubleDrop){
                this._handleDrop(event);
            }
        },

        render: function () {
            var fileDropTarget;
            var fileDropTargetClassName = "file-drop-target";
            if (this.props.targetAlwaysVisible || this.state.draggingOverFrame) {
                if (this.state.draggingOverFrame) fileDropTargetClassName += " file-drop-dragging-over-frame";
                if (this.state.draggingOverTarget) fileDropTargetClassName += " file-drop-dragging-over-target";
                fileDropTarget = (
                    React.createElement("div", {className: fileDropTargetClassName},
                        this.props.children
                    )
                );
            }
            var className = "file-drop";
            if (this.props.className) {
                className += " " + this.props.className;
            }
            return (
                React.createElement("div", {className: className, onDrop: this._handleDrop, onDragLeave: this._handleDragLeave, onDragOver: this._handleDragOver},
                    fileDropTarget
                )
            );
        },

        _handleWindowDragOverOrDrop: function(event) {
            event.preventDefault();
        },

        componentWillReceiveProps: function(nextProps) {
            if (nextProps.frame !== this.props.frame) {
                this.resetDragging();
                this.stopFrameListeners(this.props.frame);
                this.startFrameListeners(nextProps.frame);
            }
        },

        componentWillMount: function() {
            this.startFrameListeners();
            this.resetDragging();
            window.addEventListener("dragover", this._handleWindowDragOverOrDrop);
            window.addEventListener("drop", this._handleWindowDragOverOrDrop);
        },

        componentWillUnmount: function() {
            this.stopFrameListeners();
            window.removeEventListener("dragover", this._handleWindowDragOverOrDrop);
            window.removeEventListener("drop", this._handleWindowDragOverOrDrop);
        },

        stopFrameListeners: function(frame) {
            frame = frame || this.props.frame;
            frame.removeEventListener("dragenter", this._handleFrameDrag);
            frame.removeEventListener("dragleave", this._handleFrameDrag);
            frame.removeEventListener("drop", this._handleFrameDrop);
        },

        startFrameListeners: function(frame) {
            frame = frame || this.props.frame;
            frame.addEventListener("dragenter", this._handleFrameDrag);
            frame.addEventListener("dragleave", this._handleFrameDrag);
            frame.addEventListener("drop", this._handleFrameDrop);
        }
    });

    if (typeof exports === "undefined" && typeof define !== "function" && !this.ReactFileDrop) {
        this.ReactFileDrop = FileDrop;
    }

    return FileDrop;
}));
<|endoftext|>


<commit_before>#!/Users/admin/.nvm/versions/node/v4.2.4/bin/node
// ^ full path to node must be specified above, edit for your system. may also try:
// #!/usr/local/bin/node

'use strict';

// Native messaging host, provides native access to OS functions over stdin/stdout
// for the Google Chrome extension
// TODO: port off nodejs?

const process = require('process');
const fs = require('fs');
const path = require('path');
const nativeMessage = require('chrome-native-messaging');
const input = new nativeMessage.Input();
const transform = new nativeMessage.Transform(messageHandler);
const output = new nativeMessage.Output();

// Prepend all paths with this filesystem root
const ROOT = path.join(__dirname, '../sandbox');
if (!fs.existsSync(ROOT)) fs.mkdirSync(ROOT);

function fixpath(relativePath) {
  const newPath = path.join(ROOT, relativePath);
  if (!newPath.startsWith(ROOT)) {
    return ROOT; // tried to go above root, return root
  }
  return newPath;
}

process.stdin
  .pipe(input)
  .pipe(transform)
  .pipe(output)
  .pipe(process.stdout);

function encodeResult(err, data, id) {
  if (err) {
    return {error:
             {
               code: err.errno, // must be an integer, but err.code is a string like 'ENOENT'
               message: err.toString(),
               id: id,
             }
           };
  } else {
    return {result:data, id:id};
  }
}

function messageHandler(msg, push, done) {
  const method = msg.method;
  const params = msg.params;
  const id = msg.id;

  function cb(err, data) {
    push(encodeResult(err, data, id));
    done();
  }

  if (method === 'echo') {
    push(msg);
    done();
  } else if (method === 'fs.access') {
    const path = fixpath(params[0]);
    if (params.length < 2) {
      fs.access(path, cb);
    } else {
      const mode = params[1];
      fs.access(path, mode, cb);
    }
  } else if (method === 'fs.chmod') {
    const path = fixpath(params[0]);
    const mode = params[1];
    fs.chmod(path, mode, cb);
  } else if (method === 'fs.chown') {
    const path = fixpath(params[0]);
    const uid = params[1];
    const gid = params[2];
    fs.chown(path, uid, gid, cb);
  } else if (method === 'fs.close') {
    const fd = params[0];
    fs.close(fd, cb);
    /* TODO
  } else if (method === 'fs.createReadStream') {
    const path = params[0];
    */
  } else if (method === 'fs.exists') { // deprecated, by npm uses
    const path = fixpath(params[0]);
    fs.exists(path, cb);
  } else if (method === 'fs.fstat') {
    const fd = params[0];
    fs.fstat(fd, cb);
  } else if (method === 'fs.lstat') {
    const path = fixpath(params[0]);
    fs.lstat(path, cb);
  } else if (method === 'fs.mkdir') {
    const path = fixpath(params[0]);
    if (params.length < 2) {
      fs.mkdir(path, cb);
    } else {
      const mode = params[1];
      fs.mkdir(path, mode, cb);
    }
  } else if (method === 'fs.open') {
    const path = fixpath(params[0]);
    const flags = params[1];
    if (params.length < 3) {
      const mode = params[2];
      fs.open(path, flags, mode, cb);
    } else {
      fs.open(path, flags, cb);
    }
  } else if (method === 'fs.readFile') {
    const file = fixpath(params[0]);
    // TODO: restrict access to only a limited set of files
    if (params.length < 2) {
      //const callback = params[1];
      fs.readFile(file, cb);
    } else {
      const options = params[1];
      //const callback = params[2];
      fs.readFile(file, options, cb);
    }
  } else if (method === 'fs.readdir') {
    const path = fixpath(params[0]);
    fs.readdir(path, cb);
  } else if (method === 'fs.readlink') {
    const path = fixpath(params[0]);
    fs.readlink(path, cb);
  } else if (method === 'fs.realpath') {
    const path = fixpath(params[0]);
    if (params.length < 2) {
      fs.realpath(path, cb);
    } else {
      const cache = params[1];
      fs.realpath(path, cache, cb);
    }
  } else if (method === 'fs.rename') {
    const oldPath = fixpath(params[0]);
    const newPath = fixpath(params[1]);
    fs.rename(oldPath, newPath, cb);
  } else if (method === 'fs.rmdir') {
    const path = fixpath(params[0]);
    fs.rmdir(path, cb);
  } else if (method === 'fs.stat') {
    const path = fixpath(params[0]);
    fs.stat(path, cb);
  } else if (method === 'fs.symlink') {
    const target = fixpath(params[0]);
    const path = fixpath(params[1]);
    if (params.length < 3) {
      fs.symlink(target, path, cb);
    } else {
      const type = params[2];
      fs.symlink(target, path, type, cb);
    }
  } else if (method === 'fs.unlink') {
    const path = fixpath(params[0]);
    fs.unlink(path, cb);
  } else if (method === 'fs.writeFile') {
    const file = fixpath(params[0]);
    const data = params[1];
    if (params.length < 3) {
      fs.writeFile(file, data, cb);
    } else {
      const options = params[2];
      fs.writeFile(file, data, options, cb);
    }
  } else if (method === 'fs.write') {
    const fd = params[0]; // TODO: restrict fd? 0, 1, 2 stdio?
    const buffer = params[1];
    const offset = params[2];
    const length = params[3];
    if (params.length < 5) {
      fs.write(fd, data, length, cb);
    } else {
      const position = params[4];
      fd.write(fd, data, length, position, cb);
    }
  } else {
    push({error: {
      code: -32601, // defined in http://www.jsonrpc.org/specification#response_object
      message: 'Method not found',
      data: `invalid method: ${method}`,
      id: id,
    }});
    done();
  }
}
<commit_msg>Fix host 'id' value in error responses<commit_after>#!/Users/admin/.nvm/versions/node/v4.2.4/bin/node
// ^ full path to node must be specified above, edit for your system. may also try:
// #!/usr/local/bin/node

'use strict';

// Native messaging host, provides native access to OS functions over stdin/stdout
// for the Google Chrome extension
// TODO: port off nodejs?

const process = require('process');
const fs = require('fs');
const path = require('path');
const nativeMessage = require('chrome-native-messaging');
const input = new nativeMessage.Input();
const transform = new nativeMessage.Transform(messageHandler);
const output = new nativeMessage.Output();

// Prepend all paths with this filesystem root
const ROOT = path.join(__dirname, '../sandbox');
if (!fs.existsSync(ROOT)) fs.mkdirSync(ROOT);

function fixpath(relativePath) {
  const newPath = path.join(ROOT, relativePath);
  if (!newPath.startsWith(ROOT)) {
    return ROOT; // tried to go above root, return root
  }
  return newPath;
}

process.stdin
  .pipe(input)
  .pipe(transform)
  .pipe(output)
  .pipe(process.stdout);

function encodeResult(err, data, id) {
  if (err) {
    return {error:
             {
               code: err.errno, // must be an integer, but err.code is a string like 'ENOENT'
               message: err.toString(),
             },
             id: id,
           };
  } else {
    return {result:data, id:id};
  }
}

function messageHandler(msg, push, done) {
  const method = msg.method;
  const params = msg.params;
  const id = msg.id;

  function cb(err, data) {
    push(encodeResult(err, data, id));
    done();
  }

  if (method === 'echo') {
    push(msg);
    done();
  } else if (method === 'fs.access') {
    const path = fixpath(params[0]);
    if (params.length < 2) {
      fs.access(path, cb);
    } else {
      const mode = params[1];
      fs.access(path, mode, cb);
    }
  } else if (method === 'fs.chmod') {
    const path = fixpath(params[0]);
    const mode = params[1];
    fs.chmod(path, mode, cb);
  } else if (method === 'fs.chown') {
    const path = fixpath(params[0]);
    const uid = params[1];
    const gid = params[2];
    fs.chown(path, uid, gid, cb);
  } else if (method === 'fs.close') {
    const fd = params[0];
    fs.close(fd, cb);
    /* TODO
  } else if (method === 'fs.createReadStream') {
    const path = params[0];
    */
  } else if (method === 'fs.exists') { // deprecated, by npm uses
    const path = fixpath(params[0]);
    fs.exists(path, cb);
  } else if (method === 'fs.fstat') {
    const fd = params[0];
    fs.fstat(fd, cb);
  } else if (method === 'fs.lstat') {
    const path = fixpath(params[0]);
    fs.lstat(path, cb);
  } else if (method === 'fs.mkdir') {
    const path = fixpath(params[0]);
    if (params.length < 2) {
      fs.mkdir(path, cb);
    } else {
      const mode = params[1];
      fs.mkdir(path, mode, cb);
    }
  } else if (method === 'fs.open') {
    const path = fixpath(params[0]);
    const flags = params[1];
    if (params.length < 3) {
      const mode = params[2];
      fs.open(path, flags, mode, cb);
    } else {
      fs.open(path, flags, cb);
    }
  } else if (method === 'fs.readFile') {
    const file = fixpath(params[0]);
    // TODO: restrict access to only a limited set of files
    if (params.length < 2) {
      //const callback = params[1];
      fs.readFile(file, cb);
    } else {
      const options = params[1];
      //const callback = params[2];
      fs.readFile(file, options, cb);
    }
  } else if (method === 'fs.readdir') {
    const path = fixpath(params[0]);
    fs.readdir(path, cb);
  } else if (method === 'fs.readlink') {
    const path = fixpath(params[0]);
    fs.readlink(path, cb);
  } else if (method === 'fs.realpath') {
    const path = fixpath(params[0]);
    if (params.length < 2) {
      fs.realpath(path, cb);
    } else {
      const cache = params[1];
      fs.realpath(path, cache, cb);
    }
  } else if (method === 'fs.rename') {
    const oldPath = fixpath(params[0]);
    const newPath = fixpath(params[1]);
    fs.rename(oldPath, newPath, cb);
  } else if (method === 'fs.rmdir') {
    const path = fixpath(params[0]);
    fs.rmdir(path, cb);
  } else if (method === 'fs.stat') {
    const path = fixpath(params[0]);
    fs.stat(path, cb);
  } else if (method === 'fs.symlink') {
    const target = fixpath(params[0]);
    const path = fixpath(params[1]);
    if (params.length < 3) {
      fs.symlink(target, path, cb);
    } else {
      const type = params[2];
      fs.symlink(target, path, type, cb);
    }
  } else if (method === 'fs.unlink') {
    const path = fixpath(params[0]);
    fs.unlink(path, cb);
  } else if (method === 'fs.writeFile') {
    const file = fixpath(params[0]);
    const data = params[1];
    if (params.length < 3) {
      fs.writeFile(file, data, cb);
    } else {
      const options = params[2];
      fs.writeFile(file, data, options, cb);
    }
  } else if (method === 'fs.write') {
    const fd = params[0]; // TODO: restrict fd? 0, 1, 2 stdio?
    const buffer = params[1];
    const offset = params[2];
    const length = params[3];
    if (params.length < 5) {
      fs.write(fd, data, length, cb);
    } else {
      const position = params[4];
      fd.write(fd, data, length, position, cb);
    }
  } else {
    push({error: {
      code: -32601, // defined in http://www.jsonrpc.org/specification#response_object
      message: 'Method not found',
      data: `invalid method: ${method}`,
      id: id,
    }});
    done();
  }
}
<|endoftext|>


<commit_before>/* @flow */

import { PropTypes } from 'react'
import ReactNative, { TextInput, DeviceEventEmitter } from 'react-native'
import TimerMixin from 'react-timer-mixin'

const _KAM_DEFAULT_TAB_BAR_HEIGHT = 49
const _KAM_KEYBOARD_OPENING_TIME = 250

const KeyboardAwareMixin = {
  mixins: [TimerMixin],
  propTypes: {
    enableAutoAutomaticScroll: PropTypes.bool
  },

  getDefaultProps: function () {
    return {
        enableAutoAutomaticScroll: true,
    }
  },

  setViewIsInsideTabBar: function (viewIsInsideTabBar: bool) {
    this.viewIsInsideTabBar = viewIsInsideTabBar
    this.setState({keyboardSpace: _KAM_DEFAULT_TAB_BAR_HEIGHT})
  },

  setResetScrollToCoords: function (coords: {x: number, y: number}) {
    this.resetCoords = coords
  },

  getInitialState: function (props: Object) {
    this.viewIsInsideTabBar = false
    this.keyboardWillShowEvent = undefined
    this.keyboardWillHideEvent = undefined
    return {
      keyboardSpace: 0,
    }
  },

  // Keyboard actions
  updateKeyboardSpace: function (frames: Object) {
    const keyboardSpace = (this.props.viewIsInsideTabBar) ? frames.endCoordinates.height - _KAM_DEFAULT_TAB_BAR_HEIGHT : frames.endCoordinates.height
    this.setState({
      keyboardSpace: keyboardSpace,
    })
    // Automatically scroll to focused TextInput
    if (this.props.enableAutoAutomaticScroll) {
      const currentlyFocusedField = TextInput.State.currentlyFocusedField()
      if (!currentlyFocusedField) {
        return
      }
      try {
        this.scrollToFocusedInputWithNodeHandle(currentlyFocusedField)
      } catch (e) {

      }
    }
  },

  resetKeyboardSpace: function () {
    const keyboardSpace = (this.props.viewIsInsideTabBar) ? _KAM_DEFAULT_TAB_BAR_HEIGHT : 0
    this.setState({
      keyboardSpace: keyboardSpace,
    })
    // Reset scroll position after keyboard dismissal
    if (this.resetCoords) {
      this.scrollToPosition(this.resetCoords.x, this.resetCoords.y, true)
    }
  },

  componentDidMount: function () {
    // Keyboard events
    this.keyboardWillShowEvent = DeviceEventEmitter.addListener('keyboardWillShow', this.updateKeyboardSpace)
    this.keyboardWillHideEvent = DeviceEventEmitter.addListener('keyboardWillHide', this.resetKeyboardSpace)
  },

  componentWillUnmount: function () {
    this.keyboardWillShowEvent.remove()
    this.keyboardWillHideEvent.remove()
  },

  scrollToPosition: function (x: number, y: number, animated: bool = false) {
    const scrollView = this.refs._rnkasv_keyboardView.getScrollResponder()
    scrollView.scrollResponderScrollTo({x: x, y: y, animated: animated})
  },

  /**
   * @param extraHeight: takes an extra height in consideration.
   */
  scrollToFocusedInput: function (reactNode: Object, extraHeight: number = _KAM_DEFAULT_TAB_BAR_HEIGHT) {
    const scrollView = this.refs._rnkasv_keyboardView.getScrollResponder()
    this.setTimeout(() => {
      scrollView.scrollResponderScrollNativeHandleToKeyboard(
        reactNode, extraHeight, true
      )
    }, _KAM_KEYBOARD_OPENING_TIME)
  },

  scrollToFocusedInputWithNodeHandle: function (nodeID: number, extraHeight: number = _KAM_DEFAULT_TAB_BAR_HEIGHT) {
    const reactNode = ReactNative.findNodeHandle(nodeID)
    this.scrollToFocusedInput(reactNode, extraHeight)
  },
}

export default KeyboardAwareMixin
<commit_msg>Added extraHeight prop (#32)<commit_after>/* @flow */

import { PropTypes } from 'react'
import ReactNative, { TextInput, DeviceEventEmitter } from 'react-native'
import TimerMixin from 'react-timer-mixin'

const _KAM_DEFAULT_TAB_BAR_HEIGHT = 49
const _KAM_KEYBOARD_OPENING_TIME = 250
const _KAM_EXTRA_HEIGHT = 75

const KeyboardAwareMixin = {
  mixins: [TimerMixin],
  propTypes: {
    enableAutoAutomaticScroll: PropTypes.bool,
    extraHeight: PropTypes.number,
  },

  getDefaultProps: function () {
    return {
        enableAutoAutomaticScroll: true,
        extraHeight: _KAM_EXTRA_HEIGHT,
    }
  },

  setViewIsInsideTabBar: function (viewIsInsideTabBar: bool) {
    this.viewIsInsideTabBar = viewIsInsideTabBar
    this.setState({keyboardSpace: _KAM_DEFAULT_TAB_BAR_HEIGHT})
  },

  setResetScrollToCoords: function (coords: {x: number, y: number}) {
    this.resetCoords = coords
  },

  getInitialState: function (props: Object) {
    this.viewIsInsideTabBar = false
    this.keyboardWillShowEvent = undefined
    this.keyboardWillHideEvent = undefined
    return {
      keyboardSpace: 0,
    }
  },

  // Keyboard actions
  updateKeyboardSpace: function (frames: Object) {
    const keyboardSpace = (this.props.viewIsInsideTabBar) ? frames.endCoordinates.height - _KAM_DEFAULT_TAB_BAR_HEIGHT : frames.endCoordinates.height
    this.setState({
      keyboardSpace: keyboardSpace,
    })
    // Automatically scroll to focused TextInput
    if (this.props.enableAutoAutomaticScroll) {
      const currentlyFocusedField = TextInput.State.currentlyFocusedField()
      if (!currentlyFocusedField) {
        return
      }
      try {
        this.scrollToFocusedInputWithNodeHandle(currentlyFocusedField)
      } catch (e) {

      }
    }
  },

  resetKeyboardSpace: function () {
    const keyboardSpace = (this.props.viewIsInsideTabBar) ? _KAM_DEFAULT_TAB_BAR_HEIGHT : 0
    this.setState({
      keyboardSpace: keyboardSpace,
    })
    // Reset scroll position after keyboard dismissal
    if (this.resetCoords) {
      this.scrollToPosition(this.resetCoords.x, this.resetCoords.y, true)
    }
  },

  componentDidMount: function () {
    // Keyboard events
    this.keyboardWillShowEvent = DeviceEventEmitter.addListener('keyboardWillShow', this.updateKeyboardSpace)
    this.keyboardWillHideEvent = DeviceEventEmitter.addListener('keyboardWillHide', this.resetKeyboardSpace)
  },

  componentWillUnmount: function () {
    this.keyboardWillShowEvent.remove()
    this.keyboardWillHideEvent.remove()
  },

  scrollToPosition: function (x: number, y: number, animated: bool = false) {
    const scrollView = this.refs._rnkasv_keyboardView.getScrollResponder()
    scrollView.scrollResponderScrollTo({x: x, y: y, animated: animated})
  },

  /**
   * @param extraHeight: takes an extra height in consideration.
   */
  scrollToFocusedInput: function (reactNode: Object, extraHeight: number = this.props.extraHeight) {
    const scrollView = this.refs._rnkasv_keyboardView.getScrollResponder()
    this.setTimeout(() => {
      scrollView.scrollResponderScrollNativeHandleToKeyboard(
        reactNode, extraHeight, true
      )
    }, _KAM_KEYBOARD_OPENING_TIME)
  },

  scrollToFocusedInputWithNodeHandle: function (nodeID: number, extraHeight: number = this.props.extraHeight) {
    const reactNode = ReactNative.findNodeHandle(nodeID)
    this.scrollToFocusedInput(reactNode, extraHeight)
  },
}

export default KeyboardAwareMixin
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import users from './userReducer';
import documents from './documentReducer';
import search from './searchReducer';
import auth from './auth';

const rootReducer = combineReducers({
  auth,
  documents,
  users,
  search
});

export default rootReducer;

<commit_msg>feature(deleteConfirmation): add delete confirmation reducer to reducer index [#146514255]<commit_after>import { combineReducers } from 'redux';
import { reducer } from 'react-redux-sweetalert';
import users from './userReducer';
import documents from './documentReducer';
import search from './searchReducer';
import auth from './auth';

const rootReducer = combineReducers({
  auth,
  documents,
  users,
  sweetalert: reducer,
  search
});

export default rootReducer;

<|endoftext|>