<commit_before>// quarantine

var path = require('path');
var fs = require('fs');

var existsSync = require('./utils').existsSync;

exports.register = function () {
    this.register_hook('queue','quarantine');
    this.register_hook('queue_outbound','quarantine');
}

// http://unknownerror.net/2011-05/16260-nodejs-mkdirs-recursion-create-directory.html
var mkdirs = exports.mkdirs = function(dirpath, mode, callback) {
    if (existsSync(dirpath)) {
        return callback(dirpath);
    }
    mkdirs(path.dirname(dirpath), mode, function() {
        fs.mkdir(dirpath, mode, callback);
    });
}

var zeroPad = exports.zeroPad = function (n, digits) {
    n = n.toString();
    while (n.length < digits) {
        n = '0' + n;
    }
    return n;
}

exports.hook_init_master = function (next) {
    // At start-up; delete any files in the temporary directory
    // NOTE: This is deliberately syncronous to ensure that this
    //       is completed prior to any messages being received.
    var config = this.config.get('quarantine.ini');
    var base_dir = (config.main.quarantine_path) ?
                    config.main.quarantine_path  :
                    '/var/spool/haraka/quarantine';
    var tmp_dir = [ base_dir, 'tmp' ].join('/');
    if (existsSync(tmp_dir)) {
        var dirent = fs.readdirSync(tmp_dir);
        this.loginfo('Removing temporary files from: ' + tmp_dir);
        for (var i=0; i<dirent.length; i++) {
            fs.unlinkSync([ tmp_dir, dirent[i] ].join('/'));
        }
    }
    return next();
}

exports.quarantine = function (next, connection) {
    var transaction = connection.transaction;
transaction.notes.quarantine = true;
    if ((connection.notes.quarantine || transaction.notes.quarantine)) {
        // Calculate date in YYYYMMDD format
        var d = new Date();
        var yyyymmdd = d.getFullYear() + zeroPad(d.getMonth()+1, 2)
            + this.zeroPad(d.getDate(), 2);
        var config = this.config.get('quarantine.ini');
        var base_dir = (config.main.quarantine_path) ?
                        config.main.quarantine_path  :
                        '/var/spool/haraka/quarantine';
        var dir;
        // Allow either boolean or a sub-directory to be specified
        if (connection.notes.quarantine) {
            if (typeof(connection.notes.quarantine) !== 'boolean' &&
                connection.notes.quarantine !== 1)
            {
                dir = connection.notes.quarantine;
            }
        }
        else if (transaction.notes.quarantine) {
            if (typeof(transaction.notes.quarantine) !== 'boolean' &&
                transaction.notes.quarantine !== 1)
            {
                dir = transaction.notes.quarantine;
            }
        }
        if (!dir) {
            dir = yyyymmdd;
        } else {
            dir = [ dir, yyyymmdd ].join('/');
        }
        var plugin = this;
        // Create all the directories recursively if they do not exist first.
        // Then write the file to a temporary directory first, once this is
        // successful we hardlink the file to the final destination and then
        // remove the temporary file to guarantee a complete file in the
        // final destination.
        mkdirs([ base_dir, 'tmp' ].join('/'), parseInt('0770', 8), function () {
            mkdirs([ base_dir, dir ].join('/'), parseInt('0770', 8), function () {
                var ws = fs.createWriteStream([ base_dir, 'tmp', transaction.uuid ].join('/'));
                ws.on('error', function (err) {
                    connection.logerror(plugin, 'Error writing quarantine file: ' + err.message);
                    return next();
                });
                ws.on('close', function () {
                    fs.link([ base_dir, 'tmp', transaction.uuid ].join('/'),
                            [ base_dir, dir, transaction.uuid ].join('/'),
                            function (err) {
                                if (err) {
                                    connection.logerror(plugin, 'Error writing quarantine file: ' + err);
                                }
                                else {
                                    connection.loginfo(plugin, 'Stored copy of message in quarantine: ' +
                                                   [ base_dir, dir, transaction.uuid ].join('/'));
                                    // Now delete the temporary file
                                    fs.unlink([ base_dir, 'tmp', transaction.uuid ].join('/'), function () {});
                                }
                                return next();
                            }
                    );
                });
                transaction.message_stream.pipe(ws, { line_endings: '\n' });
            });
        });

    }
    else {
        return next();
    }
}
<commit_msg>Remove erroneous line from queue/quarantine plugin<commit_after>// quarantine

var path = require('path');
var fs = require('fs');

var existsSync = require('./utils').existsSync;

exports.register = function () {
    this.register_hook('queue','quarantine');
    this.register_hook('queue_outbound','quarantine');
}

// http://unknownerror.net/2011-05/16260-nodejs-mkdirs-recursion-create-directory.html
var mkdirs = exports.mkdirs = function(dirpath, mode, callback) {
    if (existsSync(dirpath)) {
        return callback(dirpath);
    }
    mkdirs(path.dirname(dirpath), mode, function() {
        fs.mkdir(dirpath, mode, callback);
    });
}

var zeroPad = exports.zeroPad = function (n, digits) {
    n = n.toString();
    while (n.length < digits) {
        n = '0' + n;
    }
    return n;
}

exports.hook_init_master = function (next) {
    // At start-up; delete any files in the temporary directory
    // NOTE: This is deliberately syncronous to ensure that this
    //       is completed prior to any messages being received.
    var config = this.config.get('quarantine.ini');
    var base_dir = (config.main.quarantine_path) ?
                    config.main.quarantine_path  :
                    '/var/spool/haraka/quarantine';
    var tmp_dir = [ base_dir, 'tmp' ].join('/');
    if (existsSync(tmp_dir)) {
        var dirent = fs.readdirSync(tmp_dir);
        this.loginfo('Removing temporary files from: ' + tmp_dir);
        for (var i=0; i<dirent.length; i++) {
            fs.unlinkSync([ tmp_dir, dirent[i] ].join('/'));
        }
    }
    return next();
}

exports.quarantine = function (next, connection) {
    var transaction = connection.transaction;
    if ((connection.notes.quarantine || transaction.notes.quarantine)) {
        // Calculate date in YYYYMMDD format
        var d = new Date();
        var yyyymmdd = d.getFullYear() + zeroPad(d.getMonth()+1, 2)
            + this.zeroPad(d.getDate(), 2);
        var config = this.config.get('quarantine.ini');
        var base_dir = (config.main.quarantine_path) ?
                        config.main.quarantine_path  :
                        '/var/spool/haraka/quarantine';
        var dir;
        // Allow either boolean or a sub-directory to be specified
        if (connection.notes.quarantine) {
            if (typeof(connection.notes.quarantine) !== 'boolean' &&
                connection.notes.quarantine !== 1)
            {
                dir = connection.notes.quarantine;
            }
        }
        else if (transaction.notes.quarantine) {
            if (typeof(transaction.notes.quarantine) !== 'boolean' &&
                transaction.notes.quarantine !== 1)
            {
                dir = transaction.notes.quarantine;
            }
        }
        if (!dir) {
            dir = yyyymmdd;
        } else {
            dir = [ dir, yyyymmdd ].join('/');
        }
        var plugin = this;
        // Create all the directories recursively if they do not exist first.
        // Then write the file to a temporary directory first, once this is
        // successful we hardlink the file to the final destination and then
        // remove the temporary file to guarantee a complete file in the
        // final destination.
        mkdirs([ base_dir, 'tmp' ].join('/'), parseInt('0770', 8), function () {
            mkdirs([ base_dir, dir ].join('/'), parseInt('0770', 8), function () {
                var ws = fs.createWriteStream([ base_dir, 'tmp', transaction.uuid ].join('/'));
                ws.on('error', function (err) {
                    connection.logerror(plugin, 'Error writing quarantine file: ' + err.message);
                    return next();
                });
                ws.on('close', function () {
                    fs.link([ base_dir, 'tmp', transaction.uuid ].join('/'),
                            [ base_dir, dir, transaction.uuid ].join('/'),
                            function (err) {
                                if (err) {
                                    connection.logerror(plugin, 'Error writing quarantine file: ' + err);
                                }
                                else {
                                    connection.loginfo(plugin, 'Stored copy of message in quarantine: ' +
                                                   [ base_dir, dir, transaction.uuid ].join('/'));
                                    // Now delete the temporary file
                                    fs.unlink([ base_dir, 'tmp', transaction.uuid ].join('/'), function () {});
                                }
                                return next();
                            }
                    );
                });
                transaction.message_stream.pipe(ws, { line_endings: '\n' });
            });
        });

    }
    else {
        return next();
    }
}
<|endoftext|>


<commit_before>/**
 * Tidy up the HTML in a given file
 */

var settings = require("./Settings");
var spawn = require('child_process').spawn;

exports.tidy = function(srcFile, callback) {
  // Don't do anything if Tidy hasn't been enabled
  if (!settings.tidyHtml) {
    return callback(null);
  }

  var errMessage = '';

  // Spawn a new tidy instance that cleans up the file inline
  var tidy = spawn(settings.tidyHtml, ['-modify', srcFile]);

  // Keep track of any error messages
  tidy.stderr.on('data', function (data) {
    errMessage += data.toString();
  });

  // Wait until Tidy is done
  tidy.on('close', function(code) {
    // Tidy returns a 0 when no errors occur and a 1 exit code when
    // the file could be tidied but a few warnings were generated
    if (code === 0 || code === 1) {
      return callback(null);
    } else {
      console.error(errMessage);
      return callback('Tidy died with exit code ' + code);
    }
  });
};
<commit_msg>Using log4js in TidyHtml<commit_after>/**
 * Tidy up the HTML in a given file
 */

var log4js = require('log4js');
var settings = require('./Settings');
var spawn = require('child_process').spawn;

