<commit_before>import mixin from 'smart-mixin';

var cache = {},
    BaseClass;

export default function(registry, {
  ruleset = {},
  naming = false
} = {}) {
  ruleset = Object.keys(ruleset)
                  .reduce((mixinRuleset, classRule) => {
                    mixinRuleset[classRule] = Object.keys(ruleset[classRule])
                                                    .reduce((mixinClassRuleset, methodRule) => {
                                                      mixinClassRuleset[methodRule] = mixin[ruleset[classRule][methodRule]];

                                                      return mixinClassRuleset;
                                                    }, {});

                    return mixinRuleset;
                  }, {});

  Object.assign(ruleset, {
    ReactComponent: {
      componentWillMount: mixin.MANY,
      componentDidMount: mixin.MANY,
      componentWillReceiveProps: mixin.MANY,
      shouldComponentUpdate: mixin.ONCE,
      componentWillUpdate: mixin.MANY,
      componentDidUpdate: mixin.MANY,
      componentWillUnmount: mixin.MANY,

      getInitialState: mixin.MANY_MERGED,
      getDefaultProps: mixin.MANY_MERGED
    }
  });

  return {
    on(baseclass) {
      BaseClass = baseclass;
    },

    using(descriptor) {
      const traits = descriptor[0].split(' '),
            traitsClassName = `${BaseClass.name}_with_${traits.join('_and_')}`;

      if (cache[traitsClassName]) {
        return cache[traitsClassName];
      } else {
        class TraitsClass extends BaseClass {
          constructor(...args) {
            super(...args);

            traits.map(x => {
              const {constructor, ...methods} = registry[x];

              'constructor' === constructor.name && constructor.call(this);

              mixin(ruleset[BaseClass.name] || {})(this.constructor.prototype, methods);
            });
          }
        }

        naming && eval(`TraitsClass = (function (BaseClass) {
                          ${TraitsClass.toString().split('TraitsClass').join(traitsClassName)}
                          _inherits(${traitsClassName}, BaseClass);

                          return ${traitsClassName};
                        })(BaseClass);`);

        return cache[traitsClassName] = TraitsClass;
      }
    }
  };
}
<commit_msg>[breaking] Adopt new API<commit_after>import mixin from 'smart-mixin';

var cache = {},
    BaseClass;

