<commit_before>'use strict'
var npm = require('../npm.js')
var util = require('util')
var nameValidator = require('validate-npm-package-name')

module.exports = errorMessage

function errorMessage (er) {
  var short = []
  var detail = []
  if (er.optional) {
    short.push(['optional', 'Skipping failed optional dependency ' + er.optional + ':'])
  }
  switch (er.code) {
    case 'ECONNREFUSED':
      short.push(['', er])
      detail.push([
        '',
        [
          '\nIf you are behind a proxy, please make sure that the',
          "'proxy' config is set properly.  See: 'npm help config'"
        ].join('\n')
      ])
      break

    case 'EACCES':
    case 'EPERM':
      short.push(['', er])
      detail.push(['', ['\nPlease try running this command again as root/Administrator.'
                ].join('\n')])
      break

    case 'ELIFECYCLE':
      short.push(['', er.message])
      detail.push([
        '',
        [
          '',
          'Failed at the ' + er.pkgid + ' ' + er.stage + " script '" + er.script + "'.",
          'Make sure you have the latest version of node.js and npm installed.',
          'If you do, this is most likely a problem with the ' + er.pkgname + ' package,',
          'not with npm itself.',
          'Tell the author that this fails on your system:',
          '    ' + er.script,
          'You can get information on how to open an issue for this project with:',
          '    npm bugs ' + er.pkgname,
          'Or if that isn\'t available, you can get their info via:',
          '    npm owner ls ' + er.pkgname,
          'There is likely additional logging output above.'
        ].join('\n')]
      )
      break

    case 'ENOGIT':
      short.push(['', er.message])
      detail.push([
        '',
        [
          '',
          'Failed using git.',
          'This is most likely not a problem with npm itself.',
          'Please check if you have git installed and in your PATH.'
        ].join('\n')
      ])
      break

    case 'EJSONPARSE':
      short.push(['', er.message])
      short.push(['', 'File: ' + er.file])
      detail.push([
        '',
        [
          'Failed to parse package.json data.',
          'package.json must be actual JSON, not just JavaScript.',
          '',
          'This is not a bug in npm.',
          'Tell the package author to fix their package.json file.'
        ].join('\n'),
        'JSON.parse'
      ])
      break

    // TODO(isaacs)
    // Add a special case here for E401 and E403 explaining auth issues?

    case 'E404':
      // There's no need to have 404 in the message as well.
      var msg = er.message.replace(/^404\s+/, '')
      short.push(['404', msg])
      if (er.pkgid && er.pkgid !== '-') {
        detail.push(['404', ''])
        detail.push(['404', '', "'" + er.pkgid + "' is not in the npm registry."])

        var valResult = nameValidator(er.pkgid)

        if (valResult.validForNewPackages) {
          detail.push(['404', 'You should bug the author to publish it (or use the name yourself!)'])
        } else {
          detail.push(['404', 'Your package name is not valid, because', ''])

          var errorsArray = (valResult.errors || []).concat(valResult.warnings || [])
          errorsArray.forEach(function (item, idx) {
            detail.push(['404', ' ' + (idx + 1) + '. ' + item])
          })
        }

        if (er.parent) {
          detail.push(['404', "It was specified as a dependency of '" + er.parent + "'"])
        }
        detail.push(['404', '\nNote that you can also install from a'])
        detail.push(['404', 'tarball, folder, http url, or git url.'])
      }
      break

    case 'EPUBLISHCONFLICT':
      short.push(['publish fail', 'Cannot publish over existing version.'])
      detail.push(['publish fail', "Update the 'version' field in package.json and try again."])
      detail.push(['publish fail', ''])
      detail.push(['publish fail', 'To automatically increment version numbers, see:'])
      detail.push(['publish fail', '    npm help version'])
      break

    case 'EISGIT':
      short.push(['git', er.message])
      short.push(['git', '    ' + er.path])
      detail.push([
        'git',
        [
          'Refusing to remove it. Update manually,',
          'or move it out of the way first.'
        ].join('\n')
      ])
      break

    case 'ECYCLE':
      short.push([
        'cycle',
        [
          er.message,
          'While installing: ' + er.pkgid
        ].join('\n')
      ])
      detail.push([
        'cycle',
        [
          'Found a pathological dependency case that npm cannot solve.',
          'Please report this to the package author.'
        ].join('\n')
      ])
      break

    case 'EBADPLATFORM':
      short.push([
        'notsup',
        [
          'Not compatible with your operating system or architecture: ' + er.pkgid
        ].join('\n')
      ])
      detail.push([
        'notsup',
        [
          'Valid OS:    ' + (er.os.join ? er.os.join(',') : util.inspect(er.os)),
          'Valid Arch:  ' + (er.cpu.join ? er.cpu.join(',') : util.inspect(er.cpu)),
          'Actual OS:   ' + process.platform,
          'Actual Arch: ' + process.arch
        ].join('\n')
      ])
      break

    case 'EEXIST':
      short.push(['', er.message])
      short.push(['', 'File exists: ' + er.path])
      detail.push(['', 'Move it away, and try again.'])
      break

    case 'ENEEDAUTH':
      short.push(['need auth', er.message])
      detail.push(['need auth', 'You need to authorize this machine using `npm adduser`'])
      break

    case 'ECONNRESET':
    case 'ENOTFOUND':
    case 'ETIMEDOUT':
    case 'EAI_FAIL':
      short.push(['network', er.message])
      detail.push([
        'network',
        [
          'This is most likely not a problem with npm itself',
          'and is related to network connectivity.',
          'In most cases you are behind a proxy or have bad network settings.',
          '\nIf you are behind a proxy, please make sure that the',
          "'proxy' config is set properly.  See: 'npm help config'"
        ].join('\n')
      ])
      break

    case 'ENOPACKAGEJSON':
      short.push(['package.json', er.message])
      detail.push([
        'package.json',
        [
          'This is most likely not a problem with npm itself.',
          "npm can't find a package.json file in your current directory."
        ].join('\n')
      ])
      break

    case 'ETARGET':
      short.push(['notarget', er.message])
      msg = [
        'This is most likely not a problem with npm itself.',
        'In most cases you or one of your dependencies are requesting',
        "a package version that doesn't exist."
      ]
      if (er.parent) {
        msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n")
      }
      detail.push(['notarget', msg.join('\n')])
      break

    case 'ENOTSUP':
      if (er.required) {
        short.push(['notsup', er.message])
        short.push(['notsup', 'Not compatible with your version of node/npm: ' + er.pkgid])
        detail.push([
          'notsup',
          [
            'Not compatible with your version of node/npm: ' + er.pkgid,
            'Required: ' + JSON.stringify(er.required),
            'Actual:   ' + JSON.stringify({
              npm: npm.version,
              node: npm.config.get('node-version')
            })
          ].join('\n')
        ])
        break
      } // else passthrough
      /*eslint no-fallthrough:0*/

    case 'ENOSPC':
      short.push(['nospc', er.message])
      detail.push([
        'nospc',
        [
          'This is most likely not a problem with npm itself',
          'and is related to insufficient space on your system.'
        ].join('\n')
      ])
      break

    case 'EROFS':
      short.push(['rofs', er.message])
      detail.push([
        'rofs',
        [
          'This is most likely not a problem with npm itself',
          'and is related to the file system being read-only.',
          '\nOften virtualized file systems, or other file systems',
          "that don't support symlinks, give this error."
        ].join('\n')
      ])
      break

    case 'ENOENT':
      short.push(['enoent', er.message])
      detail.push([
        'enoent',
        [
          er.message,
          'This is most likely not a problem with npm itself',
          'and is related to npm not being able to find a file.',
          er.file ? "\nCheck if the file '" + er.file + "' is present." : ''
        ].join('\n')
      ])
      break

    case 'EMISSINGARG':
    case 'EUNKNOWNTYPE':
    case 'EINVALIDTYPE':
    case 'ETOOMANYARGS':
      short.push(['typeerror', er.stack])
      detail.push([
        'typeerror',
        [
          'This is an error with npm itself. Please report this error at:',
          '    <http://github.com/npm/npm/issues>'
        ].join('\n')
      ])
      break

    case 'EISDIR':
      short.push(['eisdir', er.message])
      detail.push([
        'eisdir',
        [
          'This is most likely not a problem with npm itself',
          'and is related to npm not being able to find a package.json in',
          'a package you are trying to install.'
        ].join('\n')
      ])
      break

    default:
      short.push(['', er.message || er])
      detail.push([
        '',
        [
          '',
          'If you need help, you may report this error at:',
          '    <https://github.com/npm/npm/issues>'
        ].join('\n')
      ])
      break
  }
  return {summary: short, detail: detail}
}
<commit_msg>error: Correct url in an error message of typeerror<commit_after>'use strict'
var npm = require('../npm.js')
var util = require('util')
var nameValidator = require('validate-npm-package-name')

module.exports = errorMessage

