<commit_before>import {assert} from 'chai';
import {OutputModel} from '../src/output-model';

describe("Output Model Tests", function() {
    before(function(done) {
        this.model = new OutputModel();
        done();
    });
    it("Confirm the state of the default OutputModel", function(done) {
        assert.isFalse(this.model.clearQueued);
        assert.lengthOf(this.model._state, 0);
        done();
    });
    it("Set the state of OutputModel", function(done) {
        var banana = ["Banana"];
        this.model.state = banana;
        assert.lengthOf(this.model._state, 1);
        assert.equal(this.model.state, "Banana");
        this.model.state = [];
        done();
    });
    it("consumeMessage errors on unkown message type", function(done) {
        var badMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "unknown_fruit",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {}
        };
        assert.isFalse(this.model.consumeMessage(badMsg));
        done();
    });
    it("consumeMessage properly handles a clear_output message", function(done) {
        var coMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "clear_output",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {}
        };
        assert.isTrue(this.model.consumeMessage(coMsg));
        done();
    });
    it("consumeMessage properly handles a stream message", function(done) {
        var sMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "stream",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {
                "name": "stdout",
                "text": "This is a stream test"
            }
        };
        assert.isTrue(this.model.consumeMessage(sMsg));
        var expected = sMsg.content;
        assert.lengthOf(this.model.state, 1);
        assert.equal(this.model.state[0].output_type, "stream");
        assert.equal(this.model.state[0].name, "stdout");
        assert.equal(this.model.state[0].text, "This is a stream test");
        done();
    });
    it("consumeMessage properly handles a display_data message", function(done) {
        var dMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "stream",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {
                "source" : "stevo",

            }
        };
        assert.isTrue(this.model.consumeMessage(dMsg));
        done();
    });
    it("consumeMessage properly handles a execute_result message", function(done) {
        var eMsg = {
            "header": {
                "msg_id": "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username": "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "execute_result",
                "version": "5.0"
            },
            "parent_header": {},
            "metadata": {},
            "content": {
                "data": "test_data",
                "metadata": "test_metadata",
                "execution_count": 0
            }
        };
        assert.isTrue(this.model.consumeMessage(eMsg));
        done();
    });
    it("consumeMessage properly handles a error message", function(done) {
        var errMsg = {
            "header": {
                "msg_id": "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username": "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "error",
                "version": "5.0"
            },
            "parent_header": {},
            "metadata": {},
            "content": {
                "name": "big problem",
                "evalue": "You've got a big problem",
                "traceback": "Traceback \n Problems everywhere"
            }
        };
        assert.isTrue(this.model.consumeMessage(errMsg));
        done();
});
<commit_msg>Cleaned up model tests<commit_after>import {assert} from 'chai';
import {OutputModel} from '../src/output-model';

describe("Output Model Tests", function() {
    before(function(done) {
        this.model = new OutputModel();
        done();
    });
    it("Confirm the state of the default OutputModel", function(done) {
        assert.isFalse(this.model.clearQueued);
        assert.lengthOf(this.model._state, 0);
        done();
    });
    it("consumeMessage errors on unkown message type", function(done) {
        var badMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "unknown_fruit",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {}
        };
        assert.isFalse(this.model.consumeMessage(badMsg));
        assert.lengthOf(this.model.state, 0);
        done();
    });
    it("consumeMessage properly handles a clear_output message", function(done) {
        var coMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "clear_output",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {}
        };
        assert.isTrue(this.model.consumeMessage(coMsg));

        done();
    });
    it("consumeMessage properly handles a stream message", function(done) {
        var sMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "stream",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {
                "name": "stdout",
                "text": "This is a stream test"
            }
        };
        assert.isTrue(this.model.consumeMessage(sMsg));
        var expected = sMsg.content;
        assert.lengthOf(this.model.state, 1);
        assert.equal(this.model.state[0].output_type, "stream");
        assert.equal(this.model.state[0].name, "stdout");
        assert.equal(this.model.state[0].text, "This is a stream test");
        done();
    });
    it("consumeMessage properly handles a display_data message", function(done) {
        var dMsg = {
            "header" : {
                "msg_id" : "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username" : "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "stream",
                "version": "5.0"
            },
            "parent_header" : {},
            "metadata": {},
            "content": {
                "source" : "stevo",

            }
        };
        assert.isTrue(this.model.consumeMessage(dMsg));
        done();
    });
    it("consumeMessage properly handles a execute_result message", function(done) {
        var eMsg = {
            "header": {
                "msg_id": "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username": "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "execute_result",
                "version": "5.0"
            },
            "parent_header": {},
            "metadata": {},
            "content": {
                "data": "test_data",
                "metadata": "test_metadata",
                "execution_count": 0
            }
        };
        assert.isTrue(this.model.consumeMessage(eMsg));
        done();
    });
    it("consumeMessage properly handles a error message", function(done) {
        var errMsg = {
            "header": {
                "msg_id": "6e539a79-6e41-4767-ba4b-33b938fb73e2",
                "username": "tester",
                "session": "c38c32e4-be39-43e5-a8f5-36dfb2551d4c",
                "msg_type": "error",
                "version": "5.0"
            },
            "parent_header": {},
            "metadata": {},
            "content": {
                "name": "big problem",
                "evalue": "You've got a big problem",
                "traceback": "Traceback \n Problems everywhere"
            }
        };
        assert.isTrue(this.model.consumeMessage(errMsg));
        done();
    });
});
<|endoftext|>


<commit_before>import Buildfire, { components } from 'buildfire';
import React from 'react';

class LocationForm extends React.Component {
  constructor(props) {
    super(props);
    let model = {
      title: '',
      description: '',
      address: null,
      image: '',
      categories: [],
      carousel: []
    };
    this.state = Object.assign(model, props.location);
  }

  /**
   * Handles mounting of dom dependant components
   * - Google Maps
   * - Carousel
   */
  componentDidMount() {
    // Mount google map
    const { maps } = window.google;
    this.autocomplete = new maps.places.Autocomplete(this.addressInput);
    this.autocomplete.addListener('place_changed', () => this.onPlaceChanged());
    setTimeout(() => {
      let container = document.querySelector('.pac-container');
      this.addressInput.parentNode.appendChild(container);
      container.style.top = '10px';
      container.style.left = '10px';
    }, 400);

    // Mount carousel
    this.editor = new components.carousel.editor('#carousel', {
      items: this.props.location ? this.props.location.carousel : []
    });
    this.editor.onAddItems = (items) => this.updateCarouselState();
    this.editor.onDeleteItems = (items, index) => this.updateCarouselState();
    this.editor.onItemChange = (item) => this.updateCarouselState();
    this.editor.onOrderChange = (item, prevIndex, newIndex) => this.updateCarouselState();
  }

  onInputChange(e) {
    const changes = {};
    changes[e.target.name] = e.target.value;
    this.setState(changes);
  }

  onCategoryChange(e) {
    let { name, checked } = e.target;
    console.log({ name, checked });

    // Category was selected
    if (checked) {
      let { categories } = this.state;
      categories.push(name);
      this.setState({ categories });

    // Category was unselected
    } else {
      let index = this.state.categories.indexOf(name);
      let { categories } = this.state;
      categories.splice(index, 1);
      this.setState({ categories });
    }
  }

  /**
   * Handles updating the carousel state data
   */
  updateCarouselState() {
    const {items } = this.editor;
    this.setState({ carousel: items });
  }

  /**
   * Handle showing the image dialog
   */
  showImageDialog() {
    const dialogOptions = {
      showIcons: false,
      multiSelection: false
    };

    // Request user to select image
    Buildfire.imageLib.showDialog(dialogOptions, (err, result) => {
      if (err) return console.error(err);

      // Stop if we don't have any images
      if (!result || !result.selectedFiles || !result.selectedFiles.length) {
        return;
      }

      this.setState({ image: result.selectedFiles[0] });
    });
  }

  /**
   * Handle the google maps autocomplete place change
   */
  onPlaceChanged() {
    const place = this.autocomplete.getPlace();
    if (!place.geometry) {
      return this.setState({ address: null });
    }

    const address = {
      name: place.formatted_address,
      lat: place.geometry.location.lat(),
      lng: place.geometry.location.lng()
    };

    this.setState({ address });
  }

  /**
   * Pass submissions to parent component
   *
   * @param   {Event} e Form submission event
   */
  onSubmit(e) {
    e.preventDefault();
    this.props.onSubmit(this.state);
  }