export default function({
  ruleset = {},
  naming = false
} = {}) {
  ruleset = Object.keys(ruleset)
                  .reduce((mixinRuleset, classRule) => {
                    mixinRuleset[classRule] = Object.keys(ruleset[classRule])
                                                    .reduce((mixinClassRuleset, methodRule) => {
                                                      mixinClassRuleset[methodRule] = mixin[ruleset[classRule][methodRule]];

                                                      return mixinClassRuleset;
                                                    }, {});

                    return mixinRuleset;
                  }, {});

  Object.assign(ruleset, {
    ReactComponent: {
      componentWillMount: mixin.MANY,
      componentDidMount: mixin.MANY,
      componentWillReceiveProps: mixin.MANY,
      shouldComponentUpdate: mixin.ONCE,
      componentWillUpdate: mixin.MANY,
      componentDidUpdate: mixin.MANY,
      componentWillUnmount: mixin.MANY,

      getInitialState: mixin.MANY_MERGED,
      getDefaultProps: mixin.MANY_MERGED
    }
  });

  return {
    on(baseclass) {
      BaseClass = baseclass;
    },

    using(...traits) {
      const traitsClassName = `${BaseClass.name}_with_${traits.map(x => x.toString().slice(8, -1)).join('_and_').replace(' ', '_')}`;

      if (cache[traitsClassName]) {
        return cache[traitsClassName];
      } else {
        class TraitsClass extends BaseClass {
          constructor(...args) {
            super(...args);

            traits.map(x => {
              const {constructor, ...methods} = x;

              'constructor' === constructor.name && constructor.call(this);

              mixin(ruleset[BaseClass.name] || {})(this.constructor.prototype, methods);
            });
          }
        }

        naming && eval(`TraitsClass = (function (BaseClass) {
                          ${TraitsClass.toString().split('TraitsClass').join(traitsClassName)}
                          _inherits(${traitsClassName}, BaseClass);

                          return ${traitsClassName};
                        })(BaseClass);`);

        return cache[traitsClassName] = TraitsClass;
      }
    }
  };
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const _ = require('lodash');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the countingValleys function below.
function countingValleys(numberOfSteps, steps) {
    let altitude = 0;
    let enteringValley = 0;
    steps.split("").forEach(step => {
        if (step === "D") {
            if (altitude === 0) {
                enteringValley += 1
            }
            altitude -= 1
        } else if (step === "U") {
            altitude += 1
        }
    })
    return enteringValley;
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const numberOfSteps = parseInt(readLine(), 10);

    const path = readLine();

    let result = countingValleys(numberOfSteps, path);

    ws.write(result + "\n");

    ws.end();
}
<commit_msg>Extract helpers for isDownhill and isUphill<commit_after>'use strict';

const fs = require('fs');
const _ = require('lodash');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the countingValleys function below.
function countingValleys(numberOfSteps, steps) {
    let altitude = 0;
    let enteringValley = 0;
    steps.split("").forEach(step => {
        if (isDownhill(step)) {
            if (altitude === 0) {
                enteringValley += 1
            }
            altitude -= 1
        } else if (isUphill(step)) {
            altitude += 1
        }
    })
    return enteringValley;
}

function isDownhill(step) {
    return step === "D"
}

function isUphill(step) {
    return step === "U"
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const numberOfSteps = parseInt(readLine(), 10);

    const path = readLine();

    let result = countingValleys(numberOfSteps, path);

    ws.write(result + "\n");

    ws.end();
}
<|endoftext|>


<commit_before>import macro from 'vtk.js/Sources/macro';
import vtkOpenGLRenderWindow from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow';
import vtkRenderer from 'vtk.js/Sources/Rendering/Core/Renderer';
import vtkRenderWindow from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import vtkRenderWindowInteractor from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor';
import vtkInteractorStyleTrackballCamera from 'vtk.js/Sources/Interaction/Style/InteractorStyleTrackballCamera';

// Load basic classes for vtk() factory
import 'vtk.js/Sources/Common/Core/Points';
import 'vtk.js/Sources/Common/Core/DataArray';
import 'vtk.js/Sources/Common/DataModel/PolyData';
import 'vtk.js/Sources/Rendering/Core/Actor';
import 'vtk.js/Sources/Rendering/Core/Mapper';

function vtkGenericRenderWindow(publicAPI, model) {
  // Capture resize trigger method to remove from publicAPI
  const invokeResize = publicAPI.invokeResize;
  delete publicAPI.invokeResize;

  // VTK renderWindow/renderer
  model.renderWindow = vtkRenderWindow.newInstance();
  model.renderer = vtkRenderer.newInstance();
  model.renderWindow.addRenderer(model.renderer);

  // OpenGLRenderWindow
  model.openGLRenderWindow = vtkOpenGLRenderWindow.newInstance();
  model.renderWindow.addView(model.openGLRenderWindow);

  // Interactor
  model.interactor = vtkRenderWindowInteractor.newInstance();
  model.interactor.setInteractorStyle(
    vtkInteractorStyleTrackballCamera.newInstance()
  );
  model.interactor.setView(model.openGLRenderWindow);
  model.interactor.initialize();

  // Expose background
  publicAPI.setBackground = model.renderer.setBackground;

  // Update BG color
  publicAPI.setBackground(...model.background);

  // Handle window resize
  publicAPI.resize = () => {
    if (model.container) {
      const dims = model.container.getBoundingClientRect();
      const devicePixelRatio = window.devicePixelRatio || 1;
      model.openGLRenderWindow.setSize(
        Math.floor(dims.width * devicePixelRatio),
        Math.floor(dims.height * devicePixelRatio)
      );
      invokeResize();
      model.renderWindow.render();
    }
  };

  // Handle DOM container relocation
  publicAPI.setContainer = (el) => {
    if (model.container) {
      model.openGLRenderWindow.setContainer(model.container);
      model.interactor.unbindEvents(model.container);
    }

    // Switch container
    model.container = el;

    // Bind to new container
    if (model.container) {
      model.openGLRenderWindow.setContainer(model.container);
      model.interactor.bindEvents(model.container);
    }
  };

  // Properly release GL context
  publicAPI.delete = macro.chain(
    publicAPI.setContainer,
    model.openGLRenderWindow.delete,
    publicAPI.delete
  );

  // Handle size
  if (model.listenWindowResize) {
    window.addEventListener('resize', publicAPI.resize);
  }
  publicAPI.resize();
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  background: [0.32, 0.34, 0.43],
  listenWindowResize: true,
  container: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Object methods
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, [
    'renderWindow',
    'renderer',
    'openGLRenderWindow',
    'interactor',
    'container',
  ]);
  macro.event(publicAPI, model, 'resize');

  // Object specific methods
  vtkGenericRenderWindow(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(GenericRenderWindow): Properly handle container<commit_after>import macro from 'vtk.js/Sources/macro';
import vtkOpenGLRenderWindow from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow';
import vtkRenderer from 'vtk.js/Sources/Rendering/Core/Renderer';
import vtkRenderWindow from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import vtkRenderWindowInteractor from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor';
import vtkInteractorStyleTrackballCamera from 'vtk.js/Sources/Interaction/Style/InteractorStyleTrackballCamera';

// Load basic classes for vtk() factory
import 'vtk.js/Sources/Common/Core/Points';
import 'vtk.js/Sources/Common/Core/DataArray';
import 'vtk.js/Sources/Common/DataModel/PolyData';
import 'vtk.js/Sources/Rendering/Core/Actor';
import 'vtk.js/Sources/Rendering/Core/Mapper';

function vtkGenericRenderWindow(publicAPI, model) {
  // Capture resize trigger method to remove from publicAPI
  const invokeResize = publicAPI.invokeResize;
  delete publicAPI.invokeResize;

  // VTK renderWindow/renderer
  model.renderWindow = vtkRenderWindow.newInstance();
  model.renderer = vtkRenderer.newInstance();
  model.renderWindow.addRenderer(model.renderer);

  // OpenGLRenderWindow
  model.openGLRenderWindow = vtkOpenGLRenderWindow.newInstance();
  model.renderWindow.addView(model.openGLRenderWindow);

  // Interactor
  model.interactor = vtkRenderWindowInteractor.newInstance();
  model.interactor.setInteractorStyle(
    vtkInteractorStyleTrackballCamera.newInstance()
  );
  model.interactor.setView(model.openGLRenderWindow);
  model.interactor.initialize();

  // Expose background
  publicAPI.setBackground = model.renderer.setBackground;

  // Update BG color
  publicAPI.setBackground(...model.background);

  // Handle window resize
  publicAPI.resize = () => {
    if (model.container) {
      const dims = model.container.getBoundingClientRect();
      const devicePixelRatio = window.devicePixelRatio || 1;
      model.openGLRenderWindow.setSize(
        Math.floor(dims.width * devicePixelRatio),
        Math.floor(dims.height * devicePixelRatio)
      );
      invokeResize();
      model.renderWindow.render();
    }
  };

  // Handle DOM container relocation
  publicAPI.setContainer = (el) => {
    if (model.container) {
      model.interactor.unbindEvents(model.container);
    }

    // Switch container
    model.container = el;
    model.openGLRenderWindow.setContainer(model.container);

    // Bind to new container
    if (model.container) {
      model.interactor.bindEvents(model.container);
    }
  };

  // Properly release GL context
  publicAPI.delete = macro.chain(
    publicAPI.setContainer,
    model.openGLRenderWindow.delete,
    publicAPI.delete
  );

  // Handle size
  if (model.listenWindowResize) {
    window.addEventListener('resize', publicAPI.resize);
  }
  publicAPI.resize();
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  background: [0.32, 0.34, 0.43],
  listenWindowResize: true,
  container: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Object methods
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, [
    'renderWindow',
    'renderer',
    'openGLRenderWindow',
    'interactor',
    'container',
  ]);
  macro.event(publicAPI, model, 'resize');

  // Object specific methods
  vtkGenericRenderWindow(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>var ActorClient = require('../utils/ActorClient');

var VisibilityActionCreators = {
  createAppHidden: function() {
    console.warn('onAppHidden');
    ActorClient.onAppHidden();
  },

  createAppVisible: function() {
    console.warn('onAppVisible');
    ActorClient.onAppVisible();
  }
};

module.exports = VisibilityActionCreators;
<commit_msg>refactor(web): removed unnessesary logging<commit_after>var ActorClient = require('../utils/ActorClient');

var VisibilityActionCreators = {
  createAppHidden: function() {
    ActorClient.onAppHidden();
  },

  createAppVisible: function() {
    ActorClient.onAppVisible();
  }
};

module.exports = VisibilityActionCreators;
<|endoftext|>


<commit_before>function nullConverter(url) {
	return url;
}

/**
 * TinyMCE initialisation template.
 * $ variables are replaced by string search & replace.  It's pretty crude.
 */
// Prevents "Error: 'tinyMCE' is undefined" error in IE7 on Newsletter Recipient import.
if((typeof tinyMCE != 'undefined')) {
	tinyMCE.init({
		mode : "specific_textareas",
		textarea_trigger : "tinymce",
		width: -1,
		height: -1,
		auto_resize : true,
		theme : "advanced",
		content_css : "$ContentCSS",
		document_base_url: "$BaseURL",
		urlconverter_callback : "nullConverter",

		setupcontent_callback : "sapphiremce_setupcontent",
		cleanup_callback : "sapphiremce_cleanup",

		Theme_Advanced_Layout_manager : "SimpleLayout",
		theme_advanced_toolbar_location : "manually_placed",
		theme_advanced_toolbar_align : "left",
		theme_advanced_toolbar_parent : "right",
		plugins : "contextmenu,table,emotions,flash",
		table_inline_editing : true,
		theme_advanced_buttons1 : "italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,separator,bullist,numlist,outdent,indent,hr,charmap",
		theme_advanced_buttons2 : "undo,redo,separator,cut,copy,paste,separator,search,replace,separator,flash",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons3_add : "emotions",
	/*
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,separator,bullist,numlist,outdent,indent,hr,charmap",
		theme_advanced_buttons2 : "undo,redo,separator,cut,copy,paste,separator,search,replace,separator,link,unlink,anchor,image,separator,cleanup,removeformat,visualaid,code,separator,tablecontrols",
	*/
		safari_warning : false,
		relative_urls : true,
		verify_html : true,
		valid_elements : "+a[id|rel|rev|dir|tabindex|accesskey|type|name|href|target|title|class],-strong/-b[class],-em/-i[class],-strike[class],-u[class],#p[id|dir|class|align],-ol[class],-ul[class],-li[class],br,img[id|dir|longdesc|usemap|class|src|border|alt=|title|width|height|align],-sub[class],-sup[class],-blockquote[dir|class],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|dir|id|style],-tr[id|dir|class|rowspan|width|height|align|valign|bgcolor|background|bordercolor|style],tbody[id|class|style],thead[id|class|style],tfoot[id|class|style],-td[id|dir|class|colspan|rowspan|width|height|align|valign|scope|style],-th[id|dir|class|colspan|rowspan|width|height|align|valign|scope|style],caption[id|dir|class],-div[id|dir|class|align],-span[class|align],-pre[class|align],address[class|align],-h1[id|dir|class|align],-h2[id|dir|class|align],-h3[id|dir|class|align],-h4[id|dir|class|align],-h5[id|dir|class|align],-h6[id|dir|class|align],hr[class],dd[id|class|title|dir],dl[id|class|title|dir],dt[id|class|title|dir]",
		extended_valid_elements : "img[class|src|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name]"
	});
}<commit_msg>hack to fix TinyMCE not resizing properly on load (merged from 2.1.0 branch, r41582)<commit_after>function nullConverter(url) {
	return url;
}

/**
 * TinyMCE initialisation template.
 * $ variables are replaced by string search & replace.  It's pretty crude.
 */
// Prevents "Error: 'tinyMCE' is undefined" error in IE7 on Newsletter Recipient import.
if((typeof tinyMCE != 'undefined')) {
	tinyMCE.init({
		mode : "specific_textareas",
		textarea_trigger : "tinymce",
		width: -1,
		height: 240,
		auto_resize : true,
		theme : "advanced",
		content_css : "$ContentCSS",
		document_base_url: "$BaseURL",
		urlconverter_callback : "nullConverter",

		setupcontent_callback : "sapphiremce_setupcontent",
		cleanup_callback : "sapphiremce_cleanup",

		Theme_Advanced_Layout_manager : "SimpleLayout",
		theme_advanced_toolbar_location : "manually_placed",
		theme_advanced_toolbar_align : "left",
		theme_advanced_toolbar_parent : "right",
		plugins : "contextmenu,table,emotions,flash",
		table_inline_editing : true,
		theme_advanced_buttons1 : "italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,separator,bullist,numlist,outdent,indent,hr,charmap",
		theme_advanced_buttons2 : "undo,redo,separator,cut,copy,paste,separator,search,replace,separator,flash",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons3_add : "emotions",
	/*
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,separator,bullist,numlist,outdent,indent,hr,charmap",
		theme_advanced_buttons2 : "undo,redo,separator,cut,copy,paste,separator,search,replace,separator,link,unlink,anchor,image,separator,cleanup,removeformat,visualaid,code,separator,tablecontrols",
	*/
		safari_warning : false,
		relative_urls : true,
		verify_html : true,
		valid_elements : "+a[id|rel|rev|dir|tabindex|accesskey|type|name|href|target|title|class],-strong/-b[class],-em/-i[class],-strike[class],-u[class],#p[id|dir|class|align],-ol[class],-ul[class],-li[class],br,img[id|dir|longdesc|usemap|class|src|border|alt=|title|width|height|align],-sub[class],-sup[class],-blockquote[dir|class],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|dir|id|style],-tr[id|dir|class|rowspan|width|height|align|valign|bgcolor|background|bordercolor|style],tbody[id|class|style],thead[id|class|style],tfoot[id|class|style],-td[id|dir|class|colspan|rowspan|width|height|align|valign|scope|style],-th[id|dir|class|colspan|rowspan|width|height|align|valign|scope|style],caption[id|dir|class],-div[id|dir|class|align],-span[class|align],-pre[class|align],address[class|align],-h1[id|dir|class|align],-h2[id|dir|class|align],-h3[id|dir|class|align],-h4[id|dir|class|align],-h5[id|dir|class|align],-h6[id|dir|class|align],hr[class],dd[id|class|title|dir],dl[id|class|title|dir],dt[id|class|title|dir]",
		extended_valid_elements : "img[class|src|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name]"
	});
}<|endoftext|>


<commit_before>/*global requirejs,define,fs*/
/**
 * support for filling default auth data while prompting for new repo
 * */
define([
  'commander',
  'fs',
  'rc',
  'path',
  './config',
  'colors'
], function (program, fs, rc, path, config, colors) {

  var Auth = {
    answers: {},

    checkConfig: function () {
      var rcConfig = rc('bitbucketconfig');
      if(!rcConfig.repo_level ){
        console.log('Ops! Seems like your ' + this.fullPath + ' is out of date. Please reset you configuration.');
        return false;
      } else if (!rcConfig.repo_level[process.cwd()]) {
        console.log('Seems like your ' + process.cwd() + ' is not yet configured. Please set your configuration.');
        return false;
      }else{
        Object.keys(rcConfig).forEach(function(eachKey){
          config[eachKey] = rcConfig[eachKey];
        });
        return true;
      }
    },

    ask: function (question, callback, password, nonMandatory) {
      var that = this;
      if (password) {
        program.password(question, function (answer) {
          if (answer.length > 0) {
            callback(answer);
          } else {
            that.ask(question, callback, true);
          }
        });
      } else {
        program.prompt(question, function (answer) {
          if (answer.length > 0) {
            callback(answer);
          } else if(nonMandatory) {
            return callback();
          } else {
            that.ask(question, callback);
          }
        });
      }
    },

    setConfig: function (callback) {
      var that = this;
      if (this.checkConfig()) {
        return callback(true);
      } else {
        var configFile = rc('bitbucketconfig');
        if(configFile && !configFile.default && configFile.default.auth){
          console.log('default config for bitbucket cmd found on your system');
        }
        that.ask('Use default best config [y/n]', function(answer){
          if(answer !== 'n' ){
            return that.setDefaultConfig(callback);
          }
          that.ask('Team subdir URL: https://api.bitbucket.org/2.0/repositories/+',  function (answer) {
            that.answers.team = answer;
            that.answers.url = 'https://api.bitbucket.org/2.0/repositories/';
            that.ask('Username: ', function (answer) {
              that.answers.user = answer;
              that.ask('Password: ', function (answer) {
                that.answers.pass = answer;
                process.stdin.destroy();
                var reply = that.saveConfig();
                if (callback) {
                  return callback(reply);
                }
              }, true);
            });
          });
        }, true);
      }
    },

    setDefaultConfig: function(callback){
      var that = this;
      var configFile = rc('bitbucketconfig');
      that.answers.url = configFile.default.auth.url;
      that.answers.user = configFile.default.auth.user;
      that.answers.token = configFile.default.auth.token;
      that.answers.team = configFile.default.auth.team;
      var reply = that.saveConfig();
      if(callback){
        return callback(reply);
      } else {
        return reply;
      }
    },

    clearConfig: function () {
      var that = this;
      var rcConfig = rc('bitbucketconfig');
      if (!fs.existsSync(rcConfig.config)) {
        console.log('There is no stored data. Skipping.');
      } else {
        program.confirm('Are you sure you want to delete config at location '+rcConfig.config+'? ', function (answer) {
          if (answer) {
            fs.unlinkSync(rcConfig.config);
            console.log('Configuration deleted successfully!');
          }
          process.stdin.destroy();
        });
      }
    },

    saveConfig: function () {
      var configFile = rc('bitbucketconfig');
      var auth;
      if (this.answers.url) {
        if (!/\/$/.test(this.answers.url)) {
          this.answers.url += '/';
        }
      }
      if (this.answers.user && this.answers.pass) {
        this.answers.token = this.answers.user + ':' + this.answers.pass;
        delete this.answers.pass;
      }
      auth = {
        url: this.answers.url,
        user: this.answers.user,
        token: this.answers.token,
        team: this.answers.team,
        repo_name: path.basename(process.cwd())
      };

      configFile.default = configFile.default || {};
      configFile.default.auth = configFile.default.auth || auth;
      configFile.default.reviewers = configFile.default.reviewers;
      if(!configFile.default.reviewers){
        configFile.default.reviewers = [{username:"danielnv18"},{ username:"jmsv23"}];
        console.log('please go to '.red+configPath.blue+' and overwrite your reviewer names instead of danielnv18 and jmsv23 . Its important'.red);
      }
      configFile.repo_level = configFile.repo_level || {};
      var configPath = path.join(config.getHomePath(),'.'+'bitbucketconfig'+'rc');
      configFile.repo_level[process.cwd()] = {
        reviewers: [],
        auth: auth
      };
      fs.writeFileSync(configPath, JSON.stringify(configFile, null, 2));
      console.log('Information stored!');
      return this.checkConfig();
    }
  };
  return Auth;

});
<commit_msg>auth correction<commit_after>/*global requirejs,define,fs*/
/**
 * support for filling default auth data while prompting for new repo
 * */
define([
  'commander',
  'fs',
  'rc',
  'path',
  './config',
  'colors'
], function (program, fs, rc, path, config, colors) {

  var Auth = {
    answers: {},

    checkConfig: function () {
      var rcConfig = rc('bitbucketconfig');
      if(!rcConfig.repo_level ){
        console.log('Ops! Seems like your ' + this.fullPath + ' is out of date. Please reset you configuration.');
        return false;
      } else if (!rcConfig.repo_level[process.cwd()]) {
        console.log('Seems like your ' + process.cwd() + ' is not yet configured. Please set your configuration.');
        return false;
      }else{
        Object.keys(rcConfig).forEach(function(eachKey){
          config[eachKey] = rcConfig[eachKey];
        });
        return true;
      }
    },

    ask: function (question, callback, password, nonMandatory) {
      var that = this;
      if (password) {
        program.password(question, function (answer) {
          if (answer.length > 0) {
            callback(answer);
          } else {
            that.ask(question, callback, true);
          }
        });
      } else {
        program.prompt(question, function (answer) {
          if (answer.length > 0) {
            callback(answer);
          } else if(nonMandatory) {
            return callback();
          } else {
            that.ask(question, callback);
          }
        });
      }
    },

    setConfig: function (callback) {
      var that = this;
      if (this.checkConfig()) {
        return callback(true);
      } else {
        var configFile = rc('bitbucketconfig');
        if(configFile && configFile.default && configFile.default.auth){
          console.log('default config for bitbucket cmd found on your system');
        }
        that.ask('Use default best config [y/n]', function(answer){
          if(answer !== 'n' ){
            return that.setDefaultConfig(callback);
          }
          that.ask('Team subdir URL: https://api.bitbucket.org/2.0/repositories/+ ',  function (answer) {
            that.answers.team = answer;
            that.answers.url = 'https://api.bitbucket.org/2.0/repositories/';
            that.ask('Username: ', function (answer) {
              that.answers.user = answer;
              that.ask('Password: ', function (answer) {
                that.answers.pass = answer;
                process.stdin.destroy();
                var reply = that.saveConfig();
                if (callback) {
                  return callback(reply);
                }
              }, true);
            });
          });
        }, true);
      }
    },

    setDefaultConfig: function(callback){
      var that = this;
      var configFile = rc('bitbucketconfig');
      that.answers.url = configFile.default.auth.url;
      that.answers.user = configFile.default.auth.user;
      that.answers.token = configFile.default.auth.token;
      that.answers.team = configFile.default.auth.team;
      var reply = that.saveConfig();
      if(callback){
        return callback(reply);
      } else {
        return reply;
      }
    },

    clearConfig: function () {
      var that = this;
      var rcConfig = rc('bitbucketconfig');
      if (!fs.existsSync(rcConfig.config)) {
        console.log('There is no stored data. Skipping.');
      } else {
        program.confirm('Are you sure you want to delete config at location '+rcConfig.config+'? ', function (answer) {
          if (answer) {
            fs.unlinkSync(rcConfig.config);
            console.log('Configuration deleted successfully!');
          }
          process.stdin.destroy();
        });
      }
    },

    saveConfig: function () {
      var configFile = rc('bitbucketconfig');
      var auth;
      if (this.answers.url) {
        if (!/\/$/.test(this.answers.url)) {
          this.answers.url += '/';
        }
      }
      if (this.answers.user && this.answers.pass) {
        this.answers.token = this.answers.user + ':' + this.answers.pass;
        delete this.answers.pass;
      }
      auth = {
        url: this.answers.url,
        user: this.answers.user,
        token: this.answers.token,
        team: this.answers.team,
        repo_name: path.basename(process.cwd())
      };

      configFile.default = configFile.default || {};
      configFile.default.auth = configFile.default.auth || auth;
      configFile.default.reviewers = configFile.default.reviewers;
      if(!configFile.default.reviewers){
        configFile.default.reviewers = [{username:"danielnv18"},{ username:"jmsv23"}];
        console.log('please go to '.red+configPath.blue+' and overwrite your reviewer names instead of danielnv18 and jmsv23 . Its important'.red);
      }
      configFile.repo_level = configFile.repo_level || {};
      var configPath = path.join(config.getHomePath(),'.'+'bitbucketconfig'+'rc');
      configFile.repo_level[process.cwd()] = {
        reviewers: [],
        auth: auth
      };
      fs.writeFileSync(configPath, JSON.stringify(configFile, null, 2));
      console.log('Information stored!');
      return this.checkConfig();
    }
  };
  return Auth;

});
<|endoftext|>


<commit_before>var Phaser = Phaser || {};
var Tetris = Tetris || {};
var _ = _ || {};

function Tetrad() {
    this.x = 0;
    this.y = 0;
    this.createRandom = function() {
        this.matrix = []; // 2D matrix, access by [row][column]
        for (var i = 0; i < 4; i++) this.matrix.push([0, 0, 0, 0]);
        switch (_.random(6)) {
            case 0:
                /*
                0 0 0 0
                1 1 0 0
                1 0 0 0
                1 0 0 0
                */
                this.matrix[1][0] = 1;
                this.matrix[1][1] = 1;
                this.matrix[2][0] = 1;
                this.matrix[3][0] = 1;
                break;
            case 1:
                /*
                0 0 0 0
                1 1 0 0
                0 1 0 0
                0 1 0 0
                */
                this.matrix[1][0] = 1;
                this.matrix[1][1] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][1] = 1;
                break;
            case 2:
                /*
                1 0 0 0
                1 0 0 0
                1 0 0 0
                1 0 0 0
                */
                this.matrix[0][0] = 1;
                this.matrix[1][0] = 1;
                this.matrix[2][0] = 1;
                this.matrix[3][0] = 1;
                break;
            case 3:
                /*
                0 0 0 0
                0 1 0 0
                1 1 0 0
                1 0 0 0
                */
                this.matrix[1][1] = 1;
                this.matrix[2][0] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][0] = 1;
                break;
            case 4:
                /*
                0 0 0 0
                1 0 0 0
                1 1 0 0
                0 1 0 0
                */
                this.matrix[1][0] = 1;
                this.matrix[2][0] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][1] = 1;
                break;
            case 5:
                /*
                0 0 0 0
                0 0 0 0
                1 1 0 0
                1 1 0 0
                */
                this.matrix[2][0] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][0] = 1;
                this.matrix[3][1] = 1;
                break;
            case 6:
                /*
                0 0 0 0
                0 0 0 0
                0 1 0 0
                1 1 1 0
                */
                this.matrix[2][1] = 1;
                this.matrix[3][0] = 1;
                this.matrix[3][1] = 1;
                this.matrix[3][2] = 1;
                break;
        }
        return this;
    };
    this.log = function() {
        for (var row = 0; row < 4; row++) {
            var line = "";
            for (var col = 0; col < 4; col++) {
                if (this.matrix[row][col]) line += "X ";
                else line += "  ";
            }
            console.log(line);
        }
    };
    this.rotateRight = function() {
        // rotate outer layer
        for (var i = 0; i < 3; i++) {
            // save top row
            var temp = this.matrix[0][i];
            // left column to top row
            this.matrix[0][i] = this.matrix[3 - i][0];
            // bottom row to left column
            this.matrix[3 - i][0] = this.matrix[3][3 - i];
            // right column to bottom row
            this.matrix[3][3 - i] = this.matrix[i][3];
            // top row (temp) to right columm
            this.matrix[i][3] = temp;
        }
        // rotate inner layer
        var innerTemp = this.matrix[1][1];
        this.matrix[1][1] = this.matrix[2][1];
        this.matrix[2][1] = this.matrix[2][2];
        this.matrix[2][2] = this.matrix[1][2];
        this.matrix[1][2] = innerTemp;
        // fill bottom rows
        while (_.isEqual(this.matrix[3], [0, 0, 0, 0])) {
            for (var i = 2; i >= 0; i--) this.matrix[i + 1] = this.matrix[i];
            this.matrix[0] = [0, 0, 0, 0];
        }
        return this;
    };
    this.rotateLeft = function() {
        for (var i = 0; i < 3; i++) this.rotateRight();
        return this;
    };
    this.clone = function() {
        return _.cloneDeep(this);
    };
}