function errorMessage (er) {
  var short = []
  var detail = []
  if (er.optional) {
    short.push(['optional', 'Skipping failed optional dependency ' + er.optional + ':'])
  }
  switch (er.code) {
    case 'ECONNREFUSED':
      short.push(['', er])
      detail.push([
        '',
        [
          '\nIf you are behind a proxy, please make sure that the',
          "'proxy' config is set properly.  See: 'npm help config'"
        ].join('\n')
      ])
      break

    case 'EACCES':
    case 'EPERM':
      short.push(['', er])
      detail.push(['', ['\nPlease try running this command again as root/Administrator.'
                ].join('\n')])
      break

    case 'ELIFECYCLE':
      short.push(['', er.message])
      detail.push([
        '',
        [
          '',
          'Failed at the ' + er.pkgid + ' ' + er.stage + " script '" + er.script + "'.",
          'Make sure you have the latest version of node.js and npm installed.',
          'If you do, this is most likely a problem with the ' + er.pkgname + ' package,',
          'not with npm itself.',
          'Tell the author that this fails on your system:',
          '    ' + er.script,
          'You can get information on how to open an issue for this project with:',
          '    npm bugs ' + er.pkgname,
          'Or if that isn\'t available, you can get their info via:',
          '    npm owner ls ' + er.pkgname,
          'There is likely additional logging output above.'
        ].join('\n')]
      )
      break

    case 'ENOGIT':
      short.push(['', er.message])
      detail.push([
        '',
        [
          '',
          'Failed using git.',
          'This is most likely not a problem with npm itself.',
          'Please check if you have git installed and in your PATH.'
        ].join('\n')
      ])
      break

    case 'EJSONPARSE':
      short.push(['', er.message])
      short.push(['', 'File: ' + er.file])
      detail.push([
        '',
        [
          'Failed to parse package.json data.',
          'package.json must be actual JSON, not just JavaScript.',
          '',
          'This is not a bug in npm.',
          'Tell the package author to fix their package.json file.'
        ].join('\n'),
        'JSON.parse'
      ])
      break

    // TODO(isaacs)
    // Add a special case here for E401 and E403 explaining auth issues?

    case 'E404':
      // There's no need to have 404 in the message as well.
      var msg = er.message.replace(/^404\s+/, '')
      short.push(['404', msg])
      if (er.pkgid && er.pkgid !== '-') {
        detail.push(['404', ''])
        detail.push(['404', '', "'" + er.pkgid + "' is not in the npm registry."])

        var valResult = nameValidator(er.pkgid)

        if (valResult.validForNewPackages) {
          detail.push(['404', 'You should bug the author to publish it (or use the name yourself!)'])
        } else {
          detail.push(['404', 'Your package name is not valid, because', ''])

          var errorsArray = (valResult.errors || []).concat(valResult.warnings || [])
          errorsArray.forEach(function (item, idx) {
            detail.push(['404', ' ' + (idx + 1) + '. ' + item])
          })
        }

        if (er.parent) {
          detail.push(['404', "It was specified as a dependency of '" + er.parent + "'"])
        }
        detail.push(['404', '\nNote that you can also install from a'])
        detail.push(['404', 'tarball, folder, http url, or git url.'])
      }
      break

    case 'EPUBLISHCONFLICT':
      short.push(['publish fail', 'Cannot publish over existing version.'])
      detail.push(['publish fail', "Update the 'version' field in package.json and try again."])
      detail.push(['publish fail', ''])
      detail.push(['publish fail', 'To automatically increment version numbers, see:'])
      detail.push(['publish fail', '    npm help version'])
      break

    case 'EISGIT':
      short.push(['git', er.message])
      short.push(['git', '    ' + er.path])
      detail.push([
        'git',
        [
          'Refusing to remove it. Update manually,',
          'or move it out of the way first.'
        ].join('\n')
      ])
      break

    case 'ECYCLE':
      short.push([
        'cycle',
        [
          er.message,
          'While installing: ' + er.pkgid
        ].join('\n')
      ])
      detail.push([
        'cycle',
        [
          'Found a pathological dependency case that npm cannot solve.',
          'Please report this to the package author.'
        ].join('\n')
      ])
      break

    case 'EBADPLATFORM':
      short.push([
        'notsup',
        [
          'Not compatible with your operating system or architecture: ' + er.pkgid
        ].join('\n')
      ])
      detail.push([
        'notsup',
        [
          'Valid OS:    ' + (er.os.join ? er.os.join(',') : util.inspect(er.os)),
          'Valid Arch:  ' + (er.cpu.join ? er.cpu.join(',') : util.inspect(er.cpu)),
          'Actual OS:   ' + process.platform,
          'Actual Arch: ' + process.arch
        ].join('\n')
      ])
      break

    case 'EEXIST':
      short.push(['', er.message])
      short.push(['', 'File exists: ' + er.path])
      detail.push(['', 'Move it away, and try again.'])
      break

    case 'ENEEDAUTH':
      short.push(['need auth', er.message])
      detail.push(['need auth', 'You need to authorize this machine using `npm adduser`'])
      break

    case 'ECONNRESET':
    case 'ENOTFOUND':
    case 'ETIMEDOUT':
    case 'EAI_FAIL':
      short.push(['network', er.message])
      detail.push([
        'network',
        [
          'This is most likely not a problem with npm itself',
          'and is related to network connectivity.',
          'In most cases you are behind a proxy or have bad network settings.',
          '\nIf you are behind a proxy, please make sure that the',
          "'proxy' config is set properly.  See: 'npm help config'"
        ].join('\n')
      ])
      break

    case 'ENOPACKAGEJSON':
      short.push(['package.json', er.message])
      detail.push([
        'package.json',
        [
          'This is most likely not a problem with npm itself.',
          "npm can't find a package.json file in your current directory."
        ].join('\n')
      ])
      break

    case 'ETARGET':
      short.push(['notarget', er.message])
      msg = [
        'This is most likely not a problem with npm itself.',
        'In most cases you or one of your dependencies are requesting',
        "a package version that doesn't exist."
      ]
      if (er.parent) {
        msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n")
      }
      detail.push(['notarget', msg.join('\n')])
      break

    case 'ENOTSUP':
      if (er.required) {
        short.push(['notsup', er.message])
        short.push(['notsup', 'Not compatible with your version of node/npm: ' + er.pkgid])
        detail.push([
          'notsup',
          [
            'Not compatible with your version of node/npm: ' + er.pkgid,
            'Required: ' + JSON.stringify(er.required),
            'Actual:   ' + JSON.stringify({
              npm: npm.version,
              node: npm.config.get('node-version')
            })
          ].join('\n')
        ])
        break
      } // else passthrough
      /*eslint no-fallthrough:0*/

    case 'ENOSPC':
      short.push(['nospc', er.message])
      detail.push([
        'nospc',
        [
          'This is most likely not a problem with npm itself',
          'and is related to insufficient space on your system.'
        ].join('\n')
      ])
      break

    case 'EROFS':
      short.push(['rofs', er.message])
      detail.push([
        'rofs',
        [
          'This is most likely not a problem with npm itself',
          'and is related to the file system being read-only.',
          '\nOften virtualized file systems, or other file systems',
          "that don't support symlinks, give this error."
        ].join('\n')
      ])
      break

    case 'ENOENT':
      short.push(['enoent', er.message])
      detail.push([
        'enoent',
        [
          er.message,
          'This is most likely not a problem with npm itself',
          'and is related to npm not being able to find a file.',
          er.file ? "\nCheck if the file '" + er.file + "' is present." : ''
        ].join('\n')
      ])
      break

    case 'EMISSINGARG':
    case 'EUNKNOWNTYPE':
    case 'EINVALIDTYPE':
    case 'ETOOMANYARGS':
      short.push(['typeerror', er.stack])
      detail.push([
        'typeerror',
        [
          'This is an error with npm itself. Please report this error at:',
          '    <https://github.com/npm/npm/issues>'
        ].join('\n')
      ])
      break

    case 'EISDIR':
      short.push(['eisdir', er.message])
      detail.push([
        'eisdir',
        [
          'This is most likely not a problem with npm itself',
          'and is related to npm not being able to find a package.json in',
          'a package you are trying to install.'
        ].join('\n')
      ])
      break

    default:
      short.push(['', er.message || er])
      detail.push([
        '',
        [
          '',
          'If you need help, you may report this error at:',
          '    <https://github.com/npm/npm/issues>'
        ].join('\n')
      ])
      break
  }
  return {summary: short, detail: detail}
}
<|endoftext|>