  render() {
    const { title, address, description, image, categories } = this.state;

    return (
      <form onSubmit={ e => this.onSubmit(e) }>

          Title
          <input
            onChange={ e => this.onInputChange(e) }
            value={ title }
            name='title'
            type='text'
            className='form-control' />

          Categories

            { this.props.categories ? this.props.categories.map((category, index) => (

                <input
                  onChange={ e => this.onCategoryChange(e) }
                  type='checkbox'
                  name={ category.id }
                  checked={ categories.indexOf(category.id) > -1 } />

                { category.name }

            )) : null }

          Address
          <input
            key='address-input'
            ref={ n => this.addressInput = n }
            value={ address ? address.name : '' }
            type='text'
            className='form-control' />

          Description
          <textarea
            value={ description }
            onChange={ e => this.onInputChange(e) }
            className='form-control'
            name='description' rows='3' />

          List Image
          <div
            style={{ backgroundImage: image ? `url(${image})` : '' }}
            className='image-dialog'
            onClick={ () => this.showImageDialog() }>
            { this.state.image ? null : Add Image + }

          <button
            disabled={ !title.length || !description.length || !address }
            type='submit'
            className='btn btn-primary'>
            { this.props.location ? 'Save Location' : 'Save Location' }
          </button>

      </form>
    );
  }
}

export default LocationForm;
<commit_msg>handle keyup enter on autocomplete and prevent default<commit_after>import Buildfire, { components } from 'buildfire';
import React from 'react';

class LocationForm extends React.Component {
  constructor(props) {
    super(props);
    let model = {
      title: '',
      description: '',
      address: null,
      image: '',
      categories: [],
      carousel: []
    };
    this.state = Object.assign(model, props.location);
  }

  /**
   * Handles mounting of dom dependant components
   * - Google Maps
   * - Carousel
   */
  componentDidMount() {
    // Mount google map
    const { maps } = window.google;
    this.autocomplete = new maps.places.Autocomplete(this.addressInput);
    this.autocomplete.addListener('place_changed', () => this.onPlaceChanged());
    setTimeout(() => {
      let container = document.querySelector('.pac-container');
      this.addressInput.parentNode.appendChild(container);
      container.style.top = '10px';
      container.style.left = '10px';
    }, 400);

    // Mount carousel
    this.editor = new components.carousel.editor('#carousel', {
      items: this.props.location ? this.props.location.carousel : []
    });
    this.editor.onAddItems = (items) => this.updateCarouselState();
    this.editor.onDeleteItems = (items, index) => this.updateCarouselState();
    this.editor.onItemChange = (item) => this.updateCarouselState();
    this.editor.onOrderChange = (item, prevIndex, newIndex) => this.updateCarouselState();
  }

  onInputChange(e) {
    const changes = {};
    changes[e.target.name] = e.target.value;
    this.setState(changes);
  }

  onCategoryChange(e) {
    let { name, checked } = e.target;
    console.log({ name, checked });

    // Category was selected
    if (checked) {
      let { categories } = this.state;
      categories.push(name);
      this.setState({ categories });

    // Category was unselected
    } else {
      let index = this.state.categories.indexOf(name);
      let { categories } = this.state;
      categories.splice(index, 1);
      this.setState({ categories });
    }
  }

  /**
   * Handles updating the carousel state data
   */
  updateCarouselState() {
    const {items } = this.editor;
    this.setState({ carousel: items });
  }

  /**
   * Handle showing the image dialog
   */
  showImageDialog() {
    const dialogOptions = {
      showIcons: false,
      multiSelection: false
    };

    // Request user to select image
    Buildfire.imageLib.showDialog(dialogOptions, (err, result) => {
      if (err) return console.error(err);

      // Stop if we don't have any images
      if (!result || !result.selectedFiles || !result.selectedFiles.length) {
        return;
      }

      this.setState({ image: result.selectedFiles[0] });
    });
  }

  /**
   * Handle the google maps autocomplete place change
   */
  onPlaceChanged() {
    const place = this.autocomplete.getPlace();
    if (!place.geometry) {
      return this.setState({ address: null });
    }

    const address = {
      name: place.formatted_address,
      lat: place.geometry.location.lat(),
      lng: place.geometry.location.lng()
    };

    this.setState({ address });
  }

  /**
   * Pass submissions to parent component
   *
   * @param   {Event} e Form submission event
   */
  onSubmit(e) {
    e.preventDefault();
    this.props.onSubmit(this.state);
  }

  onAutoKeyUp(e) {
    let keyCode = e.keyCode || e.which;
    if (keyCode === 13) {
      e.preventDefault();
    }
  }

  render() {
    const { title, address, description, image, categories } = this.state;

    return (
      <form onSubmit={ e => this.onSubmit(e) }>

          Title
          <input
            onChange={ e => this.onInputChange(e) }
            value={ title }
            name='title'
            type='text'
            className='form-control' />

          Categories

            { this.props.categories ? this.props.categories.map((category, index) => (

                <input
                  onChange={ e => this.onCategoryChange(e) }
                  type='checkbox'
                  name={ category.id }
                  checked={ categories.indexOf(category.id) > -1 } />

                { category.name }

            )) : null }

          Address
          <input
            onKeyUp={ e => this.onAutoKeyUp(e) }
            key='address-input'
            ref={ n => this.addressInput = n }
            value={ address ? address.name : '' }
            type='text'
            className='form-control' />

          Description
          <textarea
            value={ description }
            onChange={ e => this.onInputChange(e) }
            className='form-control'
            name='description' rows='3' />

          List Image
          <div
            style={{ backgroundImage: image ? `url(${image})` : '' }}
            className='image-dialog'
            onClick={ () => this.showImageDialog() }>
            { this.state.image ? null : Add Image + }

          <button
            disabled={ !title.length || !description.length || !address }
            type='submit'
            className='btn btn-primary'>
            { this.props.location ? 'Save Location' : 'Save Location' }
          </button>

      </form>
    );
  }
}

export default LocationForm;
<|endoftext|>


<commit_before>/**
 * @file Host detection, non-UMD loader
 * @since 0.1.5
 */
/*#ifndef(UMD)*/
"use strict";
/*exported _GPF_HOST*/ // Host types
/*exported _GpfFunc*/ // Function
/*exported _gpfBootImplByHost*/ // Boot host specific implementation per host
/*exported _gpfDosPath*/ // DOS-like path
/*exported _gpfEmptyFunc*/ // An empty function
/*exported _gpfExit*/ // Exit function
/*exported _gpfHost*/ // Host type
/*exported _gpfIgnore*/ // Helper to remove unused parameter warning
/*exported _gpfMainContext*/ // Main context object
/*exported _gpfMsFSO*/ // Scripting.FileSystemObject activeX
/*exported _gpfNodeFs*/ // Node/PhantomJS require("fs")
/*exported _gpfNodePath*/ // Node require("path")
/*exported _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfVersion*/ // GPF version
/*exported _gpfWebDocument*/ // Browser document object
/*exported _gpfWebWindow*/ // Browser window object
/*eslint-disable no-unused-vars*/
/*#endif*/

/*jshint browser: true, node: true, phantom: true, rhino: true, wsh: true*/
/*eslint-env browser, node, phantomjs, rhino, wsh*/

// An empty function
function _gpfEmptyFunc () {}

var
    /**
     * GPF Version
     * @since 0.1.5
     */
    _gpfVersion = "0.2.5-alpha",

    /**
     * Host constants
     * @since 0.1.5
     */
    _GPF_HOST = {
        BROWSER:    "browser",
        NASHORN:    "nashorn",
        NODEJS:     "nodejs",
        PHANTOMJS:  "phantomjs",
        RHINO:      "rhino",
        UNKNOWN:    "unknown",
        WSCRIPT:    "wscript"
    },

    /**
     * Current host type
     *
     * @type {_GPF_HOST}
     * @since 0.1.5
     */
    _gpfHost = _GPF_HOST.UNKNOWN,

    /**
     * Indicates that paths are DOS-like (i.e. case insensitive with /)
     * @since 0.1.5
     */
    _gpfDosPath = false,

    // https://github.com/jshint/jshint/issues/525
    _GpfFunc = Function, // avoid JSHint error

    /*jshint -W040*/ // This is the common way to get the global context
    /**
     * Main context object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfMainContext = new _GpfFunc("return this")(), // Non-strict function returns global context
    /*jshint +W040*/

    /**
     * Helper to ignore unused parameter
     *
     * @param {*} param
     * @since 0.1.5
     */
    /*gpf:nop*/ _gpfIgnore = _gpfEmptyFunc,

    /**
     * Exit function
     *
     * @param {Number} code
     * @since 0.1.5
     */
    _gpfExit = _gpfEmptyFunc,

    /**
     * Browser window object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfWebWindow,

    /**
     * Browser [document](https://developer.mozilla.org/en-US/docs/Web/API/Document) object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfWebDocument,

    /**
     * [Scripting.FileSystemObject](https://msdn.microsoft.com/en-us/library/aa711216(v=vs.71).aspx) Object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfMsFSO,

    /**
     * Node [require("fs")](https://nodejs.org/api/fs.html)
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfNodeFs,

    /**
     * Node [require("path")](https://nodejs.org/api/path.html)
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfNodePath,

    /**
     * Boot host specific implementation per host
     *
     * @type {Object}
     * @since 0.2.1
     */
    _gpfBootImplByHost = {};

