<commit_before>/*!
 * chai-param
 * Copyright(c) 2014 The Blacksmith (a.k.a. Saulo Vallory) <jake@alogicalparadox.com>
 * MIT Licensed
 */

var path = require('path'),
    chalk = require('chalk'),
    stackTrace = require('stack-trace'),
    chai = require('chai'),
    utils = require('chai/lib/chai/utils');

var exports = module.exports = chaiParam;

chaiParam.config = require('./config');

// chalk wrapper for easy enabling and disabling colors
function c(color, text) {
  if(chaiParam.config.disableColors)
    return text;

  return chalk[color](text);
}

function chaiParam(chai, utils) {

  if(chaiParam._param)
    // already initialized
    return;

  var flag = utils.flag
    , objDisplay = utils.objDisplay;

  chaiParam._param = function param(val, paramName, functionName, topic) {
    var assertion = new chai.Assertion(val, functionName);

    utils.flag(assertion, 'paramName', paramName);

    if(functionName && functionName.trim && functionName.trim() != '')
      utils.flag(assertion, 'functionName', functionName);

    if(topic && topic.trim && topic.trim() != '')
      utils.flag(assertion, 'message', topic);

    return { should: assertion };
  }

  /**
   * ### .param(paramName, functionName)
   *
   * The `param` chain allows you provide metadata about
   * the parameter being validated.
   *
   *     // examples
   *     expect(text).param('text', 'log').to.be.a('string');
   *     expect(user).param('user', 'register').to.have.length.below(16);
   *
   * @name param
   * @param {String} paramName
   * @param {String} functionName _optional_ Adding this allows chai-param to look for the caller
   * @api public
   */
  utils.addMethod(chai.Assertion.prototype, 'param', function(paramName, functionName) {
    utils.flag(this, 'paramName', paramName);

    if(functionName && functionName.trim && functionName.trim() != '')
      utils.flag(this, 'functionName', functionName);
  });

  if(chaiParam.config.improveMessages) {

    // Overwriting getMessages
    var oldGetMessage = utils.getMessage;
    utils.getMessage = getMessage;

    function getMessage (obj, args) {

      if(!chaiParam.config.improveMessages)
      {
        return oldGetMessage(obj, args);
      }

      var negate = utils.flag(obj, 'negate')
        , val = utils.flag(obj, 'object')
        , expected = args[3]
        , actual = utils.getActual(obj, args)
        , msg = negate ? args[2] : args[1]
        , flagMsg = utils.flag(obj, 'message')
        , flagParam = utils.flag(obj, 'paramName')
        , fnTarget = utils.flag(obj, 'functionName');

      msg = msg || '';

      var hasActToken = msg.indexOf('#{act}') >= 0;

      msg = msg
        .replace(/#{this}/g, flagParam ? 'parameter ' + c('yellow', flagParam) + ' ('+objDisplay(val)+')': objDisplay(val))
        .replace(/#{act}/g, c('red', objDisplay(actual)))
        .replace(/#{exp}/g, c('green', objDisplay(expected)))
        .replace(/(not) to/, c('green', 'not') + ' to').replace(/to not/, 'to ' + c('green', 'not'))
        .replace(/(length )?(below|at least|above|at most|within)(\s*)([0-9]*)/, c('green', '$1$2$3$4'))
        .replace(/(include|truthy|falsy|true|false|undefined|match|satisfy|same members as)/, c('green', '$1'))
        .replace(/(exist|empty|arguments|equal|deeply equal|instance of|be a superset)/, c('green', '$1'));

      if(flagParam && !hasActToken)
        msg += ' but got ' + c('red', objDisplay(val)) + ' instead';

      var isNode = (typeof window == 'undefined');

      if(chaiParam.config.showCaller && isNode && fnTarget) // show Caller
      {
        var trace = stackTrace.get();

        var i = 0;

        if(fnTarget) {
          while(i < trace.length && trace[i].getFunctionName() != fnTarget) {
            i++;
          }

          if(++i < trace.length) {
            var file = trace[i].getFileName();
            var filePath = path.dirname(file) + path.sep + c('blue', path.basename(file));

            var spaces = flagMsg ? flagMsg.replace(/./g, ' ') : '';

            msg += '\n' + spaces + '  - Called at: ' + filePath + ':' + c('blue', trace[i].getLineNumber());
          }
        }
      }

      return flagMsg ? flagMsg + ': ' + msg : msg;
    };
  }
}

/**
 * ### param(value, name, function)
 *
 * The `param` method allows you to use the should syntax
 * and still provide metadata about the parameter being validated.
 *
 *     // examples
 *     param(text, 'text', 'log').should.be.a('string');
 *     param(user, 'user', 'register').should.have.length.below(16);
 *
 * @name param
 * @param {Mixed} value
 * @param {String} paramName
 * @param {String} functionName _optional_ Adding this allows chai-param to look for the caller
 * @param {String} topic _optional_ A prefix for the message
 * @api public
 */
chaiParam.param = function param(val, paramName, functionName, topic) {

  if(!chaiParam._param) {
    throw new Error("You need to add chai-param to chai through `chai.use()` method before using it")
  }

  return chaiParam._param(val, paramName, functionName, topic);
};
<commit_msg>Fix #1<commit_after>/*!
 * chai-param
 * Copyright(c) 2014 The Blacksmith (a.k.a. Saulo Vallory) <jake@alogicalparadox.com>
 * MIT Licensed
 */

var path = require('path'),
    chalk = require('chalk'),
    stackTrace = require('stack-trace'),
    chai = require('chai'),
    utils = require('chai/lib/chai/utils');

var exports = module.exports = chaiParam;

chaiParam.config = require('./config');

// chalk wrapper for easy enabling and disabling colors
function c(color, text) {
  if(chaiParam.config.disableColors)
    return text;

  return chalk[color](text);
}

function chaiParam(chai, utils) {

  if(chaiParam._param)
    // already initialized
    return;

  var flag = utils.flag
    , objDisplay = utils.objDisplay;

  chaiParam._param = function param(val, paramName, functionName, topic) {
    var assertion = new chai.Assertion(val, functionName);

    utils.flag(assertion, 'paramName', paramName);

    if(functionName && functionName.trim && functionName.trim() != '')
      utils.flag(assertion, 'functionName', functionName);

    if(topic && topic.trim && topic.trim() != '')
      utils.flag(assertion, 'message', topic);

    return { should: assertion };
  }

  /**
   * ### .param(paramName, functionName)
   *
   * The `param` chain allows you provide metadata about
   * the parameter being validated.
   *
   *     // examples
   *     expect(text).param('text', 'log').to.be.a('string');
   *     expect(user).param('user', 'register').to.have.length.below(16);
   *
   * @name param
   * @param {String} paramName
   * @param {String} functionName _optional_ Adding this allows chai-param to look for the caller
   * @api public
   */
  utils.addMethod(chai.Assertion.prototype, 'param', function(paramName, functionName) {
    utils.flag(this, 'paramName', paramName);

    if(functionName && functionName.trim && functionName.trim() != '')
      utils.flag(this, 'functionName', functionName);
  });

  if(chaiParam.config.improveMessages) {

    // Overwriting getMessages
    var oldGetMessage = utils.getMessage;

    utils.getMessage = function getMessage (obj, args) {

      if(!chaiParam.config.improveMessages)
      {
        return oldGetMessage(obj, args);
      }

      var negate = utils.flag(obj, 'negate')
        , val = utils.flag(obj, 'object')
        , expected = args[3]
        , actual = utils.getActual(obj, args)
        , msg = negate ? args[2] : args[1]
        , flagMsg = utils.flag(obj, 'message')
        , flagParam = utils.flag(obj, 'paramName')
        , fnTarget = utils.flag(obj, 'functionName');

      msg = msg || '';

      var hasActToken = msg.indexOf('#{act}') >= 0;

      msg = msg
        .replace(/#{this}/g, flagParam ? 'parameter ' + c('yellow', flagParam) + ' ('+objDisplay(val)+')': objDisplay(val))
        .replace(/#{act}/g, c('red', objDisplay(actual)))
        .replace(/#{exp}/g, c('green', objDisplay(expected)))
        .replace(/(not) to/, c('green', 'not') + ' to').replace(/to not/, 'to ' + c('green', 'not'))
        .replace(/(length )?(below|at least|above|at most|within)(\s*)([0-9]*)/, c('green', '$1$2$3$4'))
        .replace(/(include|truthy|falsy|true|false|undefined|match|satisfy|same members as)/, c('green', '$1'))
        .replace(/(exist|empty|arguments|equal|deeply equal|instance of|be a superset)/, c('green', '$1'));

      if(flagParam && !hasActToken)
        msg += ' but got ' + c('red', objDisplay(val)) + ' instead';

      var isNode = (typeof window == 'undefined');

      if(chaiParam.config.showCaller && isNode && fnTarget) // show Caller
      {
        var trace = stackTrace.get();

        var i = 0;

        if(fnTarget) {
          while(i < trace.length && trace[i].getFunctionName() != fnTarget) {
            i++;
          }

          if(++i < trace.length) {
            var file = trace[i].getFileName();
            var filePath = path.dirname(file) + path.sep + c('blue', path.basename(file));

            var spaces = flagMsg ? flagMsg.replace(/./g, ' ') : '';

            msg += '\n' + spaces + '  - Called at: ' + filePath + ':' + c('blue', trace[i].getLineNumber());
          }
        }
      }

      return flagMsg ? flagMsg + ': ' + msg : msg;
    };
  }
}

/**
 * ### param(value, name, function)
 *
 * The `param` method allows you to use the should syntax
 * and still provide metadata about the parameter being validated.
 *
 *     // examples
 *     param(text, 'text', 'log').should.be.a('string');
 *     param(user, 'user', 'register').should.have.length.below(16);
 *
 * @name param
 * @param {Mixed} value
 * @param {String} paramName
 * @param {String} functionName _optional_ Adding this allows chai-param to look for the caller
 * @param {String} topic _optional_ A prefix for the message
 * @api public
 */
chaiParam.param = function param(val, paramName, functionName, topic) {

  if(!chaiParam._param) {
    throw new Error("You need to add chai-param to chai through `chai.use()` method before using it")
  }

  return chaiParam._param(val, paramName, functionName, topic);
};
<|endoftext|>


<commit_before>'use strict';

/**
 * External dependencies
 */
const path = require('path');
const shelljs = require('shelljs/global'); // eslint-disable-line no-unused-vars
const program = require('commander');
const exec = require('child_process').exec;

/**
 * Local dependencies
 */
const start = require('./start');

/**
 * Create a new app with folder structure and files
 */
const create = function (name) {
  name = name || 'my-deployd-app';
  if (test('-d', name)) {
    return console.info(`${name} already exists in this directory`);
  }

  mkdir('-p', name);
  cp('-Rf', path.join(__dirname, '../createtemplate/*'), name);
  mkdir('-p', `${name}/.dpd`);
  mkdir('-p', `${name}/.dpd/pids`);
  ('').to(`${name}/.dpd/pids/mongod`);
  rm(ls('-R', name).filter(p => path.basename(p) === 'PLACEHOLDER').map(p => `${name}/${p}`));

  process.chdir(name);

  console.log('dpd is installing the dependencies... please be patient (this may take a few minutes)');
  const child = exec('npm install',
      (error, stdout, stderr) => {
        if (error !== null) {
          console.log(stderr);
          console.log(`npm install error: ${error}`);
        } else if (program.dashboard || program.open) {
          start(`${name}/app.dpd`);
        } else {
          console.info('to start your app:');
          console.info('\t$ cd', name);
          console.info('\t$ dpd');
        }
      });
};

module.exports = create;
<commit_msg>Feat: Add a .gitignore file when creating a project (#19)<commit_after>'use strict';

/**
 * External dependencies
 */
const path = require('path');
const shelljs = require('shelljs/global'); // eslint-disable-line no-unused-vars
const program = require('commander');
const exec = require('child_process').exec;

/**
 * Local dependencies
 */
const start = require('./start');

/**
 * Create a new app with folder structure and files
 */
const create = function (name) {
  name = name || 'my-deployd-app';
  if (test('-d', name)) {
    return console.info(`${name} already exists in this directory`);
  }

  mkdir('-p', name);
  cp('-Rf', path.join(__dirname, '../createtemplate/*'), name);
  mkdir('-p', `${name}/.dpd`);
  mkdir('-p', `${name}/.dpd/pids`);
  ('').to(`${name}/.dpd/pids/mongod`);
  ('# npm\r\nnode_modules/\r\nnpm-debug.log\r\n\r\n# deployd\r\n.dpd/\r\ndata/')
    .to(`${name}/.gitignore`);
  rm(ls('-R', name).filter(p => path.basename(p) === 'PLACEHOLDER').map(p => `${name}/${p}`));

  process.chdir(name);

  console.log('dpd is installing the dependencies... please be patient (this may take a few minutes)');
  const child = exec('npm install',
      (error, stdout, stderr) => {
        if (error !== null) {
          console.log(stderr);
          console.log(`npm install error: ${error}`);
        } else if (program.dashboard || program.open) {
          start(`${name}/app.dpd`);
        } else {
          console.info('to start your app:');
          console.info('\t$ cd', name);
          console.info('\t$ dpd');
        }
      });
};

module.exports = create;
<|endoftext|>


<commit_before>/*
 * Copyright 2016 resin.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict'

const _ = require('lodash')
const Bluebird = require('bluebird')
const fs = Bluebird.promisifyAll(require('fs'))
const mountutils = Bluebird.promisifyAll(require('mountutils'))
const drivelist = Bluebird.promisifyAll(require('drivelist'))
const os = require('os')
const imageStream = require('../image-stream')
const errors = require('../shared/errors')
const constraints = require('../shared/drive-constraints')
const ImageWriter = require('../writer')
const diskpart = require('./diskpart')

/**
 * @summary Timeout, in milliseconds, to wait before unmounting on success
 * @constant
 * @type {Number}
 */
const UNMOUNT_ON_SUCCESS_TIMEOUT_MS = 2000

/**
 * @summary Write an image to a disk drive
 * @function
 * @public
 *
 * @param {String} imagePath - path to image
 * @param {String} drive - drive
 * @param {Object} options - options
 * @param {Boolean} [options.unmountOnSuccess=false] - unmount on success
 * @param {Boolean} [options.validateWriteOnSuccess=false] - validate write on success
 * @param {Function} onProgress - on progress callback (state)
 *
 * @fulfil {Boolean} - whether the operation was successful
 * @returns {Promise}
 *
 * @example
 * writer.writeImage('path/to/image.img', '/dev/disk2', {
 *   unmountOnSuccess: true,
 *   validateWriteOnSuccess: true
 * }, (state) => {
 *   console.log(state.percentage);
 * }).then(() => {
 *   console.log('Done!');
 * });
 */
exports.writeImage = (imagePath, drive, options, onProgress) => {
  return drivelist.listAsync().then((drives) => {
    const selectedDrive = _.find(drives, {
      device: drive
    })

    if (!selectedDrive) {
      throw errors.createUserError({
        title: 'The selected drive was not found',
        description: `We can't find ${drive} in your system. Did you unplug the drive?`,
        code: 'EUNPLUGGED'
      })
    }

    return selectedDrive
  }).then((driveObject) => {
    return Bluebird.try(() => {
      // Unmounting a drive in Windows means we can't write to it anymore
      if (os.platform() === 'win32') {
        return Bluebird.resolve()
      }

      return mountutils.unmountDiskAsync(driveObject.device)
    }).then(() => {
      return diskpart.clean(driveObject.device)
    }).then(() => {
      /* eslint-disable no-bitwise */
      const flags = fs.constants.O_RDWR |
        fs.constants.O_EXCL |
        fs.constants.O_NONBLOCK |
        fs.constants.O_SYNC |
        fs.constants.O_DIRECT
      /* eslint-enable no-bitwise */

      return fs.openAsync(driveObject.raw, flags)
    }).then((driveFileDescriptor) => {
      return imageStream.getFromFilePath(imagePath).then((image) => {
        if (!constraints.isDriveLargeEnough(driveObject, image)) {
          throw errors.createUserError({
            title: 'The image you selected is too big for this drive',
            description: 'Please connect a bigger drive and try again'
          })
        }

        const writer = new ImageWriter({
          image,
          fd: driveFileDescriptor,
          path: driveObject.raw,
          verify: options.validateWriteOnSuccess,
          checksumAlgorithms: [ 'crc32' ]
        })

        return writer.write()
      }).then((writer) => {
        return new Bluebird((resolve, reject) => {
          writer.on('progress', onProgress)
          writer.on('error', reject)
          writer.on('finish', (results) => {
            results.drive = driveObject
            resolve(results)
          })
        })
      }).tap(() => {
        // Make sure the device stream file descriptor is closed
        // before returning control the the caller. Not closing
        // the file descriptor (and waiting for it) results in
        // `EBUSY` errors when attempting to unmount the drive
        // right afterwards in some Windows 7 systems.
        return fs.closeAsync(driveFileDescriptor).then(() => {
          if (!options.unmountOnSuccess) {
            return Bluebird.resolve()
          }

          // Closing a file descriptor on a drive containing mountable
          // partitions causes macOS to mount the drive. If we try to
          // unmount to quickly, then the drive might get re-mounted
          // right afterwards.
          return Bluebird.delay(UNMOUNT_ON_SUCCESS_TIMEOUT_MS)
            .return(driveObject.device)
            .then(mountutils.unmountDiskAsync)
        })
      })
    })
  })
}
<commit_msg>fix(cli): Remove O_DIRECT & O_EXCL<commit_after>/*
 * Copyright 2016 resin.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict'

const _ = require('lodash')
const Bluebird = require('bluebird')
const fs = Bluebird.promisifyAll(require('fs'))
const mountutils = Bluebird.promisifyAll(require('mountutils'))
const drivelist = Bluebird.promisifyAll(require('drivelist'))
const os = require('os')
const imageStream = require('../image-stream')
const errors = require('../shared/errors')
const constraints = require('../shared/drive-constraints')
const ImageWriter = require('../writer')
const diskpart = require('./diskpart')

/**
 * @summary Timeout, in milliseconds, to wait before unmounting on success
 * @constant
 * @type {Number}
 */
const UNMOUNT_ON_SUCCESS_TIMEOUT_MS = 2000

/**
 * @summary Write an image to a disk drive
 * @function
 * @public
 *
 * @param {String} imagePath - path to image
 * @param {String} drive - drive
 * @param {Object} options - options
 * @param {Boolean} [options.unmountOnSuccess=false] - unmount on success
 * @param {Boolean} [options.validateWriteOnSuccess=false] - validate write on success
 * @param {Function} onProgress - on progress callback (state)
 *
 * @fulfil {Boolean} - whether the operation was successful
 * @returns {Promise}
 *
 * @example
 * writer.writeImage('path/to/image.img', '/dev/disk2', {
 *   unmountOnSuccess: true,
 *   validateWriteOnSuccess: true
 * }, (state) => {
 *   console.log(state.percentage);
 * }).then(() => {
 *   console.log('Done!');
 * });
 */
exports.writeImage = (imagePath, drive, options, onProgress) => {
  return drivelist.listAsync().then((drives) => {
    const selectedDrive = _.find(drives, {
      device: drive
    })

    if (!selectedDrive) {
      throw errors.createUserError({
        title: 'The selected drive was not found',
        description: `We can't find ${drive} in your system. Did you unplug the drive?`,
        code: 'EUNPLUGGED'
      })
    }

    return selectedDrive
  }).then((driveObject) => {
    return Bluebird.try(() => {
      // Unmounting a drive in Windows means we can't write to it anymore
      if (os.platform() === 'win32') {
        return Bluebird.resolve()
      }

      return mountutils.unmountDiskAsync(driveObject.device)
    }).then(() => {
      return diskpart.clean(driveObject.device)
    }).then(() => {
      /* eslint-disable no-bitwise */
      const flags = fs.constants.O_RDWR |
        fs.constants.O_NONBLOCK |
        fs.constants.O_SYNC
      /* eslint-enable no-bitwise */

      return fs.openAsync(driveObject.raw, flags)
    }).then((driveFileDescriptor) => {
      return imageStream.getFromFilePath(imagePath).then((image) => {
        if (!constraints.isDriveLargeEnough(driveObject, image)) {
          throw errors.createUserError({
            title: 'The image you selected is too big for this drive',
            description: 'Please connect a bigger drive and try again'
          })
        }

        const writer = new ImageWriter({
          image,
          fd: driveFileDescriptor,
          path: driveObject.raw,
          verify: options.validateWriteOnSuccess,
          checksumAlgorithms: [ 'crc32' ]
        })

        return writer.write()
      }).then((writer) => {
        return new Bluebird((resolve, reject) => {
          writer.on('progress', onProgress)
          writer.on('error', reject)
          writer.on('finish', (results) => {
            results.drive = driveObject
            resolve(results)
          })
        })
      }).tap(() => {
        // Make sure the device stream file descriptor is closed
        // before returning control the the caller. Not closing
        // the file descriptor (and waiting for it) results in
        // `EBUSY` errors when attempting to unmount the drive
        // right afterwards in some Windows 7 systems.
        return fs.closeAsync(driveFileDescriptor).then(() => {
          if (!options.unmountOnSuccess) {
            return Bluebird.resolve()
          }

          // Closing a file descriptor on a drive containing mountable
          // partitions causes macOS to mount the drive. If we try to
          // unmount to quickly, then the drive might get re-mounted
          // right afterwards.
          return Bluebird.delay(UNMOUNT_ON_SUCCESS_TIMEOUT_MS)
            .return(driveObject.device)
            .then(mountutils.unmountDiskAsync)
        })
      })
    })
  })
}
<|endoftext|>


<commit_before>function CookieStore (name, minCustomers, maxCustomers, avgCookiesPerCust, elementId) {
    this.name = name;
    this.minCustomers = minCustomers;
    this.maxCustomers = maxCustomers;
    this.avgCookiesPerCust = avgCookiesPerCust;
    this.elementId = elementId;
    this.staticCookies = [];
    this.cookieSum = 0;
    this.addToDom();
};

CookieStore.prototype.randomCust = function () {
    return (Math.floor(Math.random() * (this.maxCustomers - this.minCustomers)) + this.minCustomers);
};

CookieStore.prototype.avgCookiesPerHour = function () {
    return this.randomCust() * this.avgCookiesPerCust;
};

CookieStore.prototype.cookieDataArray = function () {
    for (var i = 0; i < 15; i++){
        this.staticCookies.push(Math.floor(this.avgCookiesPerHour()));
    }
};

//Cookie tosser requirement formula
CookieStore.prototype.cookieTossers = function (input) {
    if (input < 40){
        return 2;
    }
    else if (input % 20 == 0){
        return input / 20;
    }
    else {
        return Math.floor(input / 20) + 1;
    }
};

//Method to make new table element with optional id
CookieStore.prototype.makeTableElement = function (elementName, elementType, newElementId) {
    var container = document.getElementById(elementName);
    var createNewElement = document.createElement(elementType);
    createNewElement.id = newElementId;
    container.appendChild( createNewElement );
};

//Method to make new TD element with inner HTML content **DOESNT WORK YET**
CookieStore.prototype.makeHTMLelement = function (container,elementType, innerHTML, tosser) {
    if (tosser) {
        var createTosserElement = document.createElement( elementType );
        createTosserElement.innerHTML = innerHTML;
        container.appendChild( createTosserElement );
    }
    else {
        var createNewElement = document.createElement(elementType);
        createNewElement.innerHTML = innerHTML;
        container.appendChild( createNewElement );
    }
};

CookieStore.prototype.addToDom = function () {
    this.cookieDataArray();
    //Create TR element with id as this.elementId
    this.makeTableElement('masterTable','tr',this.elementId);
    //cookietosser code - create same code as above in cookieTosser table
    this.makeTableElement('cookieTossers','tr',this.elementId + 'tosser','');

    //Create row of TD elements containing location name, cookie data, and total
    var container = document.getElementById(this.elementId);
    this.makeHTMLelement(container, 'td','' + this.name + '');

    //cookietosser code - apply the same code to the "elementID+tosser" element
    var tosserContainer = document.getElementById(this.elementId + 'tosser');
    this.makeHTMLelement(tosserContainer,'td','' + this.name + '', true);

    for (var i = 0; i < this.staticCookies.length; i++) { //populate table row with td elements containing each element from staticCookies array
        this.makeHTMLelement(container,'td',this.staticCookies[i]);
        //cookietosser code- does the same as above, but numbers are run through the cookieTossers method
        this.makeHTMLelement(tosserContainer,'td',this.cookieTossers(this.staticCookies[i]),true);
    }
    //calculate total
    for (var i = 0; i < this.staticCookies.length; i++){
        this.cookieSum = this.cookieSum + this.staticCookies[i];
    }
    this.makeHTMLelement(container,'td','' + this.cookieSum + '');
};

//create table headers populated with openHours elements
CookieStore.prototype.tableHeaders = function(){
    var openHours = ['6:00am','7:00am','8:00am','9:00am','10:00am','11:00am','12:00am','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm','8:00pm', 'Total'];

    //create new row for main table, inserting before all other child elements
    var headers = document.getElementById('masterTable');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'headerRow';
    headers.insertBefore(headerTableRow, headers.childNodes[0]);

    //create empty TH element
    var tableHeader = document.getElementById('headerRow');
    var createTableHead = document.createElement( 'th' );
    tableHeader.appendChild( createTableHead );

    //cookietosser code - create cookietosser headers
    var tosserHeaders = document.getElementById('cookieTossers');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'tosserRow';
    tosserHeaders.insertBefore(headerTableRow, tosserHeaders.childNodes[0]);
    //create empty TH element
    var tosserHeader = document.getElementById('tosserRow');
    var createTosserHead = document.createElement( 'th' );
    tosserHeader.appendChild( createTosserHead );

    for (var i = 0; i < openHours.length; i++) {
        var createTableHead = document.createElement( 'th' );
        createTableHead.innerHTML = openHours[i];
        tableHeader.appendChild( createTableHead );
        //cookietosser code - nested if conditional to prevent cookietosser table from loading "Total" column
        if ( i < openHours.length - 1 ){
            var createTosserHead = document.createElement( 'th' );
            createTosserHead.innerHTML = openHours[i];
            tosserHeader.appendChild( createTosserHead );
        }
    }
}; // End of tableHeaders method

//Calculate total cookies in all stores
CookieStore.prototype.totalCookies = function () {
    var totalCounter = 0;
    for (var i = 0; i < cookieStoreArray.length; i++){
        totalCounter = totalCounter + cookieStoreArray[i].cookieSum;
    }
    var container = document.getElementById('total');
    var totalHeader = document.createElement('h3');
    totalHeader.textContent = 'Total cookies in all stores : ' + totalCounter;
    console.log(totalCounter);
    container.appendChild( totalHeader );
};

var cookieStoreArray = [
    new CookieStore('PDX Airport', 23, 65, 6.3, 'pdxairport'),
    new CookieStore('Pioneer Square', 3, 24, 1.2, 'pioneersquare'),
    new CookieStore('Powells', 11, 38, 3.7, 'powells'),
    new CookieStore('St Johns', 20, 38, 2.3, 'stjohns'),
    new CookieStore('Waterfront', 2, 16, 4.6, 'waterfront')
];
cookieStoreArray[0].tableHeaders();
cookieStoreArray[0].totalCookies();<commit_msg>fix random number generator<commit_after>function CookieStore (name, minCustomers, maxCustomers, avgCookiesPerCust, elementId) {
    this.name = name;
    this.minCustomers = minCustomers;
    this.maxCustomers = maxCustomers;
    this.avgCookiesPerCust = avgCookiesPerCust;
    this.elementId = elementId;
    this.staticCookies = [];
    this.cookieSum = 0;
    this.addToDom();
};

CookieStore.prototype.randomCust = function () {
    return (Math.floor(Math.random() * (this.maxCustomers - this.minCustomers + 1)) + this.minCustomers);
};

CookieStore.prototype.avgCookiesPerHour = function () {
    return this.randomCust() * this.avgCookiesPerCust;
};

CookieStore.prototype.cookieDataArray = function () {
    for (var i = 0; i < 15; i++){
        this.staticCookies.push(Math.floor(this.avgCookiesPerHour()));
    }
};

//Cookie tosser requirement formula
CookieStore.prototype.cookieTossers = function (input) {
    if (input < 40){
        return 2;
    }
    else if (input % 20 == 0){
        return input / 20;
    }
    else {
        return Math.floor(input / 20) + 1;
    }
};

//Method to make new table element with optional id
CookieStore.prototype.makeTableElement = function (elementName, elementType, newElementId) {
    var container = document.getElementById(elementName);
    var createNewElement = document.createElement(elementType);
    createNewElement.id = newElementId;
    container.appendChild( createNewElement );
};

//Method to make new TD element with inner HTML content **DOESNT WORK YET**
CookieStore.prototype.makeHTMLelement = function (container,elementType, innerHTML, tosser) {
    if (tosser) {
        var createTosserElement = document.createElement( elementType );
        createTosserElement.innerHTML = innerHTML;
        container.appendChild( createTosserElement );
    }
    else {
        var createNewElement = document.createElement(elementType);
        createNewElement.innerHTML = innerHTML;
        container.appendChild( createNewElement );
    }
};

CookieStore.prototype.addToDom = function () {
    this.cookieDataArray();
    //Create TR element with id as this.elementId
    this.makeTableElement('masterTable','tr',this.elementId);
    //cookietosser code - create same code as above in cookieTosser table
    this.makeTableElement('cookieTossers','tr',this.elementId + 'tosser','');

    //Create row of TD elements containing location name, cookie data, and total
    var container = document.getElementById(this.elementId);
    this.makeHTMLelement(container, 'td','' + this.name + '');

    //cookietosser code - apply the same code to the "elementID+tosser" element
    var tosserContainer = document.getElementById(this.elementId + 'tosser');
    this.makeHTMLelement(tosserContainer,'td','' + this.name + '', true);

    for (var i = 0; i < this.staticCookies.length; i++) { //populate table row with td elements containing each element from staticCookies array
        this.makeHTMLelement(container,'td',this.staticCookies[i]);
        //cookietosser code- does the same as above, but numbers are run through the cookieTossers method
        this.makeHTMLelement(tosserContainer,'td',this.cookieTossers(this.staticCookies[i]),true);
    }
    //calculate total
    for (var i = 0; i < this.staticCookies.length; i++){
        this.cookieSum = this.cookieSum + this.staticCookies[i];
    }
    this.makeHTMLelement(container,'td','' + this.cookieSum + '');
};

//create table headers populated with openHours elements
CookieStore.prototype.tableHeaders = function(){
    var openHours = ['6:00am','7:00am','8:00am','9:00am','10:00am','11:00am','12:00am','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm','8:00pm', 'Total'];

    //create new row for main table, inserting before all other child elements
    var headers = document.getElementById('masterTable');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'headerRow';
    headers.insertBefore(headerTableRow, headers.childNodes[0]);

    //create empty TH element
    var tableHeader = document.getElementById('headerRow');
    var createTableHead = document.createElement( 'th' );
    tableHeader.appendChild( createTableHead );

    //cookietosser code - create cookietosser headers
    var tosserHeaders = document.getElementById('cookieTossers');
    var headerTableRow = document.createElement( 'tr' );
    headerTableRow.id = 'tosserRow';
    tosserHeaders.insertBefore(headerTableRow, tosserHeaders.childNodes[0]);
    //create empty TH element
    var tosserHeader = document.getElementById('tosserRow');
    var createTosserHead = document.createElement( 'th' );
    tosserHeader.appendChild( createTosserHead );

    for (var i = 0; i < openHours.length; i++) {
        var createTableHead = document.createElement( 'th' );
        createTableHead.innerHTML = openHours[i];
        tableHeader.appendChild( createTableHead );
        //cookietosser code - nested if conditional to prevent cookietosser table from loading "Total" column
        if ( i < openHours.length - 1 ){
            var createTosserHead = document.createElement( 'th' );
            createTosserHead.innerHTML = openHours[i];
            tosserHeader.appendChild( createTosserHead );
        }
    }
}; // End of tableHeaders method

//Calculate total cookies in all stores
CookieStore.prototype.totalCookies = function () {
    var totalCounter = 0;
    for (var i = 0; i < cookieStoreArray.length; i++){
        totalCounter = totalCounter + cookieStoreArray[i].cookieSum;
    }
    var container = document.getElementById('total');
    var totalHeader = document.createElement('h3');
    totalHeader.textContent = 'Total cookies in all stores : ' + totalCounter;
    console.log(totalCounter);
    container.appendChild( totalHeader );
};

var cookieStoreArray = [
    new CookieStore('PDX Airport', 23, 65, 6.3, 'pdxairport'),
    new CookieStore('Pioneer Square', 3, 24, 1.2, 'pioneersquare'),
    new CookieStore('Powells', 11, 38, 3.7, 'powells'),
    new CookieStore('St Johns', 20, 38, 2.3, 'stjohns'),
    new CookieStore('Waterfront', 2, 16, 4.6, 'waterfront')
];
cookieStoreArray[0].tableHeaders();
cookieStoreArray[0].totalCookies();<|endoftext|>


<commit_before>// Print all of the news items on Hacker News
var jsdom = require("jsdom");
var State = require("./state");
var request = require('request');
var app = require("express")();

var messageEndpoint = "/sms";
var clearEndpoint = "/clear";
var baseUrl = "http://localhost:80/";

var serviceUrl = "http://news.ycombinator.com/";
var serviceScripts = ["http://code.jquery.com/jquery.js"];
var activeUsers = {};

var handleClear = function(req, res) {
  var user = req.query.user;
  // If no user was given or it doesn't exist in active users
  if (!user || (user && !(user in activeUsers))) {
    res.send(400);
  }
  delete activeUsers[user];
  res.status(200).end();
};

var handleMessage = function(req, res) {
  console.log("Getting a request");
  var number = req.query.number;
  var message = req.query.message;

  // Invalid data set from main server
  if (!message || !number) {
    console.log("Message or number doesn't exist");
    res.status(400).end();
    return;
  }
  console.log("No error so far -- 1")

  var response = handleScrape(message, number, function(reply) {
    console.log("Got the content", reply);
    request(baseUrl + "sendsms?message=" + reply +
			"&number=" + encodeURIComponent(number)
    );
    res.status(200).end();
  });
};

var handleScrape = function(message, number, callback) {
  if (!(number in activeUsers)) {
    activeUsers[number] = new State();
  }

  var state = activeUsers[number];
  jsdom.env({
    url: serviceUrl,
    scripts: serviceScripts,
    done: function (errors, window) {
      var $ = window.$;
      var articles = $("td.title:not(:last) a");
      // Grab 5 pages and increment counter
      var elements = articles.slice(
        state.getPage(),
        state.getPage()+state.getNumSend()
      );
      state.incrementPage();

      // Get only the text
      var reply = $.map(elements, function(elem) {
        return $(elem).text();
      });
      callback(reply.join("\n"));
    }
  });
};
/* For testing purposes
handleMessage("lol", "123456", function(reply) {
  for (var i=0; i<reply.length; i++) {
    console.log(reply[i]);
  }
});*/

app.get(messageEndpoint, handleMessage);
app.get(clearEndpoint, handleClear);
app.get("/", function(req, res) {
  console.log("HELOHLEHOELH");
});

app.listen(3001);
<commit_msg>Cleaned logging<commit_after>// Print all of the news items on Hacker News
var jsdom = require("jsdom");
var State = require("./state");
var request = require('request');
var app = require("express")();

var messageEndpoint = "/sms";
var clearEndpoint = "/clear";
var baseUrl = "http://localhost:80/";

var serviceUrl = "http://news.ycombinator.com/";
var serviceScripts = ["http://code.jquery.com/jquery.js"];
var activeUsers = {};

var handleClear = function(req, res) {
  var user = req.query.user;
  // If no user was given or it doesn't exist in active users
  if (!user || (user && !(user in activeUsers))) {
    res.send(400);
  }
  delete activeUsers[user];
  res.status(200).end();
};

var handleMessage = function(req, res) {
  var number = req.query.number;
  var message = req.query.message;

  // Invalid data set from main server
  if (!message || !number) {
    res.status(400).end();
    return;
  }

  var response = handleScrape(message, number, function(reply) {
    request(baseUrl + "sendsms?message=" + reply +
			"&number=" + encodeURIComponent(number)
    );
    res.status(200).end();
  });
};

var handleScrape = function(message, number, callback) {
  if (!(number in activeUsers)) {
    activeUsers[number] = new State();
  }

  var state = activeUsers[number];
  jsdom.env({
    url: serviceUrl,
    scripts: serviceScripts,
    done: function (errors, window) {
      var $ = window.$;
      var articles = $("td.title:not(:last) a");
      // Grab 5 pages and increment counter
      var elements = articles.slice(
        state.getPage(),
        state.getPage()+state.getNumSend()
      );
      state.incrementPage();

      // Get only the text
      var reply = $.map(elements, function(elem) {
        return $(elem).text();
      });
      callback(reply.join("\n"));
    }
  });
};
/* For testing purposes
handleMessage("lol", "123456", function(reply) {
  for (var i=0; i<reply.length; i++) {
    console.log(reply[i]);
  }
});*/

app.get(messageEndpoint, handleMessage);
app.get(clearEndpoint, handleClear);

app.listen(3001);
<|endoftext|>


<commit_before>'use strict';
exports.info = {
  desc: 'Embeds a Giphy gif from random top 10 filtered results.',
  usage: '<search>',
  aliases: [],
};

const utils = require('../utilities');
const logger = require('winston');
const path = require('path');

// Gets G rated random giphy result from the supplied query
exports.run = (client, msg, params = []) => {
  // Exit if no search query was passed
  if (params.length === 0) {
    logger.debug('No parameters passed to giphy');
    return;
  }

  // Join params into a string
  const query = params.join(' ');
  // Create search uri
  const uri = `http://api.giphy.com/v1/gifs/search?q=${query}&api_key=dc6zaTOxFJmzC&fmt=json&limit=100`;

  // Fetch Giphy
  utils.time(msg, 'cpu');
  utils.jsonRequest(uri)
    .then(body => {
      utils.time(msg, 'io');
      if (body.data.length === 0) {
        msg.channel.sendMessage(`No Giphy results found for \`\`${query}\`\``);
        utils.finish(msg, exports.name);
        return;
      }
      // Filter out rated r results and those to large to embed
      const filtered = body.data
        .filter(g => g.rating !== 'r' && g.type === 'gif')
        .filter(g => g.images.original && g.images.original.size < 8000000);
      logger.debug('giphy results:', body.data.length, 'filtered results:', filtered.length);
      // No results remain after filtering
      if (filtered.length === 0) {
        msg.channel.sendMessage(`No Giphy results found for \`\`${query}\`\` after filtering for size and content.`);
        utils.finish(msg, exports.name);
        return;
      }
      // Set the max index to get random gif from to 10 or max results if less
      const max = filtered.length > 10 ? 10 : filtered.length;
      logger.debug('max index to search to', max);
      // Get random index
      const r = utils.getRandomInt(0, max);
      logger.debug('random index chosen', r);
      // Get gif uri
      const image = filtered[r].images.original.url;
      // Parse name for discord image name property
      const name = path.parse(image).base;
      logger.debug(image, name);
      msg.channel.sendMessage(`\`\`${query}\`\`\n${image}`);
      utils.finish(msg, exports.name);
    })
    .catch(err => {
      utils.time(msg, 'io');
      logger.error(`Error getting Giphy results for: '${query}'`, err);
      msg.channel.sendMessage(`Error getting Giphy results for:\`\`${query}\`\``);
      utils.finish(msg, exports.name);
    });
};
<commit_msg>Promise giphy command<commit_after>'use strict';
exports.info = {
  desc: 'Embeds a Giphy gif from random top 10 filtered results.',
  usage: '<search>',
  aliases: [],
};

const utils = require('../utilities');
const logger = require('winston');
const path = require('path');

// Gets G rated random giphy result from the supplied query
exports.run = function Giphy(client, msg, params = []) {
  return new Promise(async(resolve, reject) => {
    // Exit if no search query was passed
    if (params.length === 0) {
      logger.debug('No parameters passed to giphy');
      resolve();
      return;
    }
    // Join params into a string
    const query = params.join(' ');
    // Create search uri
    const uri = `http://api.giphy.com/v1/gifs/search?q=${query}&api_key=dc6zaTOxFJmzC&fmt=json&limit=100`;
    utils.time(msg, 'cpu');
    try {
      const giphy = await utils.jsonRequest(uri);
      utils.time(msg, 'io');
      if (giphy.data.length === 0) {
        msg.channel.sendMessage(`No Giphy results found for \`\`${query}\`\``);
        resolve();
        return;
      }
      // Filter out rated r results and those to large to embed
      const filtered = giphy.data
        .filter(g => g.rating !== 'r' && g.type === 'gif')
        .filter(g => g.images.original && g.images.original.size < 8000000);
      logger.debug('giphy results:', giphy.data.length, 'filtered results:', filtered.length);
      // No results remain after filtering
      if (filtered.length === 0) {
        msg.channel.sendMessage(`No Giphy results found for \`\`${query}\`\` after filtering for size and content.`);
        resolve();
        return;
      }
      // Set the max index to get random gif from to 10 or max results if less
      const max = filtered.length > 10 ? 10 : filtered.length;
      logger.debug('max index to search to', max);
      // Get random index
      const r = utils.getRandomInt(0, max);
      logger.debug('random index chosen', r);
      // Get gif uri
      const image = filtered[r].images.original.url;
      // Parse name for discord image name property
      const name = path.parse(image).base;
      logger.debug(image, name);
      msg.channel.sendMessage(`\`\`${query}\`\`\n${image}`);
      resolve();
    } catch (e) {
      logger.error(`Error getting Giphy results for: '${query}'`, e);
      msg.channel.sendMessage(`Error getting Giphy results for:\`\`${query}\`\``);
      reject(e);
    }
  });
};
<|endoftext|>


<commit_before>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
import { isEmpty } from '../common.js';
const log = require('../configs/log').log;
import formdata from 'form-data';

export default {
    name: 'media',
    create: (req, resource, params, config, emptyObject, callback) => {
        if (resource === 'media.create') {
            // It was hard to send a files data to the service.
            // giving the file as parameter to here is not possible because it gets parsed before send via https
            // FileReader does not create Array buffers (is just undefined)
            // Not all outputs of FileReader are accepted by the API
            // form-data could not be used because the API does not expect multiform

            //NOTE available but currently not used params: copyrightHolderURL and copyrightAdditions
            let holder = '';
            //if(context.getUser() && context.getUser().username) holder = context.getUser().username + ', id=' + params.userID; else holder = params.userID;
            if (params.license === 'CC0')
                holder = '';
            else if (params.copyrightHolder === '' && params.copyrightHolder === '')
                holder = '&copyrightHolder=' + encodeURIComponent(params.userID); //NOTE prefer to use a real world name or the username at SlideWiki + it's ID
            else
                holder = '&copyrightHolder=' + encodeURIComponent(params.copyrightHolder); //NOTE prefer to use a real world name or the username at SlideWiki + it's ID

            let url = Microservices.file.uri + '/v2/picture?' +
                'license=' + encodeURIComponent(params.license) +
                 holder +
                '&title=' + encodeURIComponent(params.title) +
                '&altText='+encodeURIComponent(params.text);
            let headers = {
                '----jwt----': params.jwt,
                'content-type': params.type
            };
            rp.post({
                uri: url,
                body: new Buffer(params.bytes.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''), 'base64'),
                headers: headers,
                json: false
            })
                .then((res) => {
                    console.log('response from saving image:', res);
                    //callback(null, res);
                    callback(null, JSON.parse(res));
                })
                .catch((err) => {
                    console.log('Error while saving image', (err.response) ? {body: err.response.body, headers: err.response.request.headers} : err);
                    callback(err, null);
                });
        }
        else if (resource === 'media.uploadProfilePicture') {
            let url = Microservices.file.uri + '/profilepicture/' + params.username;
            let headers = {
                '----jwt----': params.jwt,
                'content-type': params.type
            };
            rp.put({
                uri: url,
                body: new Buffer(params.bytes.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''), 'base64'),
                headers: headers
            })
                .then((res) => {
                    // console.log('media: response from saving image:', res);
                    callback(null, Microservices.file.uri + JSON.parse(res).url);
                })
                .catch((err) => {
                    // console.log('media: Error while saving image', (err.response) ? {body: err.response.body, headers: err.response.request.headers} : err);
                    callback(err, null);
                });
        }
    }
};
<commit_msg>Encoding body of media.create service to send proper post request to the file service in case of SVG graphics.<commit_after>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
import { isEmpty } from '../common.js';
const log = require('../configs/log').log;
import formdata from 'form-data';

export default {
    name: 'media',
    create: (req, resource, params, config, emptyObject, callback) => {
        if (resource === 'media.create') {
            // It was hard to send a files data to the service.
            // giving the file as parameter to here is not possible because it gets parsed before send via https
            // FileReader does not create Array buffers (is just undefined)
            // Not all outputs of FileReader are accepted by the API
            // form-data could not be used because the API does not expect multiform

            //NOTE available but currently not used params: copyrightHolderURL and copyrightAdditions
            let holder = '';
            //if(context.getUser() && context.getUser().username) holder = context.getUser().username + ', id=' + params.userID; else holder = params.userID;
            if (params.license === 'CC0')
                holder = '';
            else if (params.copyrightHolder === '' && params.copyrightHolder === '')
                holder = '&copyrightHolder=' + encodeURIComponent(params.userID); //NOTE prefer to use a real world name or the username at SlideWiki + it's ID
            else
                holder = '&copyrightHolder=' + encodeURIComponent(params.copyrightHolder); //NOTE prefer to use a real world name or the username at SlideWiki + it's ID

            let url = Microservices.file.uri + '/v2/picture?' +
                'license=' + encodeURIComponent(params.license) +
                 holder +
                '&title=' + encodeURIComponent(params.title) +
                '&altText='+encodeURIComponent(params.text);
            let headers = {
                '----jwt----': params.jwt,
                'content-type': params.type
            };
            let body = params.type === 'image/svg+xml' ? params.bytes : new Buffer(params.bytes.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''), 'base64');
            rp.post({
                uri: url,
                body: body,
                headers: headers,
                json: false
            })
                .then((res) => {
                    console.log('response from saving image:', res);
                    //callback(null, res);
                    callback(null, JSON.parse(res));
                })
                .catch((err) => {
                    console.log('Error while saving image', (err.response) ? {body: err.response.body, headers: err.response.request.headers} : err);
                    callback(err, null);
                });
        }
        else if (resource === 'media.uploadProfilePicture') {
            let url = Microservices.file.uri + '/profilepicture/' + params.username;
            let headers = {
                '----jwt----': params.jwt,
                'content-type': params.type
            };
            rp.put({
                uri: url,
                body: new Buffer(params.bytes.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''), 'base64'),
                headers: headers
            })
                .then((res) => {
                    // console.log('media: response from saving image:', res);
                    callback(null, Microservices.file.uri + JSON.parse(res).url);
                })
                .catch((err) => {
                    // console.log('media: Error while saving image', (err.response) ? {body: err.response.body, headers: err.response.request.headers} : err);
                    callback(err, null);
                });
        }
    }
};
<|endoftext|>


<commit_before>import { RelayConnectionTypesSpec } from '../../src/rules/relay_connection_types_spec';
import { expectFailsRule, expectPassesRule } from '../assertions';

describe('RelayConnectionTypesSpec  rule', () => {
  it('catches object types that have missing fields', () => {
    expectFailsRule(
      RelayConnectionTypesSpec,
      `
      type BadConnection {
        a: String
      }
    `,
      [
        {
          message:
            'Connection `BadConnection` is missing the following fields: pageInfo, edges.',
          locations: [{ line: 2, column: 7 }],
        },
      ]
    );
  });

  it('accepts object types with the correct fields.', () => {
    expectPassesRule(
      RelayConnectionTypesSpec,
      `
      type PageInfo {
        a: String
      }

      type Edge {
        a: String
      }

      type BetterConnection {
        pageInfo: PageInfo!
        edges: [Edge]
      }

      type AnotherConnection {
        pageInfo: PageInfo!
        edges: [Edge]!
      }

      type AnotherGoodConnection {
        pageInfo: PageInfo!
        edges: [Edge!]!
      }

      type AgainAnotherConnection {
        pageInfo: PageInfo!
        edges: [Edge!]
      }
    `
    );
  });

  it('catches edges fields that are not lists of edges', () => {
    expectFailsRule(
      RelayConnectionTypesSpec,
      `
      type PageInfo {
        a: String
      }

      type Edge {
        a: String
      }

      type BadConnection {
        pageInfo: PageInfo!
        edges: String
      }

      type AnotherBadConnection {
        pageInfo: String
        edges: [Edge]
      }

      type YetAnotherBadConnection {
        pageInfo: String!
        edges: [Edge]
      }
    `,
      [
        {
          message:
            'The `BadConnection.edges` field must return a list of edges not `String`.',
          locations: [{ line: 10, column: 7 }],
        },
        {
          message:
            'The `AnotherBadConnection.pageInfo` field must return a non-null `PageInfo` object not `String`',
          locations: [
            {
              column: 7,
              line: 15,
            },
          ],
        },
        {
          message:
            'The `YetAnotherBadConnection.pageInfo` field must return a non-null `PageInfo` object not `String!`',
          locations: [
            {
              column: 7,
              line: 20,
            },
          ],
        },
      ]
    );
  });

  it('ignores types that are not objects', () => {
    expectPassesRule(
      RelayConnectionTypesSpec,
      `
      scalar A

      interface B {
        a: String
      }

      union C = F

      enum D {
        SOMETHING
      }

      input E {
        a: String!
      }

      type F {
        a: String!
      }
    `
    );
  });

  it('catches types that end in Connection but that are not objects', () => {
    expectFailsRule(
      RelayConnectionTypesSpec,
      `
      scalar AConnection

      interface BConnection {
        a: String!
      }

      type F {
        a: String!
      }
      union CConnection = F

      enum DConnection {
        SOMETHING
      }

      input EConnection {
        a: String!
      }
      `,
      [
        {
          locations: [
            {
              column: 7,
              line: 2,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `AConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 4,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `BConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 11,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `CConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 13,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `DConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 17,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `EConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
      ]
    );
  });
});
<commit_msg>Fix spacing<commit_after>import { RelayConnectionTypesSpec } from '../../src/rules/relay_connection_types_spec';
import { expectFailsRule, expectPassesRule } from '../assertions';

describe('RelayConnectionTypesSpec rule', () => {
  it('catches object types that have missing fields', () => {
    expectFailsRule(
      RelayConnectionTypesSpec,
      `
      type BadConnection {
        a: String
      }
    `,
      [
        {
          message:
            'Connection `BadConnection` is missing the following fields: pageInfo, edges.',
          locations: [{ line: 2, column: 7 }],
        },
      ]
    );
  });

  it('accepts object types with the correct fields.', () => {
    expectPassesRule(
      RelayConnectionTypesSpec,
      `
      type PageInfo {
        a: String
      }

      type Edge {
        a: String
      }

      type BetterConnection {
        pageInfo: PageInfo!
        edges: [Edge]
      }

      type AnotherConnection {
        pageInfo: PageInfo!
        edges: [Edge]!
      }

      type AnotherGoodConnection {
        pageInfo: PageInfo!
        edges: [Edge!]!
      }

      type AgainAnotherConnection {
        pageInfo: PageInfo!
        edges: [Edge!]
      }
    `
    );
  });

  it('catches edges fields that are not lists of edges', () => {
    expectFailsRule(
      RelayConnectionTypesSpec,
      `
      type PageInfo {
        a: String
      }

      type Edge {
        a: String
      }

      type BadConnection {
        pageInfo: PageInfo!
        edges: String
      }

      type AnotherBadConnection {
        pageInfo: String
        edges: [Edge]
      }

      type YetAnotherBadConnection {
        pageInfo: String!
        edges: [Edge]
      }
    `,
      [
        {
          message:
            'The `BadConnection.edges` field must return a list of edges not `String`.',
          locations: [{ line: 10, column: 7 }],
        },
        {
          message:
            'The `AnotherBadConnection.pageInfo` field must return a non-null `PageInfo` object not `String`',
          locations: [
            {
              column: 7,
              line: 15,
            },
          ],
        },
        {
          message:
            'The `YetAnotherBadConnection.pageInfo` field must return a non-null `PageInfo` object not `String!`',
          locations: [
            {
              column: 7,
              line: 20,
            },
          ],
        },
      ]
    );
  });

  it('ignores types that are not objects', () => {
    expectPassesRule(
      RelayConnectionTypesSpec,
      `
      scalar A

      interface B {
        a: String
      }

      union C = F

      enum D {
        SOMETHING
      }

      input E {
        a: String!
      }

      type F {
        a: String!
      }
    `
    );
  });

  it('catches types that end in Connection but that are not objects', () => {
    expectFailsRule(
      RelayConnectionTypesSpec,
      `
      scalar AConnection

      interface BConnection {
        a: String!
      }

      type F {
        a: String!
      }
      union CConnection = F

      enum DConnection {
        SOMETHING
      }

      input EConnection {
        a: String!
      }
      `,
      [
        {
          locations: [
            {
              column: 7,
              line: 2,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `AConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 4,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `BConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 11,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `CConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 13,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `DConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
        {
          locations: [
            {
              column: 7,
              line: 17,
            },
          ],
          message:
            'Types that end in `Connection` must be an object type as per the relay spec. `EConnection` is not an object type.',
          path: [undefined],
          ruleName: 'relay-connection-types-spec',
        },
      ]
    );
  });
});
<|endoftext|>


<commit_before>'use strict';

describe('Directive: composeDirectives', function () {

    // load the directive's module
    beforeEach(module('svardMailApp'));

    var element,
        scope;

    beforeEach(inject(function ($rootScope) {
        scope = $rootScope.$new();
    }));

    it('should make hidden element visible', inject(function ($compile) {

    }));
});
<commit_msg>Added test for the composeDirective.<commit_after>'use strict';

describe('ComposeDirectives', function () {

    // load the directive's module
    beforeEach(module('svardMailApp'));

    var element,
        scope;

    beforeEach(inject(function ($rootScope, $compile) {
        scope = $rootScope.$new();
        scope.body = {text: 'The mail body text'};
        element = angular.element('<editable ng-model="body.text"></editable>');
        element = $compile(element)(scope);
        scope.$digest();
    }));

    it('should data-bind from model to view', function () {
        expect(element.text()).toEqual(scope.body.text);
    });
});
<|endoftext|>


<commit_before>import jsonfile from 'jsonfile';
import mongoose from 'mongoose';
import path from 'path';

const jsonPath = path.join(__dirname, '..', '..', 'config.json');
const config = jsonfile.readFileSync(jsonPath);
mongoose.connect(config.MONGODB_PATH);

const newVideoSchema = new mongoose.Schema({
  id: Number,
  code: String,
  search_code: String,
  title: String,
  models: String,
  count: Number,
  url: String,
  img_url: String,
});

const videoSchema = new mongoose.Schema({
  id: Number,
  code: String,
  search_code: String,
  title: String,
  models: String,
  count: Number,
  url: String,
  img_url: String,
});

const logSchema = new mongoose.Schema({
  successOrNot: String,
  senderID: String,
  messageText: String,
  result: String,
});

const subscribeIdSchema = new mongoose.Schema({
  senderID: String,
});

export const VideoCollection = mongoose.model('Video', videoSchema);
export const NewVideoCollection = mongoose.model('NewVideo', newVideoSchema);
export const LogCollection = mongoose.model('Log', logSchema);
export const SubscribeIdCollection = mongoose.model('SubscribeId', subscribeIdSchema);
<commit_msg>change type<commit_after>import jsonfile from 'jsonfile';
import mongoose from 'mongoose';
import path from 'path';

const jsonPath = path.join(__dirname, '..', '..', 'config.json');
const config = jsonfile.readFileSync(jsonPath);
mongoose.connect(config.MONGODB_PATH);

const newVideoSchema = new mongoose.Schema({
  id: Number,
  code: String,
  search_code: String,
  title: String,
  models: String,
  count: Number,
  url: String,
  img_url: String,
});

const videoSchema = new mongoose.Schema({
  id: Number,
  code: String,
  search_code: String,
  title: String,
  models: String,
  count: Number,
  url: String,
  img_url: String,
});

const logSchema = new mongoose.Schema({
  successOrNot: Boolean,
  senderID: String,
  messageText: String,
  result: String,
});

const subscribeIdSchema = new mongoose.Schema({
  senderID: String,
});

export const VideoCollection = mongoose.model('Video', videoSchema);
export const NewVideoCollection = mongoose.model('NewVideo', newVideoSchema);
export const LogCollection = mongoose.model('Log', logSchema);
export const SubscribeIdCollection = mongoose.model('SubscribeId', subscribeIdSchema);
<|endoftext|>


<commit_before>const path = require('path');
const helmet = require('helmet');
const http = require('http');
const https = require('https');
const compression = require('compression');
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = require('@jeneric/app');

class Server {

    constructor() {

        this.config = app.config.server;

        this.pathToKeyPem = path.join(app.config.app.path, 'config/key.pem');
        this.pathToCertPem = path.join(app.config.app.path, 'config/cert.pem');

        this.express = express();

        this.express.enable('strict routing');
        this.express.use(helmet());
        this.express.set('view engine', 'pug');
        this.express.use(compression());

        this.express.set('views', path.join(app.config.app.path, 'view'));
        this.express.use(cookieParser());
        this.express.use(bodyParser.urlencoded({ extended: false }));

        let publicPath = path.join(app.config.app.path, 'public');

        if (app.util.fs.isDirectorySync(publicPath)) {
            this.express.use(express.static(publicPath, { maxAge: '30 days' }));
        }

        // add access middleware
        let middleware = {
            access: new (require('@jeneric/app/src/middleware/access'))(),
            error: new (require('@jeneric/app/src/middleware/error'))(),
            notFound: new (require('@jeneric/app/src/middleware/not-found'))()
        };

        this.express.use(middleware.access.handle);

        // add custom middleware and routes
        this.addRoutes(this.config.routes, []);

        // add error middleware
        this.express.use(middleware.error.handle);

        // add notFound middleware
        this.express.use(middleware.notFound.handle);

    }

    get routes() {
        return this.config.routes;
    }

    addRoutes(routes) {

        for (let routeName in routes) {

            let routeConfig = routes[routeName];

            // sanitize routeConfig
            if('string' !== typeof routeConfig.path) routeConfig.path = '/' + routeName;
            if('object' !== typeof routeConfig.methods) routeConfig.methods = ['get'];
            if('object' !== typeof routeConfig.handler) {

                let pathToHandler = path.join(app.config.app.path, 'src/handler', routeName);

                let handler = require(pathToHandler);

                console.log(handler);
            }

            return;

            let handler = undefined;

            try {
                handler = parts.reduce((o, i) => o[i], jeneric.handler);
            } catch (err) {
                handler = undefined;
            }

            if (undefined === handler) {
                for (let k = 1; k <= parts.length; k++) {

                    let firstParts = parts.slice(0);
                    let lastParts = firstParts.splice(-k, k);

                    for (let l = 1; l < lastParts.length; l++) {
                        lastParts[l] = lastParts[l].charAt(0).toUpperCase() + lastParts[l].slice(1);
                    }

                    firstParts.push(lastParts.join(''));

                    try {
                        handler = firstParts.reduce((o, i) => o[i], jeneric.handler);
                    } catch (err) {
                        handler = undefined;
                    }

                    if ('object' === typeof handler) break;

                }
            }

            if (null === handler || 'object' !== typeof handler || 'function' !== typeof handler.handle) {
                jeneric.logger.warning(`route ${routeName} has no handler`);
                continue;
            }

            if ('object' !== typeof route.methods || null === route.methods) {
                jeneric.logger.warning(`route ${routeName} has no methods`);
                continue;
            }

            // register middlewares
            for (let m in this.config.middleware) {

                let middlewareName = this.config.middleware[m];

                switch (middlewareName) {
                    case 'roles':
                        if ('object' === typeof route.roles) {
                            for (let method of route.methods) {
                                this._app[method](route.path, jeneric.middleware[middlewareName].handle.bind(jeneric.middleware[middlewareName]));
                            }
                        }
                        break;
                    case 'handler':
                        for (let method of route.methods) {
                            this._app[method](route.path, handler.handle.bind(handler));
                        }
                        break;
                    default:
                        this._app.use(route.path, jeneric.middleware[middlewareName].handle.bind(jeneric.middleware[middlewareName]));
                        break;
                }
            }

        }
    }

    init() {

        let server = null;

        // check certificates
        if (!app.util.fs.isFileSync(this.pathToKeyPem) || !app.util.fs.isFileSync(this.pathToCertPem)) {
            app.logger.warning(`can not start server: .key and .pem files missing`, [this.pathToKeyPem, this.pathToCertPem]);

            server = this.express;

        } else {
            // start https server
            server = https.createServer({
                key: app.util.fs.readFileSync(this.pathToKeyPem),
                cert: app.util.fs.readFileSync(this.pathToCertPem)
            }, this.express);
        }

        server.listen(this.config.port);

        app.logger.notice(`server started with port ${this.config.port}`);
    }
}

module.exports = Server;
<commit_msg>update server module<commit_after>const path = require('path');
const helmet = require('helmet');
const http = require('http');
const https = require('https');
const compression = require('compression');
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = require('@jeneric/app');

class Server {

    constructor() {

        this.config = app.config.server;

        this.pathToKeyPem = path.join(app.config.app.path, 'config/key.pem');
        this.pathToCertPem = path.join(app.config.app.path, 'config/cert.pem');

        this.express = express();

        this.express.enable('strict routing');
        this.express.use(helmet());
        this.express.set('view engine', 'pug');
        this.express.use(compression());

        this.express.set('views', path.join(app.config.app.path, 'view'));
        this.express.use(cookieParser());
        this.express.use(bodyParser.urlencoded({ extended: false }));

        let publicPath = path.join(app.config.app.path, 'public');

        if (app.util.fs.isDirectorySync(publicPath)) {
            this.express.use(express.static(publicPath, { maxAge: '30 days' }));
        }

        // add access middleware
        let middleware = {
            access: new (require('@jeneric/app/src/middleware/access'))(),
            error: new (require('@jeneric/app/src/middleware/error'))(),
            notFound: new (require('@jeneric/app/src/middleware/not-found'))()
        };

        this.express.use(middleware.access.handle);

        // add custom middleware and routes
        this.addRoutes(this.config.routes, []);

        // add error middleware
        this.express.use(middleware.error.handle);

        // add notFound middleware
        this.express.use(middleware.notFound.handle);

    }

    get routes() {
        return this.config.routes;
    }

    addRoutes(routes) {

        for (let routeName in routes) {

            let route = routes[routeName];
            let handler = null;

            // sanitize routeConfig
            if('string' !== typeof route.path) route.path = '/' + routeName;
            if('object' !== typeof route.methods) route.methods = ['get'];

            if('object' !== typeof route.handler) {
                let pathToHandler = path.join(app.config.app.path, 'src/handler', routeName);
                handler = new (require(pathToHandler))();
            } else{
                handler = route.handler;
            }

            if('function' !== typeof handler.handle) {
                throw new Error(`${routeName} has no valid handler`);
            }

            // register middlewares
            for (let m in this.config.middleware) {

                let middlewareName = this.config.middleware[m];
                let middleware = null;

                switch (middlewareName) {
                    case 'roles':
                        middleware = new (require(path.join(app.config.app.path, 'src/middleware', middlewareName)))();

                        if ('object' === typeof route.roles) {
                            for (let method of route.methods) {
                                this.express[method](route.path, middleware.handle);
                            }
                        }
                        break;
                    case 'handler':
                        for (let method of route.methods) {
                            this.express[method](route.path, handler.handle);
                        }
                        break;
                    default:
                        middleware = new (require(path.join(app.config.app.path, 'src/middleware', middlewareName)))();
                        this.express.use(route.path, middleware.handle);
                        break;
                }
            }

        }
    }

    init() {

        let server = null;

        // check certificates
        if (!app.util.fs.isFileSync(this.pathToKeyPem) || !app.util.fs.isFileSync(this.pathToCertPem)) {
            app.logger.warning(`can not start server: .key and .pem files missing`, [this.pathToKeyPem, this.pathToCertPem]);

            server = this.express;

        } else {
            // start https server
            server = https.createServer({
                key: app.util.fs.readFileSync(this.pathToKeyPem),
                cert: app.util.fs.readFileSync(this.pathToCertPem)
            }, this.express);
        }

        server.listen(this.config.port);

        app.logger.notice(`server started with port ${this.config.port}`);
    }
}

module.exports = Server;
<|endoftext|>


<commit_before>var _         = require('_'),
    overload  = require('overload'),
    O         = overload.O,

    _selector = require('./selectors'),
    _array    = require('./array'),
    _utils    = require('../utils'),
    _order    = require('../order'),

    _data     = require('./data'),

    parser    = require('../D/parser'),
    utils     = require('../utils');

var _empty = function(arr) {
        var idx = 0, length = arr.length;
        for (; idx < length; idx++) {

            var elem = arr[idx],
                descendants = elem.querySelectorAll('*'),
                i = descendants.length,
                desc;
            while (i--) {
                desc = descendants[i];
                _data.destroyData(desc);
            }

            elem.innerHTML = '';
        }
    },

    _remove = function(arr) {
        var idx = 0, length = arr.length,
            elem, parent;
        for (; idx < length; idx++) {
            elem = arr[idx];
            if (elem && (parent = elem.parentNode)) {
                _data.destroyData(elem);
                parent.removeChild(elem);
            }
        }
    },

    _detach = function(arr) {
        var idx = 0, length = arr.length,
            elem, parent;
        for (; idx < length; idx++) {
            elem = arr[idx];
            if (elem && (parent = elem.parentNode)) {
                parent.removeChild(elem);
            }
        }
    },

    _clone = function(elem) {
        return elem.cloneNode(true);
    },

    _stringToFrag = function(str) {
        var frag = document.createDocumentFragment();
        frag.textContent = str;
        return frag;
    },

    _appendPrependFunc = function(d, fn, pender) {
        _.each(d, function(elem, idx) {
            var result = fn.call(elem, idx, elem.innerHTML);

            if (!_.exists(result)) {

                // do nothing

            } else if (_.isString(result)) {

                if (utils.isHTML(value)) {
                    _appendPrependArrayToElem(elem, parser.parseHtml(value), pender);
                    return this;
                }

                pender(elem, _stringToFrag(result));

            } else if (_.isElement(result)) {

                pender(elem, result);

            } else if (_.isNodeList(result) || result instanceof D) {

                _appendPrependArrayToElem(elem, result, pender);

            } else {
                // do nothing
            }
        });
    },
    _appendPrependMergeArray = function(arrOne, arrTwo, pender) {
        var idx = 0, length = arrOne.length;
        for (; idx < length; idx++) {
            var i = 0, len = arrTwo.length;
            for (; i < len; i++) {
                pender(arrOne[idx], arrTwo[i]);
            }
        }
    },
    _appendPrependElemToArray = function(arr, elem, pender) {
        _.each(arr, function(arrElem) {
            pender(arrElem, elem);
        });
    },
    _appendPrependArrayToElem = function(elem, arr, pender) {
        _.each(arr, function(arrElem) {
            pender(elem, arrElem);
        });
    },

    _append = function(base, elem) {
        if (!base || !elem || !_.isElement(elem)) { return; }
        base.appendChild(elem);
    },
    _prepend = function(base, elem) {
        if (!base || !elem || !_.isElement(elem)) { return; }
        base.insertBefore(elem, base.firstChild);
    };

module.exports = {
    append  : _append,
    prepend : _prepend,

    fn: {
        clone: function() {
            return _.fastmap(this.slice(), function(elem) {
                return _clone(elem);
            });
        },

        append: overload()
            .args(String)
            .use(function(value) {
                if (utils.isHtml(value)) {
                    _appendPrependMergeArray(this, parser.parseHtml(value), _append);
                    return this;
                }

                _appendPrependElemToArray(this, _stringToFrag(value), _append);

                return this;
            })

            .args(Number)
            .use(function(value) {
                _appendPrependElemToArray(this, _stringToFrag('' + value), _append);
                return this;
            })

            .args(Function)
            .use(function(fn) {
                _appendPrependFunc(this, fn, _append);
                return this;
            })

            .args(Element)
            .use(function(elem) {
                _appendPrependElemToArray(this, elem, _append);
                return this;
            })

            .args(O.collection)
            .use(function(arr) {
                _appendPrependMergeArray(this, arr, _append);
                return this;
            })

            .expose(),

        // TODO: These methods
        before: function() { return this; },
        after: function() { return this; },
        insertBefore: function() { return this; },
        insertAfter: function() { return this; },

        appendTo: overload()
            .args(O.D)
            .use(function(d) {
                d.append(this);
                return this;
            })

            .fallback(function(obj) {
                D(obj).append(this);
                return this;
            })

            .expose(),

        prepend: overload()
            .args(String)
            .use(function(value) {
                if (utils.isHtml(value)) {
                    _appendPrependMergeArray(this, parser.parseHtml(value), _prepend);
                    return this;
                }

                _appendPrependElemToArray(this, _stringToFrag(value), _prepend);

                return this;
            })

            .args(Number)
            .use(function(value) {
                _appendPrependElemToArray(this, _stringToFrag('' + value), _prepend);
                return this;
            })

            .args(Function)
            .use(function(fn) {
                _appendPrependFunc(this, fn, _prepend);
                return this;
            })

            .args(Element)
            .use(function(elem) {
                _appendPrependElemToArray(this, elem, _prepend);
                return this;
            })

            .args(O.collection)
            .use(function(arr) {
                _appendPrependMergeArray(this, arr, _prepend);
                return this;
            })

            .expose(),

        prependTo: overload()
            .args(O.D)
            .use(function(d) {
                d.prepend(this);
                return this;
            })

            .fallback(function(obj) {
                D(obj).prepend(this);
                return this;
            })

            .expose(),

        empty: function() {
            _empty(this);
            return this;
        },

        add: overload()
            // String selector
            .args(String)
            .use(function(selector) {
                var elems = _array.unique(
                    [].concat(this.get(), D(selector).get())
                );
                _order.sort(elems);
                return D(elems);
            })

            // Array of elements
            .args(O.collection)
            .use(function(arr) {
                var elems = _array.unique(
                    [].concat(this.get(), _.toArray(arr))
                );
                _order.sort(elems);
                return D(elems);
            })

            // Single element
            .args(O.any(O.window, O.document, Element))
            .use(function(elem) {
                var elems = _array.unique(
                    [].concat(this.get(), [ elem ])
                );
                _order.sort(elems);
                return D(elems);
            })

            // Everything else
            .fallback(function() {
                return D(this);
            })

            .expose(),

        remove: overload()
            .args(String)
            .use(function(selector) {
                if (selector === '') { return; }
                var arr = _selector.filter(this, selector);
                _remove(arr);
                return this;
            })

            .fallback(function() {
                _remove(this);
                return this;
            })

            .expose(),

        detach: overload()
            .args(String)
            .use(function(selector) {
                if (selector === '') { return; }
                var arr = _selector.filter(this, selector);
                _detach(arr);
                return this;
            })

            .fallback(function() {
                _detach(this);
                return this;
            })

            .expose()
    }
};
<commit_msg>Completed partial refactor<commit_after>var _         = require('_'),
    overload  = require('overload'),
    O         = overload.O,

    _selector = require('./selectors'),
    _array    = require('./array'),
    _utils    = require('../utils'),
    _order    = require('../order'),

    _data     = require('./data'),

    parser    = require('../D/parser'),
    utils     = require('../utils');

var _empty = function(arr) {
        var idx = 0, length = arr.length;
        for (; idx < length; idx++) {

            var elem = arr[idx],
                descendants = elem.querySelectorAll('*'),
                i = descendants.length,
                desc;
            while (i--) {
                desc = descendants[i];
                _data.remove(desc);
            }

            elem.innerHTML = '';
        }
    },

    _remove = function(arr) {
        var idx = 0, length = arr.length,
            elem, parent;
        for (; idx < length; idx++) {
            elem = arr[idx];
            if (elem && (parent = elem.parentNode)) {
                _data.remove(elem);
                parent.removeChild(elem);
            }
        }
    },

    _detach = function(arr) {
        var idx = 0, length = arr.length,
            elem, parent;
        for (; idx < length; idx++) {
            elem = arr[idx];
            if (elem && (parent = elem.parentNode)) {
                parent.removeChild(elem);
            }
        }
    },

    _clone = function(elem) {
        return elem.cloneNode(true);
    },

    _stringToFrag = function(str) {
        var frag = document.createDocumentFragment();
        frag.textContent = str;
        return frag;
    },

    _appendPrependFunc = function(d, fn, pender) {
        _.each(d, function(elem, idx) {
            var result = fn.call(elem, idx, elem.innerHTML);

            if (!_.exists(result)) {

                // do nothing

            } else if (_.isString(result)) {

                if (utils.isHTML(value)) {
                    _appendPrependArrayToElem(elem, parser.parseHtml(value), pender);
                    return this;
                }

                pender(elem, _stringToFrag(result));

            } else if (_.isElement(result)) {

                pender(elem, result);

            } else if (_.isNodeList(result) || result instanceof D) {

                _appendPrependArrayToElem(elem, result, pender);

            } else {
                // do nothing
            }
        });
    },
    _appendPrependMergeArray = function(arrOne, arrTwo, pender) {
        var idx = 0, length = arrOne.length;
        for (; idx < length; idx++) {
            var i = 0, len = arrTwo.length;
            for (; i < len; i++) {
                pender(arrOne[idx], arrTwo[i]);
            }
        }
    },
    _appendPrependElemToArray = function(arr, elem, pender) {
        _.each(arr, function(arrElem) {
            pender(arrElem, elem);
        });
    },
    _appendPrependArrayToElem = function(elem, arr, pender) {
        _.each(arr, function(arrElem) {
            pender(elem, arrElem);
        });
    },

    _append = function(base, elem) {
        if (!base || !elem || !_.isElement(elem)) { return; }
        base.appendChild(elem);
    },
    _prepend = function(base, elem) {
        if (!base || !elem || !_.isElement(elem)) { return; }
        base.insertBefore(elem, base.firstChild);
    };

module.exports = {
    append  : _append,
    prepend : _prepend,

    fn: {
        clone: function() {
            return _.fastmap(this.slice(), function(elem) {
                return _clone(elem);
            });
        },

        append: overload()
            .args(String)
            .use(function(value) {
                if (utils.isHtml(value)) {
                    _appendPrependMergeArray(this, parser.parseHtml(value), _append);
                    return this;
                }

                _appendPrependElemToArray(this, _stringToFrag(value), _append);

                return this;
            })

            .args(Number)
            .use(function(value) {
                _appendPrependElemToArray(this, _stringToFrag('' + value), _append);
                return this;
            })

            .args(Function)
            .use(function(fn) {
                _appendPrependFunc(this, fn, _append);
                return this;
            })

            .args(Element)
            .use(function(elem) {
                _appendPrependElemToArray(this, elem, _append);
                return this;
            })

            .args(O.collection)
            .use(function(arr) {
                _appendPrependMergeArray(this, arr, _append);
                return this;
            })

            .expose(),

        // TODO: These methods
        before: function() { return this; },
        after: function() { return this; },
        insertBefore: function() { return this; },
        insertAfter: function() { return this; },

        appendTo: overload()
            .args(O.D)
            .use(function(d) {
                d.append(this);
                return this;
            })

            .fallback(function(obj) {
                D(obj).append(this);
                return this;
            })

            .expose(),

        prepend: overload()
            .args(String)
            .use(function(value) {
                if (utils.isHtml(value)) {
                    _appendPrependMergeArray(this, parser.parseHtml(value), _prepend);
                    return this;
                }

                _appendPrependElemToArray(this, _stringToFrag(value), _prepend);

                return this;
            })

            .args(Number)
            .use(function(value) {
                _appendPrependElemToArray(this, _stringToFrag('' + value), _prepend);
                return this;
            })

            .args(Function)
            .use(function(fn) {
                _appendPrependFunc(this, fn, _prepend);
                return this;
            })

            .args(Element)
            .use(function(elem) {
                _appendPrependElemToArray(this, elem, _prepend);
                return this;
            })

            .args(O.collection)
            .use(function(arr) {
                _appendPrependMergeArray(this, arr, _prepend);
                return this;
            })

            .expose(),

        prependTo: overload()
            .args(O.D)
            .use(function(d) {
                d.prepend(this);
                return this;
            })

            .fallback(function(obj) {
                D(obj).prepend(this);
                return this;
            })

            .expose(),

        empty: function() {
            _empty(this);
            return this;
        },

        add: overload()
            // String selector
            .args(String)
            .use(function(selector) {
                var elems = _array.unique(
                    [].concat(this.get(), D(selector).get())
                );
                _order.sort(elems);
                return D(elems);
            })

            // Array of elements
            .args(O.collection)
            .use(function(arr) {
                var elems = _array.unique(
                    [].concat(this.get(), _.toArray(arr))
                );
                _order.sort(elems);
                return D(elems);
            })

            // Single element
            .args(O.any(O.window, O.document, Element))
            .use(function(elem) {
                var elems = _array.unique(
                    [].concat(this.get(), [ elem ])
                );
                _order.sort(elems);
                return D(elems);
            })

            // Everything else
            .fallback(function() {
                return D(this);
            })

            .expose(),

        remove: overload()
            .args(String)
            .use(function(selector) {
                if (selector === '') { return; }
                var arr = _selector.filter(this, selector);
                _remove(arr);
                return this;
            })

            .fallback(function() {
                _remove(this);
                return this;
            })

            .expose(),

        detach: overload()
            .args(String)
            .use(function(selector) {
                if (selector === '') { return; }
                var arr = _selector.filter(this, selector);
                _detach(arr);
                return this;
            })

            .fallback(function() {
                _detach(this);
                return this;
            })

            .expose()
    }
};
<|endoftext|>