<commit_before>(function($) {
    $.fn.scrollWhere = function() {
        //Insert HTML
        $(this).html(' \

 \

 \
                     \

 \

 \
                     \

 \

 \

 \
                     \

 \

 \
        ');

        $('.fallzu-scroll-return').hide();
        $(window).scroll(function() {
            var returnTop = $('.fallzu-scroll-return-top').stop(true, true);
            var returnBottom = $('.fallzu-scroll-return-bottom').stop(true, true);
            var windowHeight = $(this).height();
            var documentHeight = $(document).height();
            var scrollHeight = $(this).scrollTop();

            //Top
            if (scrollHeight) {
                returnTop.fadeIn();
            } else {
                returnTop.fadeOut();
            }

            //Bottom
            if (windowHeight + scrollHeight < documentHeight) {
                returnBottom.fadeIn();
            } else {
                returnBottom.fadeOut();
            }
        });

        //Top
        $('.fallzu-scroll-return-top').click(function(e) {
            e.preventDefault();
            $('html, body').animate({scrollTop:0}, 500);
        });

        //Bottom
        $('.fallzu-scroll-return-bottom').click(function(e) {
            e.preventDefault();
            $('html, body').animate({scrollTop:$(document).height() - $(window).height()}, 500);
        });

        //Remember
        $('.fallzu-scroll-remember').click(function(e) {
            e.preventDefault();
            var windowHeight = $(window).scrollTop();
            $('.fallzu-scroll-area').append('

');

            //Anchor
            $('.fallzu-scroll-area .fallzu-scroll-btn:last').on('click', function(e) {
                e.preventDefault();
                $('html, body').animate({scrollTop:$(this).data('scroll')}, 500);
            });
        });

        return $(this);
    };
})(jQuery);
<commit_msg>Insert CSS<commit_after>(function($) {
    $.fn.scrollWhere = function() {
        //Insert HTML
        $(this).html(' \

 \

 \
                     \

 \

 \
                     \

 \

 \

 \
                     \

 \

 \
        ');

        //CSS
        $('.fallzu-scroll-bar').css({
            'position'      : 'fixed',
            'right'         : '30px',
            'bottom'        : '30px'
        });

        $('.fallzu-scroll-btn').css({
            'width'         : '50px',
            'height'        : '50px',
            'background'    : '#333',
            'border-radius' : '25px',
            'text-align'    : 'center',
            'margin-bottom' : '10px'
        });

        $('.fallzu-scroll-btn > a').css({
            'display'       : 'block',
            'color'         : '#FFF'
        });

        $('.fallzu-scroll-return').hide();
        $(window).scroll(function() {
            var returnTop = $('.fallzu-scroll-return-top').stop(true, true);
            var returnBottom = $('.fallzu-scroll-return-bottom').stop(true, true);
            var windowHeight = $(this).height();
            var documentHeight = $(document).height();
            var scrollHeight = $(this).scrollTop();

            //Top
            if (scrollHeight) {
                returnTop.fadeIn();
            } else {
                returnTop.fadeOut();
            }

            //Bottom
            if (windowHeight + scrollHeight < documentHeight) {
                returnBottom.fadeIn();
            } else {
                returnBottom.fadeOut();
            }
        });

        //Top
        $('.fallzu-scroll-return-top').click(function(e) {
            e.preventDefault();
            $('html, body').animate({scrollTop:0}, 500);
        });

        //Bottom
        $('.fallzu-scroll-return-bottom').click(function(e) {
            e.preventDefault();
            $('html, body').animate({scrollTop:$(document).height() - $(window).height()}, 500);
        });

        //Remember
        $('.fallzu-scroll-remember').click(function(e) {
            e.preventDefault();
            var windowHeight = $(window).scrollTop();
            $('.fallzu-scroll-area').append('

');

            //Anchor
            $('.fallzu-scroll-area .fallzu-scroll-btn:last').on('click', function(e) {
                e.preventDefault();
                $('html, body').animate({scrollTop:$(this).data('scroll')}, 500);
            });
        });

        return $(this);
    };
})(jQuery);
<|endoftext|>


<commit_before>/**
@module ember-metal
*/

import { assert } from 'ember-debug';
import { isPath, hasThis } from './path_cache';

const ALLOWABLE_TYPES = {
  object: true,
  function: true,
  string: true
};

// ..........................................................
// GET AND SET
//
// If we are on a platform that supports accessors we can use those.
// Otherwise simulate accessors by looking up the property directly on the
// object.

/**
  Gets the value of a property on an object. If the property is computed,
  the function will be invoked. If the property is not defined but the
  object implements the `unknownProperty` method then that will be invoked.

  ```javascript
  Ember.get(obj, "name");
  ```

  If you plan to run on IE8 and older browsers then you should use this
  method anytime you want to retrieve a property on an object that you don't
  know for sure is private. (Properties beginning with an underscore '_'
  are considered private.)

  On all newer browsers, you only need to use this method to retrieve
  properties if the property might not be defined on the object and you want
  to respect the `unknownProperty` handler. Otherwise you can ignore this
  method.

  Note that if the object itself is `undefined`, this method will throw
  an error.

  @method get
  @for Ember
  @param {Object} obj The object to retrieve from.
  @param {String} keyName The property key to retrieve
  @return {Object} the property value or `null`.
  @public
*/
export function get(obj, keyName) {
  assert(`Get must be called with two arguments; an object and a property key`, arguments.length === 2);
  assert(`Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null);
  assert(`The key provided to get must be a string, you passed ${keyName}`, typeof keyName === 'string');
  assert(`'this' in paths is not supported`, !hasThis(keyName));
  assert('Cannot call `Ember.get` with an empty string', keyName !== '');

  let value = obj[keyName];
  let isDescriptor = value !== null && typeof value === 'object' && value.isDescriptor;

  if (!isDescriptor && isPath(keyName)) {
    return _getPath(obj, keyName);
  }

  if (isDescriptor) {
    return value.get(obj, keyName);
  } else {
    if (value === undefined &&
        'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) {
      return obj.unknownProperty(keyName);
    }

    return value;
  }
}

export function _getPath(root, path) {
  let obj = root;
  let parts = path.split('.');

  for (let i = 0; i < parts.length; i++) {
    if (!isGettable(obj)) {
      return undefined;
    }

    obj = get(obj, parts[i]);

    if (obj && obj.isDestroyed) {
      return undefined;
    }
  }

  return obj;
}

function isGettable(obj) {
  if (obj === undefined || obj === null) {
    return false;
  }

  return ALLOWABLE_TYPES[typeof obj];
}

/**
  Retrieves the value of a property from an Object, or a default value in the
  case that the property returns `undefined`.

  ```javascript
  Ember.getWithDefault(person, 'lastName', 'Doe');
  ```

  @method getWithDefault
  @for Ember
  @param {Object} obj The object to retrieve from.
  @param {String} keyName The name of the property to retrieve
  @param {Object} defaultValue The value to return if the property value is undefined
  @return {Object} The property value or the defaultValue.
  @public
*/
export function getWithDefault(root, key, defaultValue) {
  let value = get(root, key);

  if (value === undefined) { return defaultValue; }
  return value;
}

export default get;
<commit_msg>cleanup `if statements` in `property_get`<commit_after>/**
@module ember-metal
*/

import { assert } from 'ember-debug';
import { isPath, hasThis } from './path_cache';

const ALLOWABLE_TYPES = {
  object: true,
  function: true,
  string: true
};

// ..........................................................
// GET AND SET
//
// If we are on a platform that supports accessors we can use those.
// Otherwise simulate accessors by looking up the property directly on the
// object.

/**
  Gets the value of a property on an object. If the property is computed,
  the function will be invoked. If the property is not defined but the
  object implements the `unknownProperty` method then that will be invoked.

  ```javascript
  Ember.get(obj, "name");
  ```

  If you plan to run on IE8 and older browsers then you should use this
  method anytime you want to retrieve a property on an object that you don't
  know for sure is private. (Properties beginning with an underscore '_'
  are considered private.)

  On all newer browsers, you only need to use this method to retrieve
  properties if the property might not be defined on the object and you want
  to respect the `unknownProperty` handler. Otherwise you can ignore this
  method.

  Note that if the object itself is `undefined`, this method will throw
  an error.

  @method get
  @for Ember
  @param {Object} obj The object to retrieve from.
  @param {String} keyName The property key to retrieve
  @return {Object} the property value or `null`.
  @public
*/
export function get(obj, keyName) {
  assert(`Get must be called with two arguments; an object and a property key`, arguments.length === 2);
  assert(`Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null);
  assert(`The key provided to get must be a string, you passed ${keyName}`, typeof keyName === 'string');
  assert(`'this' in paths is not supported`, !hasThis(keyName));
  assert('Cannot call `Ember.get` with an empty string', keyName !== '');

  let value = obj[keyName];
  let isDescriptor = value !== null && typeof value === 'object' && value.isDescriptor;

  if (isDescriptor) {
    return value.get(obj, keyName);
  } else if (isPath(keyName)) {
    return _getPath(obj, keyName);
  } else if (value === undefined &&
    'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) {
    return obj.unknownProperty(keyName);
  } else {
    return value;
  }
}

export function _getPath(root, path) {
  let obj = root;
  let parts = path.split('.');

  for (let i = 0; i < parts.length; i++) {
    if (!isGettable(obj)) {
      return undefined;
    }

    obj = get(obj, parts[i]);

    if (obj && obj.isDestroyed) {
      return undefined;
    }
  }

  return obj;
}

function isGettable(obj) {
  return obj !== undefined && obj !== null && ALLOWABLE_TYPES[typeof obj];
}

/**
  Retrieves the value of a property from an Object, or a default value in the
  case that the property returns `undefined`.

  ```javascript
  Ember.getWithDefault(person, 'lastName', 'Doe');
  ```

  @method getWithDefault
  @for Ember
  @param {Object} obj The object to retrieve from.
  @param {String} keyName The name of the property to retrieve
  @param {Object} defaultValue The value to return if the property value is undefined
  @return {Object} The property value or the defaultValue.
  @public
*/
export function getWithDefault(root, key, defaultValue) {
  let value = get(root, key);

  if (value === undefined) { return defaultValue; }
  return value;
}

export default get;
<|endoftext|>


<commit_before>import { assign } from 'ember-utils';
import { assert, deprecate } from 'ember-metal';

/**
@module ember
@submodule ember-routing
*/

function DSL(name, options) {
  this.parent = name;
  this.enableLoadingSubstates = options && options.enableLoadingSubstates;
  this.matches = [];
  this.explicitIndex = undefined;
  this.options = options;
}

export default DSL;

DSL.prototype = {
  route(name, options, callback) {
    let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
    if (arguments.length === 2 && typeof options === 'function') {
      callback = options;
      options = {};
    }

    if (arguments.length === 1) {
      options = {};
    }

    assert(
      `'${name}' cannot be used as a route name.`,
      (function() {
        if (options.overrideNameAssertion === true) { return true; }

        return ['array', 'basic', 'object', 'application'].indexOf(name) === -1;
      })()
    );

    if (this.enableLoadingSubstates) {
      createRoute(this, `${name}_loading`, { resetNamespace: options.resetNamespace });
      createRoute(this, `${name}_error`, { resetNamespace: options.resetNamespace, path: dummyErrorRoute });
    }

    if (callback) {
      let fullName = getFullName(this, name, options.resetNamespace);
      let dsl = new DSL(fullName, this.options);

      createRoute(dsl, 'loading');
      createRoute(dsl, 'error', { path: dummyErrorRoute });

      callback.call(dsl);

      createRoute(this, name, options, dsl.generate());
    } else {
      createRoute(this, name, options);
    }
  },

  push(url, name, callback, serialize) {
    let parts = name.split('.');

    if (this.options.engineInfo) {
      let localFullName = name.slice(this.options.engineInfo.fullName.length + 1);
      let routeInfo = assign({ localFullName }, this.options.engineInfo);

      if (serialize) {
        routeInfo.serializeMethod = serialize;
      }

      this.options.addRouteForEngine(name, routeInfo);
    } else if (serialize) {
      throw new Error(`Defining a route serializer on route '${name}' outside an Engine is not allowed.`);
    }

    if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; }

    this.matches.push([url, name, callback]);
  },

  resource(name, options, callback) {
    if (arguments.length === 2 && typeof options === 'function') {
      callback = options;
      options = {};
    }

    if (arguments.length === 1) {
      options = {};
    }

    options.resetNamespace = true;
    deprecate('this.resource() is deprecated. Use this.route(\'name\', { resetNamespace: true }, function () {}) instead.', false, { id: 'ember-routing.router-resource', until: '3.0.0' });
    this.route(name, options, callback);
  },

  generate() {
    let dslMatches = this.matches;

    if (!this.explicitIndex) {
      this.route('index', { path: '/' });
    }

    return match => {
      for (let i = 0; i < dslMatches.length; i++) {
        let dslMatch = dslMatches[i];
        match(dslMatch[0]).to(dslMatch[1], dslMatch[2]);
      }
    };
  }
};

function canNest(dsl) {
  return dsl.parent && dsl.parent !== 'application';
}

function getFullName(dsl, name, resetNamespace) {
  if (canNest(dsl) && resetNamespace !== true) {
    return `${dsl.parent}.${name}`;
  } else {
    return name;
  }
}

function createRoute(dsl, name, options = {}, callback) {
  let fullName = getFullName(dsl, name, options.resetNamespace);

  if (typeof options.path !== 'string') {
    options.path = `/${name}`;
  }

  dsl.push(options.path, fullName, callback, options.serialize);
}

DSL.map = callback => {
  let dsl = new DSL();
  callback.call(dsl);
  return dsl;
};

let uuid = 0;

DSL.prototype.mount = function(_name, options = {}) {
  let engineRouteMap = this.options.resolveRouteMap(_name);
  let name = _name;

  if (options.as) {
    name = options.as;
  }

  let fullName = getFullName(this, name, options.resetNamespace);

  let engineInfo = {
    name: _name,
    instanceId: uuid++,
    mountPoint: fullName,
    fullName
  };

  let path = options.path;

  if (typeof path !== 'string') {
    path = `/${name}`;
  }

  let callback;
  let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
  if (engineRouteMap) {
    let shouldResetEngineInfo = false;
    let oldEngineInfo = this.options.engineInfo;
    if (oldEngineInfo) {
      shouldResetEngineInfo = true;
      this.options.engineInfo = engineInfo;
    }

    let optionsForChild = assign({ engineInfo }, this.options);
    let childDSL = new DSL(fullName, optionsForChild);

    createRoute(childDSL, 'loading');
    createRoute(childDSL, 'error', { path: dummyErrorRoute });

    engineRouteMap.class.call(childDSL);

    callback = childDSL.generate();

    if (shouldResetEngineInfo) {
      this.options.engineInfo = oldEngineInfo;
    }
  }

  let localFullName = 'application';
  let routeInfo = assign({ localFullName }, engineInfo);

  if (this.enableLoadingSubstates) {
    // These values are important to register the loading routes under their
    // proper names for the Router and within the Engine's registry.
    let substateName = `${name}_loading`;
    let localFullName = `application_loading`;
    let routeInfo = assign({ localFullName }, engineInfo);
    createRoute(this, substateName, { resetNamespace: options.resetNamespace });
    this.options.addRouteForEngine(substateName, routeInfo);

    substateName = `${name}_error`;
    localFullName = `application_error`;
    routeInfo = assign({ localFullName }, engineInfo);
    createRoute(this, substateName, { resetNamespace: options.resetNamespace, path: dummyErrorRoute });
    this.options.addRouteForEngine(substateName, routeInfo);
  }

  this.options.addRouteForEngine(fullName, routeInfo);

  this.push(path, fullName, callback);
};
<commit_msg>replace prototypal on classical inheritance<commit_after>import { assign } from 'ember-utils';
import { assert, deprecate } from 'ember-metal';

/**
@module ember
@submodule ember-routing
*/

let uuid = 0;

class DSL {
  constructor(name, options) {
    this.parent = name;
    this.enableLoadingSubstates = options && options.enableLoadingSubstates;
    this.matches = [];
    this.explicitIndex = undefined;
    this.options = options;
  }

  route(name, options, callback) {
    let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
    if (arguments.length === 2 && typeof options === 'function') {
      callback = options;
      options = {};
    }

    if (arguments.length === 1) {
      options = {};
    }

    assert(
      `'${name}' cannot be used as a route name.`,
      ((() => {
        if (options.overrideNameAssertion === true) { return true; }

        return ['array', 'basic', 'object', 'application'].indexOf(name) === -1;
      }))()
    );

    if (this.enableLoadingSubstates) {
      createRoute(this, `${name}_loading`, { resetNamespace: options.resetNamespace });
      createRoute(this, `${name}_error`, { resetNamespace: options.resetNamespace, path: dummyErrorRoute });
    }

    if (callback) {
      let fullName = getFullName(this, name, options.resetNamespace);
      let dsl = new DSL(fullName, this.options);

      createRoute(dsl, 'loading');
      createRoute(dsl, 'error', { path: dummyErrorRoute });

      callback.call(dsl);

      createRoute(this, name, options, dsl.generate());
    } else {
      createRoute(this, name, options);
    }
  }

  push(url, name, callback, serialize) {
    let parts = name.split('.');

    if (this.options.engineInfo) {
      let localFullName = name.slice(this.options.engineInfo.fullName.length + 1);
      let routeInfo = assign({ localFullName }, this.options.engineInfo);

      if (serialize) {
        routeInfo.serializeMethod = serialize;
      }

      this.options.addRouteForEngine(name, routeInfo);
    } else if (serialize) {
      throw new Error(`Defining a route serializer on route '${name}' outside an Engine is not allowed.`);
    }

    if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; }

    this.matches.push([url, name, callback]);
  }

  resource(name, options, callback) {
    if (arguments.length === 2 && typeof options === 'function') {
      callback = options;
      options = {};
    }

    if (arguments.length === 1) {
      options = {};
    }

    options.resetNamespace = true;
    deprecate('this.resource() is deprecated. Use this.route(\'name\', { resetNamespace: true }, function () {}) instead.', false, { id: 'ember-routing.router-resource', until: '3.0.0' });
    this.route(name, options, callback);
  }

  generate() {
    let dslMatches = this.matches;

    if (!this.explicitIndex) {
      this.route('index', { path: '/' });
    }

    return match => {
      for (let i = 0; i < dslMatches.length; i++) {
        let dslMatch = dslMatches[i];
        match(dslMatch[0]).to(dslMatch[1], dslMatch[2]);
      }
    };
  }

  mount(_name, options = {}) {
    let engineRouteMap = this.options.resolveRouteMap(_name);
    let name = _name;

    if (options.as) {
      name = options.as;
    }

    let fullName = getFullName(this, name, options.resetNamespace);

    let engineInfo = {
      name: _name,
      instanceId: uuid++,
      mountPoint: fullName,
      fullName
    };

    let path = options.path;

    if (typeof path !== 'string') {
      path = `/${name}`;
    }

    let callback;
    let dummyErrorRoute = `/_unused_dummy_error_path_route_${name}/:error`;
    if (engineRouteMap) {
      let shouldResetEngineInfo = false;
      let oldEngineInfo = this.options.engineInfo;
      if (oldEngineInfo) {
        shouldResetEngineInfo = true;
        this.options.engineInfo = engineInfo;
      }

      let optionsForChild = assign({ engineInfo }, this.options);
      let childDSL = new DSL(fullName, optionsForChild);

      createRoute(childDSL, 'loading');
      createRoute(childDSL, 'error', { path: dummyErrorRoute });

      engineRouteMap.class.call(childDSL);

      callback = childDSL.generate();

      if (shouldResetEngineInfo) {
        this.options.engineInfo = oldEngineInfo;
      }
    }

    let localFullName = 'application';
    let routeInfo = assign({ localFullName }, engineInfo);

    if (this.enableLoadingSubstates) {
      // These values are important to register the loading routes under their
      // proper names for the Router and within the Engine's registry.
      let substateName = `${name}_loading`;
      let localFullName = `application_loading`;
      let routeInfo = assign({ localFullName }, engineInfo);
      createRoute(this, substateName, { resetNamespace: options.resetNamespace });
      this.options.addRouteForEngine(substateName, routeInfo);

      substateName = `${name}_error`;
      localFullName = `application_error`;
      routeInfo = assign({ localFullName }, engineInfo);
      createRoute(this, substateName, { resetNamespace: options.resetNamespace, path: dummyErrorRoute });
      this.options.addRouteForEngine(substateName, routeInfo);
    }

    this.options.addRouteForEngine(fullName, routeInfo);

    this.push(path, fullName, callback);
  }
}

export default DSL;

function canNest(dsl) {
  return dsl.parent && dsl.parent !== 'application';
}

function getFullName(dsl, name, resetNamespace) {
  if (canNest(dsl) && resetNamespace !== true) {
    return `${dsl.parent}.${name}`;
  } else {
    return name;
  }
}

function createRoute(dsl, name, options = {}, callback) {
  let fullName = getFullName(dsl, name, options.resetNamespace);

  if (typeof options.path !== 'string') {
    options.path = `/${name}`;
  }

  dsl.push(options.path, fullName, callback, options.serialize);
}

DSL.map = callback => {
  let dsl = new DSL();
  callback.call(dsl);
  return dsl;
};
<|endoftext|>


<commit_before>/**
 * A config function that will create the Destiny account route, which is the parent of
 * all views that care about a particular Destiny account.
 */
export function destinyAccountRoute($stateProvider) {
  'ngInject';

  $stateProvider.state({
    name: 'destiny-account',
    redirectTo: 'destiny2.inventory',
    url: '/:membershipId-{platformType:int}',
    resolve: {
      // TODO: move this to platform/account service
      account: ($transition$, dimPlatformService, $state) => {
        'ngInject';

        const { membershipId, platformType } = $transition$.params();

        // TODO: shouldn't need to load all platforms for this. How can we avoid that?
        return dimPlatformService.getPlatforms()
          .then(() => {
            // TODO: getPlatformMatching should be able to load an account that we don't know
            // TODO: make sure it's a "real" account
            const account = dimPlatformService.getPlatformMatching({
              membershipId,
              platformType,
              destinyVersion: $transition$.$().includes.destiny2 ? 2 : 1
            });
            if (!account) {
              // If we didn't load an account, kick out and re-resolve
              $state.go('default-account');
              return undefined;
            }
            dimPlatformService.setActive(account);
            return account;
          });
      }
    }
  });
}<commit_msg>Fix this thing<commit_after>/**
 * A config function that will create the Destiny account route, which is the parent of
 * all views that care about a particular Destiny account.
 */
export function destinyAccountRoute($stateProvider) {
  'ngInject';

  $stateProvider.state({
    name: 'destiny-account',
    redirectTo: 'destiny2.inventory',
    url: '/:membershipId-{platformType:int}',
    resolve: {
      // TODO: move this to platform/account service
      account: ($transition$, dimPlatformService, $state) => {
        'ngInject';

        const { membershipId, platformType } = $transition$.params();

        // TODO: shouldn't need to load all platforms for this. How can we avoid that?
        return dimPlatformService.getPlatforms()
          .then(() => {
            // TODO: getPlatformMatching should be able to load an account that we don't know
            // TODO: make sure it's a "real" account
            const account = dimPlatformService.getPlatformMatching({
              membershipId,
              platformType,
              destinyVersion: $transition$.$to().includes.destiny2 ? 2 : 1
            });
            if (!account) {
              // If we didn't load an account, kick out and re-resolve
              $state.go('default-account');
              return undefined;
            }
            dimPlatformService.setActive(account);
            return account;
          });
      }
    }
  });
}<|endoftext|>


<commit_before>cc.Class({
    extends: cc.Component,

    properties: {
        attackRadius: 0,
        xSpeed: 0,
        ySpeed: 0,
        animation:{
            default: null,
            type:cc.Animation,
        },
        strength: 0,
        health: 0,
        enemyType: 'dummy',
    },

    // use this for initialization
    onLoad: function () {
        //Will be triggered after being hit by player. This is so that a player
        //will only hit the enemy once with each punch.
        this.left = false;
        this.triggeredAnim = false;
        this.isStanding = false;
        this.isAttacking = false;
        this.animation.play("enemyRunRightAnim_"+this.enemyType);
    },

    getPlayerDistance: function () {
        var playerPos = this.game.player.getPosition();
        var dist = cc.pDistance(this.node.position, playerPos);
        return dist;
    },

    attack: function () {
        // triggerAnimation

        this.animation.play("enemyShootAnim_" + this.enemyType);
        this.isAttacking = true;
        this.node.runAction(
            cc.sequence(
                cc.delayTime(5),
                cc.callFunc(() => {
                    if (Math.abs(this.node.x - this.game.player.x) < this.attackRadius) {
                        this.game.player.getComponent('PlayerScript').health -= this.strength;
                    }
                    this.isAttacking = false;
                    this.isStanding = false;
                    cc.log(this.game.player.getComponent('PlayerScript').health)
                })
            )
        )

    },

    moveEnemy: function(dt){
        var playerX = this.game.player.getPositionX();
        var playerY = this.game.player.getPositionY();
        var xPos = this.node.x;
        var yPos = this.node.y;

        if(!this.isStanding){
            if(yPos <= playerY){
              this.node.y = yPos + this.ySpeed * dt;
            }else {
              this.node.y = yPos - this.ySpeed * dt;
            }

            //von links nach rechts
             if(xPos <= playerX){
                if(this.left == false){
                    this.triggeredAnim = false;
                }else {
                    this.triggeredAnim = true;
                }
              this.node.x = xPos + this.xSpeed * dt;
              this.left = false;

            //von rechts nach links
            }else{
                if(this.left == true){
                    this.triggeredAnim = false;
                }
                else{
                    this.triggeredAnim = true;
                }
              this.node.x = xPos - this.xSpeed * dt;
              this.left = true;
            }

            if(this.left == true && this.triggeredAnim == true){
                this.animation.play("enemyRunLeftAnim_"+this.enemyType);
                            this.triggeredAnim = false;

            }else if (this.left == false && this.triggeredAnim == true){
                this.animation.play("enemyRunRightAnim_"+this.enemyType);
                            this.triggeredAnim = false;
            }
        }
    },

    checkPlayerAttack: function () {
        let playerDirection = this.game.player.getChildByName('PlayerAnimation').scaleX;
        let playerX = this.game.player.getPositionX();
        let playerY = this.game.player.getPositionY();
        let playerStrength = this.game.player.getComponent('PlayerScript').strength;
        let enemyX = this.node.x;
        let enemyY = this.node.y;
        let playerPunch = this.game.player.getComponent('PlayerScript').punch;
        //let playerAttackRadius = this.game.player.getComponent('PlayerScript').attackRadius;
        let playerAttackRadius = 100;

        if(((enemyX - playerX <= 0 && playerDirection <= 0) || (enemyX - playerX >= 0 && playerDirection >= 0)) && playerPunch) {
            if(Math.abs(enemyY - playerY) <= 100 && playerAttackRadius >= Math.abs(enemyX - playerX)){
                this.health -= playerStrength;
                cc.warn('playerx: ', playerX, 'playerY: ', playerY);
                cc.warn('enemyX: ', enemyX, 'enemyY: ', enemyY);
            }
        }
    },

    // called every frame
    update: function (dt) {
        if (this.getPlayerDistance() < this.attackRadius) {
            this.isStanding = true;
            if (!this.isAttacking) {
                this.attack();
            }
            return;
        }
        this.moveEnemy(dt);

        this.checkPlayerAttack();

        if(this.health <= 0) {
            this.node.destroy();
        }
    },
});
<commit_msg>fix enemyAnimation bug #I'mTheBest<commit_after>cc.Class({
    extends: cc.Component,

    properties: {
        attackRadius: 0,
        xSpeed: 0,
        ySpeed: 0,
        animation: {
            default: null,
            type: cc.Animation,
        },
        strength: 0,
        health: 0,
        enemyType: 'dummy',
    },

    // use this for initialization
    onLoad: function () {
        //Will be triggered after being hit by player. This is so that a player
        //will only hit the enemy once with each punch.
        this.left = true;
        this.isStanding = false;
        this.animation.play("enemyRunLeftAnim_" + this.enemyType);
    },

    getPlayerDistance: function () {
        var playerPos = this.game.player.getPosition();
        var dist = cc.pDistance(this.node.position, playerPos);
        return dist;
    },

    attack: function () {
        if (this.getPlayerDistance() < this.attackRadius) {
            this.isStanding = true;
            this.animation.play("enemyShootAnim_" + this.enemyType),
            this.node.runAction(
                cc.sequence(
                    cc.delayTime(5),
                    cc.callFunc(() => {
                        if(this.getPlayerDistance() < this.attackRadius) {
                            this.game.player.getComponent('PlayerScript').health -= this.strength;
                        }
                        this.isStanding = false;
                    })
                )
            )
        }
    },

    moveEnemy: function (dt){
        var playerX = this.game.player.getPositionX();
        var playerY = this.game.player.getPositionY();
        var xPos = this.node.x;
        var yPos = this.node.y;

        // Bewegung in y-Richtung
        if(yPos <= playerY){
          this.node.y += this.ySpeed * dt;
        }else {
          this.node.y -= this.ySpeed * dt;
        }

        // Bewegung in x-Richtung
        if (xPos <= playerX) {
            this.node.x += this.xSpeed * dt;
            this.left = false;
        } else {
            this.node.x -= this.xSpeed * dt;
            this.left = true;
        }

        // Animation
        if (this.left && !this.animation.currentClip.name.includes('enemyRunLeftAnim')) {
            this.animation.play("enemyRunLeftAnim_" + this.enemyType);

        } else if (!this.left && !this.animation.currentClip.name.includes('enemyRunRightAnim')) {
            this.animation.play("enemyRunRightAnim_" + this.enemyType);
        }

    },

    checkPlayerAttack: function () {
        let playerDirection = this.game.player.getChildByName('PlayerAnimation').scaleX;
        let playerX = this.game.player.getPositionX();
        let playerY = this.game.player.getPositionY();
        let playerStrength = this.game.player.getComponent('PlayerScript').strength;
        let enemyX = this.node.x;
        let enemyY = this.node.y;
        let playerPunch = this.game.player.getComponent('PlayerScript').punch;
        //let playerAttackRadius = this.game.player.getComponent('PlayerScript').attackRadius;
        let playerAttackRadius = 100;

        if(((enemyX - playerX <= 0 && playerDirection <= 0) || (enemyX - playerX >= 0 && playerDirection >= 0)) && playerPunch) {
            if(Math.abs(enemyY - playerY) <= 100 && playerAttackRadius >= Math.abs(enemyX - playerX)){
                this.health -= playerStrength;
            }
        }
    },

    // called every frame
    update: function (dt) {
        if (!this.isStanding) this.attack();

        if (!this.isStanding) this.moveEnemy(dt);

        if(this.health <= 0) this.node.destroy();

        this.checkPlayerAttack();
    },
});
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/* jshint maxparams:5 */