/*#ifdef(DEBUG)*/

_gpfVersion += "-debug";

/*#endif*/

/*#ifndef(UMD)*/

_gpfVersion += "-source";

/**
 * Synchronous read function
 *
 * @param {String} srcFileName
 * @return {String} content of the srcFileName
 * @since 0.1.5
 */
var _gpfSyncReadForBoot;

/*#endif*/

/* Host detection */

// Microsoft cscript / wscript
if ("undefined" !== typeof WScript) {
    _gpfHost = _GPF_HOST.WSCRIPT;
    _gpfDosPath = true;

    /*#ifndef(UMD)*/
    /*eslint-disable new-cap*/

    _gpfMsFSO = new ActiveXObject("Scripting.FileSystemObject");

    _gpfSyncReadForBoot = function (srcFileName) {
        var srcFile = _gpfMsFSO.OpenTextFile(srcFileName, 1),
            srcContent = srcFile.ReadAll();
        srcFile.Close();
        return srcContent;
    };

    /*eslint-enable new-cap*/
    /*#endif*/

} else if ("undefined" !== typeof print && "undefined" !== typeof java) {
    _gpfDosPath = String(java.lang.System.getProperty("file.separator")) === "\\";

    if ("undefined" === typeof readFile) {
        _gpfHost = _GPF_HOST.NASHORN;

        /*#ifndef(UMD)*/

        _gpfSyncReadForBoot = function (srcFileName) {
            return [].join.call(java.nio.file.Files.readAllLines(java.nio.file.Paths.get(srcFileName)), "\n");
        };

        /*#endif*/

    } else {
        _gpfHost = _GPF_HOST.RHINO;

        /*#ifndef(UMD)*/

        _gpfSyncReadForBoot = readFile;

        /*#endif*/

    }

// PhantomJS - When used as a command line (otherwise considered as a browser)
} else if ("undefined" !== typeof phantom && phantom.version && !document.currentScript) {
    _gpfHost = _GPF_HOST.PHANTOMJS;
    _gpfDosPath = require("fs").separator === "\\";
    _gpfMainContext = window;

    /*#ifndef(UMD)*/

    _gpfNodeFs =  require("fs");

    _gpfSyncReadForBoot = function (srcFileName) {
        return _gpfNodeFs.read(srcFileName);
    };

    /*#endif*/

// Nodejs
} else if ("undefined" !== typeof module && module.exports) {
    _gpfHost = _GPF_HOST.NODEJS;
    _gpfNodePath = require("path");
    _gpfDosPath = _gpfNodePath.sep === "\\";
    _gpfMainContext = global;

    /*#ifndef(UMD)*/
    /*eslint-disable no-sync*/ // Simpler this way

    _gpfNodeFs =  require("fs");

    _gpfSyncReadForBoot = function (srcFileName) {
        return _gpfNodeFs.readFileSync(srcFileName).toString();
    };

    /*#endif*/

// Browser
/* istanbul ignore else */ // unknown.1
} else if ("undefined" !== typeof window) {

    _gpfHost = _GPF_HOST.BROWSER;
    _gpfMainContext = window;

    /*#ifndef(UMD)*/

    _gpfSyncReadForBoot = function (srcFileName) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", srcFileName, false);
        xhr.send();
        return xhr.responseText;
    };

    /*#endif*/

}

/*#ifndef(UMD)*/

/**
 * Loading sources occurs here for the non UMD version.
 * UMD versions (debug / release) will have everything concatenated.
 * @since 0.1.5
 */

// Need to create the gpf name 'manually'
_gpfMainContext.gpf = {
    internals: {} // To support testable internals
};

/**
 * Contains the root path of GPF sources
 *
 * @name gpfSourcesPath
 * @type {String}
 * @private
 * @since 0.0.1
 */

/**
 * Reads a source file (only in source mode)
 *
 * NOTE this method is available only when running the source version
 *
 * @param {String} sourceFileName Source file name (relative to src folder)
 * @return {String} Source content
 * @since 0.1.7
 */
function _gpfSyncReadSourceJSON (sourceFileName) {
    /*jslint evil: true*/
    var result;
    eval("result = " + _gpfSyncReadForBoot(gpfSourcesPath + sourceFileName) + ";"); //eslint-disable-line no-eval
    return result;
}

/**
 * Load content of all sources
 *
 * @return {String} Consolidated sources
 * @since 0.1.9
 */
function _gpfLoadSources () { //jshint ignore:line
    /*jslint evil: true*/
    var sourceListContent = _gpfSyncReadForBoot(gpfSourcesPath + "sources.json"),
        _gpfSources,
        allContent = [],
        idx = 0,
        source;
    eval("_gpfSources = " + sourceListContent + ";"); //eslint-disable-line no-eval
    for (; idx < _gpfSources.length; ++idx) {
        source = _gpfSources[idx];
        if (source.load !== false) {
            allContent.push(_gpfSyncReadForBoot(gpfSourcesPath + source.name + ".js"));
        }
    }
    return allContent.join("\r\n");
}

/*jshint ignore:start*/ // Best way I found
eval(_gpfLoadSources()); //eslint-disable-line no-eval
/*jshint ignore:end*/

/*#endif*/

/**
 * Host type enumeration
 *
 * @enum {String}
 * @readonly
 * @since 0.1.5
 */
gpf.hosts = {
    /**
     * Any browser (phantomjs is recognized separately)
     * @since 0.1.5
     */
    browser: _GPF_HOST.BROWSER,
    /**
     * [Nashorn](https://en.wikipedia.org/wiki/Nashorn_%28JavaScript_engine%29)
     * @since 0.2.4
     */
    nashorn: _GPF_HOST.NASHORN,
    /**
     * [NodeJs](http://nodejs.org/)
     * @since 0.1.5
     */
    nodejs: _GPF_HOST.NODEJS,
    /**
     * [PhantomJS](http://phantomjs.org/)
     * @since 0.1.5
     */
    phantomjs: _GPF_HOST.PHANTOMJS,
    /**
     * [Rhino](http://developer.mozilla.org/en/docs/Rhino)
     * @since 0.1.5
     */
    rhino: _GPF_HOST.RHINO,
    /**
     * Unknown (detection failed or the host is unknown)
     * @since 0.1.5
     */
    unknown: _GPF_HOST.UNKNOWN,
    /**
     * [cscript/wscript](http://technet.microsoft.com/en-us/library/bb490887.aspx)
     * @since 0.1.5
     */
    wscript: _GPF_HOST.WSCRIPT
};

/**
 * Returns the detected host type
 *
 * @return {gpf.hosts} Host type
 * @since 0.1.5
 */
gpf.host = function () {
    return _gpfHost;
};

/**
 * Returns the current version
 *
 * @return {String} Version
 * @since 0.1.5
 */