exports.tidy = function(srcFile, callback) {
  var logger = log4js.getLogger('TidyHtml');

  // Don't do anything if Tidy hasn't been enabled
  if (!settings.tidyHtml) {
    logger.debug('tidyHtml has not been configured yet, ignoring tidy request');
    return callback(null);
  }

  var errMessage = '';

  // Spawn a new tidy instance that cleans up the file inline
  logger.debug('Tidying ' + srcFile);
  var tidy = spawn(settings.tidyHtml, ['-modify', srcFile]);

  // Keep track of any error messages
  tidy.stderr.on('data', function (data) {
    errMessage += data.toString();
  });

  // Wait until Tidy is done
  tidy.on('close', function(code) {
    // Tidy returns a 0 when no errors occur and a 1 exit code when
    // the file could be tidied but a few warnings were generated
    if (code === 0 || code === 1) {
      logger.debug('Tidied ' + srcFile + ' successfully');
      return callback(null);
    } else {
      logger.error('Failed to tidy ' + srcFile + '\n' + errMessage);
      return callback('Tidy died with exit code ' + code);
    }
  });
};
<|endoftext|>


<commit_before>import {isString} from 'lodash';
import RedditContent from './RedditContent.js';

/**
* @summary A class representing a multireddit.
* <style> #MultiReddit {display: none} </style>
*
* // Get a multireddit belonging to a specific user
* r.getUser('multi-mod').getMultireddit('coding_languages')
*/
const MultiReddit = class MultiReddit extends RedditContent {
  constructor (options, _r, _hasFetched) {
    super(options, _r, _hasFetched);
    if (_hasFetched) {
      this.curator = _r.getUser(this.path.split('/')[2]);
      this.subreddits = this.subreddits.map(item => this._r._newObject('Subreddit', item.data || {display_name: item.name}));
    }
  }
  get _uri () {
    return `api/multi${this._path}?expand_srs=true`;
  }
  get _path () {
    return `/user/${this.curator.name}/m/${this.name}`;
  }
  /**
  * @summary Copies this multireddit to the requester's own account.
  * @param {object} options
  * @param {string} options.newName The new name for the copied multireddit
  * @returns {Promise} A Promise for the newly-copied multireddit
  * @example r.getUser('multi-mod').getMultireddit('coding_languages').copy({newName: 'my_coding_languages_copy'})
  */
  copy ({new_name, newName = new_name}) {
    return this._r._getMyName().then(name => {
      return this._post({uri: 'api/multi/copy', form: {
        from: this._path,
        to: `/user/${name}/m/${newName}`,
        display_name: newName
      }});
    });
  }
  /**
  * @summary Renames this multireddit.
  * @desc **Note**: This method mutates this MultiReddit.
  * @param {object} options
  * @param {string} options.newName The new name for this multireddit.
  * @returns {Promise} A Promise that fulfills with this multireddit
  * @example r.getUser('multi-mod').getMultireddit('coding_languages').copy({newName: 'cookie_languages '})
  */
  rename ({new_name, newName = new_name}) {
    return this._r._getMyName().then(name => this._post({
      uri: 'api/multi/rename',
      form: {from: this._path, to: `/user/${name}/m/${newName}`, display_name: newName}
    })).then(res => {
      this.name = res.name;
    }).return(this);
  }
  /**
  * @summary Edits the properties of this multireddit.
  * @desc **Note**: Any omitted properties here will simply retain their previous values.
  * @param {object} options
  * @param {string} [options.name] The name of the new multireddit. 50 characters max
  * @param {string} [options.description] A description for the new multireddit, in markdown.
  * @param {string} [options.visibility] The multireddit's visibility setting. One of `private`, `public`, `hidden`.
  * @param {string} [options.icon_name] One of `art and design`, `ask`, `books`, `business`, `cars`, `comics`, `cute animals`,
  `diy`, `entertainment`, `food and drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`, `models pinup`,
  `music`, `news`, `philosophy`, `pictures and gifs`, `science`, `shopping`, `sports`, `style`, `tech`, `travel`,
  `unusual stories`, `video`, `None`
  * @param {string} [options.key_color] A six-digit RGB hex color, preceded by '#'
  * @param {string} [options.weighting_scheme] One of 'classic', 'fresh'
  * @returns {Promise} The updated version of this multireddit
  * @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').edit({visibility: 'hidden'})
  */
  edit ({description, icon_name, key_color, visibility, weighting_scheme}) {
    return this._put({uri: `api/multi${this._path}`, form: {model: JSON.stringify({
      description_md: description,
      display_name: this.name,
      icon_name,
      key_color,
      visibility,
      weighting_scheme
    })}});
  }
  /**
  * @summary Adds a subreddit to this multireddit.
  * @param {Subreddit} sub The Subreddit object to add (or a string representing a subreddit name)
  * @returns {Promise} A Promise that fulfills with this multireddit when the reuqest is complete
  * @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').addSubreddit('cookies')
  */
  addSubreddit (sub) {
    sub = isString(sub) ? sub : sub.display_name;
    return this._put({uri: `api/multi${this._path}/r/${sub}`, form: {model: JSON.stringify({name: sub})}}).return(this);
  }
  /**
  * @summary Removes a subreddit from this multireddit.
  * @param {Subreddit} sub The Subreddit object to remove (or a string representing a subreddit name)
  * @returns {Promise} A Promise that fulfills with this multireddit when the request is complete
  * @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').removeSubreddit('cookies')
  */
  removeSubreddit (sub) {
    return this._delete({uri: `api/multi${this._path}/r/${isString(sub) ? sub : sub.display_name}`}).return(this);
  }
  /* Note: The endpoints GET/PUT /api/multi/multipath/description and GET /api/multi/multipath/r/srname are intentionally not
  included, because they're redundant and the same thing can be achieved by simply using fetch() and edit(). */
};

// MultiReddit#delete is not in the class body since Safari 9 can't parse the `delete` function name in class bodies.
/**
* @function
* @name delete
* @summary Deletes this multireddit.
* @returns {Promise} A Promise that fulfills when this request is complete
* @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').delete()
* @memberof MultiReddit
* @instance
*/
Object.defineProperty(MultiReddit.prototype, 'delete', {value () {
  return this._delete({uri: `api/multi${this._path}`});
}, configurable: true, writable: true});

export default MultiReddit;
<commit_msg>Fix the formatting for the MultiReddit docs<commit_after>import {isString} from 'lodash';
import RedditContent from './RedditContent.js';

/**
* @summary A class representing a multireddit.
* <style> #MultiReddit {display: none} </style>
* @example
*
* // Get a multireddit belonging to a specific user
* r.getUser('multi-mod').getMultireddit('coding_languages')
*/
const MultiReddit = class MultiReddit extends RedditContent {
  constructor (options, _r, _hasFetched) {
    super(options, _r, _hasFetched);
    if (_hasFetched) {
      this.curator = _r.getUser(this.path.split('/')[2]);
      this.subreddits = this.subreddits.map(item => this._r._newObject('Subreddit', item.data || {display_name: item.name}));
    }
  }
  get _uri () {
    return `api/multi${this._path}?expand_srs=true`;
  }
  get _path () {
    return `/user/${this.curator.name}/m/${this.name}`;
  }
  /**
  * @summary Copies this multireddit to the requester's own account.
  * @param {object} options
  * @param {string} options.newName The new name for the copied multireddit
  * @returns {Promise} A Promise for the newly-copied multireddit
  * @example r.getUser('multi-mod').getMultireddit('coding_languages').copy({newName: 'my_coding_languages_copy'})
  */
  copy ({new_name, newName = new_name}) {
    return this._r._getMyName().then(name => {
      return this._post({uri: 'api/multi/copy', form: {
        from: this._path,
        to: `/user/${name}/m/${newName}`,
        display_name: newName
      }});
    });
  }
  /**
  * @summary Renames this multireddit.
  * @desc **Note**: This method mutates this MultiReddit.
  * @param {object} options
  * @param {string} options.newName The new name for this multireddit.
  * @returns {Promise} A Promise that fulfills with this multireddit
  * @example r.getUser('multi-mod').getMultireddit('coding_languages').copy({newName: 'cookie_languages '})
  */
  rename ({new_name, newName = new_name}) {
    return this._r._getMyName().then(name => this._post({
      uri: 'api/multi/rename',
      form: {from: this._path, to: `/user/${name}/m/${newName}`, display_name: newName}
    })).then(res => {
      this.name = res.name;
    }).return(this);
  }
  /**
  * @summary Edits the properties of this multireddit.
  * @desc **Note**: Any omitted properties here will simply retain their previous values.
  * @param {object} options
  * @param {string} [options.name] The name of the new multireddit. 50 characters max
  * @param {string} [options.description] A description for the new multireddit, in markdown.
  * @param {string} [options.visibility] The multireddit's visibility setting. One of `private`, `public`, `hidden`.
  * @param {string} [options.icon_name] One of `art and design`, `ask`, `books`, `business`, `cars`, `comics`, `cute animals`,
  `diy`, `entertainment`, `food and drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`, `models pinup`,
  `music`, `news`, `philosophy`, `pictures and gifs`, `science`, `shopping`, `sports`, `style`, `tech`, `travel`,
  `unusual stories`, `video`, `None`
  * @param {string} [options.key_color] A six-digit RGB hex color, preceded by '#'
  * @param {string} [options.weighting_scheme] One of 'classic', 'fresh'
  * @returns {Promise} The updated version of this multireddit
  * @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').edit({visibility: 'hidden'})
  */
  edit ({description, icon_name, key_color, visibility, weighting_scheme}) {
    return this._put({uri: `api/multi${this._path}`, form: {model: JSON.stringify({
      description_md: description,
      display_name: this.name,
      icon_name,
      key_color,
      visibility,
      weighting_scheme
    })}});
  }
  /**
  * @summary Adds a subreddit to this multireddit.
  * @param {Subreddit} sub The Subreddit object to add (or a string representing a subreddit name)
  * @returns {Promise} A Promise that fulfills with this multireddit when the reuqest is complete
  * @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').addSubreddit('cookies')
  */
  addSubreddit (sub) {
    sub = isString(sub) ? sub : sub.display_name;
    return this._put({uri: `api/multi${this._path}/r/${sub}`, form: {model: JSON.stringify({name: sub})}}).return(this);
  }
  /**
  * @summary Removes a subreddit from this multireddit.
  * @param {Subreddit} sub The Subreddit object to remove (or a string representing a subreddit name)
  * @returns {Promise} A Promise that fulfills with this multireddit when the request is complete
  * @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').removeSubreddit('cookies')
  */
  removeSubreddit (sub) {
    return this._delete({uri: `api/multi${this._path}/r/${isString(sub) ? sub : sub.display_name}`}).return(this);
  }
  /* Note: The endpoints GET/PUT /api/multi/multipath/description and GET /api/multi/multipath/r/srname are intentionally not
  included, because they're redundant and the same thing can be achieved by simply using fetch() and edit(). */
};