var test = require('tape');
var fs = require('fs');
var path = require('path');
var tcurl = require('../index.js');
var TChannel = require('tchannel');
var TChannelAsThrift = require('tchannel/as/thrift.js');

var meta = fs.readFileSync(path.join(__dirname, '..', 'meta.thrift'), 'ascii');
var legacy = fs.readFileSync(path.join(__dirname, 'legacy.thrift'), 'ascii');

test('getting an ok response', function t(assert) {

    var serviceName = 'meta';
    var server = new TChannel({
        serviceName: serviceName
    });

    var opts = {isOptions: true};
    var hostname = '127.0.0.1';
    var port;
    var endpoint = 'Meta::health';

    var tchannelAsThrift = TChannelAsThrift({source: meta});
    tchannelAsThrift.register(server, endpoint, opts, health);

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    function onListening() {
        var cmd = [
            '-p', hostname + ':' + port,
            serviceName,
            endpoint,
            '-t', path.join(__dirname, '..'),
            '-2', JSON.stringify({
                headerName: 'requestHeader'
            })
        ];

        tcurl.exec(cmd, {
            error: function error(err) {
                assert.ifError(err);
            },
            response: function response(res) {
                assert.deepEqual(res.head, {
                    headerName: 'responseHeader'
                }, 'caller receives headers from handler');
                assert.deepEqual(res.body, {
                    ok: true,
                    message: null
                }, 'caller receives thrift body from handler');
            },
            exit: function exit() {
                server.close();
                assert.end();
            }
        });
    }

    function health(options, req, head, body, cb) {
        assert.deepEqual(options, {
            isOptions: true
        }, 'handler receives options through registration');
        assert.deepEqual(head, {
            headerName: 'requestHeader'
        }, 'handler receives request header from CLI');
        assert.deepEqual(body, {}, 'handler receives body from CLI');
        cb(null, {
            ok: true,
            head: {
                headerName: 'responseHeader'
            },
            body: {
                ok: true
            }
        });
    }

});