Tetris.COLUMNS = 10;
Tetris.ROWS = 18;
Tetris.TILE_SIZE = 33; // pixels square
Tetris.tickLength = 1000; // milliseconds
Tetris.field = [];
var game = new Phaser.Game(Tetris.COLUMNS * Tetris.TILE_SIZE,
    Tetris.ROWS * Tetris.TILE_SIZE, Phaser.AUTO, '', {
        preload: preload,
        create: create,
        update: update
    }, true);
var actionQueue = [];
var counter = 0; // milliseconds

function preload() {
    game.load.image('block', 'block.png');
}

function create() {
    for (var i = 0; i < Tetris.ROWS; i++) {
        var row = [];
        for (var j = 0; j < Tetris.COLUMNS; j++)
            row.push(0);
        Tetris.field.push(row);
    }
    Tetris.activeTetrad = new Tetrad().createRandom();
    var leftKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
    leftKey.onDown.add(function() {
        actionQueue.push(function() {
            var copy = Tetris.activeTetrad.clone();
            copy.x -= 1;
            if (!checkCollision(copy))
                Tetris.activeTetrad.x -= 1;
        });
    });
    var rightKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
    rightKey.onDown.add(function() {
        actionQueue.push(function() {
            var copy = Tetris.activeTetrad.clone();
            copy.x += 1;
            if (!checkCollision(copy))
                Tetris.activeTetrad.x += 1;
        });
    });
    var upKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
    upKey.onDown.add(function() {
        actionQueue.push(function() {
            var copy = Tetris.activeTetrad.clone().rotateRight();
            if (!checkCollision(copy))
                Tetris.activeTetrad.rotateRight();
        });
    });
    var downKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
    downKey.onDown.add(function() {
        actionQueue.push(function() {
            processTick();
        });
    });
}