// MultiReddit#delete is not in the class body since Safari 9 can't parse the `delete` function name in class bodies.
/**
* @function
* @name delete
* @summary Deletes this multireddit.
* @returns {Promise} A Promise that fulfills when this request is complete
* @example r.getUser('not_an_aardvark').getMultireddit('cookie_languages').delete()
* @memberof MultiReddit
* @instance
*/
Object.defineProperty(MultiReddit.prototype, 'delete', {value () {
  return this._delete({uri: `api/multi${this._path}`});
}, configurable: true, writable: true});

export default MultiReddit;
<|endoftext|>


<commit_before>"use strict";

var
    esPhinx;

(function ($) {

    $.extend({

        prototype: {

            //
|

            // text: function () {
            // },

            hasClass: function (classList) {
                var
                    self = this,
                    first = $(self.first()),
                    pattern;

                if (arguments.length > 1) {
                    classList = Array.from(arguments);
                    pattern = new RegExp("(?=.*(\\b" + classList
                        .join("(?=(\\b| ))))(?=.*(\\b")
                        + "(?=(\\b| )))).*", "g");
                } else {
                    pattern = new RegExp("(?=.*(\\b" + classList.split(" ")
                        .join("(?=(\\b| ))))(?=.*(\\b")
                        + "(?=(\\b| )))).*", "g");
                }

                if (pattern.test(first.attr("class"))) {
                    return true;
                }

                return false;
            },

            removeClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    pattern,
                    removed;

                if (arguments.length > 1) {
                    classList = Array.from(arguments);
                    pattern = new RegExp("\\b((" + classList
                        .join(")|(")  + "))(?=(\\b| ))", "g");
                } else {
                    pattern = new RegExp("\\b((" + classList.split(" ")
                        .join(")|(") + "))(?=(\\b| ))", "g");
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    removed = currentClassList.replace(pattern, "");
                    $(node).attr("class", removed.replace(/(  )+/g, " ").trim());
                });

                return self;
            },

            addClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    asString;

                if (arguments.length > 1) {
                    classList = Array.from(arguments);
                    asString = classList.join(" ");
                } else if (typeof classList === "string") {
                    asString = classList;
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    $(node).attr("class", (currentClassList + " " + asString)
                        .trim());
                });

                return self;
            },

            find: function (query) {
                var
                    self = this;

                return $(query, self.first());
            },

            check: function () {
                var
                    self = this;

                if (!self.checked()) {
                    self.property("checked", true);
                }

                return self;
            },

            uncheck: function () {
                var
                    self = this;

                return self.property("checked", false);
            },

            removeAttr: function (attrName) {
                var
                    self = this;

                self.each(function (node) {
                    node.removeAttribute(attrName);
                });

                return self;
            },

            attr: function (attrName, value) {
                var
                    self = this,
                    first = self.first(),
                    attr;

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node.setAttribute(attrName, value);
                    });

                    return self;
                } else {
                    if (attr = first.getAttribute(attrName)) {
                        return attr;
                    }
                }

                return undefined;
            },

            property: function (propertyName, value) {
                var
                    self = this,
                    first = self.first();

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node[propertyName] = value;
                    });

                    return self;
                } else {
                    if (first[propertyName] ||
                        typeof first[propertyName] === "boolean") {
                        return first[propertyName];
                    }
                }

                return undefined;
            },

            firstNode: function () {
                var
                    self = this,
                    nodes = self.first().childNodes;

                return $(nodes[0]);
            },

            firstElement: function () {
                var
                    self = this,
                    elements = self.first().children;

                return $(elements[0]);
            },

            rootText: function () {
                var
                    self = this,
                    text = "";

                Enumerator.each(self.first().childNodes, function (v) {
                    if (v.nodeType === Node.TEXT_NODE) {
                        text += v.textContent.trim();
                    }
                });

                return text;
            },

            // add support to multi nodes
            append: function(nodes) {
                var
                    self = this;

                if (typeof nodes === "string") {
                    nodes = document.createTextNode(nodes);
                } else if (nodes instanceof $) {
                    nodes = nodes.first();
                } else if (!nodes instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    element.appendChild(node);
                });

                return self;
            },

            prepend: function(node) {
                var
                    self = this,
                    firstNode;

                if (typeof node === "string") {
                    node = document.createTextNode(node);
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    firstNode = $(element).firstNode();
                    $(node).insertBefore(firstNode);
                });

                return self;
            },

            insertBefore: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node);

                return self;
            },

            insertAfter: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node.nextSibling);

                return self;
            },

            parent: function (query) {
                var
                    self = this;

                if (query) {
                    return $(self.first().closest(query));
                } else {
                    return $(self.first().parentNode);
                }

                return $();
            },

            html: function (content) {
                var
                    self = this;

                if (typeof content === "string") {
                    self.each(function (node) {
                        node.innerHTML = content;
                    });
                } else if (content instanceof Node) {
                    self.each(function (node) {
                        node.innerHTML = null;
                        node.appendChild(content);
                    });
                }

                return self;
            },

            first: function () {
                return this[0];
            },

            count: function () {
                return Object.keys(this).length;
            }

        }

    });

}(esPhinx));

/*$.prototype.ancestors = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/<commit_msg>tsc tsc<commit_after>"use strict";

var
    esPhinx;

(function ($) {

    $.extend({

        prototype: {

            //
|

            // text: function () {
            // },

            hasClass: function (classList) {
                var
                    self = this,
                    first = $(self.first()),
                    pattern;

                if (arguments.length > 1) {
                    classList = Array.from(arguments);
                    pattern = new RegExp("(?=.*(\\b" + classList
                        .join("(?=(\\b| ))))(?=.*(\\b")
                        + "(?=(\\b| )))).*", "g");
                } else {
                    pattern = new RegExp("(?=.*(\\b" + classList.split(" ")
                        .join("(?=(\\b| ))))(?=.*(\\b")
                        + "(?=(\\b| )))).*", "g");
                }

                if (pattern.test(first.attr("class"))) {
                    return true;
                }

                return false;
            },

            removeClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    pattern,
                    removed;

                if (arguments.length > 1) {
                    classList = Array.from(arguments);
                    pattern = new RegExp("\\b((" + classList
                        .join(")|(")  + "))(?=(\\b| ))", "g");
                } else {
                    pattern = new RegExp("\\b((" + classList.split(" ")
                        .join(")|(") + "))(?=(\\b| ))", "g");
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    removed = currentClassList.replace(pattern, "");
                    $(node).attr("class", removed.replace(/(  )+/g, " ").trim());
                });

                return self;
            },

            addClass: function (classList) {
                var
                    self = this,
                    currentClassList,
                    asString;

                if (arguments.length > 1) {
                    classList = Array.from(arguments);
                    asString = classList.join(" ");
                } else if (typeof classList === "string") {
                    asString = classList;
                }

                self.each(function (node) {
                    currentClassList = $(node).attr("class");
                    $(node).attr("class", (currentClassList + " " + asString)
                        .trim());
                });

                return self;
            },

            find: function (query) {
                var
                    self = this;

                return $(query, self.first());
            },

            check: function () {
                var
                    self = this;

                if (!self.checked()) {
                    self.property("checked", true);
                }

                return self;
            },

            uncheck: function () {
                var
                    self = this;

                return self.property("checked", false);
            },

            removeAttr: function (attrName) {
                var
                    self = this;

                self.each(function (node) {
                    node.removeAttribute(attrName);
                });

                return self;
            },

            attr: function (attrName, value) {
                var
                    self = this,
                    first = self.first(),
                    attr;

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node.setAttribute(attrName, value);
                    });

                    return self;
                } else {
                    if (attr = first.getAttribute(attrName)) {
                        return attr;
                    }
                }

                return undefined;
            },

            property: function (propertyName, value) {
                var
                    self = this,
                    first = self.first();

                if (self.length === 0) {
                    return self;
                }

                if (typeof value === "boolean" || value || value === "") {
                    self.each(function (node) {
                        node[propertyName] = value;
                    });

                    return self;
                } else {
                    if (first[propertyName] ||
                        typeof first[propertyName] === "boolean") {
                        return first[propertyName];
                    }
                }

                return undefined;
            },

            firstNode: function () {
                var
                    self = this,
                    nodes = self.first().childNodes;

                return $(nodes[0]);
            },

            firstElement: function () {
                var
                    self = this,
                    elements = self.first().children;

                return $(elements[0]);
            },

            rootText: function () {
                var
                    self = this,
                    text = "";

                Enumerator.each(self.first().childNodes, function (v) {
                    if (v.nodeType === Node.TEXT_NODE) {
                        text += v.textContent.trim();
                    }
                });

                return text;
            },

            append: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = document.createTextNode(node);
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    element.appendChild(node);
                });

                return self;
            },

            prepend: function(node) {
                var
                    self = this,
                    firstNode;

                if (typeof node === "string") {
                    node = document.createTextNode(node);
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                self.each(function (element) {
                    firstNode = $(element).firstNode();
                    $(node).insertBefore(firstNode);
                });

                return self;
            },

            insertBefore: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node);

                return self;
            },

            insertAfter: function(node) {
                var
                    self = this;

                if (typeof node === "string") {
                    node = $(node).first();
                } else if (node instanceof $) {
                    node = node.first();
                } else if (!node instanceof Node) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node.nextSibling);

                return self;
            },

            parent: function (query) {
                var
                    self = this;

                if (query) {
                    return $(self.first().closest(query));
                } else {
                    return $(self.first().parentNode);
                }

                return $();
            },

            html: function (content) {
                var
                    self = this;

                if (typeof content === "string") {
                    self.each(function (node) {
                        node.innerHTML = content;
                    });
                } else if (content instanceof Node) {
                    self.each(function (node) {
                        node.innerHTML = null;
                        node.appendChild(content);
                    });
                }

                return self;
            },

            first: function () {
                return this[0];
            },

            count: function () {
                return Object.keys(this).length;
            }

        }

    });

}(esPhinx));

/*$.prototype.ancestors = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/<|endoftext|>


<commit_before>var dot = require('dot');
var fs = require('fs');
var path = require('path');
var step = require('step');

function HealthCheck(metadataBackend, tilelive) {
    this.metadataBackend = metadataBackend;
    this.tilelive = tilelive;
}

module.exports = HealthCheck;

var mapnikOptions = {
    query: {
        metatile: 1,
        poolSize: 4,
        bufferSize: 64
    },
    protocol: 'mapnik:',
    slashes: true,
    xml: null
};

var xmlTemplate = dot.template(fs.readFileSync(path.resolve(__dirname, 'map-config.xml'), 'utf-8'));

HealthCheck.prototype.check = function(config, callback) {

    var self = this,
        startTime,
        result = {
            redis: {
                ok: false
            },
            mapnik: {
                ok: false
            },
            tile: {
                ok: false
            }
        };
    var mapnikXmlParams = config;

    step(
        function getManualDisable() {
          disabled_file = global.environment.disabled_file;
          fs.readFile(disabled_file, this);
        },
        function handleDisabledFile(err, data) {
          var next = this;
          if (err) {
            return next();
          }
          if (!!data) {
            err = new Error(data);
            err.http_status = 503;
            throw err;
          }
        },
        function getDBParams(err) {
            if (err) {
              throw err;
            }
            startTime = Date.now();
            self.metadataBackend.getAllUserDBParams(config.username, this);
        },
        function loadMapnik(err, dbParams) {
            if (err) {
                throw err;
            }
            result.redis = {
                ok: !err,
                elapsed: Date.now() - startTime,
                size: Object.keys(dbParams).length
            };
            mapnikOptions.xml = xmlTemplate(mapnikXmlParams);

            startTime = Date.now();
            self.tilelive.load(mapnikOptions, this);
        },
        function getTile(err, source) {
            if (err) {
                throw err;
            }

            result.mapnik = {
                ok: !err,
                elapsed: Date.now() - startTime
            };

            startTime = Date.now();
            source.getTile(config.z, config.x, config.y, this);
        },
        function handleTile(err, tile) {
            result.tile = {
                ok: !err
            };

            if (tile) {
                result.tile.elapsed = Date.now() - startTime;
                result.tile.size = tile.length;
            }

            callback(err, result);
        }
    );
};
<commit_msg>Remove unnecesary variable in health check<commit_after>var dot = require('dot');
var fs = require('fs');
var path = require('path');
var step = require('step');

function HealthCheck(metadataBackend, tilelive) {
    this.metadataBackend = metadataBackend;
    this.tilelive = tilelive;
}

module.exports = HealthCheck;

var mapnikOptions = {
    query: {
        metatile: 1,
        poolSize: 4,
        bufferSize: 64
    },
    protocol: 'mapnik:',
    slashes: true,
    xml: null
};

var xmlTemplate = dot.template(fs.readFileSync(path.resolve(__dirname, 'map-config.xml'), 'utf-8'));

HealthCheck.prototype.check = function(config, callback) {

    var self = this,
        startTime,
        result = {
            redis: {
                ok: false
            },
            mapnik: {
                ok: false
            },
            tile: {
                ok: false
            }
        };
    var mapnikXmlParams = config;

    step(
        function getManualDisable() {
          fs.readFile(global.environment.disabled_file, this);
        },
        function handleDisabledFile(err, data) {
          var next = this;
          if (err) {
            return next();
          }
          if (!!data) {
            err = new Error(data);
            err.http_status = 503;
            throw err;
          }
        },
        function getDBParams(err) {
            if (err) {
              throw err;
            }
            startTime = Date.now();
            self.metadataBackend.getAllUserDBParams(config.username, this);
        },
        function loadMapnik(err, dbParams) {
            if (err) {
                throw err;
            }
            result.redis = {
                ok: !err,
                elapsed: Date.now() - startTime,
                size: Object.keys(dbParams).length
            };
            mapnikOptions.xml = xmlTemplate(mapnikXmlParams);

            startTime = Date.now();
            self.tilelive.load(mapnikOptions, this);
        },
        function getTile(err, source) {
            if (err) {
                throw err;
            }

            result.mapnik = {
                ok: !err,
                elapsed: Date.now() - startTime
            };

            startTime = Date.now();
            source.getTile(config.z, config.x, config.y, this);
        },
        function handleTile(err, tile) {
            result.tile = {
                ok: !err
            };

            if (tile) {
                result.tile.elapsed = Date.now() - startTime;
                result.tile.size = tile.length;
            }

            callback(err, result);
        }
    );
};
<|endoftext|>


<commit_before>goog.provide('ol.format.IGC');
goog.provide('ol.format.IGCZ');

goog.require('goog.asserts');
goog.require('goog.string');
goog.require('goog.string.newlines');
goog.require('ol.Feature');
goog.require('ol.format.Text');
goog.require('ol.geom.LineString');
goog.require('ol.proj');

/**
 * @enum {string}
 */