gpf.version = function () {
    return _gpfVersion;
};
<commit_msg>Useless \r (#183)<commit_after>/**
 * @file Host detection, non-UMD loader
 * @since 0.1.5
 */
/*#ifndef(UMD)*/
"use strict";
/*exported _GPF_HOST*/ // Host types
/*exported _GpfFunc*/ // Function
/*exported _gpfBootImplByHost*/ // Boot host specific implementation per host
/*exported _gpfDosPath*/ // DOS-like path
/*exported _gpfEmptyFunc*/ // An empty function
/*exported _gpfExit*/ // Exit function
/*exported _gpfHost*/ // Host type
/*exported _gpfIgnore*/ // Helper to remove unused parameter warning
/*exported _gpfMainContext*/ // Main context object
/*exported _gpfMsFSO*/ // Scripting.FileSystemObject activeX
/*exported _gpfNodeFs*/ // Node/PhantomJS require("fs")
/*exported _gpfNodePath*/ // Node require("path")
/*exported _gpfSyncReadSourceJSON*/ // Reads a source json file (only in source mode)
/*exported _gpfVersion*/ // GPF version
/*exported _gpfWebDocument*/ // Browser document object
/*exported _gpfWebWindow*/ // Browser window object
/*eslint-disable no-unused-vars*/
/*#endif*/

/*jshint browser: true, node: true, phantom: true, rhino: true, wsh: true*/
/*eslint-env browser, node, phantomjs, rhino, wsh*/

// An empty function
function _gpfEmptyFunc () {}

var
    /**
     * GPF Version
     * @since 0.1.5
     */
    _gpfVersion = "0.2.5-alpha",

    /**
     * Host constants
     * @since 0.1.5
     */
    _GPF_HOST = {
        BROWSER:    "browser",
        NASHORN:    "nashorn",
        NODEJS:     "nodejs",
        PHANTOMJS:  "phantomjs",
        RHINO:      "rhino",
        UNKNOWN:    "unknown",
        WSCRIPT:    "wscript"
    },

    /**
     * Current host type
     *
     * @type {_GPF_HOST}
     * @since 0.1.5
     */
    _gpfHost = _GPF_HOST.UNKNOWN,

    /**
     * Indicates that paths are DOS-like (i.e. case insensitive with /)
     * @since 0.1.5
     */
    _gpfDosPath = false,

    // https://github.com/jshint/jshint/issues/525
    _GpfFunc = Function, // avoid JSHint error

    /*jshint -W040*/ // This is the common way to get the global context
    /**
     * Main context object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfMainContext = new _GpfFunc("return this")(), // Non-strict function returns global context
    /*jshint +W040*/

    /**
     * Helper to ignore unused parameter
     *
     * @param {*} param
     * @since 0.1.5
     */
    /*gpf:nop*/ _gpfIgnore = _gpfEmptyFunc,

    /**
     * Exit function
     *
     * @param {Number} code
     * @since 0.1.5
     */
    _gpfExit = _gpfEmptyFunc,

    /**
     * Browser window object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfWebWindow,

    /**
     * Browser [document](https://developer.mozilla.org/en-US/docs/Web/API/Document) object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfWebDocument,

    /**
     * [Scripting.FileSystemObject](https://msdn.microsoft.com/en-us/library/aa711216(v=vs.71).aspx) Object
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfMsFSO,

    /**
     * Node [require("fs")](https://nodejs.org/api/fs.html)
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfNodeFs,

    /**
     * Node [require("path")](https://nodejs.org/api/path.html)
     *
     * @type {Object}
     * @since 0.1.5
     */
    _gpfNodePath,

    /**
     * Boot host specific implementation per host
     *
     * @type {Object}
     * @since 0.2.1
     */
    _gpfBootImplByHost = {};

/*#ifdef(DEBUG)*/

_gpfVersion += "-debug";

/*#endif*/

/*#ifndef(UMD)*/

_gpfVersion += "-source";

/**
 * Synchronous read function
 *
 * @param {String} srcFileName
 * @return {String} content of the srcFileName
 * @since 0.1.5
 */
var _gpfSyncReadForBoot;

/*#endif*/

/* Host detection */

// Microsoft cscript / wscript
if ("undefined" !== typeof WScript) {
    _gpfHost = _GPF_HOST.WSCRIPT;
    _gpfDosPath = true;

    /*#ifndef(UMD)*/
    /*eslint-disable new-cap*/

    _gpfMsFSO = new ActiveXObject("Scripting.FileSystemObject");

    _gpfSyncReadForBoot = function (srcFileName) {
        var srcFile = _gpfMsFSO.OpenTextFile(srcFileName, 1),
            srcContent = srcFile.ReadAll();
        srcFile.Close();
        return srcContent;
    };

    /*eslint-enable new-cap*/
    /*#endif*/

} else if ("undefined" !== typeof print && "undefined" !== typeof java) {
    _gpfDosPath = String(java.lang.System.getProperty("file.separator")) === "\\";

    if ("undefined" === typeof readFile) {
        _gpfHost = _GPF_HOST.NASHORN;

        /*#ifndef(UMD)*/

        _gpfSyncReadForBoot = function (srcFileName) {
            return [].join.call(java.nio.file.Files.readAllLines(java.nio.file.Paths.get(srcFileName)), "\n");
        };

        /*#endif*/

    } else {
        _gpfHost = _GPF_HOST.RHINO;

        /*#ifndef(UMD)*/

        _gpfSyncReadForBoot = readFile;

        /*#endif*/

    }

// PhantomJS - When used as a command line (otherwise considered as a browser)
} else if ("undefined" !== typeof phantom && phantom.version && !document.currentScript) {
    _gpfHost = _GPF_HOST.PHANTOMJS;
    _gpfDosPath = require("fs").separator === "\\";
    _gpfMainContext = window;

    /*#ifndef(UMD)*/

    _gpfNodeFs =  require("fs");

    _gpfSyncReadForBoot = function (srcFileName) {
        return _gpfNodeFs.read(srcFileName);
    };

    /*#endif*/

// Nodejs
} else if ("undefined" !== typeof module && module.exports) {
    _gpfHost = _GPF_HOST.NODEJS;
    _gpfNodePath = require("path");
    _gpfDosPath = _gpfNodePath.sep === "\\";
    _gpfMainContext = global;

    /*#ifndef(UMD)*/
    /*eslint-disable no-sync*/ // Simpler this way

    _gpfNodeFs =  require("fs");

    _gpfSyncReadForBoot = function (srcFileName) {
        return _gpfNodeFs.readFileSync(srcFileName).toString();
    };

    /*#endif*/

// Browser
/* istanbul ignore else */ // unknown.1
} else if ("undefined" !== typeof window) {

    _gpfHost = _GPF_HOST.BROWSER;
    _gpfMainContext = window;

    /*#ifndef(UMD)*/

    _gpfSyncReadForBoot = function (srcFileName) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", srcFileName, false);
        xhr.send();
        return xhr.responseText;
    };

    /*#endif*/

}

/*#ifndef(UMD)*/

/**
 * Loading sources occurs here for the non UMD version.
 * UMD versions (debug / release) will have everything concatenated.
 * @since 0.1.5
 */

// Need to create the gpf name 'manually'
_gpfMainContext.gpf = {
    internals: {} // To support testable internals
};

/**
 * Contains the root path of GPF sources
 *
 * @name gpfSourcesPath
 * @type {String}
 * @private
 * @since 0.0.1
 */

/**
 * Reads a source file (only in source mode)
 *
 * NOTE this method is available only when running the source version
 *
 * @param {String} sourceFileName Source file name (relative to src folder)
 * @return {String} Source content
 * @since 0.1.7
 */
function _gpfSyncReadSourceJSON (sourceFileName) {
    /*jslint evil: true*/
    var result;
    eval("result = " + _gpfSyncReadForBoot(gpfSourcesPath + sourceFileName) + ";"); //eslint-disable-line no-eval
    return result;
}

/**
 * Load content of all sources
 *
 * @return {String} Consolidated sources
 * @since 0.1.9
 */
function _gpfLoadSources () { //jshint ignore:line
    /*jslint evil: true*/
    var sourceListContent = _gpfSyncReadForBoot(gpfSourcesPath + "sources.json"),
        _gpfSources,
        allContent = [],
        idx = 0,
        source;
    eval("_gpfSources = " + sourceListContent + ";"); //eslint-disable-line no-eval
    for (; idx < _gpfSources.length; ++idx) {
        source = _gpfSources[idx];
        if (source.load !== false) {
            allContent.push(_gpfSyncReadForBoot(gpfSourcesPath + source.name + ".js"));
        }
    }
    return allContent.join("\n");
}

/*jshint ignore:start*/ // Best way I found
eval(_gpfLoadSources()); //eslint-disable-line no-eval
/*jshint ignore:end*/

/*#endif*/

/**
 * Host type enumeration
 *
 * @enum {String}
 * @readonly
 * @since 0.1.5
 */