var blocks = [];

function update() {
    blocks.forEach(function(element) {
        element.destroy();
    });
    blocks = [];
    counter += game.time.elapsed;
    if (counter > Tetris.tickLength)
        processTick();
    for (var row = 0; row < 4; row++)
        for (var col = 0; col < 4; col++)
            if (Tetris.activeTetrad.matrix[row][col])
                blocks.push(game.add.image((col + Tetris.activeTetrad.x) * Tetris.TILE_SIZE, (row + Tetris.activeTetrad.y) * Tetris.TILE_SIZE, 'block'));
    for (var fieldRow = 0; fieldRow < Tetris.ROWS; fieldRow++)
        for (var fieldCol = 0; fieldCol < Tetris.COLUMNS; fieldCol++)
            if (Tetris.field[fieldRow][fieldCol])
                blocks.push(game.add.image(fieldCol * Tetris.TILE_SIZE, fieldRow * Tetris.TILE_SIZE, 'block'));
    for (var i = 0; i < actionQueue.length; i++) actionQueue[i]();
    actionQueue = [];
}

function processTick() {
    actionQueue.push(function() {
        counter = 0;
        var copy = Tetris.activeTetrad.clone();
        copy.y += 1;
        if (!checkCollision(copy))
            Tetris.activeTetrad.y += 1;
        else {
            for (var row = 0; row < 4; row++)
                for (var col = 0; col < 4; col++)
                    if (Tetris.activeTetrad.x + col < 10)
                        Tetris.field[row + Tetris.activeTetrad.y][col + Tetris.activeTetrad.x] += Tetris.activeTetrad.matrix[row][col];
            Tetris.activeTetrad = new Tetrad().createRandom();
        }
    });
    actionQueue.push(function() {
        var filledRow = [];
        var emptyRow = [];
        _(Tetris.COLUMNS).times(function() {
            filledRow.push(1);
            emptyRow.push(0);
        });
        for (var row = 0; row < Tetris.ROWS; row++) {
            if (_.isEqual(filledRow, Tetris.field[row])) {
                Tetris.tickLength -= 1;
                for (var i = row; i > 0; i--) {
                    Tetris.field[i] = Tetris.field[i - 1];
                }
                Tetris.field[0] = emptyRow;
            }
        }
    });
}

function checkCollision(testTetrad) {
    if (testTetrad.x < 0 || testTetrad.x >= Tetris.COLUMNS) return true;
    if (testTetrad.y + 3 >= Tetris.ROWS) return true;
    for (var row = 0; row < 4; row++) {
        for (var col = 0; col < 4; col++) {
            if (testTetrad.matrix[row][col] &&
                (
                    Tetris.field[row + testTetrad.y][col + testTetrad.x] ||
                    testTetrad.x + col >= Tetris.COLUMNS
                )
            )
                return true;
        }
    }
    return false;
}<commit_msg>Checkpoint commit.<commit_after>var Phaser = Phaser || {};
var Tetris = Tetris || {};
var _ = _ || {};

function Tetrad() {
    this.x = 0;
    this.y = 0;
    this.createRandom = function() {
        this.matrix = []; // 2D matrix, access by [row][column]
        for (var i = 0; i < 4; i++) this.matrix.push([0, 0, 0, 0]);
        switch (_.random(6)) {
            case 0:
                /*
                0 0 0 0
                1 1 0 0
                1 0 0 0
                1 0 0 0
                */
                this.matrix[1][0] = 1;
                this.matrix[1][1] = 1;
                this.matrix[2][0] = 1;
                this.matrix[3][0] = 1;
                break;
            case 1:
                /*
                0 0 0 0
                1 1 0 0
                0 1 0 0
                0 1 0 0
                */
                this.matrix[1][0] = 1;
                this.matrix[1][1] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][1] = 1;
                break;
            case 2:
                /*
                1 0 0 0
                1 0 0 0
                1 0 0 0
                1 0 0 0
                */
                this.matrix[0][0] = 1;
                this.matrix[1][0] = 1;
                this.matrix[2][0] = 1;
                this.matrix[3][0] = 1;
                break;
            case 3:
                /*
                0 0 0 0
                0 1 0 0
                1 1 0 0
                1 0 0 0
                */
                this.matrix[1][1] = 1;
                this.matrix[2][0] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][0] = 1;
                break;
            case 4:
                /*
                0 0 0 0
                1 0 0 0
                1 1 0 0
                0 1 0 0
                */
                this.matrix[1][0] = 1;
                this.matrix[2][0] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][1] = 1;
                break;
            case 5:
                /*
                0 0 0 0
                0 0 0 0
                1 1 0 0
                1 1 0 0
                */
                this.matrix[2][0] = 1;
                this.matrix[2][1] = 1;
                this.matrix[3][0] = 1;
                this.matrix[3][1] = 1;
                break;
            case 6:
                /*
                0 0 0 0
                0 0 0 0
                0 1 0 0
                1 1 1 0
                */
                this.matrix[2][1] = 1;
                this.matrix[3][0] = 1;
                this.matrix[3][1] = 1;
                this.matrix[3][2] = 1;
                break;
        }
        return this;
    };
    this.log = function() {
        for (var row = 0; row < 4; row++) {
            var line = "";
            for (var col = 0; col < 4; col++) {
                if (this.matrix[row][col]) line += "X ";
                else line += "  ";
            }
            console.log(line);
        }
    };
    this.rotateRight = function() {
        // rotate outer layer
        for (var i = 0; i < 3; i++) {
            // save top row
            var temp = this.matrix[0][i];
            // left column to top row
            this.matrix[0][i] = this.matrix[3 - i][0];
            // bottom row to left column
            this.matrix[3 - i][0] = this.matrix[3][3 - i];
            // right column to bottom row
            this.matrix[3][3 - i] = this.matrix[i][3];
            // top row (temp) to right columm
            this.matrix[i][3] = temp;
        }
        // rotate inner layer
        var innerTemp = this.matrix[1][1];
        this.matrix[1][1] = this.matrix[2][1];
        this.matrix[2][1] = this.matrix[2][2];
        this.matrix[2][2] = this.matrix[1][2];
        this.matrix[1][2] = innerTemp;
        // fill bottom rows
        while (_.isEqual(this.matrix[3], [0, 0, 0, 0])) {
            for (var i = 2; i >= 0; i--) this.matrix[i + 1] = this.matrix[i];
            this.matrix[0] = [0, 0, 0, 0];
        }
        return this;
    };
    this.rotateLeft = function() {
        for (var i = 0; i < 3; i++) this.rotateRight();
        return this;
    };
    this.clone = function() {
        return _.cloneDeep(this);
    };
}

Tetris.COLUMNS = 10;
Tetris.ROWS = 18;
Tetris.TILE_SIZE = 33; // pixels square
Tetris.tickLength = 990; // milliseconds
Tetris.field = [];
var game = new Phaser.Game(Tetris.COLUMNS * Tetris.TILE_SIZE,
    Tetris.ROWS * Tetris.TILE_SIZE, Phaser.AUTO, '', {
        preload: preload,
        create: create,
        update: update
    }, true);