ol.format.IGCZ = {
  BAROMETRIC: 'barometric',
  GPS: 'gps',
  NONE: 'none'
};

/**
 * @constructor
 * @extends {ol.format.Text}
 * @param {olx.format.IGCOptions=} opt_options Options.
 */
ol.format.IGC = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};

  goog.base(this);

  /**
   * @private
   * @type {ol.format.IGCZ}
   */
  this.altitudeMode_ = goog.isDef(options.altitudeMode) ?
      options.altitudeMode : ol.format.IGCZ.NONE;

};
goog.inherits(ol.format.IGC, ol.format.Text);

/**
 * @const
 * @type {Array.<string>}
 * @private
 */
ol.format.IGC.EXTENSIONS_ = ['.igc'];

/**
 * @const
 * @type {RegExp}
 * @private
 */
ol.format.IGC.B_RECORD_RE_ =
    /^B(\d{2})(\d{2})(\d{2})(\d{2})(\d{5})([NS])(\d{3})(\d{5})([EW])([AV])(\d{5})(\d{5})/;

/**
 * @const
 * @type {RegExp}
 * @private
 */
ol.format.IGC.H_RECORD_RE_ = /^H.([A-Z]{3}).*?:(.*)/;

/**
 * @const
 * @type {RegExp}
 * @private
 */
ol.format.IGC.HFDTE_RECORD_RE_ = /^HFDTE(\d{2})(\d{2})(\d{2})/;

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.getExtensions = function() {
  return ol.format.IGC.EXTENSIONS_;
};

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.readFeatureFromText = function(text) {
  var altitudeMode = this.altitudeMode_;
  var lines = goog.string.newlines.splitLines(text);
  /** @type {Object.<string, string>} */
  var properties = {};
  var flatCoordinates = [];
  var year = 2000;
  var month = 1;
  var day = 1;
  var i, ii;
  for (i = 0, ii = lines.length; i < ii; ++i) {
    var line = lines[i];
    var m;
    if (line.charAt(0) == 'B') {
      m = ol.format.IGC.B_RECORD_RE_.exec(line);
      if (m) {
        var hour = parseInt(m[1], 10);
        var minute = parseInt(m[2], 10);
        var second = parseInt(m[3], 10);
        var y = parseInt(m[4], 10) + parseInt(m[5], 10) / 60000;
        if (m[6] == 'S') {
          y = -y;
        }
        var x = parseInt(m[7], 10) + parseInt(m[8], 10) / 60000;
        if (m[9] == 'W') {
          x = -x;
        }
        flatCoordinates.push(x, y);
        if (altitudeMode != ol.format.IGCZ.NONE) {
          var z;
          if (altitudeMode == ol.format.IGCZ.GPS) {
            z = parseInt(m[11], 10);
          } else if (altitudeMode == ol.format.IGCZ.BAROMETRIC) {
            z = parseInt(m[12], 10);
          } else {
            goog.asserts.fail();
            z = 0;
          }
          flatCoordinates.push(z);
        }
        var dateTime = Date.UTC(year, month, day, hour, minute, second, 0);
        flatCoordinates.push(dateTime / 1000);
      }
    } else if (line.charAt(0) == 'H') {
      m = ol.format.IGC.HFDTE_RECORD_RE_.exec(line);
      if (m) {
        day = parseInt(m[1], 10);
        month = parseInt(m[2], 10);
        year = 2000 + parseInt(m[3], 10);
      } else {
        m = ol.format.IGC.H_RECORD_RE_.exec(line);
        if (m) {
          properties[m[1]] = goog.string.trim(m[2]);
          m = ol.format.IGC.HFDTE_RECORD_RE_.exec(line);
        }
      }
    }
  }
  var lineString = new ol.geom.LineString(null);
  var layout = altitudeMode == ol.format.IGCZ.NONE ?
      ol.geom.GeometryLayout.XYM : ol.geom.GeometryLayout.XYZM;
  lineString.setFlatCoordinates(layout, flatCoordinates);
  var feature = new ol.Feature(lineString);
  feature.setValues(properties);
  return feature;
};

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.readFeaturesFromText = function(text) {
  var feature = this.readFeatureFromText(text);
  if (!goog.isNull(feature)) {
    return [feature];
  } else {
    return [];
  }
};

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.readProjectionFromText = function(text) {
  return ol.proj.get('EPSG:4326');
};
<commit_msg>Correct month calculation in ol.format.IGC<commit_after>goog.provide('ol.format.IGC');
goog.provide('ol.format.IGCZ');

goog.require('goog.asserts');
goog.require('goog.string');
goog.require('goog.string.newlines');
goog.require('ol.Feature');
goog.require('ol.format.Text');
goog.require('ol.geom.LineString');
goog.require('ol.proj');

/**
 * @enum {string}
 */
ol.format.IGCZ = {
  BAROMETRIC: 'barometric',
  GPS: 'gps',
  NONE: 'none'
};

/**
 * @constructor
 * @extends {ol.format.Text}
 * @param {olx.format.IGCOptions=} opt_options Options.
 */
ol.format.IGC = function(opt_options) {

  var options = goog.isDef(opt_options) ? opt_options : {};

  goog.base(this);

  /**
   * @private
   * @type {ol.format.IGCZ}
   */
  this.altitudeMode_ = goog.isDef(options.altitudeMode) ?
      options.altitudeMode : ol.format.IGCZ.NONE;

};
goog.inherits(ol.format.IGC, ol.format.Text);

/**
 * @const
 * @type {Array.<string>}
 * @private
 */