gpf.hosts = {
    /**
     * Any browser (phantomjs is recognized separately)
     * @since 0.1.5
     */
    browser: _GPF_HOST.BROWSER,
    /**
     * [Nashorn](https://en.wikipedia.org/wiki/Nashorn_%28JavaScript_engine%29)
     * @since 0.2.4
     */
    nashorn: _GPF_HOST.NASHORN,
    /**
     * [NodeJs](http://nodejs.org/)
     * @since 0.1.5
     */
    nodejs: _GPF_HOST.NODEJS,
    /**
     * [PhantomJS](http://phantomjs.org/)
     * @since 0.1.5
     */
    phantomjs: _GPF_HOST.PHANTOMJS,
    /**
     * [Rhino](http://developer.mozilla.org/en/docs/Rhino)
     * @since 0.1.5
     */
    rhino: _GPF_HOST.RHINO,
    /**
     * Unknown (detection failed or the host is unknown)
     * @since 0.1.5
     */
    unknown: _GPF_HOST.UNKNOWN,
    /**
     * [cscript/wscript](http://technet.microsoft.com/en-us/library/bb490887.aspx)
     * @since 0.1.5
     */
    wscript: _GPF_HOST.WSCRIPT
};

/**
 * Returns the detected host type
 *
 * @return {gpf.hosts} Host type
 * @since 0.1.5
 */
gpf.host = function () {
    return _gpfHost;
};

/**
 * Returns the current version
 *
 * @return {String} Version
 * @since 0.1.5
 */
gpf.version = function () {
    return _gpfVersion;
};
<|endoftext|>