test('hitting non-existent endpoint', function t(assert) {

    var serviceName = 'meta';
    var server = new TChannel({
        serviceName: serviceName
    });

    var hostname = '127.0.0.1';
    var port;
    var endpoint = 'Meta::health';
    var nonexistentEndpoint = endpoint + 'Foo';

    var tchannelAsThrift = TChannelAsThrift({source: meta});
    tchannelAsThrift.register(server, endpoint, {}, noop);

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    function onListening() {
        var cmd = [
            '-p', hostname + ':' + port,
            serviceName,
            nonexistentEndpoint,
            '-t', path.join(__dirname, '..')
        ];

        tcurl.exec(cmd, {
            error: function error(err) {
                assert.equal(err,
                    nonexistentEndpoint + ' endpoint does not exist',
                    'Warned about non-existent endpoint');
            },
            response: function response(res) {
                assert.fail('should be no response');
            },
            exit: function exit(err) {
                server.close();
                assert.end(err);
            }
        });
    }

    function noop() {}

});

test('fails to run for invalid thrift', function t(assert) {

    var serviceName = 'meta';
    var server = new TChannel({
        serviceName: serviceName
    });

    var hostname = '127.0.0.1';
    var port;

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    function onListening() {

        var cmd = [
            '-p', [hostname, port].join(':'),
            'no-service',
            'no-endpoint',
            '-t', path.join(__dirname, 'legacy.thrift')
        ];

        tcurl.exec(cmd, {
            errorNo: 0,
            error: function error(err) {
                this['error' + (this.errorNo++)](err);
            },
            error0: function error0(err) {
                assert.equal(err, 'Error parsing Thrift IDL');
            },
            error1: function error1(err) {
                assert.equal(err.message,
                    'every field must be marked optional, ' +
                    'required, or have a default value on Feckless including ' +
                    '"ambiguity" in strict mode', 'expected thrift IDL validation error');
            },
            error2: function error2(err) {
                assert.equal(err, 'Consider using --no-strict to bypass mandatory optional/required fields');
            },
            exit: function exit() {
                assert.equal(this.errorNo, 3, 'expect three error lines');
                server.close();
                assert.end();
            }
        });
    }

});