ol.format.IGC.EXTENSIONS_ = ['.igc'];

/**
 * @const
 * @type {RegExp}
 * @private
 */
ol.format.IGC.B_RECORD_RE_ =
    /^B(\d{2})(\d{2})(\d{2})(\d{2})(\d{5})([NS])(\d{3})(\d{5})([EW])([AV])(\d{5})(\d{5})/;

/**
 * @const
 * @type {RegExp}
 * @private
 */
ol.format.IGC.H_RECORD_RE_ = /^H.([A-Z]{3}).*?:(.*)/;

/**
 * @const
 * @type {RegExp}
 * @private
 */
ol.format.IGC.HFDTE_RECORD_RE_ = /^HFDTE(\d{2})(\d{2})(\d{2})/;

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.getExtensions = function() {
  return ol.format.IGC.EXTENSIONS_;
};

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.readFeatureFromText = function(text) {
  var altitudeMode = this.altitudeMode_;
  var lines = goog.string.newlines.splitLines(text);
  /** @type {Object.<string, string>} */
  var properties = {};
  var flatCoordinates = [];
  var year = 2000;
  var month = 0;
  var day = 1;
  var i, ii;
  for (i = 0, ii = lines.length; i < ii; ++i) {
    var line = lines[i];
    var m;
    if (line.charAt(0) == 'B') {
      m = ol.format.IGC.B_RECORD_RE_.exec(line);
      if (m) {
        var hour = parseInt(m[1], 10);
        var minute = parseInt(m[2], 10);
        var second = parseInt(m[3], 10);
        var y = parseInt(m[4], 10) + parseInt(m[5], 10) / 60000;
        if (m[6] == 'S') {
          y = -y;
        }
        var x = parseInt(m[7], 10) + parseInt(m[8], 10) / 60000;
        if (m[9] == 'W') {
          x = -x;
        }
        flatCoordinates.push(x, y);
        if (altitudeMode != ol.format.IGCZ.NONE) {
          var z;
          if (altitudeMode == ol.format.IGCZ.GPS) {
            z = parseInt(m[11], 10);
          } else if (altitudeMode == ol.format.IGCZ.BAROMETRIC) {
            z = parseInt(m[12], 10);
          } else {
            goog.asserts.fail();
            z = 0;
          }
          flatCoordinates.push(z);
        }
        var dateTime = Date.UTC(year, month, day, hour, minute, second, 0);
        flatCoordinates.push(dateTime / 1000);
      }
    } else if (line.charAt(0) == 'H') {
      m = ol.format.IGC.HFDTE_RECORD_RE_.exec(line);
      if (m) {
        day = parseInt(m[1], 10);
        month = parseInt(m[2], 10) - 1;
        year = 2000 + parseInt(m[3], 10);
      } else {
        m = ol.format.IGC.H_RECORD_RE_.exec(line);
        if (m) {
          properties[m[1]] = goog.string.trim(m[2]);
          m = ol.format.IGC.HFDTE_RECORD_RE_.exec(line);
        }
      }
    }
  }
  var lineString = new ol.geom.LineString(null);
  var layout = altitudeMode == ol.format.IGCZ.NONE ?
      ol.geom.GeometryLayout.XYM : ol.geom.GeometryLayout.XYZM;
  lineString.setFlatCoordinates(layout, flatCoordinates);
  var feature = new ol.Feature(lineString);
  feature.setValues(properties);
  return feature;
};

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.readFeaturesFromText = function(text) {
  var feature = this.readFeatureFromText(text);
  if (!goog.isNull(feature)) {
    return [feature];
  } else {
    return [];
  }
};

/**
 * @inheritDoc
 */
ol.format.IGC.prototype.readProjectionFromText = function(text) {
  return ol.proj.get('EPSG:4326');
};
<|endoftext|>


<commit_before>;(function(sm) {
	var ontology = new sm.Ontology('sm.nodes');

	ontology.addTerm('insert');
	ontology.addTerm('connect');
	ontology.addTerm('set');
	ontology.addTerm('get');
	ontology.addTerm('initialize');

	var Node = function(item, paper) {
		this.id = item.id || (function() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
				return v.toString(16);
			});
		})();
		this.width = parseFloat(item.width) || 50;
		this.height = parseFloat(item.height) || 50;
		this.y = parseFloat(item.y);
		this.x = parseFloat(item.x);
		this.edges = item.edges || [];
		this.label = item.label || this.id;
		this.paper = paper;
		return this;
	};

	Node.prototype.update = function(message) {
		var element = this.paper.circle(this.x,
									 	this.y,
									 	this.width / 2,
									 	this.height / 2);
		element.id = this.id;
		element.attr({
			fill : '#ffffff'
		});
		this.paper.text(this.x, this.y, this.label);
		return true;
	};

	var Edge = function(a, b, index, paper) {
		this.id1 = a.id;
		this.id2 = b.id;
		this.x1 = parseFloat(a.x);
		this.y1 = parseFloat(a.y);
		this.x2 = parseFloat(b.x);
		this.y2 = parseFloat(b.y);
		this.label = a.edges[index].label || '';
		this.paper = paper;
		return this;
	};

	Edge.prototype.update = function(message) {
		this.paper.path( ["M", this.x1, this.y1, "L", this.x2, this.y2] );
		var x1 = parseFloat(this.x1);
		var y1 = parseFloat(this.y1);
		var x2 = parseFloat(this.x2);
		var y2 = parseFloat(this.y2);
		var a = x1 - x2;
		var b = y1 - y2;
		var cX = (x1 + x2) / 2;
		var cY = (y1 + y2) / 2;
		var textLabel = this.paper.text(cX, cY - 6, this.label);
		var dX = x2 - x1;
		var dY = y2 - y1;
		var angle = Math.atan2(dY, dX) * 180 / Math.PI;
		textLabel.transform('r' + angle);
		return true;
	};

	var getObjectNode = function(message, id) {
		for (var i = 0; i < message.length; i++) {
			if (message[i].id === id) {
				return message[i];
			}
		}
		return null;
	};

	var InitializerDelegate = function(model) {
		this._model = model;
		this.handleError = function(Error) {
			model.messenger.error.publish(Error);
		};
		return this;
	};

	var LeafSort = function(a, b) {
		return a.edges.length - b.edges.length;
	};

	InitializerDelegate.prototype.update = function(message) {
		if (sm.typeMask(message, { length : true, sort : 'function' } ) !== null) {
			sm.error(new Error('Cannot determine the message type; expecting an array (or comparable object) of node objects but received ' + message), this);
		}
		var paper = new sm.type.NamedValue('sm.raphaeljs', 'paper', null);
		this._model.get.publish(paper);
		var edges = [];
		for(var i = 0; i < message.length; i++) {
			var node = new Node(message[i], paper.value);
			for (var j = 0; j < node.edges.length; j++) {
				var objectNode = getObjectNode(message, node.edges[j].id);
				if (objectNode !== null) {
					var edge = new Edge(node, objectNode, j, paper.value);
					this._model.connect.publish(edge);
				}
			}
			this._model.insert.publish(node);
		}
	};

	var activator = function(model) {
		model.initialize.subscribe({
			update : function(message) {
				if (sm.typeMask(message, { length : true, sort : 'function' } ) === null) {
					return function(message) {
						message.sort(LeafSort);
						return false;
					};
				}
			}
			});
		// default behaviors
		var delegate = new InitializerDelegate(model);
		model.initialize.subscribe({ update : function(message) { return delegate; } });
		model.connect.subscribe({ update : function(message) { return message; } });
		model.insert.subscribe({ update : function(message) { return message; } });
	};

	ontology.registerActivator(activator, ['sm.channels', 'sm.raphaeljs'])

	try {
		sm.ontology.extendedBy(ontology);
	}
	catch (error) {
		sm.error(new Error('Could not extend the smallmachine.ontology property with the \'sm.nodes\' ontology: ' + error.message + '\n' + error.stack));
	}
}(smallmachine));

<commit_msg>nodes ontology supports default error handler<commit_after>;(function(sm) {
	var ontology = new sm.Ontology('sm.nodes');

	ontology.addTerm('insert');
	ontology.addTerm('connect');
	ontology.addTerm('set');
	ontology.addTerm('get');
	ontology.addTerm('initialize');

	var Node = function(item, paper) {
		this.id = item.id || (function() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
				return v.toString(16);
			});
		})();
		this.width = parseFloat(item.width) || 50;
		this.height = parseFloat(item.height) || 50;
		this.y = parseFloat(item.y);
		this.x = parseFloat(item.x);
		this.edges = item.edges || [];
		this.label = item.label || this.id;
		this.paper = paper;
		return this;
	};

	Node.prototype.update = function(message) {
		var element = this.paper.circle(this.x,
									 	this.y,
									 	this.width / 2,
									 	this.height / 2);
		element.id = this.id;
		element.attr({
			fill : '#ffffff'
		});
		this.paper.text(this.x, this.y, this.label);
		return true;
	};

	var Edge = function(a, b, index, paper) {
		this.id1 = a.id;
		this.id2 = b.id;
		this.x1 = parseFloat(a.x);
		this.y1 = parseFloat(a.y);
		this.x2 = parseFloat(b.x);
		this.y2 = parseFloat(b.y);
		this.label = a.edges[index].label || '';
		this.paper = paper;
		return this;
	};

	Edge.prototype.update = function(message) {
		this.paper.path( ["M", this.x1, this.y1, "L", this.x2, this.y2] );
		var x1 = parseFloat(this.x1);
		var y1 = parseFloat(this.y1);
		var x2 = parseFloat(this.x2);
		var y2 = parseFloat(this.y2);
		var a = x1 - x2;
		var b = y1 - y2;
		var cX = (x1 + x2) / 2;
		var cY = (y1 + y2) / 2;
		var textLabel = this.paper.text(cX, cY - 6, this.label);
		var dX = x2 - x1;
		var dY = y2 - y1;
		var angle = Math.atan2(dY, dX) * 180 / Math.PI;
		textLabel.transform('r' + angle);
		return true;
	};

	var getObjectNode = function(message, id) {
		for (var i = 0; i < message.length; i++) {
			if (message[i].id === id) {
				return message[i];
			}
		}
		return null;
	};

	var InitializerDelegate = function(model) {
		this._model = model;
		this.handleError = function(Error) {
			model.messenger.error.publish(Error);
		};
		return this;
	};

	var LeafSort = function(a, b) {
		return a.edges.length - b.edges.length;
	};

	InitializerDelegate.prototype.update = function(message) {
		if (sm.typeMask(message, { length : true, sort : 'function' } ) !== null) {
			sm.error(new Error('Cannot determine the message type; expecting an array (or comparable object) of node objects but received ' + message), this);
		}
		var paper = new sm.type.NamedValue('sm.raphaeljs', 'paper', null);
		this._model.get.publish(paper);
		var edges = [];
		for(var i = 0; i < message.length; i++) {
			var node = new Node(message[i], paper.value);
			for (var j = 0; j < node.edges.length; j++) {
				var objectNode = getObjectNode(message, node.edges[j].id);
				if (objectNode !== null) {
					var edge = new Edge(node, objectNode, j, paper.value);
					this._model.connect.publish(edge);
				}
			}
			this._model.insert.publish(node);
		}
	};

	var activator = function(model) {
		model.initialize.subscribe(function(message) {
			if (sm.typeMask(message, { length : true, sort : 'function' } ) === null) {
				return function(message) {
					message.sort(LeafSort);
					return false; // continue to delegates by default
				};
			}
		});
		// default behaviors
		var delegate = new InitializerDelegate(model);
		model.initialize.subscribe(function(message) { return delegate; });
		model.connect.subscribe(function(message) { return message; });
		model.insert.subscribe(function(message) { return message; });
	};

	ontology.registerActivator(activator, ['sm.channels', 'sm.raphaeljs'])

	try {
		sm.ontology.extendedBy(ontology);
	}
	catch (error) {
		sm.error(new Error('Could not extend the smallmachine.ontology property with the \'sm.nodes\' ontology: ' + error.message + '\n' + error.stack));
	}
}(smallmachine));