<commit_before>(function () {
	"use strict";

	var bullshits = [
		'24/7',
		'a-b testing',
		'acquisition',
		'action items?',
		'advantages?',
		'agenda',
		'aggregate',
		'agnostic',
		'application service providers?',
		'assets?',
		'at the end of the day',
		'automated',
		'b2b',
		'back to the drawing board',
		'ball.?park',
		'band.aid',
		'bandwidth',
		'basically',
		'benchmark',
		'benefit analysis',
		'best.of.breed',
		'best.practice',
		'big picture',
		'bottom line',
		'bottom.up',
		'brain.?storm',
		'brain.?dump',
		'brand(?:s?|ing|ed)',
		'burn rates?',
		'business cases?',
		'business plans?',
		'business.centricity',
		'business.centric',
		'buzz',
		'call to action',
		'capacity',
		'capitalize',
		'center of excellence',
		'challenges?',
		'change agent',
		'circle the wagons',
		'client focus',
		'client.focused',
		'cloud.based',
		'collaborate',
		'collaboration',
		'communicate',
		'communication',
		'compelling',
		'competitive advantage',
		'competitive',
		'connect the dots',
		'content management',
		'contingency plan',
		'control group',
		'convergent',
		'conversation',
		'conversion',
		'core business',
		'core competenc(?:y|ies)',
		'cost-effective',
		'cost/benefit',
		'craftsmanship',
		'critical path',
		'crm',
		'cross.sell',
		'customer.(?:centric|facing|oriented|service|driven)',
		'cutting.edge',
		'dashboard',
		'data mining',
		'deadlines',
		'deep dive',
		'delight the customer',
		'deliverables?',
		'demographic',
		'discovery',
		'diversity',
		'downsize',
		'drill down',
		'drink the kool-aid',
		'drop the ball',
		'due dilligence',
		'dynamic',
		'e-business',
		'e-commerce',
		'e-tailers',
		'ecosystem',
		'efficiency',
		'efficient',
		'elephant in the room',
		'elevator pitch',
		'emerging markets',
		'empower',
		'empowerment',
		'end of the day',
		'end to end',
		'engage',
		'enhance',
		'enterprise',
		'eta',
		'etched in stone',
		'exceed expectations',
		'expectations',
		'experiences',
		'exposure',
		'eyeballs',
		'facilitate',
		'facilitator',
		'fast track',
		'fault tolerant',
		'first to market',
		'flexibility',
		'focused',
		'followup',
		'foot view',
		'front lines',
		'functionality',
		'full benefit',
		'game plan',
		'gap analysis',
		'go live',
		'go public',
		'go to market',
		'goals',
		'goal.oriented',
		'going forward',
		'google juice',
		'granular',
		'green',
		'growth',
		'grow',
		'guidance',
		'hardball',
		'having said that',
		'heads.up',
		'heavy.lifting',
		'herding cats',
		'high.level',
		'high.impact',
		'impactful',
		'implementation',
		'in a nutshell',
		'incent',
		'incentivize',
		'innovated',
		'innovation',
		'innovative',
		'innovating',
		'innovate',
		'integrated',
		'integration',
		'intellectual property',
		'knowledge base',
		'knowledge transfer',
		'landing page',
		'landing pages',
		'lead the field',
		'leadership',
		'legacy',
		'lessons learned',
		'level playing field',
		'level set',
		'leverage',
		'low-hanging fruit',
		'market driven',
		'market leader',
		'market window',
		'marketing collateral',
		'mass.impact',
		'maximize',
		'measurement',
		'methodolog(?:y|ies)',
		'metrics',
		'middleware',
		'milestone',
		'mind share',
		'mind shower',
		'mindset',
		'mindshare',
		'mission.critical',
		'monetize',
		'moving forward',
		'multitask',
		'multitasking',
		'negotiated',
		'networking',
		'new economy',
		'next level',
		'niche',
		'niches',
		'no-brainer',
		'non-traditional management',
		'objectives',
		'occupy the field',
		'off.site meeting',
		'off.the.(?:radar|shelf)',
		'off-?line',
		'on board',
		'on the (?:back end|radar screen|same page)',
		'one to one',
        'OOP',
        '(?:(?:O|o)bject|(?:A|a)spect|(?:R|r)ole|(?:S|s)ubject)-oriented',
		'opportunit(?:y|ies)',
		'optimization',
		'out.of.the.(?:box|loop)',
		'outsourc(?:e|ed|ing)',
		'ownership',
		'paradigm shift',
		'paradigms?',
		'partnerships?',
		'partner',
		'patent',
		'performance indicators',
		'performance',
		'personalization',
		'perspective',
		'phase',
		'phased approach',
		'pipeline',
		'planning horizon',
		'prioritized?',
		'proactive',
		'problem space',
		'process assessment',
		'processes',
		'process-centric',
		'profitability',
		'profit',
		'promotional collateral',
		'promotion',
        'proprietary',
		'proof.of.concept',
		'prototype',
		'push the envelope',
		'pushback',
		'quality.driven',
		'quick win',
		'rais(?:e|ing) the bar',
		'ramp.up',
		'relationship management',
		'engagements?',
		'engage',
		'reach out',
		'reactivation',
		'real.time',
		'real.world',
		'reconfigure',
		'red flag',
		'reengineering',
		'reinvent(?:ing)? the wheel',
		'reinvigorate',
		'relevance',
		'repurpose',
		'resource allocation',
		'resources?',
		'restructuring',
		'results.driven',
		'retention',
		'return on investment',
		'reusability',
		'reuse',
		'revenue',
		'reverse.engineer',
		'revisit',
		'road ?map',
		'robust',
		'roi',
		'run the numbers',
		'sales.driven',
		'scale',
		'scenarios?',
		'scope',
		'seamless',
		'search engine optimization',
		'secret sauce',
		'segment',
		'self-managed team',
		'seo',
		'service oriented',
		'shareholder value',
		'single-source responsibility',
		'skill sets?',
		'smoke (?:&|and) mirrors',
		'solutions?',
		'soup to nuts',
		'sow',
		'stakeholder',
		'statement of work',
		'sticky-?ness',
		'strateg(?:y|ic|ize)',
		'streamline',
		'success',
		'sustainab(?:le|ility)',
		'synerg(?:y|ies)',
		'tailwinds?',
		'take offline',
		'talking points',
		'target (?:audience|group)',
		'targeted',
		'tasked',
		'tco',
		'team building',
		'team player',
		'teamwork',
		'technologies',
		'technology solutions',
		'that being said',
		'think(?:ing)? outside the box',
		'time to market',
		'time.critical',
		'timelines?',
		'top.down',
		'top of the game',
		'total cost of ownership',
		'total quality',
		'touch base',
		'touchpoints',
		'traction',
		'turnkey',
		'up to speed',
		'up-?sell',
		'upside',
		'user.friendly',
		'utilize',
		'unique approach',
		'value-added',
		'values?',
		'vertical market',
		'viral',
		'virtual(?:ization)?',
		'visibility',
		'vision statement',
		'walk the talk',
		'web 2\\.0',
		'web 3\\.0',
		'web-enabled',
		'win-win',
		'window of opportunity',
		'workflow',
		'workshop',
		'world.class',
		'wow factor'
	];

	function bulshitize(term) {
		var c = term.charAt(0),
		    bullshit = (c === c.toUpperCase() ? 'B' : 'b') + 'ullshit';

		if (term.substr(term.length - 3) === 'ing') {
			bullshit += 'ing';
		}

		return '' + bullshit + '';
	}

	var re = new RegExp('(' + bullshits.join('|') + ')(?!\\w|[^<]*>)', 'gi'),
	    body = document.body;

	body.innerHTML = body.innerHTML.replace(re, bulshitize);
}());
<commit_msg>usually code for out of date<commit_after>(function () {
	"use strict";

	var bullshits = [
		'24/7',
		'a-b testing',
		'acquisition',
		'action items?',
		'advantages?',
		'agenda',
		'aggregate',
		'agnostic',
		'application service providers?',
		'assets?',
		'at the end of the day',
        'authoritative',
		'automated',
		'b2b',
		'back to the drawing board',
		'ball.?park',
		'band.aid',
		'bandwidth',
		'basically',
		'benchmark',
		'benefit analysis',
		'best.of.breed',
		'best.practice',
		'big picture',
		'bottom line',
		'bottom.up',
		'brain.?storm',
		'brain.?dump',
		'brand(?:s?|ing|ed)',
		'burn rates?',
		'business cases?',
		'business plans?',
		'business.centricity',
		'business.centric',
		'buzz',
		'call to action',
		'capacity',
		'capitalize',
		'center of excellence',
		'challenges?',
		'change agent',
		'circle the wagons',
		'client focus',
		'client.focused',
		'cloud.based',
		'collaborate',
		'collaboration',
		'communicate',
		'communication',
		'compelling',
		'competitive advantage',
		'competitive',
		'connect the dots',
		'content management',
		'contingency plan',
		'control group',
		'convergent',
		'conversation',
		'conversion',
		'core business',
		'core competenc(?:y|ies)',
		'cost-effective',
		'cost/benefit',
		'craftsmanship',
		'critical path',
		'crm',
		'cross.sell',
		'customer.(?:centric|facing|oriented|service|driven)',
		'cutting.edge',
		'dashboard',
		'data mining',
		'deadlines',
		'deep dive',
		'delight the customer',
		'deliverables?',
		'demographic',
		'discovery',
		'diversity',
		'downsize',
		'drill down',
		'drink the kool-aid',
		'drop the ball',
		'due dilligence',
		'dynamic',
		'e-business',
		'e-commerce',
		'e-tailers',
		'ecosystem',
		'efficiency',
		'efficient',
		'elephant in the room',
		'elevator pitch',
		'emerging markets',
		'empower',
		'empowerment',
		'end of the day',
		'end to end',
		'engage',
		'enhance',
		'enterprise',
		'eta',
		'etched in stone',
		'exceed expectations',
		'expectations',
		'experiences',
		'exposure',
		'eyeballs',
		'facilitate',
		'facilitator',
		'fast track',
		'fault tolerant',
		'first to market',
		'flexibility',
		'focused',
		'followup',
		'foot view',
		'front lines',
		'functionality',
		'full benefit',
		'game plan',
		'gap analysis',
		'go live',
		'go public',
		'go to market',
		'goals',
		'goal.oriented',
		'going forward',
		'google juice',
		'granular',
		'green',
		'growth',
		'grow',
		'guidance',
		'hardball',
		'having said that',
		'heads.up',
		'heavy.lifting',
		'herding cats',
		'high.level',
		'high.impact',
		'impactful',
		'implementation',
		'in a nutshell',
		'incent',
		'incentivize',
		'innovated',
		'innovation',
		'innovative',
		'innovating',
		'innovate',
		'integrated',
		'integration',
		'intellectual property',
		'knowledge base',
		'knowledge transfer',
		'landing page',
		'landing pages',
		'lead the field',
		'leadership',
		'legacy',
		'lessons learned',
		'level playing field',
		'level set',
		'leverage',
		'low-hanging fruit',
		'market driven',
		'market leader',
		'market window',
		'marketing collateral',
		'mass.impact',
		'maximize',
		'measurement',
		'methodolog(?:y|ies)',
		'metrics',
		'middleware',
		'milestone',
		'mind share',
		'mind shower',
		'mindset',
		'mindshare',
		'mission.critical',
		'monetize',
		'moving forward',
		'multitask',
		'multitasking',
		'negotiated',
		'networking',
		'new economy',
		'next level',
		'niche',
		'niches',
		'no-brainer',
		'non-traditional management',
		'objectives',
		'occupy the field',
		'off.site meeting',
		'off.the.(?:radar|shelf)',
		'off-?line',
		'on board',
		'on the (?:back end|radar screen|same page)',
		'one to one',
        'OOP',
        '(?:object|aspect|role|subject)-oriented',
		'opportunit(?:y|ies)',
		'optimization',
		'out.of.the.(?:box|loop)',
		'outsourc(?:e|ed|ing)',
		'ownership',
		'paradigm shift',
		'paradigms?',
		'partnerships?',
		'partner',
		'patent',
		'performance indicators',
		'performance',
		'personalization',
		'perspective',
		'phase',
		'phased approach',
		'pipeline',
		'planning horizon',
		'prioritized?',
		'proactive',
		'problem space',
		'process assessment',
		'processes',
		'process-centric',
		'profitability',
		'profit',
		'promotional collateral',
		'promotion',
        'proprietary',
		'proof.of.concept',
		'prototype',
		'push the envelope',
		'pushback',
		'quality.driven',
		'quick win',
		'rais(?:e|ing) the bar',
		'ramp.up',
		'relationship management',
		'engagements?',
		'engage',
		'reach out',
		'reactivation',
		'real.time',
		'real.world',
		'reconfigure',
		'red flag',
		'reengineering',
		'reinvent(?:ing)? the wheel',
		'reinvigorate',
		'relevance',
		'repurpose',
		'resource allocation',
		'resources?',
		'restructuring',
		'results.driven',
		'retention',
		'return on investment',
		'reusability',
		'reuse',
		'revenue',
		'reverse.engineer',
		'revisit',
		'road ?map',
		'robust',
		'roi',
		'run the numbers',
		'sales.driven',
		'scale',
		'scenarios?',
		'scope',
		'seamless',
		'search engine optimization',
		'secret sauce',
		'segment',
		'self-managed team',
		'seo',
		'service oriented',
		'shareholder value',
		'single-source responsibility',
		'skill sets?',
		'smoke (?:&|and) mirrors',
		'solutions?',
		'soup to nuts',
		'sow',
		'stakeholder',
		'statement of work',
		'sticky-?ness',
		'strateg(?:y|ic|ize)',
		'streamline',
		'success',
		'sustainab(?:le|ility)',
		'synerg(?:y|ies)',
		'tailwinds?',
		'take offline',
		'talking points',
		'target (?:audience|group)',
		'targeted',
		'tasked',
		'tco',
		'team building',
		'team player',
		'teamwork',
		'technologies',
		'technology solutions',
		'that being said',
		'think(?:ing)? outside the box',
		'time to market',
		'time.critical',
		'timelines?',
		'top.down',
		'top of the game',
		'total cost of ownership',
		'total quality',
		'touch base',
		'touchpoints',
		'traction',
		'turnkey',
		'up to speed',
		'up-?sell',
		'upside',
		'user.friendly',
		'utilize',
		'unique approach',
		'value-added',
		'values?',
		'vertical market',
		'viral',
		'virtual(?:ization)?',
		'visibility',
		'vision statement',
		'walk the talk',
		'web 2\\.0',
		'web 3\\.0',
		'web-enabled',
		'win-win',
		'window of opportunity',
		'workflow',
		'workshop',
		'world.class',
		'wow factor'
	];

	function bulshitize(term) {
		var c = term.charAt(0),
		    bullshit = (c === c.toUpperCase() ? 'B' : 'b') + 'ullshit';

		if (term.substr(term.length - 3) === 'ing') {
			bullshit += 'ing';
		}

		return '' + bullshit + '';
	}

	var re = new RegExp('(' + bullshits.join('|') + ')(?!\\w|[^<]*>)', 'gi'),
	    body = document.body;

	body.innerHTML = body.innerHTML.replace(re, bulshitize);
}());
<|endoftext|>


<commit_before>var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , dialect   = Support.getTestDialect()
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , _         = require('lodash')

chai.config.includeStack = true