test('tolerates loose thrift with --no-strict', function t(assert) {

    var serviceName = 'legacy';
    var server = new TChannel({
        serviceName: serviceName
    });

    var hostname = '127.0.0.1';
    var port;

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    var tchannelAsThrift = TChannelAsThrift({source: legacy, strict: false});
    tchannelAsThrift.register(server, 'Pinger::ping', {}, ping);

    function onListening() {

        var cmd = [
            '-p', [hostname, port].join(':'),
            'legacy',
            'Pinger::ping',
            '--no-strict',
            '-t', path.join(__dirname, 'legacy.thrift')
        ];

        tcurl.exec(cmd, {
            responded: false,
            error: function error(err) {
                assert.ifError(err);
            },
            response: function response(res) {
                assert.deepEquals(res, {
                    ok: true,
                    body: {pong: true},
                    head: {},
                    headers: {as: 'thrift'},
                    typeName: undefined
                }, 'response ok');
                this.responded = true;
            },
            exit: function exit() {
                assert.ok(this.responded, 'response expected');
                server.close();
                assert.end();
            }
        });
    }

});

function ping(options, req, head, body, cb) {
    cb(null, {ok: true, head: {}, body: {pong: true}});
}
<commit_msg>Use new entryPoint for as=thrift<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

/* jshint maxparams:5 */

var test = require('tape');
var fs = require('fs');
var path = require('path');
var tcurl = require('../index.js');
var TChannel = require('tchannel');
var TChannelAsThrift = require('tchannel/as/thrift.js');

test('getting an ok response', function t(assert) {

    var serviceName = 'meta';
    var server = new TChannel({
        serviceName: serviceName
    });

    var opts = {isOptions: true};
    var hostname = '127.0.0.1';
    var port;
    var endpoint = 'Meta::health';

    var tchannelAsThrift = TChannelAsThrift({
        entryPoint: path.join(__dirname, '..', 'meta.thrift')
    });
    tchannelAsThrift.register(server, endpoint, opts, health);

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    function onListening() {
        var cmd = [
            '-p', hostname + ':' + port,
            serviceName,
            endpoint,
            '-t', path.join(__dirname, '..'),
            '-2', JSON.stringify({
                headerName: 'requestHeader'
            })
        ];

        tcurl.exec(cmd, {
            error: function error(err) {
                assert.ifError(err);
            },
            response: function response(res) {
                assert.deepEqual(res.head, {
                    headerName: 'responseHeader'
                }, 'caller receives headers from handler');
                assert.deepEqual(res.body, {
                    ok: true,
                    message: null
                }, 'caller receives thrift body from handler');
            },
            exit: function exit() {
                server.close();
                assert.end();
            }
        });
    }

    function health(options, req, head, body, cb) {
        assert.deepEqual(options, {
            isOptions: true
        }, 'handler receives options through registration');
        assert.deepEqual(head, {
            headerName: 'requestHeader'
        }, 'handler receives request header from CLI');
        assert.deepEqual(body, {}, 'handler receives body from CLI');
        cb(null, {
            ok: true,
            head: {
                headerName: 'responseHeader'
            },
            body: {
                ok: true
            }
        });
    }

});

test('hitting non-existent endpoint', function t(assert) {

    var serviceName = 'meta';
    var server = new TChannel({
        serviceName: serviceName
    });

    var hostname = '127.0.0.1';
    var port;
    var endpoint = 'Meta::health';
    var nonexistentEndpoint = endpoint + 'Foo';

    var tchannelAsThrift = TChannelAsThrift({
        entryPoint: path.join(__dirname, '..', 'meta.thrift')
    });
    tchannelAsThrift.register(server, endpoint, {}, noop);

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    function onListening() {
        var cmd = [
            '-p', hostname + ':' + port,
            serviceName,
            nonexistentEndpoint,
            '-t', path.join(__dirname, '..')
        ];

        tcurl.exec(cmd, {
            error: function error(err) {
                assert.equal(err,
                    nonexistentEndpoint + ' endpoint does not exist',
                    'Warned about non-existent endpoint');
            },
            response: function response(res) {
                assert.fail('should be no response');
            },
            exit: function exit(err) {
                server.close();
                assert.end(err);
            }
        });
    }

    function noop() {}

});

test('fails to run for invalid thrift', function t(assert) {

    var serviceName = 'meta';
    var server = new TChannel({
        serviceName: serviceName
    });

    var hostname = '127.0.0.1';
    var port;

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    function onListening() {

        var cmd = [
            '-p', [hostname, port].join(':'),
            'no-service',
            'no-endpoint',
            '-t', path.join(__dirname, 'legacy.thrift')
        ];

        tcurl.exec(cmd, {
            errorNo: 0,
            error: function error(err) {
                this['error' + (this.errorNo++)](err);
            },
            error0: function error0(err) {
                assert.equal(err, 'Error parsing Thrift IDL');
            },
            error1: function error1(err) {
                assert.equal(err.message,
                    'every field must be marked optional, ' +
                    'required, or have a default value on Feckless including ' +
                    '"ambiguity" in strict mode', 'expected thrift IDL validation error');
            },
            error2: function error2(err) {
                assert.equal(err, 'Consider using --no-strict to bypass mandatory optional/required fields');
            },
            exit: function exit() {
                assert.equal(this.errorNo, 3, 'expect three error lines');
                server.close();
                assert.end();
            }
        });
    }

});

test('tolerates loose thrift with --no-strict', function t(assert) {

    var serviceName = 'legacy';
    var server = new TChannel({
        serviceName: serviceName
    });

    var hostname = '127.0.0.1';
    var port;

    function onServerListen() {
        port = server.address().port;
        onListening();
    }

    server.listen(0, hostname, onServerListen);

    var tchannelAsThrift = TChannelAsThrift({
        entryPoint: path.join(__dirname, 'legacy.thrift'),
        strict: false
    });
    tchannelAsThrift.register(server, 'Pinger::ping', {}, ping);

    function onListening() {

        var cmd = [
            '-p', [hostname, port].join(':'),
            'legacy',
            'Pinger::ping',
            '--no-strict',
            '-t', path.join(__dirname, 'legacy.thrift')
        ];

        tcurl.exec(cmd, {
            responded: false,
            error: function error(err) {
                assert.ifError(err);
            },
            response: function response(res) {
                assert.deepEquals(res, {
                    ok: true,
                    body: {pong: true},
                    head: {},
                    headers: {as: 'thrift'},
                    typeName: undefined
                }, 'response ok');
                this.responded = true;
            },
            exit: function exit() {
                assert.ok(this.responded, 'response expected');
                server.close();
                assert.end();
            }
        });
    }

});

function ping(options, req, head, body, cb) {
    cb(null, {ok: true, head: {}, body: {pong: true}});
}
<|endoftext|>