<|endoftext|>


<commit_before>// Load in dependencies
var _ = require('underscore');

// Define helper function to parse data
function normalizeMultipart(info) {
  // Find the content type header
  var contentTypeKey = 'content-type';
  var contentType = info.headers[contentTypeKey];
  if (!contentType) {
    contentTypeKey = 'Content-Type';
    contentType = info.headers[contentTypeKey];
  }

  // If we have a multipart form
  // TODO: Get full string for multipart
  if (contentType && contentType.indexOf('multipart') !== -1) {
    // Replace the random boundary with a predictable form
    info.headers = _.clone(info.headers);
    info.headers[contentTypeKey] = contentType.replace(/(\-+)\d+/, '$1somenumber');

    // Replace the boundary in the body as well
    info.body = info.body.toString().replace(/(\-+)\d+/g, '$1somenumber');
  }

  // Return our info
  return info;
}

// Export our helper function
module.exports = normalizeMultipart;
<commit_msg>Fixed up content type string<commit_after>// Load in dependencies
var _ = require('underscore');

// Define helper function to parse data
function normalizeMultipart(info) {
  // Find the content type header
  var contentTypeKey = 'content-type';
  var contentType = info.headers[contentTypeKey];
  if (!contentType) {
    contentTypeKey = 'Content-Type';
    contentType = info.headers[contentTypeKey];
  }

  // If we have a multipart form
  if (contentType && contentType.indexOf('multipart/form-data') !== -1) {
    // Replace the random boundary with a predictable form
    info.headers = _.clone(info.headers);
    info.headers[contentTypeKey] = contentType.replace(/(\-+)\d+/, '$1somenumber');

    // Replace the boundary in the body as well
    info.body = info.body.toString().replace(/(\-+)\d+/g, '$1somenumber');
  }

  // Return our info
  return info;
}

// Export our helper function
module.exports = normalizeMultipart;
<|endoftext|>


<commit_before>  module.exports = {
    addFields: [
      {
        type: 'string',
        name: 'description',
        label: 'Description',
        textarea: true,
        required: true
      },
      {
        type: 'string',
        name: 'contactPerson',
        label: 'Contact Person'
      },
      {
        type: 'string',
        name: 'contactEmail',
        label: 'Contact Email'
      },
      {
        type: 'string',
        name: 'contactPhone',
        label: 'Contact Phone'
      },
      {
        name: 'image',
        label: 'Image',
        type: 'singleton',
        widgetType: 'apostrophe-images',
        options: {
          size: 'one-sixth'
          limit: 1
        }
      },
    ],
    arrangeFields: [
      {
        name: 'basic',
        label: 'Basics',
        fields: ['title', 'description', 'startDate', 'allDay', 'startTime', 'endTime', 'image']
      },
      {
        name: 'advanced',
        label: 'Advanced',
        fields: ['dateType', 'endDate', 'repeatInterval', 'repeatCount']
      },
      {
        name: 'contactInfo',
        label: 'Contact Info (Optional)',
        fields: ['contactPerson', 'contactEmail', 'contactPhone']
      },
      {
        name: 'admin',
        label: 'Administrative',
        fields: ['slug', 'published', 'tags']
      },
    ]
  };
<commit_msg>Add missing comma<commit_after>  module.exports = {
    addFields: [
      {
        type: 'string',
        name: 'description',
        label: 'Description',
        textarea: true,
        required: true
      },
      {
        type: 'string',
        name: 'contactPerson',
        label: 'Contact Person'
      },
      {
        type: 'string',
        name: 'contactEmail',
        label: 'Contact Email'
      },
      {
        type: 'string',
        name: 'contactPhone',
        label: 'Contact Phone'
      },
      {
        name: 'image',
        label: 'Image',
        type: 'singleton',
        widgetType: 'apostrophe-images',
        options: {
          size: 'one-sixth',
          limit: 1
        }
      },
    ],
    arrangeFields: [
      {
        name: 'basic',
        label: 'Basics',
        fields: ['title', 'description', 'startDate', 'allDay', 'startTime', 'endTime', 'image']
      },
      {
        name: 'advanced',
        label: 'Advanced',
        fields: ['dateType', 'endDate', 'repeatInterval', 'repeatCount']
      },
      {
        name: 'contactInfo',
        label: 'Contact Info (Optional)',
        fields: ['contactPerson', 'contactEmail', 'contactPhone']
      },
      {
        name: 'admin',
        label: 'Administrative',
        fields: ['slug', 'published', 'tags']
      },
    ]
  };
<|endoftext|>


<commit_before>/*
 * container.js: Base container from which all pkgcloud containers inherit from
 *
 * (C) 2010 Nodejitsu Inc.
 *
 */

var utile = require('utile'),
    model = require('../base/model');

var Container = exports.Container = function (client, details) {
  model.Model.call(this, client, details);

  this.files = [];
};

utile.inherits(Container, model.Model);

Container.prototype.create = function (callback) {
  this.client.createContainer(this.name, callback);
};

Container.prototype.refresh = function (callback) {
  this.client.getContainer(this, callback);
};

Container.prototype.destroy = function (callback) {
  this.client.destroyContainer(this.name, callback);
};

Container.prototype.upload = function (file, local, options, callback) {
  this.client.upload(this.name, file, local, options, callback);
};

Container.prototype.getFiles = function (download, callback) {
  var self = this;

  // download can be omitted: (...).getFiles(callback);
  // In this case first argument will be a function
  if (typeof download === 'function' && !(download instanceof RegExp)) {
    callback = download;
    download = false;
  }

  this.client.getFiles(this.name, download, function (err, files) {
    if (err) {
      return callback(err);
    }

    self.files = files;
    callback(null, files);
  });
};

Container.prototype.removeFile = function (file, callback) {
  this.client.removeFile(this.name, file, callback);
};<commit_msg>(fix) amzn container model attempts to use this.files [storage]<commit_after>/*
 * container.js: Base container from which all pkgcloud containers inherit from
 *
 * (C) 2010 Nodejitsu Inc.
 *
 */

var utile = require('utile'),
    model = require('../base/model');

var Container = exports.Container = function (client, details) {
  this.files = [];

  model.Model.call(this, client, details);
};

utile.inherits(Container, model.Model);

Container.prototype.create = function (callback) {
  this.client.createContainer(this.name, callback);
};

Container.prototype.refresh = function (callback) {
  this.client.getContainer(this, callback);
};

Container.prototype.destroy = function (callback) {
  this.client.destroyContainer(this.name, callback);
};

Container.prototype.upload = function (file, local, options, callback) {
  this.client.upload(this.name, file, local, options, callback);
};

Container.prototype.getFiles = function (download, callback) {
  var self = this;

  // download can be omitted: (...).getFiles(callback);
  // In this case first argument will be a function
  if (typeof download === 'function' && !(download instanceof RegExp)) {
    callback = download;
    download = false;
  }

  this.client.getFiles(this.name, download, function (err, files) {
    if (err) {
      return callback(err);
    }

    self.files = files;
    callback(null, files);
  });
};

Container.prototype.removeFile = function (file, callback) {
  this.client.removeFile(this.name, file, callback);
};<|endoftext|>


<commit_before>'use strict';

var LAMPApp = require('./LAMPApp');
var configFiles = require('./wordpress/config');
var constants = require('./constants');

class WordPressApp extends LAMPApp {

  /**
   * Options (used by this task):
   *   @param {object} container - An instantiated and configured Container object.
   *   @param {object} options - A hash of configuration options specific to this task.
   *   @param {string} options.devDomain - The url of the dev site. This is replaced by the probo url in the db.
   *   @param {string} options.devHome - The homepage url of the dev site (including the domain). This is replaced by
   *      the probo url in the db.
   *   @param {string} options.database - The filename of the database to import if specified. Note that this database
   *      *must be added to the assets array separately*.
   *   @param {string} [options.databaseName] - The name of the database. Defaults to 'wordpress'.
   *   @param {boolean} [options.databaseGzipped] - Whether the database was sent gzipped and whether it should therefore
   *      be gunzipped before importing.
   *   @param {string} [options.subDirectory] - The directory of the actual web root (defaults to 'docroot').
   *   @param {boolean} [options.flushCaches] - Whether to flush the cache.
   *   @augments LAMPApp
   */
  constructor(container, options) {
    super(container, options);
    this.databaseName = options.databaseName || constants.WORDPRESS_DATABASE_NAME;

    this.options.siteFolder = options.siteFolder || 'default';
    this.options.profileName = options.profileName || 'standard';
    this.options.flushCaches = (options.flushCaches || typeof options.flushCaches === 'undefined');
    this.options.devHome = options.devHome;
    this.options.devDomain = options.devDomain;
    // TODO: Add some kind of validation.

    // Filter out secret strings
    options.secrets = [
    ];

    // Allow for subdirectory to be explicitly set to "" without being overwritten for being falsy.
    this.subDirectory = options.subDirectory || 'docroot';
    this.script = [];
    this.populateScriptArray();
    this.setScript(this.script);
  }