if (dialect.match(/^postgres/)) {
  describe('[POSTGRES Specific] DAO', function() {
    beforeEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      this.User = this.sequelize.define('User', {
        username: DataTypes.STRING,
        email: { type: DataTypes.ARRAY(DataTypes.TEXT) },
        settings: DataTypes.HSTORE,
        document: { type: DataTypes.HSTORE, defaultValue: { default: 'value' } }
      })
      this.User.sync({ force: true }).success(function() {
        done()
      })
    })

    afterEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      done()
    })

    it('should be able to search within an array', function(done) {
      this.User.all({where: {email: ['hello', 'world']}}).on('sql', function(sql) {
        expect(sql).to.equal('SELECT * FROM "Users" AS "User" WHERE "User"."email" && ARRAY[\'hello\',\'world\']::TEXT[];')
        done()
      })
    })

    it('should be able to find a record while searching in an array', function(done) {
      var self = this
      this.User.bulkCreate([
        {username: 'bob', email: ['myemail@email.com']},
        {username: 'tony', email: ['wrongemail@email.com']}
      ]).success(function() {
        self.User.all({where: {email: ['myemail@email.com']}}).success(function(user) {
          expect(user).to.be.instanceof(Array)
          expect(user).to.have.length(1)
          expect(user[0].username).to.equal('bob')
          done()
        })
      })
    })

    describe('hstore', function() {
      it('should tell me that a column is hstore and not USER-DEFINED', function(done) {
        this.sequelize.queryInterface.describeTable('Users').success(function(table) {
          expect(table.settings.type).to.equal('HSTORE')
          expect(table.document.type).to.equal('HSTORE')
          done()
        })
      })

      it('should stringify hstore with insert', function(done) {
        this.User.create({
          username: 'bob',
          email: ['myemail@email.com'],
          settings: {mailing: false, push: 'facebook', frequency: 3}
        }).on('sql', function(sql) {
          var expected = 'INSERT INTO "Users" ("id","username","email","settings","document","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'myemail@email.com\']::TEXT[],\'"mailing"=>false,"push"=>"facebook","frequency"=>3\',\'"default"=>"value"\''
          expect(sql.indexOf(expected)).to.equal(0)
          done()
        })
      })
    })

    describe('enums', function() {
      it('should be able to ignore enum types that already exist', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync().success(function() {
            done()
          })
        })
      })

      it('should be able to create/drop enums multiple times', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync({ force: true }).success(function() {
            done()
          })
        })
      })

      it("should be able to create/drop multiple enums multiple times", function(done) {
        var DummyModel = this.sequelize.define('Dummy-pg', {
          username: DataTypes.STRING,
          theEnumOne: {
            type: DataTypes.ENUM,
            values:[
              'one',
              'two',
              'three',
            ]
          },
          theEnumTwo: {
            type: DataTypes.ENUM,
            values:[
              'four',
              'five',
              'six',
            ],
          }
        })

        DummyModel.sync({ force: true }).done(function(err) {
          expect(err).not.to.be.ok
          // now sync one more time:
          DummyModel.sync({force: true}).done(function(err) {
            expect(err).not.to.be.ok
            // sync without dropping
            DummyModel.sync().done(function(err) {
              expect(err).not.to.be.ok
              done();
            })
          })
        })
      })

      it('should be able to add enum types', function(done) {
        var self = this
          , User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        var _done = _.after(4, function() {
          done()
        })

        User.sync({ force: true }).success(function() {
          User = self.sequelize.define('UserEnums', {
            mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
          })

          User.sync().success(function() {
            expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful'])
            _done()
          }).on('sql', function(sql) {
            if (sql.indexOf('neutral') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'")
              _done()
            }
            else if (sql.indexOf('ecstatic') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'")
              _done()
            }
            else if (sql.indexOf('joyful') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'")
              _done()
            }
          })
        })
      })
    })

    describe('integers', function() {
      describe('integer', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.INTEGER
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: 2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(2147483647)
            User.find({where: {aNumber: 2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(2147483647)
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: -2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(-2147483647)
            User.find({where: {aNumber: -2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(-2147483647)
              done()
            })
          })
        })
      })

      describe('bigint', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.BIGINT
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: '9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('9223372036854775807')
            User.find({where: {aNumber: '9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('9223372036854775807')
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: '-9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('-9223372036854775807')
            User.find({where: {aNumber: '-9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('-9223372036854775807')
              done()
            })
          })
        })
      })
    })

    describe('model', function() {
      it("create handles array correctly", function(done) {
        this.User
          .create({ username: 'user', email: ['foo@bar.com', 'bar@baz.com'] })
          .success(function(oldUser) {
            expect(oldUser.email).to.contain.members(['foo@bar.com', 'bar@baz.com'])
            done()
          })
          .error(function(err) {
            console.log(err)
          })
      })

      it("should save hstore correctly", function(done) {
        this.User
          .create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .success(function(newUser) {
            // Check to see if the default value for an hstore field works
            expect(newUser.document).to.deep.equal({default: 'value'})
            expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})

            // Check to see if updating an hstore field works
            newUser.updateAttributes({settings: {should: 'update', to: 'this', first: 'place'}}).success(function(oldUser){
              // Postgres always returns keys in alphabetical order (ascending)
              expect(oldUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
              done()
            })
          })
          .error(console.log)
      })

      it("should update hstore correctly", function(done) {
        var self = this

        this.User
          .create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .success(function(newUser) {
            // Check to see if the default value for an hstore field works
            expect(newUser.document).to.deep.equal({default: 'value'})
            expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})

            // Check to see if updating an hstore field works
            self.User.update({settings: {should: 'update', to: 'this', first: 'place'}}, newUser.identifiers).success(function() {
              newUser.reload().success(function() {
                // Postgres always returns keys in alphabetical order (ascending)
                expect(newUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
                done()
              });
            })
          })
          .error(console.log)
      })

      it("should read hstore correctly", function(done) {
        var self = this
        var data = { username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}}

        this.User
          .create(data)
          .success(function() {
            // Check that the hstore fields are the same when retrieving the user
            self.User.find({ where: { username: 'user' }})
              .success(function(user) {
                expect(user.settings).to.deep.equal(data.settings)

                done()
              })
          })
          .error(console.log)
      })

      it("should read hstore correctly from multiple rows", function(done) {
        var self = this

        self.User
          .create({ username: 'user1', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .then(function() {
            return self.User.create({ username: 'user2', email: ['foo2@bar.com'], settings: { updated: { another: '"example"' }}})
          })
          .then(function() {
            // Check that the hstore fields are the same when retrieving the user
            return self.User.findAll({ order: 'username' })
          })
          .then(function(users) {
            expect(users[0].settings).to.deep.equal({ created: { test: '"value"' }})
            expect(users[1].settings).to.deep.equal({ updated: { another: '"example"' }})

            done()
          })
          .error(console.log)
      })
    })

    describe('[POSTGRES] Unquoted identifiers', function() {
      it("can insert and select", function(done) {
        var self = this
        this.sequelize.options.quoteIdentifiers = false
        this.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = false

        this.User = this.sequelize.define('Userxs', {
          username: DataTypes.STRING,
          fullName: DataTypes.STRING // Note mixed case
        }, {
          quoteIdentifiers: false
        })

        this.User.sync({ force: true }).success(function() {
          self.User
            .create({ username: 'user', fullName: "John Smith" })
            .success(function(user) {
              // We can insert into a table with non-quoted identifiers
              expect(user.id).to.exist
              expect(user.id).not.to.be.null
              expect(user.username).to.equal('user')
              expect(user.fullName).to.equal('John Smith')

              // We can query by non-quoted identifiers
              self.User.find({
                where: {fullName: "John Smith"}
              })
              .success(function(user2) {
                self.sequelize.options.quoteIndentifiers = true
                self.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = true
                self.sequelize.options.logging = false
                // We can map values back to non-quoted identifiers
                expect(user2.id).to.equal(user.id)
                expect(user2.username).to.equal('user')
                expect(user2.fullName).to.equal('John Smith')
                done()
              })
            })
        })
      })
    })
  })
}
<commit_msg>test(postgres/instance): fix sql matched against<commit_after>var chai      = require('chai')
  , expect    = chai.expect
  , Support   = require(__dirname + '/../support')
  , dialect   = Support.getTestDialect()
  , DataTypes = require(__dirname + "/../../lib/data-types")
  , _         = require('lodash')

chai.config.includeStack = true