<commit_before>var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var SimpleGame;
(function (SimpleGame) {
    var Preloader = (function (_super) {
        __extends(Preloader, _super);
        function Preloader() {
            _super.apply(this, arguments);
        }
        Preloader.prototype.preload = function () {
            //  Set-up our preloader sprite
            this.preloadBar = this.add.sprite(200, 250, 'preloadBar');
            this.load.setPreloadSprite(this.preloadBar);
            //  Load our actual games assets
            this.load.image('titlepage', 'assets/titlepage.jpg');
            this.load.image('logo', 'assets/logo.png');
            this.load.audio('music', 'assets/title.mp3', true);
            //this.load.spritesheet('simon', 'assets/simon.png', 58, 96, 5);
            this.load.spritesheet('knight', 'assets/knight2.png', 48, 96, 3);
            this.load.image('level1', 'assets/level1.png');
            this.load.image('platform', 'assets/platform.png');
        };
        Preloader.prototype.create = function () {
            var tween = this.add.tween(this.preloadBar).to({ alpha: 0 }, 1000, Phaser.Easing.Linear.None, true);
            tween.onComplete.add(this.startMainMenu, this);
        };
        Preloader.prototype.startMainMenu = function () {
            //this.game.state.start('MainMenu', true, false);
            this.game.state.start('Level1', true, false);
        };
        return Preloader;
    })(Phaser.State);
    SimpleGame.Preloader = Preloader;
})(SimpleGame || (SimpleGame = {}));
//# sourceMappingURL=Preloader.js.map<commit_msg>Delete Preloader.js<commit_after><|endoftext|>


<commit_before>var tape = require('tape');
var queue = require('../');

tape('autostart', function(t) {
  t.plan(9);
  var expected = [ 'one', 'two', 'three' ];
  var actual = [];
  var q = queue({ autostart: true });
  var numEndHandlers = 0;

  q.on('end', function() {
    numEndHandlers++;
    t.equal(actual.length, numEndHandlers);

    for (var i in actual) {
      t.equal(actual[i], expected[i]);
    }
  });

  q.push(function(cb) {
    actual.push('one');
    cb();
  });
  q.push(function (cb) {
    actual.push('two');
    cb();
  });
  setTimeout(function () {
    q.push(function (cb) {
      actual.push('three');
      cb();
    });
  }, 1000);
})
<commit_msg>autostart test: style nits<commit_after>var tape = require('tape');
var queue = require('../');

tape('autostart', function(t) {
  t.plan(9);

  var expected = [ 'one', 'two', 'three' ];
  var actual = [];
  var q = queue({ autostart: true });
  var numEndHandlers = 0;

  q.on('end', function() {
    numEndHandlers++;
    t.equal(actual.length, numEndHandlers);

    for (var i in actual) {
      t.equal(actual[i], expected[i]);
    }
  });

  q.push(function(cb) {
    actual.push('one');
    cb();
  });

  q.push(function (cb) {
    actual.push('two');
    cb();
  });

  setTimeout(function () {
    q.push(function (cb) {
      actual.push('three');
      cb();
    });
  }, 100);
})
<|endoftext|>


<commit_before>var expect = require('expect.js');
var conf = require('../config.js');