var actionQueue = [];
var counter = 0; // milliseconds

function preload() {
    game.load.image('block', 'block.png');
}

function create() {
    for (var i = 0; i < Tetris.ROWS; i++) {
        var row = [];
        for (var j = 0; j < Tetris.COLUMNS; j++)
            row.push(0);
        Tetris.field.push(row);
    }
    Tetris.activeTetrad = new Tetrad().createRandom();
    var leftKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
    leftKey.onDown.add(function() {
        actionQueue.push(function() {
            var copy = Tetris.activeTetrad.clone();
            copy.x -= 1;
            if (!checkCollision(copy))
                Tetris.activeTetrad.x -= 1;
        });
    });
    var rightKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
    rightKey.onDown.add(function() {
        actionQueue.push(function() {
            var copy = Tetris.activeTetrad.clone();
            copy.x += 1;
            if (!checkCollision(copy))
                Tetris.activeTetrad.x += 1;
        });
    });
    var upKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
    upKey.onDown.add(function() {
        actionQueue.push(function() {
            var copy = Tetris.activeTetrad.clone().rotateRight();
            if (!checkCollision(copy))
                Tetris.activeTetrad.rotateRight();
        });
    });
    var downKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
    downKey.onDown.add(function() {
        actionQueue.push(function() {
            // processTick();
            counter = Tetris.tickLength + 1;
        });
    });
}

var blocks = [];

function update() {
    for (var i = 0; i < actionQueue.length; i++) actionQueue[i]();
    actionQueue = [];
    blocks.forEach(function(element) {
        element.destroy();
    });
    blocks = [];
    counter += game.time.elapsed;
    if (counter > Tetris.tickLength)
        processTick();
    for (var row = 0; row < 4; row++)
        for (var col = 0; col < 4; col++)
            if (Tetris.activeTetrad.matrix[row][col])
                blocks.push(game.add.image((col + Tetris.activeTetrad.x) * Tetris.TILE_SIZE, (row + Tetris.activeTetrad.y) * Tetris.TILE_SIZE, 'block'));
    for (var fieldRow = 0; fieldRow < Tetris.ROWS; fieldRow++)
        for (var fieldCol = 0; fieldCol < Tetris.COLUMNS; fieldCol++)
            if (Tetris.field[fieldRow][fieldCol])
                blocks.push(game.add.image(fieldCol * Tetris.TILE_SIZE, fieldRow * Tetris.TILE_SIZE, 'block'));
}

function processTick() {
    actionQueue = [];
    counter = 0;
    actionQueue.push(function() {
        counter = 0;
        var copy = Tetris.activeTetrad.clone();
        copy.y += 1;
        if (!checkCollision(copy))
            Tetris.activeTetrad.y += 1;
        else {
            for (var row = 0; row < 4; row++)
                for (var col = 0; col < 4; col++)
                    if (Tetris.activeTetrad.x + col < 10 && Tetris.activeTetrad.matrix[row][col])
                        Tetris.field[row + Tetris.activeTetrad.y][col + Tetris.activeTetrad.x] = 1;
            Tetris.activeTetrad = new Tetrad().createRandom();
        }
    });
    actionQueue.push(function() {
        var filledRow = [];
        var emptyRow = [];
        _(Tetris.COLUMNS).times(function() {
            filledRow.push(1);
            emptyRow.push(0);
        });
        for (var row = 0; row < Tetris.ROWS; row++) {
            if (_.isEqual(filledRow, Tetris.field[row])) {
                Tetris.tickLength -= 1;
                for (var i = row; i > 0; i--) {
                    Tetris.field[i] = Tetris.field[i - 1];
                }
                Tetris.field[0] = emptyRow;
            }
        }
    });
}

function checkCollision(testTetrad) {
    if (testTetrad.x < 0 || testTetrad.x >= Tetris.COLUMNS) return true;
    if (testTetrad.y + 3 >= Tetris.ROWS) return true;
    for (var row = 0; row < 4; row++) {
        for (var col = 0; col < 4; col++) {
            if (testTetrad.matrix[row][col] &&
                (
                    Tetris.field[row + testTetrad.y][col + testTetrad.x] ||
                    testTetrad.x + col >= Tetris.COLUMNS
                )
            )
                return true;
        }
    }
    return false;
}<|endoftext|>


<commit_before>const expect = require('chai').expect
const FieldsetValidator = require('../../../../app/services/validators/fieldset-validator')
const ErrorHandler = require('../../../../app/services/validators/error-handler')
const ERROR_MESSAGES = require('../../../../app/services/validators/validation-error-messages')
const dateFormatter = require('../../../../app/services/date-formatter')