if (dialect.match(/^postgres/)) {
  describe('[POSTGRES Specific] DAO', function() {
    beforeEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      this.User = this.sequelize.define('User', {
        username: DataTypes.STRING,
        email: { type: DataTypes.ARRAY(DataTypes.TEXT) },
        settings: DataTypes.HSTORE,
        document: { type: DataTypes.HSTORE, defaultValue: { default: 'value' } }
      })
      this.User.sync({ force: true }).success(function() {
        done()
      })
    })

    afterEach(function(done) {
      this.sequelize.options.quoteIdentifiers = true
      done()
    })

    it('should be able to search within an array', function(done) {
      this.User.all({where: {email: ['hello', 'world']}}).on('sql', function(sql) {
        expect(sql).to.equal('SELECT "id", "username", "email", "settings", "document", "createdAt", "updatedAt" FROM "Users" AS "User" WHERE "User"."email" && ARRAY[\'hello\',\'world\']::TEXT[];')
        done()
      })
    })

    it('should be able to find a record while searching in an array', function(done) {
      var self = this
      this.User.bulkCreate([
        {username: 'bob', email: ['myemail@email.com']},
        {username: 'tony', email: ['wrongemail@email.com']}
      ]).success(function() {
        self.User.all({where: {email: ['myemail@email.com']}}).success(function(user) {
          expect(user).to.be.instanceof(Array)
          expect(user).to.have.length(1)
          expect(user[0].username).to.equal('bob')
          done()
        })
      })
    })

    describe('hstore', function() {
      it('should tell me that a column is hstore and not USER-DEFINED', function(done) {
        this.sequelize.queryInterface.describeTable('Users').success(function(table) {
          expect(table.settings.type).to.equal('HSTORE')
          expect(table.document.type).to.equal('HSTORE')
          done()
        })
      })

      it('should stringify hstore with insert', function(done) {
        this.User.create({
          username: 'bob',
          email: ['myemail@email.com'],
          settings: {mailing: false, push: 'facebook', frequency: 3}
        }).on('sql', function(sql) {
          var expected = 'INSERT INTO "Users" ("id","username","email","settings","document","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'myemail@email.com\']::TEXT[],\'"mailing"=>false,"push"=>"facebook","frequency"=>3\',\'"default"=>"value"\''
          expect(sql.indexOf(expected)).to.equal(0)
          done()
        })
      })
    })

    describe('enums', function() {
      it('should be able to ignore enum types that already exist', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync().success(function() {
            done()
          })
        })
      })

      it('should be able to create/drop enums multiple times', function(done) {
        var User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        User.sync({ force: true }).success(function() {
          User.sync({ force: true }).success(function() {
            done()
          })
        })
      })

      it("should be able to create/drop multiple enums multiple times", function(done) {
        var DummyModel = this.sequelize.define('Dummy-pg', {
          username: DataTypes.STRING,
          theEnumOne: {
            type: DataTypes.ENUM,
            values:[
              'one',
              'two',
              'three',
            ]
          },
          theEnumTwo: {
            type: DataTypes.ENUM,
            values:[
              'four',
              'five',
              'six',
            ],
          }
        })

        DummyModel.sync({ force: true }).done(function(err) {
          expect(err).not.to.be.ok
          // now sync one more time:
          DummyModel.sync({force: true}).done(function(err) {
            expect(err).not.to.be.ok
            // sync without dropping
            DummyModel.sync().done(function(err) {
              expect(err).not.to.be.ok
              done();
            })
          })
        })
      })

      it('should be able to add enum types', function(done) {
        var self = this
          , User = this.sequelize.define('UserEnums', {
          mood: DataTypes.ENUM('happy', 'sad', 'meh')
        })

        var _done = _.after(4, function() {
          done()
        })

        User.sync({ force: true }).success(function() {
          User = self.sequelize.define('UserEnums', {
            mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
          })

          User.sync().success(function() {
            expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful'])
            _done()
          }).on('sql', function(sql) {
            if (sql.indexOf('neutral') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'")
              _done()
            }
            else if (sql.indexOf('ecstatic') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'")
              _done()
            }
            else if (sql.indexOf('joyful') > -1) {
              expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'")
              _done()
            }
          })
        })
      })
    })

    describe('integers', function() {
      describe('integer', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.INTEGER
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: 2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(2147483647)
            User.find({where: {aNumber: 2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(2147483647)
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: -2147483647}).success(function(user) {
            expect(user.aNumber).to.equal(-2147483647)
            User.find({where: {aNumber: -2147483647}}).success(function(_user) {
              expect(_user.aNumber).to.equal(-2147483647)
              done()
            })
          })
        })
      })

      describe('bigint', function() {
        beforeEach(function(done) {
          this.User = this.sequelize.define('User', {
            aNumber: DataTypes.BIGINT
          })

          this.User.sync({ force: true }).success(function() {
            done()
          })
        })

        it('positive', function(done) {
          var User = this.User

          User.create({aNumber: '9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('9223372036854775807')
            User.find({where: {aNumber: '9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('9223372036854775807')
              done()
            })
          })
        })

        it('negative', function(done) {
          var User = this.User

          User.create({aNumber: '-9223372036854775807'}).success(function(user) {
            expect(user.aNumber).to.equal('-9223372036854775807')
            User.find({where: {aNumber: '-9223372036854775807'}}).success(function(_user) {
              expect(_user.aNumber).to.equal('-9223372036854775807')
              done()
            })
          })
        })
      })
    })

    describe('model', function() {
      it("create handles array correctly", function(done) {
        this.User
          .create({ username: 'user', email: ['foo@bar.com', 'bar@baz.com'] })
          .success(function(oldUser) {
            expect(oldUser.email).to.contain.members(['foo@bar.com', 'bar@baz.com'])
            done()
          })
          .error(function(err) {
            console.log(err)
          })
      })

      it("should save hstore correctly", function(done) {
        this.User
          .create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .success(function(newUser) {
            // Check to see if the default value for an hstore field works
            expect(newUser.document).to.deep.equal({default: 'value'})
            expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})

            // Check to see if updating an hstore field works
            newUser.updateAttributes({settings: {should: 'update', to: 'this', first: 'place'}}).success(function(oldUser){
              // Postgres always returns keys in alphabetical order (ascending)
              expect(oldUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
              done()
            })
          })
          .error(console.log)
      })

      it("should update hstore correctly", function(done) {
        var self = this

        this.User
          .create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .success(function(newUser) {
            // Check to see if the default value for an hstore field works
            expect(newUser.document).to.deep.equal({default: 'value'})
            expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})

            // Check to see if updating an hstore field works
            self.User.update({settings: {should: 'update', to: 'this', first: 'place'}}, newUser.identifiers).success(function() {
              newUser.reload().success(function() {
                // Postgres always returns keys in alphabetical order (ascending)
                expect(newUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
                done()
              });
            })
          })
          .error(console.log)
      })

      it("should read hstore correctly", function(done) {
        var self = this
        var data = { username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}}

        this.User
          .create(data)
          .success(function() {
            // Check that the hstore fields are the same when retrieving the user
            self.User.find({ where: { username: 'user' }})
              .success(function(user) {
                expect(user.settings).to.deep.equal(data.settings)

                done()
              })
          })
          .error(console.log)
      })

      it("should read hstore correctly from multiple rows", function(done) {
        var self = this

        self.User
          .create({ username: 'user1', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
          .then(function() {
            return self.User.create({ username: 'user2', email: ['foo2@bar.com'], settings: { updated: { another: '"example"' }}})
          })
          .then(function() {
            // Check that the hstore fields are the same when retrieving the user
            return self.User.findAll({ order: 'username' })
          })
          .then(function(users) {
            expect(users[0].settings).to.deep.equal({ created: { test: '"value"' }})
            expect(users[1].settings).to.deep.equal({ updated: { another: '"example"' }})

            done()
          })
          .error(console.log)
      })
    })

    describe('[POSTGRES] Unquoted identifiers', function() {
      it("can insert and select", function(done) {
        var self = this
        this.sequelize.options.quoteIdentifiers = false
        this.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = false

        this.User = this.sequelize.define('Userxs', {
          username: DataTypes.STRING,
          fullName: DataTypes.STRING // Note mixed case
        }, {
          quoteIdentifiers: false
        })

        this.User.sync({ force: true }).success(function() {
          self.User
            .create({ username: 'user', fullName: "John Smith" })
            .success(function(user) {
              // We can insert into a table with non-quoted identifiers
              expect(user.id).to.exist
              expect(user.id).not.to.be.null
              expect(user.username).to.equal('user')
              expect(user.fullName).to.equal('John Smith')

              // We can query by non-quoted identifiers
              self.User.find({
                where: {fullName: "John Smith"}
              })
              .success(function(user2) {
                self.sequelize.options.quoteIndentifiers = true
                self.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = true
                self.sequelize.options.logging = false
                // We can map values back to non-quoted identifiers
                expect(user2.id).to.equal(user.id)
                expect(user2.username).to.equal('user')
                expect(user2.fullName).to.equal('John Smith')
                done()
              })
            })
        })
      })
    })
  })
}
<|endoftext|>