describe('Config', function() {
    it('should, by, default, return empty configuration', function(done) {
        var result = conf.getConfig();
        expect(result).to.equal({});
        done();
    });

    it('should throw an exception if the base config file does not exist',
        function(done) {
            expect(function() {
                conf.setBaseConfig('bad-path.json');
            }).to.throwException();
            done();
        }
    );

    it('should throw an exception if the base config if not JSON',
        function(done) {
            expect(function() {
                conf.setBaseConfig('data/invalid-base-config.txt');
            }).to.throwException();
            done();
        }
    );

    it('should not error if the environment prefix is undefined',
        function(done) {
            conf.setEnvironmentPrefix(undefined);
            done();
        }
    );

    it('should throw an exception if the config does not exist',
        function(done) {
            expect(function() {
                conf.init('bad-path.json');
            }).to.throwException();
            done();
        }
    );

    it('should throw an exception if the config is not JSON',
        function(done) {
            expect(function() {
                conf.init('data/invalid-config.txt');
            }).to.throwException();
            done();
        }
    );

    it('should correctly return environment overridden string values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 'string-item1-env-value';
            var element = 'string-item1';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return environment overridden boolean values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = true;
            var element = 'boolean-item1';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return environment overridden int values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 11;
            var element = 'int-item1';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return environment overridden float values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 1.1;
            var element = 'float-item1';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return environment overridden nested values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 'nested-item1-env-value';
            var config = conf.getConfig();
            var value = conf.getConfig('nested-items.nested-item1');
            expect(config['nested-items']['nested-item1']).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return environment overridden list values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = [ "env-list1-item1",
                               "env-list1-item2",
                               "env-list1-item3" ];
            var element = 'list-items1';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return overridden string values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 'string-item2-config-value';
            var element = 'string-item2';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return overridden boolean values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = false;
            var element = 'boolean-item2';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return overridden int values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 22;
            var element = 'int-item2';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return overridden float values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 2.2;
            var element = 'float-item2';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return overridden nested values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 'nested-item2-config-value';
            var config = conf.getConfig();
            var value = conf.getConfig('nested-items.nested-item2');
            expect(config['nested-items']['nested-item2']).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return overridden list values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = [ "config-list1-item1",
                               "config-list1-item2",
                               "config-list1-item3" ];
            var element = 'list-items2';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return un-overridden string base values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 'string-item3-base-value';
            var element = 'string-item3';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return un-overridden boolean base values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = true;
            var element = 'boolean-item3';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return un-overridden int base values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 33;
            var element = 'int-item3';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return un-overridden float base values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 3.3;
            var element = 'float-item3';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return un-overridden nested base values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 'nested-item3-base-value';
            var config = conf.getConfig();
            var value = conf.getConfig('nested-items.nested-item3');
            expect(config['nested-items']['nested-item3']).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should correctly return un-overridden list base values',
        function(done) {
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = [ "base-list1-item1",
                               "base-list1-item2",
                               "base-list1-item3" ];
            var element = 'list-items3';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );

    it('should allow an environment prefix',
        function(done) {
            conf.setEnvironmentPrefix("PREFIX");
            conf.setBaseConfig('data/valid-base-config.json');
            conf.init('data/valid-config.json');

            var validValue = 'string-item1-prefix-value';
            var element = 'string-item1';
            var config = conf.getConfig();
            var value = conf.getConfig(element);
            expect(config[element]).to.equal(validValue);
            expect(value).to.equal(validValue);
            done();
        }
    );
});<commit_msg>Rewrite unit tests to compare against an expected JSON file<commit_after>var expect = require('expect.js');
var conf = require('../config.js');

describe('Config', function() {
    it('should, by, default, return empty configuration', function(done) {
        var result = conf.getConfig();
        expect(result).to.eql({});
        done();
    });

    it('should throw an exception if the base config file does not exist',
        function(done) {
            expect(function() {
                conf.setBaseConfig('bad-path.json');
            }).to.throwException();
            done();
        }
    );

    it('should throw an exception if the base config if not JSON',
        function(done) {
            expect(function() {
                conf.setBaseConfig('./test/data/invalid-base-config.txt');
            }).to.throwException();
            done();
        }
    );

    it('should not error if the environment prefix is undefined',
        function(done) {
            conf.setEnvironmentPrefix(undefined);
            done();
        }
    );

    it('should throw an exception if the config does not exist',
        function(done) {
            expect(function() {
                conf.init('bad-path.json');
            }).to.throwException();
            done();
        }
    );

    it('should throw an exception if the config is not JSON',
        function(done) {
            expect(function() {
                conf.init('./test/data/invalid-config.txt');
            }).to.throwException();
            done();
        }
    );

    it('should construct a correctly merged and overridden config object',
        function(done) {
            conf.setBaseConfig('./test/data/valid-base-config.json');
            conf.init('./test/data/valid-config.json');

            var expected = require('./data/expected-config.json');
            var config = conf.getConfig();
            expect(config).to.eql(expected);
            done();
        }
    );

    it('should allow an environment prefix',
        function(done) {
            conf.setEnvironmentPrefix("PREFIX");
            conf.setBaseConfig('./test/data/valid-base-config.json');
            conf.init('./test/data/valid-config.json');

            var config = conf.getConfig();
            expect(config['string-item1']).to.equal('string-item1-prefix-value');
            done();
        }
    );
});<|endoftext|>


<commit_before>import { type } from './type'

export function composeAsync(...inputArguments){
  return async function (startArgument){
    let argumentsToPass = startArgument

    while (inputArguments.length !== 0){
      const fn = inputArguments.pop()
      const typeFn = type(fn)

      if (typeFn === 'Async'){
        argumentsToPass = await fn(argumentsToPass)
      } else {
        argumentsToPass = fn(argumentsToPass)
        if(type(argumentsToPass) === 'Promise'){
          argumentsToPass = await argumentsToPass
          console.log(23)
        }
        const a = type(argumentsToPass)
        console.log(argumentsToPass,a )
      }
    }

    return argumentsToPass
  }
}
<commit_msg>chore@small remove logs<commit_after>import { type } from './type'

export function composeAsync(...inputArguments){
  return async function (startArgument){
    let argumentsToPass = startArgument

    while (inputArguments.length !== 0){
      const fn = inputArguments.pop()
      const typeFn = type(fn)

      if (typeFn === 'Async'){
        argumentsToPass = await fn(argumentsToPass)
      } else {
        argumentsToPass = fn(argumentsToPass)
        if(type(argumentsToPass) === 'Promise'){
          argumentsToPass = await argumentsToPass
        }
      }
    }

    return argumentsToPass
  }
}
<|endoftext|>


<commit_before>
require.paths.unshift(__dirname + '/../lib/');

Client = require('client');
EventEmitter = require('events').EventEmitter;

sys = require('sys');
assert = require('assert');
BufferList = require(__dirname+'/buffer-list')
buffers = require(__dirname + '/test-buffers');
Connection = require('connection');
var args = require(__dirname + '/cli');

assert.same = function(actual, expected) {
  for(var key in expected) {
    assert.equal(actual[key], expected[key]);
  }
};

assert.emits = function(item, eventName, callback) {
  var called = false;
  var id = setTimeout(function() {
    test("Should have called " + eventName, function() {
      assert.ok(called, "Expected '" + eventName + "' to be called.")
    });
  },20000);

  item.once(eventName, function() {
    called = true;
    clearTimeout(id);
    assert.ok(true);
    if(callback) {
      callback.apply(item, arguments);
    }
  });
};

assert.UTCDate = function(actual, year, month, day, hours, min, sec, milisecond) {
  var actualYear = actual.getUTCFullYear();
  assert.equal(actualYear, year, "expected year " + year + " but got " + actualYear);

  var actualDate = actual.getUTCDate();
  assert.equal(actualDate, day, "expected day " + day + " but got " + actualDate);

  var actualHours = actual.getUTCHours();
  assert.equal(actualHours, hours, "expected hours " + hours + " but got " + actualHours);

  var actualMin = actual.getUTCMinutes();
  assert.equal(actualMin, min, "expected min " + min + " but got " + actualMin);

  var actualSec = actual.getUTCSeconds();
  assert.equal(actualSec, sec, "expected sec " + sec + " but got " + actualSec);

  var actualMili = actual.getUTCMilliseconds();
  assert.equal(actualMili, milisecond, "expected milisecond " + milisecond + " but got " + actualMili);
};

assert.equalBuffers = function(actual, expected) {
  if(actual.length != expected.length) {
    console.log("");
    console.log("actual " + sys.inspect(actual));
    console.log("expect " + sys.inspect(expected));
    console.log("");
    assert.equal(actual.length, expected.length);
  }
  for(var i = 0; i < actual.length; i++) {
    if(actual[i] != expected[i]) {
      console.log(actual);
      console.log(expected);
    }
    assert.equal(actual[i],expected[i]);
  }
};

assert.empty = function(actual) {
  assert.length(actual, 0);
};

assert.length = function(actual, expectedLength) {
  assert.equal(actual.length, expectedLength);
};

var expect = function(callback) {
  var executed = false;
  var id = setTimeout(function() {
    assert.ok(executed, "Expected execution of " + callback + " fired");
  }, 1000)

  return function(err, queryResult) {
    clearTimeout(id);
    assert.ok(true);
    callback.apply(this, arguments)
  }
}
assert.calls = expect;

['equal', 'length', 'empty', 'strictEqual', 'emits', 'equalBuffers', 'same', 'calls', 'ok'].forEach(function(name) {
  var old = assert[name];
  assert[name] = function() {
    test.assertCount++
    return old.apply(this, arguments);
  };
});

test = function(name, action) {
  try{
    test.testCount ++;
    var result = action();
    if(result === false) {
      test.ignored.push(name);
      process.stdout.write('?');
    }else{
      process.stdout.write('.');
    }
  }catch(e) {
    process.stdout.write('E');
    test.errors.push({name: name, e: e});
  }
};

test.assertCount = test.assertCount || 0;
test.testCount = test.testCount || 0;
test.ignored = test.ignored || [];
test.errors = test.errors || [];
test.start = test.start || new Date();

process.on('exit', function() {
  console.log('');
  var duration = ((new Date() - test.start)/1000);
  console.log(test.testCount + ' tests ' + test.assertCount + ' assertions in ' + duration + ' seconds');
  test.ignored.forEach(function(name) {
    console.log("Ignored: " + name);
  });
  test.errors.forEach(function(error) {
    console.log("Error: " + error.name);
  });
  test.errors.forEach(function(error) {
    throw error.e;
  });
});

module.exports = {
  args: args
};
<commit_msg>made timeout lenght of assert.calls configurable and made tests die sooner on error<commit_after>
require.paths.unshift(__dirname + '/../lib/');

Client = require('client');
EventEmitter = require('events').EventEmitter;

sys = require('sys');
assert = require('assert');
BufferList = require(__dirname+'/buffer-list')
buffers = require(__dirname + '/test-buffers');
Connection = require('connection');
var args = require(__dirname + '/cli');

assert.same = function(actual, expected) {
  for(var key in expected) {
    assert.equal(actual[key], expected[key]);
  }
};

assert.emits = function(item, eventName, callback) {
  var called = false;
  var id = setTimeout(function() {
    test("Should have called " + eventName, function() {
      assert.ok(called, "Expected '" + eventName + "' to be called.")
    });
  },20000);

  item.once(eventName, function() {
    called = true;
    clearTimeout(id);
    assert.ok(true);
    if(callback) {
      callback.apply(item, arguments);
    }
  });
};

assert.UTCDate = function(actual, year, month, day, hours, min, sec, milisecond) {
  var actualYear = actual.getUTCFullYear();
  assert.equal(actualYear, year, "expected year " + year + " but got " + actualYear);

  var actualDate = actual.getUTCDate();
  assert.equal(actualDate, day, "expected day " + day + " but got " + actualDate);

  var actualHours = actual.getUTCHours();
  assert.equal(actualHours, hours, "expected hours " + hours + " but got " + actualHours);

  var actualMin = actual.getUTCMinutes();
  assert.equal(actualMin, min, "expected min " + min + " but got " + actualMin);

  var actualSec = actual.getUTCSeconds();
  assert.equal(actualSec, sec, "expected sec " + sec + " but got " + actualSec);

  var actualMili = actual.getUTCMilliseconds();
  assert.equal(actualMili, milisecond, "expected milisecond " + milisecond + " but got " + actualMili);
};

assert.equalBuffers = function(actual, expected) {
  if(actual.length != expected.length) {
    console.log("");
    console.log("actual " + sys.inspect(actual));
    console.log("expect " + sys.inspect(expected));
    console.log("");
    assert.equal(actual.length, expected.length);
  }
  for(var i = 0; i < actual.length; i++) {
    if(actual[i] != expected[i]) {
      console.log(actual);
      console.log(expected);
    }
    assert.equal(actual[i],expected[i]);
  }
};

assert.empty = function(actual) {
  assert.length(actual, 0);
};

assert.length = function(actual, expectedLength) {
  assert.equal(actual.length, expectedLength);
};

var expect = function(callback, timeout) {
  var executed = false;
  var id = setTimeout(function() {
    assert.ok(executed, "Expected execution of " + callback + " fired");
  }, timeout || 1000)

  return function(err, queryResult) {
    clearTimeout(id);
    assert.ok(true);
    callback.apply(this, arguments)
  }
}
assert.calls = expect;

['equal', 'length', 'empty', 'strictEqual', 'emits', 'equalBuffers', 'same', 'calls', 'ok'].forEach(function(name) {
  var old = assert[name];
  assert[name] = function() {
    test.assertCount++
    return old.apply(this, arguments);
  };
});

test = function(name, action) {
  test.testCount ++;
  var result = action();
  if(result === false) {
    test.ignored.push(name);
    process.stdout.write('?');
  }else{
    process.stdout.write('.');
  }
};

test.assertCount = test.assertCount || 0;
test.testCount = test.testCount || 0;
test.ignored = test.ignored || [];
test.errors = test.errors || [];
test.start = test.start || new Date();

process.on('exit', function() {
  console.log('');
  var duration = ((new Date() - test.start)/1000);
  console.log(test.testCount + ' tests ' + test.assertCount + ' assertions in ' + duration + ' seconds');
  test.ignored.forEach(function(name) {
    console.log("Ignored: " + name);
  });
  test.errors.forEach(function(error) {
    console.log("Error: " + error.name);
  });
  test.errors.forEach(function(error) {
    throw error.e;
  });
});

module.exports = {
  args: args
};
<|endoftext|>


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

var dummyLayoutEngine = require('./../lib/layout/dummyLayout');
var springLayoutEngine = require('./../lib/layout/forceDirectedLayout');

var parse = require('./../lib/parse/parse.js');
var graphsDir = path.join(__dirname , 'graphs');

var getGraph = function(name) {
  var gcl = String(fs.readFileSync(path.join(graphsDir, name + '.gcl')));
  var graph = parse(gcl);
  return graph;
};

describe('dummy layout engine', function() {
  it('should take a graph and not blow up', function(done) {
    var testGraph = getGraph('edge');
    dummyLayoutEngine(testGraph);
    testGraph.should.be.an.instanceOf(Graph);
    done();
  });
});

describe('spring layout engine', function() {
  it('should take a graph and not blow up', function(done) {
    var testGraph = getGraph('getGraph');
    springLayoutEngine(testGraph);
    testGraph.should.be.an.instanceOf(Graph);
    done();
  });
});
<commit_msg>bad file name<commit_after>var fs = require('fs');
var path = require('path');
var should = require('should');

var dummyLayoutEngine = require('./../lib/layout/dummyLayout');
var springLayoutEngine = require('./../lib/layout/forceDirectedLayout');

var parse = require('./../lib/parse/parse.js');
var graphsDir = path.join(__dirname , 'graphs');

var getGraph = function(name) {
  var gcl = String(fs.readFileSync(path.join(graphsDir, name + '.gcl')));
  var graph = parse(gcl);
  return graph;
};

describe('dummy layout engine', function() {
  it('should take a graph and not blow up', function(done) {
    var testGraph = getGraph('edge');
    dummyLayoutEngine(testGraph);
    testGraph.should.be.an.instanceOf(Graph);
    done();
  });
});

describe('spring layout engine', function() {
  it('should take a graph and not blow up', function(done) {
    var testGraph = getGraph('edge');
    springLayoutEngine(testGraph);
    testGraph.should.be.an.instanceOf(Graph);
    done();
  });
});
<|endoftext|>


<commit_before><commit_msg>Fix remaining block type reference<commit_after><|endoftext|>