  description() {
    return `${this.plugin} 'Provisioning WordPress!'`;
  }

  /**
   *
   */
  populateScriptArray() {
    this.addScriptSetup();
    this.addScriptSymlinks();
    this.addScriptCreateDatbase();
    this.addScriptImportDatabase();
    this.addScriptAppendWPConfigSettings();
    this.addScriptFixFilePerms();
    this.addScriptReplaceDomain();
    if (this.options.flushCaches) {
      this.addScriptFlushCaches();
    }
    this.addScriptApachePhp();
  }

  addScriptAppendWPConfigSettings() {
    this.script = this.script.concat([
      // create a wp-config file if needed and insert the snippet at the correct line number
      `if [ ! -a "/var/www/html/wp-config.php" ] ; then`,
      `  echo "${configFiles.wpDefaultConfig}" > /var/www/html/wp-config.php`,
      'fi',
      // Prepend the probo-config.php file to the wp-config file.
      `sed -i "1i <?php require('probo-config.php'); ?>" /var/www/html/wp-config.php`,

      // Create the probo-config file to override any user defined settings.
      `echo "<?php`,
      `define('DB_NAME', '${this.databaseName}');`,
      `define('DB_USER', '${constants.DATABASE_USER}');`,
      `define('DB_PASSWORD', '${constants.DATABASE_PASSWORD}');`,
      `define('DB_HOST', 'localhost');`,
      `?>" >> /var/www/html/probo-config.php;`,
    ]);
  }

  addScriptUpdatePlugins() {
    this.script.push('cd $SRC_DIR ; wp plugin update --allow-root');
  }

  addScriptFlushCaches() {
    this.script.push('cd $SRC_DIR ; wp cache flush --allow-root');
  }

  addScriptFixFilePerms() {
    this.script = this.script.concat([
      // Ensure we have an uploads directory and that it is writable.
      `mkdir -p /var/www/html/wp-content/uploads`,
      `chown www-data:www-data /var/www/html/wp-content/uploads`,
      `chmod 755 /var/www/html/wp-content/uploads`,
    ]);
  }

  addScriptReplaceDomain() {
    // flatten home page url first, so that it points to probo root

    this.script.push(this.replaceOption('$BUILD_DOMAIN', 'home'));
    this.script.push(this.replaceTextDb('$DEV_HOME', '$BUILD_DOMAIN'));

    this.script.push(this.replaceOption('$BUILD_DOMAIN', 'siteurl'));
    this.script.push(this.replaceTextDb('$DEV_DOMAIN', '$BUILD_DOMAIN'));
  }

  /**
   * Use wp-cli to replace an option.
   * @param {string} updated - The new value for the option.
   * @param {string} option - The option to replace.
   * @return {string} - The wp-cli command.
   */
  replaceOption(updated, option) {
    var command = `cd $SRC_DIR/${this.subDirectory} ; wp option update ${option} ${updated} --allow-root`;
    return command;
  }

  /**
   * Use wp-cli to replace text in the database.
   * @param {string} orig- The original string.
   * @param {string} updated - The new string.
   * @return {string} - The wp-cli command.
   */
  replaceTextDb(orig, updated) {
    var command = `cd $SRC_DIR/${this.subDirectory} ; wp search-replace '${orig}' '${updated}' --skip-columns=guid --allow-root`;
    return command;
  }
}

module.exports = WordPressApp;
<commit_msg>Adjust WP options and docs.<commit_after>'use strict';

var LAMPApp = require('./LAMPApp');
var configFiles = require('./wordpress/config');
var constants = require('./constants');

class WordPressApp extends LAMPApp {

  /**
   * Options (used by this task):
   *   @param {object} container - An instantiated and configured Container
   *      object.
   *   @param {object} options - A hash of configuration options specific to
   *      this task.
   *   @param {string} options.wpUrl - The url of the original site. This is
   *      replaced by the probo url in the db.
   *   @param {string} options.wpHome - The homepage url of the original site.
   *      This is replaced by the probo url in the db.
   *   @param {string} options.database - The filename of the database to import
   *      if specified. Note that this database *must be added to the assets
   *      array separately*.
   *   @param {boolean} options.updatePlugins - If true, will attempt to update
   *      wordpress plugins to latest versions.
   *   @param {string} [options.databaseName] - The name of the database.
   *      Defaults to 'wordpress'.
   *   @param {boolean} [options.databaseGzipped] - Whether the database was
   *      sent gzipped and whether it should therefore be gunzipped before
   *      importing.
   *   @param {string} [options.subDirectory] - The directory of the actual web
   *      root (defaults to 'docroot').
   *   @param {boolean} [options.flushCaches] - Whether to flush the cache.
   *      Defaults to true.
   *   @augments LAMPApp
   */
  constructor(container, options) {
    super(container, options);
    this.databaseName = options.databaseName || constants.WORDPRESS_DATABASE_NAME;

    this.options.siteFolder = options.siteFolder || 'default';
    this.options.profileName = options.profileName || 'standard';
    this.options.flushCaches = !!options.flushCaches || true;
    // Allow backwards compatibility to old settings.
    this.options.wpHome = options.wpHome || options.devHome || null;
    this.options.wpDomain = options.wpDomain || options.devDomain || null;
    this.options.updatePlugins = !!options.updatePlugins || false;
    // TODO: Add some kind of validation.

    // Filter out secret strings
    options.secrets = [
    ];

    // Allow for subdirectory to be explicitly set to "" without being overwritten for being falsy.
    this.subDirectory = options.subDirectory || 'docroot';
    this.script = [];
    this.populateScriptArray();
    this.setScript(this.script);
  }

  description() {
    return `${this.plugin} 'Provisioning WordPress!'`;
  }

  /**
   *
   */
  populateScriptArray() {
    this.addScriptSetup();
    this.addScriptSymlinks();
    this.addScriptCreateDatbase();
    this.addScriptImportDatabase();
    this.addScriptAppendWPConfigSettings();
    this.addScriptFixFilePerms();
    this.addScriptReplaceDomain();
    if (this.options.updatePlugins) {
      this.addScriptUpdatePlugins();
    }
    if (this.options.flushCaches) {
      this.addScriptFlushCaches();
    }
    this.addScriptApachePhp();
  }

  addScriptAppendWPConfigSettings() {
    this.script = this.script.concat([
      // create a wp-config file if needed and insert the snippet at the correct line number
      `if [ ! -a "/var/www/html/wp-config.php" ] ; then`,
      `  echo "${configFiles.wpDefaultConfig}" > /var/www/html/wp-config.php`,
      'fi',
      // Prepend the probo-config.php file to the wp-config file.
      `sed -i "1i <?php require('probo-config.php'); ?>" /var/www/html/wp-config.php`,

      // Create the probo-config file to override any user defined settings.
      `echo "<?php`,
      `define('DB_NAME', '${this.databaseName}');`,
      `define('DB_USER', '${constants.DATABASE_USER}');`,
      `define('DB_PASSWORD', '${constants.DATABASE_PASSWORD}');`,
      `define('DB_HOST', 'localhost');`,
      `?>" >> /var/www/html/probo-config.php;`,
    ]);
  }

  addScriptUpdatePlugins() {
    this.script.push('cd /var/www/html/ ; wp plugin update --all --allow-root');
  }

  addScriptFlushCaches() {
    this.script.push('cd /var/www/html/ ; wp cache flush --allow-root');
  }

  addScriptFixFilePerms() {
    this.script = this.script.concat([
      // Ensure we have an uploads directory and that it is writable.
      `mkdir -p /var/www/html/wp-content/uploads`,
      `chown www-data:www-data /var/www/html/wp-content/uploads`,
      `chmod 755 /var/www/html/wp-content/uploads`,
    ]);
  }

  addScriptReplaceDomain() {
    // flatten home page url first, so that it points to probo root
    this.script.push(this.replaceOption('$BUILD_DOMAIN', 'home'));
    this.script.push(this.replaceOption('$BUILD_DOMAIN', 'siteurl'));

    if (this.options.wpHome) {
      this.script.push(`export WP_HOME=${this.options.wpHome}`);
      this.script.push(this.replaceTextDb('$WP_HOME', '$BUILD_DOMAIN'));
    }

    if (this.options.wpDomain) {
      this.script.push(`export WP_DOMAIN=${this.options.wpDomain}`);
      this.script.push(this.replaceTextDb('$WP_DOMAIN', '$BUILD_DOMAIN'));
    }
  }

  /**
   * Use wp-cli to replace an option.
   * @param {string} updated - The new value for the option.
   * @param {string} option - The option to replace.
   * @return {string} - The wp-cli command.
   */
  replaceOption(updated, option) {
    var command = `cd /var/www/html/ ; wp option update ${option} ${updated} --allow-root`;
    return command;
  }

  /**
   * Use wp-cli to replace text in the database.
   * @param {string} orig- The original string.
   * @param {string} updated - The new string.
   * @return {string} - The wp-cli command.
   */
  replaceTextDb(orig, updated) {
    var command = `cd /var/www/html/ ; wp search-replace '${orig}' '${updated}' --skip-columns=guid --allow-root`;
    return command;
  }
}

module.exports = WordPressApp;
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const fm = require('front-matter');

const splitBody = require('./split_body');

// slideName => { attributes (front-matter stuff), data }
function prepareFilenameToContentMap(filepaths, fileReader, options) {
  const filenameToContentMap = filepaths
      .map((filepath) => {
        return {
          name: path.basename(filepath, path.extname(filepath)),
          content: fm(fileReader.read(filepath))
        };
      }).map((file) => {
        const data = Object.assign(
            {},
            options.layoutAttributes, {
              sections: splitBody(file.content.body, options.sectionSplitter)
            },
            file.content.attributes
        );
        return {
          name: file.name,
          content: {
            attributes: file.content.attributes,
            data
          }
        };
      }).reduce((map, current) => {
        map.set(current.name, current.content);
        return map;
      }, new Map());

  return filenameToContentMap;
}