describe('services/validators/fieldset-validator', function () {
  const VALID_DATA_ITEM_1 = 'data 1'
  const VALID_DATA_ITEM_2 = 'data 2'
  const INVALID_DATA_ITEM_1 = ''
  const DATA = [
    VALID_DATA_ITEM_1,
    VALID_DATA_ITEM_2,
    INVALID_DATA_ITEM_1
  ]
  const FIELD_NAME = 'field name'
  const ERROR_HANDLER = ErrorHandler()

  beforeEach(function () {
    this.error = ErrorHandler()
    this.fieldsetValidator = FieldsetValidator(DATA, FIELD_NAME, this.error)
  })

  describe('isRequired', function () {
    it('should return false if data is null', function () {
      FieldsetValidator(null, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.be.equal(false)
    })

    it('should return false if data is undefined', function () {
      FieldsetValidator(undefined, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.be.equal(false)
    })

    it('should return false if data is an object', function () {
      FieldsetValidator({}, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.be.equal(false)
    })

    it('should return an error object if passed an array containing invalid data', function () {
      FieldsetValidator(DATA, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isRequired()
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })

  describe('isValidDate', function () {
    it('should return error object if data is null', function () {
      this.fieldsetValidator.isValidDate(null)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is undefined', function () {
      this.fieldsetValidator.isValidDate(undefined)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is not a valid date object', function () {
      this.fieldsetValidator.isValidDate({})
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return false if the date given is valid', function () {
      this.fieldsetValidator.isValidDate(dateFormatter.now().subtract(18, 'years'))
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isValidDate(dateFormatter.now())
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })

  describe('isPastDate', function () {
    const PAST_DATE = dateFormatter.now().subtract(1, 'day')
    const FUTURE_DATE = dateFormatter.now().add(1, 'day')

    it('should return error object if data is null', function () {
      this.fieldsetValidator.isPastDate(null)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is undefined', function () {
      this.fieldsetValidator.isPastDate(undefined)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is not a valid date object', function () {
      this.fieldsetValidator.isPastDate({})
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if the date given is in the future', function () {
      this.fieldsetValidator.isPastDate(FUTURE_DATE)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return false if the date given is in the past', function () {
      this.fieldsetValidator.isPastDate(PAST_DATE)
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isPastDate(dateFormatter.now())
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })

  describe('isOlderThanMaxHistory', function () {
    const MAX_HISTORY = 6
    const GREATER_THAN_MAX_HISTORY_LIMIT = dateFormatter.now().subtract(MAX_HISTORY + 1, 'years')
    const EXACTLY_MAX_HISTORY_LIMIT = dateFormatter.now().subtract(MAX_HISTORY, 'years')
    const LESS_THAN_MAX_HISTORY_LIMIT = dateFormatter.now().subtract(MAX_HISTORY, 'years').add(1, 'days')

    it(`should return error object if the date is more than ${MAX_HISTORY} years ago.`, function () {
      this.fieldsetValidator.isOlderThanMaxHistory(GREATER_THAN_MAX_HISTORY_LIMIT)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it(`should return false if the date given is less than ${MAX_HISTORY} years ago.`, function () {
      this.fieldsetValidator.isOlderThanMaxHistory(LESS_THAN_MAX_HISTORY_LIMIT)
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it(`should return false if the date given is exactly ${MAX_HISTORY} years ago.`, function () {
      this.fieldsetValidator.isOlderThanMaxHistory(EXACTLY_MAX_HISTORY_LIMIT)
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isOlderThanMaxHistory(LESS_THAN_MAX_HISTORY_LIMIT)
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })
})
<commit_msg>WMT-275: added missed constant reuse<commit_after>const expect = require('chai').expect
const FieldsetValidator = require('../../../../app/services/validators/fieldset-validator')
const ErrorHandler = require('../../../../app/services/validators/error-handler')
const ERROR_MESSAGES = require('../../../../app/services/validators/validation-error-messages')
const dateFormatter = require('../../../../app/services/date-formatter')
const CASELOAD_CAPACITY = require('../../../../app/constants/caseload-capacity')

describe('services/validators/fieldset-validator', function () {
  const VALID_DATA_ITEM_1 = 'data 1'
  const VALID_DATA_ITEM_2 = 'data 2'
  const INVALID_DATA_ITEM_1 = ''
  const DATA = [
    VALID_DATA_ITEM_1,
    VALID_DATA_ITEM_2,
    INVALID_DATA_ITEM_1
  ]
  const FIELD_NAME = 'field name'
  const ERROR_HANDLER = ErrorHandler()

  beforeEach(function () {
    this.error = ErrorHandler()
    this.fieldsetValidator = FieldsetValidator(DATA, FIELD_NAME, this.error)
  })

  describe('isRequired', function () {
    it('should return false if data is null', function () {
      FieldsetValidator(null, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.be.equal(false)
    })

    it('should return false if data is undefined', function () {
      FieldsetValidator(undefined, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.be.equal(false)
    })

    it('should return false if data is an object', function () {
      FieldsetValidator({}, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.be.equal(false)
    })

    it('should return an error object if passed an array containing invalid data', function () {
      FieldsetValidator(DATA, FIELD_NAME, ERROR_HANDLER)
        .isRequired()
      var errors = ERROR_HANDLER.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isRequired()
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })

  describe('isValidDate', function () {
    it('should return error object if data is null', function () {
      this.fieldsetValidator.isValidDate(null)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is undefined', function () {
      this.fieldsetValidator.isValidDate(undefined)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is not a valid date object', function () {
      this.fieldsetValidator.isValidDate({})
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return false if the date given is valid', function () {
      this.fieldsetValidator.isValidDate(dateFormatter.now().subtract(18, 'years'))
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isValidDate(dateFormatter.now())
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })

  describe('isPastDate', function () {
    const PAST_DATE = dateFormatter.now().subtract(1, 'day')
    const FUTURE_DATE = dateFormatter.now().add(1, 'day')

    it('should return error object if data is null', function () {
      this.fieldsetValidator.isPastDate(null)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is undefined', function () {
      this.fieldsetValidator.isPastDate(undefined)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if data is not a valid date object', function () {
      this.fieldsetValidator.isPastDate({})
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return error object if the date given is in the future', function () {
      this.fieldsetValidator.isPastDate(FUTURE_DATE)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it('should return false if the date given is in the past', function () {
      this.fieldsetValidator.isPastDate(PAST_DATE)
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isPastDate(dateFormatter.now())
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })

  describe('isOlderThanMaxHistory', function () {
    const GREATER_THAN_MAX_HISTORY_LIMIT = dateFormatter.now().subtract(CASELOAD_CAPACITY.MAX_HISTORY + 1, 'years')
    const EXACTLY_MAX_HISTORY_LIMIT = dateFormatter.now().subtract(CASELOAD_CAPACITY.MAX_HISTORY, 'years')
    const LESS_THAN_MAX_HISTORY_LIMIT = dateFormatter.now().subtract(CASELOAD_CAPACITY.MAX_HISTORY, 'years').add(1, 'days')

    it(`should return error object if the date is more than ${CASELOAD_CAPACITY.MAX_HISTORY} years ago.`, function () {
      this.fieldsetValidator.isOlderThanMaxHistory(GREATER_THAN_MAX_HISTORY_LIMIT)
      var errors = this.error.get()
      expect(errors).to.have.property(FIELD_NAME)
    })

    it(`should return false if the date given is less than ${CASELOAD_CAPACITY.MAX_HISTORY} years ago.`, function () {
      this.fieldsetValidator.isOlderThanMaxHistory(LESS_THAN_MAX_HISTORY_LIMIT)
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it(`should return false if the date given is exactly ${CASELOAD_CAPACITY.MAX_HISTORY} years ago.`, function () {
      this.fieldsetValidator.isOlderThanMaxHistory(EXACTLY_MAX_HISTORY_LIMIT)
      var errors = this.error.get()
      expect(errors).to.equal(false)
    })

    it('should return the fieldsetValidator after being called to allow function chaining.', function () {
      var result = this.fieldsetValidator.isOlderThanMaxHistory(LESS_THAN_MAX_HISTORY_LIMIT)
      expect(result).to.be.equal(this.fieldsetValidator)
    })
  })
})
<|endoftext|>


<commit_before>"use strict";

if (process.platform === "darwin") {
  var option = {
    fontName: "Menlo",
    fontSize: 15,
    background: "#333",
    foreground: "#ccc",
    cols: 80,
    rows: 24,
  };
} else {
  var option = {
    fontName: "monospace",
    fontSize: 14,
    background: "#333",
    foreground: "#ccc",
    cols: 80,
    rows: 24,
  };
}

exports.option = option;
<commit_msg>Revert "add darwin option"<commit_after>"use strict";

var option = {
  fontName: "monospace",
  fontSize: 14,
  background: "#333",
  foreground: "#ccc",
  cols: 80,
  rows: 24,
};

exports.option = option;
<|endoftext|>


<commit_before>
/**
 *  Too Much Information -- send JSON telemetry from the servers to an all-points chat.
 */
var sg                  = require('sgsg');
var _                   = sg._;
var request             = sg.extlibs.superagent;

var tmi = {};

//
// Like this:
//
// ```js
// var ct = new Room();       // aka cluster-telemetry
// ct.emit(event);
// ct.set(status);
// ```
//

tmi.trace = function(who, where_, params) {
  var now = _.now();
  var where = where_;
  if (!_.isArray(where)) {
    where = [where];
  }

  console.log('asdfasdfsdfasdfasdfasfasf------------------');
  request
    .post('http://localhost:54321/event/'+who)
    .send(_.extend({foo:'bar', where: where, trace: true}, params || {}))
    .end(function(err, res) {
    });
};

tmi.Room = function(name_) {
  var self = this;
  var name = name_ || 'tmi';

  self.emit = function(eventName /*, value */) {
  };
};

_.each(tmi, function(value, key) {
  exports[key] = value;
});

<commit_msg>Fixed<commit_after>
/**
 *  Too Much Information -- send JSON telemetry from the servers to an all-points chat.
 */
var sg                  = require('sgsg');
var _                   = sg._;
var request             = sg.extlibs.superagent;

var tmi = {};

//
// Like this:
//
// ```js
// var ct = new Room();       // aka cluster-telemetry
// ct.emit(event);
// ct.set(status);
// ```
//

tmi.trace = function(who, where_, params) {
  var now = _.now();
  var where = where_;
  if (!_.isArray(where)) {
    where = [where];
  }

  request
    .post('http://localhost:54321/event/'+who)
    .send(_.extend({foo:'bar', where: where, trace: true}, params || {}))
    .end(function(err, res) {
    });
};

tmi.Room = function(name_) {
  var self = this;
  var name = name_ || 'tmi';

  self.emit = function(eventName /*, value */) {
  };
};

_.each(tmi, function(value, key) {
  exports[key] = value;
});

<|endoftext|>


<commit_before>'use strict';

const Boom = require('boom');

const createLambdaContext = require('./createLambdaContext');
const functionHelper = require('./functionHelper');
const debugLog = require('./debugLog');
const _ = require('lodash');

module.exports = function createAuthScheme(authFun, authorizerOptions, funName, endpointPath, options, serverlessLog, servicePath, serverless) {
  const authFunName = authorizerOptions.name;

  const identitySourceMatch = /^method.request.header.((?:\w+-?)+\w+)$/.exec(authorizerOptions.identitySource);
  if (!identitySourceMatch || identitySourceMatch.length !== 2) {
    throw new Error(`Serverless Offline only supports retrieving tokens from the headers (λ: ${authFunName})`);
  }

  const identityHeader = identitySourceMatch[1].toLowerCase();
  const funOptions = functionHelper.getFunctionOptions(authFun, funName, servicePath);

  // Create Auth Scheme
  return () => ({
    authenticate(request, reply) {
      process.env = _.extend({}, serverless.service.provider.environment, process.env);
      console.log(''); // Just to make things a little pretty
      serverlessLog(`Running Authorization function for ${request.method} ${request.path} (λ: ${authFunName})`);

      // Get Authorization header
      const req = request.raw.req;
      const authorization = req.headers[identityHeader];

      debugLog(`Retrieved ${identityHeader} header ${authorization}`);

      // Create event Object for authFunction
      //   methodArn is the ARN of the function we are running we are authorizing access to (or not)
      //   Account ID and API ID are not simulated
      const event = {
        type: 'TOKEN',
        authorizationToken: authorization,
        methodArn: `arn:aws:execute-api:${options.region}:random-account-id:random-api-id/${options.stage}/${request.method.toUpperCase()}${request.path.replace(new RegExp(`^/${options.stage}`), '')}`,
      };

      // Create the Authorization function handler
      let handler;

      try {
        handler = functionHelper.createHandler(funOptions, options);
      }
      catch (err) {
        debugLog(`create authorization function handler error: ${err}`);

        return reply(Boom.badImplementation(null, `Error while loading ${authFunName}: ${err.message}`));
      }

      // Creat the Lambda Context for the Auth function
      const lambdaContext = createLambdaContext(authFun, (err, result) => {
        // Return an unauthorized response
        const onError = error => {
          serverlessLog(`Authorization function returned an error response: (λ: ${authFunName})`, error);

          return reply(Boom.unauthorized('Unauthorized'));
        };

        if (err) {
          return onError(err);
        }

        const onSuccess = policy => {
        // Validate that the policy document has the principalId set
          if (!policy.principalId) {
            serverlessLog(`Authorization response did not include a principalId: (λ: ${authFunName})`, err);

            return reply(Boom.forbidden('No principalId set on the Response'));
          }

          serverlessLog(`Authorization function returned a successful response: (λ: ${authFunName})`, policy);

          if (policy.policyDocument.Statement[0].Effect === 'Deny') {
            serverlessLog(`Authorization response didn't authorize user to access resource: (λ: ${authFunName})`, err);

            return reply(Boom.forbidden('User is not authorized to access this resource'));
          }

          // Set the credentials for the rest of the pipeline
          return reply.continue({ credentials: { user: policy.principalId, context: policy.context } });
        };

        if (result && typeof result.then === 'function' && typeof result.catch === 'function') {
          debugLog('Auth function returned a promise');
          result.then(onSuccess).catch(onError);
        }
        else if (result instanceof Error) {
          onError(result);
        }
        else {
          onSuccess(result);
        }
      });

      // Execute the Authorization Function
      handler(event, lambdaContext, lambdaContext.done);
    },
  });
};
<commit_msg>adding support for request authorizers<commit_after>'use strict';

const Boom = require('boom');

const createLambdaContext = require('./createLambdaContext');
const functionHelper = require('./functionHelper');
const debugLog = require('./debugLog');
const utils = require('./utils');
const _ = require('lodash');

module.exports = function createAuthScheme(authFun, authorizerOptions, funName, endpointPath, options, serverlessLog, servicePath, serverless) {
  const authFunName = authorizerOptions.name;

  const identitySourceMatch = /^method.request.header.((?:\w+-?)+\w+)$/.exec(authorizerOptions.identitySource);
  if (!identitySourceMatch || identitySourceMatch.length !== 2) {
    throw new Error(`Serverless Offline only supports retrieving tokens from the headers (λ: ${authFunName})`);
  }

  const identityHeader = identitySourceMatch[1].toLowerCase();
  const funOptions = functionHelper.getFunctionOptions(authFun, funName, servicePath);

  // Create Auth Scheme
  return () => ({
    authenticate(request, reply) {
      process.env = _.extend({}, serverless.service.provider.environment, process.env);
      console.log(''); // Just to make things a little pretty
      serverlessLog(`Running Authorization function for ${request.method} ${request.path} (λ: ${authFunName})`);

      // Get Authorization header
      const req = request.raw.req;
      const authorization = req.headers[identityHeader];

      debugLog(`Retrieved ${identityHeader} header ${authorization}`);

      // Get path params
      const pathParams = {};
      Object.keys(request.params).forEach(key => {
        // aws doesn't auto decode path params - hapi does
        pathParams[key] = encodeURIComponent(request.params[key]);
      });

      let event, handler;

      // Create event Object for authFunction
      //   methodArn is the ARN of the function we are running we are authorizing access to (or not)
      //   Account ID and API ID are not simulated
      if (authorizerOptions.type === 'request') {
        event = {
          type: 'REQUEST',
          headers: request.headers,
          pathParameters: utils.nullIfEmpty(pathParams),
          queryStringParameters: utils.nullIfEmpty(request.query),
          methodArn: `arn:aws:execute-api:${options.region}:random-account-id:random-api-id/${options.stage}/${request.method.toUpperCase()}${request.path.replace(new RegExp(`^/${options.stage}`), '')}`,
        };
      }
      else {
        event = {
          type: 'TOKEN',
          authorizationToken: authorization,
          methodArn: `arn:aws:execute-api:${options.region}:random-account-id:random-api-id/${options.stage}/${request.method.toUpperCase()}${request.path.replace(new RegExp(`^/${options.stage}`), '')}`,
        };
      }

      // Create the Authorization function handler
      try {
        handler = functionHelper.createHandler(funOptions, options);
      }
      catch (err) {
        debugLog(`create authorization function handler error: ${err}`);

        return reply(Boom.badImplementation(null, `Error while loading ${authFunName}: ${err.message}`));
      }

      // Creat the Lambda Context for the Auth function
      const lambdaContext = createLambdaContext(authFun, (err, result) => {
        // Return an unauthorized response
        const onError = error => {
          serverlessLog(`Authorization function returned an error response: (λ: ${authFunName})`, error);

          return reply(Boom.unauthorized('Unauthorized'));
        };

        if (err) {
          return onError(err);
        }

        const onSuccess = policy => {
        // Validate that the policy document has the principalId set
          if (!policy.principalId) {
            serverlessLog(`Authorization response did not include a principalId: (λ: ${authFunName})`, err);

            return reply(Boom.forbidden('No principalId set on the Response'));
          }

          serverlessLog(`Authorization function returned a successful response: (λ: ${authFunName})`, policy);

          if (policy.policyDocument.Statement[0].Effect === 'Deny') {
            serverlessLog(`Authorization response didn't authorize user to access resource: (λ: ${authFunName})`, err);

            return reply(Boom.forbidden('User is not authorized to access this resource'));
          }

          // Set the credentials for the rest of the pipeline
          return reply.continue({ credentials: { user: policy.principalId, context: policy.context } });
        };

        if (result && typeof result.then === 'function' && typeof result.catch === 'function') {
          debugLog('Auth function returned a promise');
          result.then(onSuccess).catch(onError);
        }
        else if (result instanceof Error) {
          onError(result);
        }
        else {
          onSuccess(result);
        }
      });

      // Execute the Authorization Function
      handler(event, lambdaContext, lambdaContext.done);
    },
  });
};
<|endoftext|>


<commit_before>  'user strict';

/**
 * Module dependencies
 */
var path = require('path'),
  config = require(path.resolve('./config/config'));

/**
 * Module init function.
 */
module.exports = function (app, db) {

};
<commit_msg>Fix typo<commit_after>'use strict';

/**
 * Module dependencies
 */
var path = require('path'),
  config = require(path.resolve('./config/config'));

/**
 * Module init function.
 */
module.exports = function (app, db) {

};
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var sinon = require('sinon');

let LMLayerWorker = require('../../worker');

describe('LMLayerWorker', function() {

  describe('#constructor()', function() {

    it('should allow for the mocking of postMessage()', function () {
      var fakePostMessage = sinon.fake();
      var worker = new LMLayerWorker({postMessage: fakePostMessage});

      // Sending it the initialize it should notify us that it's initialized!
      worker.onMessage({
        data: {
          message: 'initialize',
          model: 'en-x-dummy'
        }
      });
      assert(fakePostMessage.called);
    });

    it('should work with zero arguments within a Web Worker', function() {
      var fakePostMessage;
      var WorkerInSandbox = defineLMLayerWorkerWithinSandbox({
        postMessage: fakePostMessage = sinon.fake()
      });
      let worker = new WorkerInSandbox();
      assert.isOk(worker);

      // Now try it out.
      worker.onMessage({
        data: {
          message: 'initialize',
          model: 'en-x-dummy'
        }
      });
      assert(fakePostMessage.calledOnce);
    });
  });

  describe('#onMessage()', function() {
    it('should fail if not given the `message` attribute', function () {
      var worker = new LMLayerWorker({postMessage: sinon.fake()});
      // Every message is a discriminated union with the tag being `message`.
      // If it doesn't see message, something is deeply wrong,
      // and it should loudly let us know.
      assert.throws(function () {
        worker.onMessage({
          data: {
            model: 'dummy attribute'
          }
        });
      })
    });
  });

  /**
   * Evaluate the source code of the LMLayerWorker within a
   * sandbox, with our own mocked self. Create a new
   * "sandboxed" LMLayer. It's only "sandboxed", in that it
   * believes it's in a WebWorker.
   *
   * @param self `self` used in the fake Worker. You should add
   * at least `postMessage()` to this object.
   */
  function defineLMLayerWorkerWithinSandbox(self) {
    var fs = require('fs');
    var sourceCode = fs.readFileSync(require.resolve('../../worker'));
    var sandbox = `(function (self) {
      var exports = {}; // TypeScript CommonJS code generation will attempt to write to this.
      var postMessage = self.postMessage;
      ${sourceCode}
      return LMLayerWorker;
    })`;
    return eval(sandbox)(self);
  }
});
<commit_msg>Factor out creating MessageEvent in the tests.<commit_after>var assert = require('chai').assert;
var sinon = require('sinon');

let LMLayerWorker = require('../../worker');

describe('LMLayerWorker', function() {

  describe('#constructor()', function() {
    it('should allow for the mocking of postMessage()', function () {
      var fakePostMessage = sinon.fake();
      var worker = new LMLayerWorker({postMessage: fakePostMessage});

      // Sending it the initialize it should notify us that it's initialized!
      worker.onMessage(createMessageEventWithData({
        message: 'initialize',
        model: 'en-x-dummy'
      }));
      assert(fakePostMessage.called);
    });

    it('should work with zero arguments within a Web Worker', function() {
      var fakePostMessage;
      var WorkerInSandbox = defineLMLayerWorkerWithinSandbox({
        postMessage: fakePostMessage = sinon.fake()
      });
      let worker = new WorkerInSandbox();
      assert.isOk(worker);

      // Now try it out.
      worker.onMessage(createMessageEventWithData({
        message: 'initialize',
        model: 'en-x-dummy'
      }));
      assert(fakePostMessage.calledOnce);
    });
  });

  describe('#onMessage()', function() {
    it('should fail if not given the `message` attribute', function () {
      var worker = new LMLayerWorker({postMessage: sinon.fake()});
      // Every message is a discriminated union with the tag being `message`.
      // If it doesn't see message, something is deeply wrong,
      // and it should loudly let us know.
      assert.throws(function () {
        worker.onMessage(createMessageEventWithData({
          model: 'dummy attribute'
        }));
      })
    });
  });

  /**
   * Creates a MessageEvent (for inter-worker communication), with the given data payload.
   * @param {*} data
   */
  function createMessageEventWithData(data) {
    return { data };
  }

  /**
   * Evaluate the source code of the LMLayerWorker within a
   * sandbox, with our own mocked self. Create a new
   * "sandboxed" LMLayer. It's only "sandboxed", in that it
   * believes it's in a WebWorker.
   *
   * @param self `self` used in the fake Worker. You should add
   * at least `postMessage()` to this object.
   */
  function defineLMLayerWorkerWithinSandbox(self) {
    var fs = require('fs');
    var sourceCode = fs.readFileSync(require.resolve('../../worker'));
    var sandbox = `(function (self) {
      var exports = {}; // TypeScript CommonJS code generation will attempt to write to this.
      var postMessage = self.postMessage;
      ${sourceCode}
      return LMLayerWorker;
    })`;
    return eval(sandbox)(self);
  }
});
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var stream = require('stream');

var protocols = {
  http: require('http'),
  https: require('https'),
  // https://github.com/molnarg/node-http2/wiki/Public-API
  http2: require('http2')
};

var ports = {
  http: 80,
  https: 443,
  http2: 443
};

/**
 * An API Call
 *
 * @param {RAIL} rail
 * @param {?Object=} opt_options
 *
 * @constructor
 * @extends {stream.Writable}
 */
function Call(rail, opt_options) {
  stream.Writable.call(this);
  opt_options = opt_options || {};

  this.rail = rail;

  this.request = null;
  this.response = null;

  this.ended = false;

  // stack of request configurations
  this._stack = [];
  this._pointer = -1;

  // event interceptors
  this._interceptors = {};

  // first plugin event
  this.rail.emit('plugin-call', this, opt_options);

  // configure the first request
  this.__configure(opt_options);
}
util.inherits(Call, stream.Writable);
module.exports = Call;

/**
 * @return {Object}
 */
Call.prototype.__configure = function(options) {
  var i, keys;
  var req = options.request;
  var defaults = this.rail.defaults;

  if (!req) {
    req = options;
  }

  var request = {
    method: req.method || defaults.method,
    path: req.path || defaults.path,
    host: req.host || defaults.host,
    port: req.port || defaults.port,
    headers: {},
    auth: req.auth || defaults.auth,
    agent: req.agent !== undefined ? req.agent : defaults.agent
  };

  if (defaults.headers) {
    keys = Object.keys(defaults.headers);

    for (i = 0; i < keys.length; ++i) {
      request.headers[keys[i]] = defaults.headers[keys[i]];
    }
  }

  if (req.headers) {
    keys = Object.keys(req.headers);

    for (i = 0; i < keys.length; ++i) {
      request.headers[keys[i]] = req.headers[keys[i]];
    }
  }

  var opts = {
    proto: options.proto || req.proto || this.rail.proto,
    request: request,
    response: options.response
  };

  if (!request.port) {
    request.port = ports[opts.proto];
  }

  if (opts.proto === 'https' || opts.proto === 'http2') {
    request.ca = req.ca || defaults.ca;
    request.pfx = req.pfx || defaults.pfx;
    request.key = req.key || defaults.key;
    request.cert = req.cert || defaults.cert;
    request.ciphers = req.ciphers || defaults.ciphers;
    request.passphrase = req.passphrase || defaults.passphrase;
    request.servername = req.servername || defaults.servername;
    request.secureProtocol = req.secureProtocol || defaults.secureProtocol;
    request.rejectUnauthorized =
        req.rejectUnauthorized || defaults.rejectUnauthorized;
  }

  // apply plugin configuration
  keys = Object.keys(this.rail.plugins);

  for (i = 0; i < keys.length; ++i) {
    if (options[keys[i]]) {
      opts[keys[i]] = options[keys[i]];
    }
  }

  this.rail.emit('plugin-configure', this, opts);
  this._pointer = this._stack.push(opts) - 1;

  return opts;
};

Call.prototype.__request = function() {
  var self = this;
  var request;
  var options = this._stack[this._pointer];

  if (this.request) {
    return true;
  } else if (!options) {
    return this.emit('error', new Error('No options available'));
  } else if (!protocols[options.proto]) {
    return this.emit('error',
        new Error('Unknown protocol "' + options.proto + '"'));
  }
  request = protocols[options.proto].request(options.request);

  this.rail.emit('plugin-request', this, options, request);

  request.once('response', function(response) {
    self.rail.emit('plugin-response', self, options, response);

    response.once('end', function() {
      self.request = null;
      self.response = null;
    });

    self.__emit('response', response); // interceptable event
  });

  request.on('error', function(err) {
    self.__emit('error', err);

    self.request = null;
    self.response = null;
  });

  // TODO: timeout handling

  this.request = request;

  process.nextTick(function() {
    self.__emit('request', request); // interceptable event
  });

  return request;
};

Call.prototype._write = function(chunk, encoding, callback) {
  if (this.__request()) {
    // TODO: allow intercepting outgoing body
    this.request.write(chunk, encoding, callback);
  } else {
    callback(new Error('Not connected')); // ZALGO!
  }
};

Call.prototype._end = Call.prototype.end;

Call.prototype.end = function(chunk, encoding, callback) {
  var self = this;

  if (typeof encoding === 'function') {
    callback = encoding;
    encoding = null;
  } else if (!encoding) {
    encoding = null;
  }

  if (this.ended) {
    if (callback) {
      setImmediate(callback, new Error('Trying to write after end'));
    } else {
      this.emit('error', new Error('Trying to write after end'));
    }
    return;
  }

  this.ended = true;

  if (this.__request()) {
    this._end(chunk, encoding, function(err) {
      self.request.end();

      if (callback) {
        return callback(err);
      }
      if (err) {
        self.emit('error', err);
      }
    });
  } else if (callback) {
    setImmediate(callback, new Error('Not connected'));
  } else {
    this.emit('error', new Error('Not connected'));
  }
};

/**
 * Interceptable Events
 */
Call.prototype.__emit = function(event, object) {
  var listener;

  if (this._interceptors[event] && this._interceptors[event].length) {
    listener = this._interceptors[event].shift();
    listener(this, this._stack[this._pointer], object);
  } else {
    this.emit(event, object);
  }
};

Call.prototype.__intercept = function(event, listener) {
  this._interceptors[event] = this._interceptors[event] || [];

  if (this._interceptors[event].indexOf(listener) === -1) {
    this._interceptors[event].push(listener);
  }
};

Call.prototype.__clear = function() {
  this._interceptors = {};
};
<commit_msg>call: allow passing of url<commit_after>'use strict';
var util = require('util');
var stream = require('stream');
var parseURL = require('url').parse;

var protocols = {
  http: require('http'),
  https: require('https'),
  // https://github.com/molnarg/node-http2/wiki/Public-API
  http2: require('http2')
};

var ports = {
  http: 80,
  https: 443,
  http2: 443
};

/**
 * An API Call
 *
 * @param {RAIL} rail
 * @param {?(Object|string)=} opt_options
 *
 * @constructor
 * @extends {stream.Writable}
 */
function Call(rail, opt_options) {
  stream.Writable.call(this);
  opt_options = opt_options || {};

  this.rail = rail;

  this.request = null;
  this.response = null;

  this.ended = false;

  // stack of request configurations
  this._stack = [];
  this._pointer = -1;

  // event interceptors
  this._interceptors = {};

  // first plugin event
  rail.emit('plugin-call', this, opt_options);

  // configure the first request
  this.__configure(opt_options);
}
util.inherits(Call, stream.Writable);
module.exports = Call;

Call.prototype._urlToOptions = function(options, url) {
  var parsed = parseURL(url);

  options.proto = parsed.protocol.substr(0, parsed.protocol.length - 1);

  if (options.request) {
    options.request.host = parsed.hostname;
    options.request.port = parsed.port;
    options.request.path = parsed.path;
  } else {
    options.host = parsed.hostname;
    options.port = parsed.port ? parseInt(parsed.port, 10) : null;
    options.path = parsed.path;
  }

  return options;
};

/**
 * @param {Object|string} options
 *
 * @return {Object}
 */
Call.prototype.__configure = function(options) {
  var i, keys, req;
  var defaults = this.rail.defaults;

  if (typeof options === 'string') {
    options = this._urlToOptions({}, options);
  } else if (typeof options.url === 'string') {
    options = this._urlToOptions(options, options.url);
  }

  req = options.request;

  if (!req) {
    req = options;
  }

  var request = {
    method: req.method || defaults.method,
    path: req.path || defaults.path,
    host: req.host || defaults.host,
    port: req.port || defaults.port,
    headers: {},
    auth: req.auth || defaults.auth,
    agent: req.agent !== undefined ? req.agent : defaults.agent
  };

  if (defaults.headers) {
    keys = Object.keys(defaults.headers);

    for (i = 0; i < keys.length; ++i) {
      request.headers[keys[i]] = defaults.headers[keys[i]];
    }
  }

  if (req.headers) {
    keys = Object.keys(req.headers);

    for (i = 0; i < keys.length; ++i) {
      request.headers[keys[i]] = req.headers[keys[i]];
    }
  }

  var opts = {
    proto: options.proto || req.proto || this.rail.proto,
    request: request,
    response: options.response
  };

  if (!request.port) {
    request.port = ports[opts.proto];
  }

  if (opts.proto === 'https' || opts.proto === 'http2') {
    request.ca = req.ca || defaults.ca;
    request.pfx = req.pfx || defaults.pfx;
    request.key = req.key || defaults.key;
    request.cert = req.cert || defaults.cert;
    request.ciphers = req.ciphers || defaults.ciphers;
    request.passphrase = req.passphrase || defaults.passphrase;
    request.servername = req.servername || defaults.servername;
    request.secureProtocol = req.secureProtocol || defaults.secureProtocol;
    request.rejectUnauthorized =
        req.rejectUnauthorized || defaults.rejectUnauthorized;
  }

  // apply plugin configuration
  keys = Object.keys(this.rail.plugins);

  for (i = 0; i < keys.length; ++i) {
    if (options[keys[i]]) {
      opts[keys[i]] = options[keys[i]];
    }
  }

  this.rail.emit('plugin-configure', this, opts);
  this._pointer = this._stack.push(opts) - 1;

  return opts;
};

Call.prototype.__request = function() {
  var self = this;
  var request;
  var options = this._stack[this._pointer];

  if (this.request) {
    return true;
  } else if (!options) {
    return this.emit('error', new Error('No options available'));
  } else if (!protocols[options.proto]) {
    return this.emit('error',
        new Error('Unknown protocol "' + options.proto + '"'));
  }
  request = protocols[options.proto].request(options.request);

  this.rail.emit('plugin-request', this, options, request);

  request.once('response', function(response) {
    self.rail.emit('plugin-response', self, options, response);

    response.once('end', function() {
      self.request = null;
      self.response = null;
    });

    self.__emit('response', response); // interceptable event
  });

  request.on('error', function(err) {
    self.__emit('error', err);

    self.request = null;
    self.response = null;
  });

  // TODO: timeout handling

  this.request = request;

  process.nextTick(function() {
    self.__emit('request', request); // interceptable event
  });

  return request;
};

Call.prototype._write = function(chunk, encoding, callback) {
  if (this.__request()) {
    // TODO: allow intercepting outgoing body
    this.request.write(chunk, encoding, callback);
  } else {
    callback(new Error('Not connected')); // ZALGO!
  }
};

Call.prototype._end = Call.prototype.end;

Call.prototype.end = function(chunk, encoding, callback) {
  var self = this;

  if (typeof encoding === 'function') {
    callback = encoding;
    encoding = null;
  } else if (!encoding) {
    encoding = null;
  }

  if (this.ended) {
    if (callback) {
      setImmediate(callback, new Error('Trying to write after end'));
    } else {
      this.emit('error', new Error('Trying to write after end'));
    }
    return;
  }

  this.ended = true;

  if (this.__request()) {
    this._end(chunk, encoding, function(err) {
      self.request.end();

      if (callback) {
        return callback(err);
      }
      if (err) {
        self.emit('error', err);
      }
    });
  } else if (callback) {
    setImmediate(callback, new Error('Not connected'));
  } else {
    this.emit('error', new Error('Not connected'));
  }
};

/**
 * Interceptable Events
 */
Call.prototype.__emit = function(event, object) {
  var listener;

  if (this._interceptors[event] && this._interceptors[event].length) {
    listener = this._interceptors[event].shift();
    listener(this, this._stack[this._pointer], object);
  } else {
    this.emit(event, object);
  }
};

Call.prototype.__intercept = function(event, listener) {
  this._interceptors[event] = this._interceptors[event] || [];

  if (this._interceptors[event].indexOf(listener) === -1) {
    this._interceptors[event].push(listener);
  }
};

Call.prototype.__clear = function() {
  this._interceptors = {};
};
<|endoftext|>