module.exports = prepareFilenameToContentMap;
<commit_msg>make options optional. Expect function as reader<commit_after>'use strict';

const path = require('path');
const fm = require('front-matter');

const splitBody = require('./split_body');

// slideName => { attributes (front-matter stuff), data }
function prepareFilenameToContentMap(filepaths, readFile, options) {
  options = options || {};
  const filenameToContentMap = filepaths
      .map((filepath) => {
        return {
          name: path.basename(filepath, path.extname(filepath)),
          content: fm(readFile(filepath))
        };
      }).map((file) => {
        const data = Object.assign(
            {},
            options.layoutAttributes, {
              sections: splitBody(file.content.body, options.sectionSplitter)
            },
            file.content.attributes
        );
        return {
          name: file.name,
          content: {
            attributes: file.content.attributes,
            data
          }
        };
      }).reduce((map, current) => {
        map.set(current.name, current.content);
        return map;
      }, new Map());

  return filenameToContentMap;
}

module.exports = prepareFilenameToContentMap;
<|endoftext|>


<commit_before>const graphqlTester  = require('graphql-tester')
const expressGraphql = require('express-graphql')
const {expect}       = require('chai')
const cookieSession  = require('cookie-session')
const express        = require('express')
const schema         = require('../lib/schema')
const createExpressWrapper = require('graphql-tester/lib/main/servers/express.js').create

describe('api' , () => {
  const app = express()
  const session = cookieSession({
      name: 'session',
      keys: ['secret squirrel'],
      maxAge: 24 * 60 * 60 * 1000 // 24 hours
  })
  app.use(session)
  app.use('/graphql', expressGraphql((req) =>  {
     return {
         schema,
         graphiql: true,
         rootValue: { session: req.session },
     }
  }))
  const test = graphqlTester.tester({
    server: createExpressWrapper(app),
    url: '/graphql'
  })

  it('responds with session id', done => {
    test('{sessionId}').then(response => {
      expect(response.success).to.be.ok
      expect(response.status).to.equal(200)
      expect(response.data.sessionId).to.not.equal('')
      return done()
    })
  })
  it('gives out unique session ids', done => {
    test('{sessionId}').then(response1 => {
      expect(response1.success).to.be.ok
      expect(response1.status).to.equal(200)
      test('{sessionId}').then(response2 => {
        expect(response1.success).to.be.ok
        expect(response1.status).to.equal(200)
        expect(response1.data.sessionId).to.not.equal(response2.data.sessionId)
        return done()
      })
    })
  })
})
<commit_msg>Fix express wrapper<commit_after>const graphqlTester  = require('graphql-tester')
const expressGraphql = require('express-graphql')
const {expect}       = require('chai')
const cookieSession  = require('cookie-session')
const express        = require('express')
const schema         = require('../lib/schema')
const shortid        = require('shortid')
const createExpressWrapper = require('graphql-tester/lib/main/servers/express.js').create

describe('api' , () => {
  const app = express()
  const session = cookieSession({
      name: 'session',
      keys: ['secret squirrel'],
      maxAge: 24 * 60 * 60 * 1000 // 24 hours
  })
  app.use(session)
  app.all('*', (req, res, next) =>  {
      if (req.session.id == null) {
          req.session.id = shortid.generate()
      }
      return next()
  })

  app.get('/', (req, res) =>  {
      return res.send(req.session.id)
  })
  app.use('/graphql', expressGraphql((req) =>  {
     return {
         schema,
         graphiql: true,
         rootValue: { session: req.session },
     }
  }))
  const test = graphqlTester.tester({
    server: createExpressWrapper(app),
    url: '/graphql'
  })

  it('responds with session id', done => {
    test('{sessionId}').then(response => {
      expect(response.success).to.be.ok
      expect(response.status).to.equal(200)
      expect(response.data.sessionId).to.not.equal('')
      return done()
    })
  })
  it('gives out unique session ids', done => {
    test('{sessionId}').then(response1 => {
      expect(response1.success).to.be.ok
      expect(response1.status).to.equal(200)
      test('{sessionId}').then(response2 => {
        expect(response1.success).to.be.ok
        expect(response1.status).to.equal(200)
        expect(response1.data.sessionId).to.not.equal(response2.data.sessionId)
        return done()
      })
    })
  })
})
<|endoftext|>


<commit_before>/*global availity, describe, it, beforeEach, expect, module*/

describe('dropdown', function() {

  'use strict';

  var $el;

  var fixtures = {
    'default': '<select name="demoSelect" class="form-control select2" placeholder="Select One" data-av-dropdown data-ng-model="demo.selected" data-ng-options="selection for selection in demo.selections"></select>'
  };

  beforeEach(function() {
    module('availity');
    module('availity.ui');
  });

  availity.mock.directiveSpecHelper();

  it('should create DOM structure', function () {
    $el = availity.mock.compileDirective(fixtures['default']);
    availity.mock.flush();
    expect($el.siblings().is('div.select2-container')).toBe(true);
  });

  describe('control should be in proper state ', function() {

    it('to be $pristine on load', function() {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = ['first', 'second', 'third'];
      availity.mock.$scope.demo.selected = null;

      $el = availity.mock.compileDirective(fixtures['default']);
      availity.mock.flush();

      expect($el.data('$ngModelController').$pristine).toBe(true);

      // this should update the model and control state
      $el.trigger('change');
      expect($el.data('$ngModelController').$pristine).toBe(false);

    });
  });

  describe('should update dropdown model', function() {

    it('for string array', function () {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = ['first', 'second', 'third'];
      availity.mock.$scope.demo.selected = 'first';

      $el = availity.mock.compileDirective(fixtures['default']);

      availity.mock.flush();

      availity.mock.$scope.demo.selected = 'second';
      availity.mock.$scope.$apply();
      availity.mock.flush();
      expect($el.select2('val')).toBe('1');

    });

    it('for object array', function () {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = [
        {
          id: 1,
          value: 'first'
        },
        {
          id: 2,
          value: 'second'
        },
        {
          id: 3,
          value: 'third'
        }
      ];
      availity.mock.$scope.demo.selected = availity.mock.$scope.demo.selections[0];

      $el = availity.mock.compileDirective(fixtures['default']);

      availity.mock.flush();

      availity.mock.$scope.demo.selected = availity.mock.$scope.demo.selections[1];
      availity.mock.$scope.$apply();
      availity.mock.flush();
      expect($el.select2('val')).toBe('1');

    });

    it('for null value', function () {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = [
        {
          id: 1,
          value: 'first'
        },
        {
          id: 2,
          value: 'second'
        },
        {
          id: 3,
          value: 'third'
        }
      ];
      availity.mock.$scope.demo.selected = availity.mock.$scope.demo.selections[0];

      $el = availity.mock.compileDirective(fixtures['default']);

      availity.mock.flush();

      availity.mock.$scope.demo.selected = null;
      availity.mock.$scope.$apply();
      availity.mock.flush();
      expect($el.select2('val')).toBe('');

    });

  });

});
<commit_msg>update spec for dropdowns<commit_after>/*global availity, describe, it, beforeEach, expect, module*/

describe('dropdown', function() {

  'use strict';

  var $el;

  var fixtures = {
    'default': '<select name="demoSelect" class="form-control select2" placeholder="Select One" data-av-dropdown data-ng-model="demo.selected" data-ng-options="selection for selection in demo.selections"></select>'
  };

  beforeEach(function() {
    module('availity');
    module('availity.ui');
  });

  availity.mock.directiveSpecHelper();

  it('should create DOM structure', function () {
    $el = availity.mock.compileDirective(fixtures['default']);
    availity.mock.flush();
    expect($el.siblings().is('div.select2-container')).toBe(true);
  });

  describe('control should be in proper state ', function() {

    it('to be $pristine on load', function() {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = ['first', 'second', 'third'];
      availity.mock.$scope.demo.selected = null;

      $el = availity.mock.compileDirective(fixtures['default']);
      availity.mock.flush();

      expect($el.data('$ngModelController').$pristine).toBe(true);

      // this should update the model and control state. this test is here
      // just to demonstrate the behavior and refresh our memory
      $el.trigger('change');
      expect($el.data('$ngModelController').$pristine).toBe(false);
      expect($el.data('$ngModelController').$dirty).toBe(true);

    });
  });

  describe('should update dropdown model', function() {

    it('for string array', function () {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = ['first', 'second', 'third'];
      availity.mock.$scope.demo.selected = 'first';

      $el = availity.mock.compileDirective(fixtures['default']);

      availity.mock.flush();

      availity.mock.$scope.demo.selected = 'second';
      availity.mock.$scope.$apply();
      availity.mock.flush();
      expect($el.select2('val')).toBe('1');

    });

    it('for object array', function () {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = [
        {
          id: 1,
          value: 'first'
        },
        {
          id: 2,
          value: 'second'
        },
        {
          id: 3,
          value: 'third'
        }
      ];
      availity.mock.$scope.demo.selected = availity.mock.$scope.demo.selections[0];

      $el = availity.mock.compileDirective(fixtures['default']);

      availity.mock.flush();

      availity.mock.$scope.demo.selected = availity.mock.$scope.demo.selections[1];
      availity.mock.$scope.$apply();
      availity.mock.flush();
      expect($el.select2('val')).toBe('1');

    });

    it('for null value', function () {

      availity.mock.$scope.demo = {};
      availity.mock.$scope.demo.selections = [
        {
          id: 1,
          value: 'first'
        },
        {
          id: 2,
          value: 'second'
        },
        {
          id: 3,
          value: 'third'
        }
      ];
      availity.mock.$scope.demo.selected = availity.mock.$scope.demo.selections[0];

      $el = availity.mock.compileDirective(fixtures['default']);

      availity.mock.flush();

      availity.mock.$scope.demo.selected = null;
      availity.mock.$scope.$apply();
      availity.mock.flush();
      expect($el.select2('val')).toBe('');

    });

  });

});
<|endoftext|>