<commit_before>import React from 'react';
import cx from 'classnames';
import { noop } from 'lodash';
import Paper from '@material-ui/core/Paper';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemText from '@material-ui/core/ListItemText';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import {
  string,
  bool,
  func,
  arrayOf,
  element,
  number,
  shape
} from 'prop-types';

import { appBarHeight } from '../AppBar';
import styles from './styles.scss';

export const topBarHeight = 45;
export default class TopBar extends React.Component {
  static propTypes = {
    appBarOffset: bool,
    elevation: number,
    leftOffset: number,
    menuButton: bool,
    backButton: bool,
    renderActionButton: func,
    actionButtonContainerWidth: number,
    selected: bool,
    rightMenu: bool,
    rightMenuItems: arrayOf(
      shape({
        label: string.isRequired,
        handler: func.isRequired
      })
    ),
    leftText: string,
    rightIconButtons: arrayOf(element),
    onRequestOpenMenu: func,
    onClickBackButton: func
  };
  static defaultProps = {
    elevation: 2,
    leftOffset: 0,
    actionButtonContainerWidth: 245,
    renderActionButton: noop
  };

  state = {
    rightMenuOpen: false,
    rightMenuAnchorEl: null
  };

  openRightMenu = event => {
    this.setState({
      rightMenuOpen: true,
      rightMenuAnchorEl: event.currentTarget
    });
  };

  closeRightMenu = () => {
    this.setState({
      rightMenuOpen: false
    });
  };

  render() {
    return (
      <Paper
        style={{
          top: this.props.appBarOffset ? appBarHeight : 0,
          height: topBarHeight,
          marginLeft: this.props.leftOffset,
          background: '#fafafa'
        }}
        className={cx(styles.container, {
          [styles.selected]: this.props.selected
        })}
        square
        elevation={this.props.elevation}
      >

          {this.props.renderActionButton()}

          {this.props.menuButton && (

              <IconButton
                style={{ height: '100%' }}
                onClick={this.props.onRequestOpenMenu}
                className="menuButton"
              >
                <MenuIcon />
              </IconButton>

          )}

          {this.props.backButton && (
            <IconButton
              style={{ height: '100%' }}
              onClick={this.props.onClickBackButton}
              className="backButton"
            >
              <ArrowBackIcon />
            </IconButton>
          )}

            {this.props.leftText}

            {this.props.rightIconButtons}

            {this.props.rightMenu &&
              this.props.rightMenuItems &&
              this.props.rightMenuItems.length && [
                <IconButton
                  onClick={this.openRightMenu}
                  key="button"
                  className="rightMenuButton"
                >
                  <MoreVertIcon />
                </IconButton>,

                <Menu
                  key="menu"
                  open={this.state.rightMenuOpen}
                  onClose={this.closeRightMenu}
                  anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
                  anchorEl={this.state.rightMenuAnchorEl}
                  getContentAnchorEl={null}
                >
                  {this.props.rightMenuItems.map(({ label, handler }) => (
                    <MenuItem button key={label} onClick={handler}>
                      <ListItemText primary={label} />
                    </MenuItem>
                  ))}
                </Menu>
              ]}

      </Paper>
    );
  }
}
<commit_msg>only render action button container if one is provided<commit_after>import React from 'react';
import cx from 'classnames';
import Paper from '@material-ui/core/Paper';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemText from '@material-ui/core/ListItemText';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import {
  string,
  bool,
  func,
  arrayOf,
  element,
  number,
  shape
} from 'prop-types';

import { appBarHeight } from '../AppBar';
import styles from './styles.scss';

export const topBarHeight = 45;
export default class TopBar extends React.Component {
  static propTypes = {
    appBarOffset: bool,
    elevation: number,
    leftOffset: number,
    menuButton: bool,
    backButton: bool,
    renderActionButton: func,
    actionButtonContainerWidth: number,
    selected: bool,
    rightMenu: bool,
    rightMenuItems: arrayOf(
      shape({
        label: string.isRequired,
        handler: func.isRequired
      })
    ),
    leftText: string,
    rightIconButtons: arrayOf(element),
    onRequestOpenMenu: func,
    onClickBackButton: func
  };
  static defaultProps = {
    elevation: 2,
    leftOffset: 0,
    actionButtonContainerWidth: 245
  };

  state = {
    rightMenuOpen: false,
    rightMenuAnchorEl: null
  };

  openRightMenu = event => {
    this.setState({
      rightMenuOpen: true,
      rightMenuAnchorEl: event.currentTarget
    });
  };

  closeRightMenu = () => {
    this.setState({
      rightMenuOpen: false
    });
  };

  render() {
    return (
      <Paper
        style={{
          top: this.props.appBarOffset ? appBarHeight : 0,
          height: topBarHeight,
          marginLeft: this.props.leftOffset,
          background: '#fafafa'
        }}
        className={cx(styles.container, {
          [styles.selected]: this.props.selected
        })}
        square
        elevation={this.props.elevation}
      >
        {this.props.renderActionButton && (

            {this.props.renderActionButton()}

        )}

          {this.props.menuButton && (

              <IconButton
                style={{ height: '100%' }}
                onClick={this.props.onRequestOpenMenu}
                className="menuButton"
              >
                <MenuIcon />
              </IconButton>

          )}

          {this.props.backButton && (
            <IconButton
              style={{ height: '100%' }}
              onClick={this.props.onClickBackButton}
              className="backButton"
            >
              <ArrowBackIcon />
            </IconButton>
          )}

            {this.props.leftText}

            {this.props.rightIconButtons}

            {this.props.rightMenu &&
              this.props.rightMenuItems &&
              this.props.rightMenuItems.length && [
                <IconButton
                  onClick={this.openRightMenu}
                  key="button"
                  className="rightMenuButton"
                >
                  <MoreVertIcon />
                </IconButton>,

                <Menu
                  key="menu"
                  open={this.state.rightMenuOpen}
                  onClose={this.closeRightMenu}
                  anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
                  anchorEl={this.state.rightMenuAnchorEl}
                  getContentAnchorEl={null}
                >
                  {this.props.rightMenuItems.map(({ label, handler }) => (
                    <MenuItem button key={label} onClick={handler}>
                      <ListItemText primary={label} />
                    </MenuItem>
                  ))}
                </Menu>
              ]}

      </Paper>
    );
  }
}
<|endoftext|>


<commit_before>//
// Created by Bradley Austin Davis on 2016/12/12
// Copyright 2013-2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
/*global print, Resources, Test, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
/*global ColorIndicator */

'use strict';

Script.include("./BenchmarkLib.js");

var AVATAR_TRACING_RULES = "" +
    "trace.*=true\n" +
    "*.detail=true\n" +
    "";

Resources.overrideUrlPrefix(TEST_ROOT, Script.resolvePath(".."));
var testScript = new TestScript();
testScript.addTest({
    name: "50Avatars",
    loader: TestScript.locationLoader("hifi://dev-chris2.highfidelity.io/115.3,0.1,31.4/0,0.737,0, 0.676", 1),
    tracingRules: AVATAR_TRACING_RULES,
    traceActions: TestScript.locationSteps([ {dt:0, pos:{x:115.3, y:0.1, z:31.4}, yaw:95},
    										 {dt:5, yaw:130},
    										 {dt:5, pos:{x:113.0, y:1.8, z:48.1}, yaw:31},
    										 {dt:5, yaw:90},
    										 {dt:5, yaw:50},
    										 {dt:5, pos:{x:99.9, y:0.0, z:22.2}, yaw:179}
    									   ]),
    duration: 30
});

testScript.runTests();

<commit_msg>adjusting the behavior of the benchmark with regard to the Duration field to make sure, this is the total duration of the test. Added a simple way to provide steps within the test to move the avatar around. Added the 50 avatar test in the dev-chris2<commit_after>//
// Created by Bradley Austin Davis on 2016/12/12
// Copyright 2013-2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
/*global print, Resources, Test, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
/*global ColorIndicator */

'use strict';

Script.include("./BenchmarkLib.js");

var AVATAR_TRACING_RULES = "" +
    "trace.*=true\n" +
    "*.detail=true\n" +
    "";

Resources.overrideUrlPrefix(TEST_ROOT, Script.resolvePath(".."));
var testScript = new TestScript();
testScript.addTest({
    name: "50Avatars",
    loader: TestScript.locationLoader("hifi://dev-chris2.highfidelity.io/115.3,0.1,31.4/0,0.737,0, 0.676", 1),
    tracingRules: AVATAR_TRACING_RULES,
    traceActions: TestScript.locationSteps([ {dt:2, pos:{x:99.9, y:0.0, z:22.2}, yaw:179},
    										 {dt:2, pos:{x:115.3, y:0.1, z:31.4}, yaw:95},
    										 {dt:5, yaw:130},
    										 {dt:5, pos:{x:113.0, y:1.8, z:48.1}, yaw:31},
    										 {dt:5, yaw:90},
    										 {dt:5, yaw:50},
    										 {dt:5, pos:{x:99.9, y:0.0, z:22.2}, yaw:179}
    									   ]),
    duration: 30
});

testScript.runTests();

<|endoftext|>


<commit_before>define(['CircleObject', 'PointObject', 'AABBObject', 'OBBObject', 'KDopObject',
    'Point', 'Vector', 'MathUtils'], function(CircleObject, PointObject,
    AABBObject, OBBObject, KDopObject, P, V, M) {
	'use strict';

	function ObjectGenerator(number, gameObjects, physicsEngine, maxWidth,
        maxHeight) {
        this.number = number;
        this.gameObjects = gameObjects;
        this.physicsEngine = physicsEngine;
        this.maxWidth = maxWidth;
        this.maxHeight = maxHeight;
        this.objectTypes = ['AABBObject',
            'KDopObject'];
        this.createObjectsHashmap();
        this.createColorBank();
	}

	ObjectGenerator.prototype.generate = function () {
        for (var i = 1; i < this.number; i++) {
            this.generateGameObject();
        }
	};

    ObjectGenerator.prototype.generateGameObject = function () {
        var size = this.objectTypes.length;
        var newGameObject;

        do {
            newGameObject
                = this.objectGenerators[this.objectTypes[
                M.randomInt(0, size-1)]]();
        } while (this.checkIfCollisions(newGameObject));

        this.gameObjects.push(newGameObject);
    };

    ObjectGenerator.prototype.generatePoint = function () {
            return new P(M.randomInt(0, this.maxWidth),
                M.randomInt(0, this.maxHeight));
    };

    ObjectGenerator.prototype.generateSpeed = function () {
            return new V(M.randomInt(-10, 10), M.randomInt(-10, 10));
    };

    ObjectGenerator.prototype.checkIfCollisions = function (newGameObject) {
        for (var gameObject of this.gameObjects) {
            if (newGameObject != gameObject
                && this.physicsEngine.isCollision(gameObject,
                newGameObject)) {
                return true;
            }

            if (!this.physicsEngine.bounds.contains(newGameObject)) {
                return true;
            }
        }

        return false;
    };

    ObjectGenerator.prototype.generatePointObject = function () {
        return new PointObject(this.generatePoint(), this.generateSpeed(),
            this.getColor());
	};

    ObjectGenerator.prototype.generateCircleObject = function () {
        return new CircleObject(this.generatePoint(),
            M.randomInt(20, 100), 0, Math.PI * 2, true,
            this.generateSpeed(), this.getColor());
	};

    ObjectGenerator.prototype.generateAABBObject = function () {
        var point = this.generatePoint();

        return new AABBObject(point, new P(point.x + this.generateLength(),
            point.y + this.generateLength()), this.generateSpeed(),this.getColor());
	};

    ObjectGenerator.prototype.generateOBBObject = function () {
        return new OBBObject(this.generatePoint(), new V(M.randomInt(0, 20),
            M.randomInt(0, 20)), this.generateLength(), this.generateLength(),
            this.generateSpeed(), this.getColor());
	};

    ObjectGenerator.prototype.generateKDopObject = function () {
        var maxLength = 250;
        var minx = M.randomInt(0, maxLength);
        var maxx = M.randomInt(minx, minx+maxLength);
        var miny = M.randomInt(0, maxLength);
        var maxy = M.randomInt(miny, miny+maxLength);
        var dif = Math.min(maxx-minx, maxy-miny)
        var mina = M.randomInt(minx+miny, minx+miny+dif);
        var maxa = M.randomInt(maxx+maxy-dif, maxx+maxy);
        var minb = M.randomInt(minx-maxy, Math.min(2*minx-mina, -2*maxy+maxa));
        var maxb = M.randomInt(Math.max(2*maxx-maxa, mina-2*miny), maxx-miny);
        var min = [minb, minx, mina, miny];
        var max = [maxb, maxx, maxa, maxy];

        return new KDopObject(null, [new V(1, -1),
            new V(1, 0),
            new V(1, 1),
            new V(0, 1)], this.generateSpeed(), this.getColor(), min, max);
	};

    ObjectGenerator.prototype.createObjectsHashmap = function () {
        this.objectGenerators = [];
        this.objectGenerators['PointObject']
            = this.generatePointObject.bind(this);
        this.objectGenerators['CircleObject']
            = this.generateCircleObject.bind(this);
        this.objectGenerators['AABBObject']
            = this.generateAABBObject.bind(this);
        this.objectGenerators['OBBObject'] = this.generateOBBObject.bind(this);
        this.objectGenerators['KDopObject']
            = this.generateKDopObject.bind(this);
    };

    ObjectGenerator.prototype.createColorBank = function () {
        this.colorBank = ['#3d5afe', '#ff5722', '#ff9800', '#ff1744',
            '#ba68C8', '#f06292', '#2196f3', '#006064', '#009688', '#00c853',
            '#8bc34a', '#cddc39', '#ffeb3b', '#ffc107', '#ffa000', '#ff5722',
            '#795548', '#bcaaa4', '#a1887f', '#4e342e', '#9e9e9e', '#607d8b',
            '#b0bec5'];
    };

    ObjectGenerator.prototype.getColor = function () {
        return this.colorBank[M.randomInt(0, this.colorBank.length-1)];
    };

    ObjectGenerator.prototype.generateLength = function () {
        return M.randomInt(10, 200);
    };

	return ObjectGenerator;
});
<commit_msg>restore default parameter<commit_after>define(['CircleObject', 'PointObject', 'AABBObject', 'OBBObject', 'KDopObject',
    'Point', 'Vector', 'MathUtils'], function(CircleObject, PointObject,
    AABBObject, OBBObject, KDopObject, P, V, M) {
	'use strict';

	function ObjectGenerator(number, gameObjects, physicsEngine, maxWidth,
        maxHeight) {
        this.number = number;
        this.gameObjects = gameObjects;
        this.physicsEngine = physicsEngine;
        this.maxWidth = maxWidth;
        this.maxHeight = maxHeight;
        this.objectTypes = ['PointObject', 'CircleObject', 'AABBObject',
            'OBBObject', 'KDopObject'];
        this.createObjectsHashmap();
        this.createColorBank();
	}

	ObjectGenerator.prototype.generate = function () {
        for (var i = 1; i < this.number; i++) {
            this.generateGameObject();
        }
	};

    ObjectGenerator.prototype.generateGameObject = function () {
        var size = this.objectTypes.length;
        var newGameObject;

        do {
            newGameObject
                = this.objectGenerators[this.objectTypes[
                M.randomInt(0, size-1)]]();
        } while (this.checkIfCollisions(newGameObject));

        this.gameObjects.push(newGameObject);
    };

    ObjectGenerator.prototype.generatePoint = function () {
            return new P(M.randomInt(0, this.maxWidth),
                M.randomInt(0, this.maxHeight));
    };

    ObjectGenerator.prototype.generateSpeed = function () {
            return new V(M.randomInt(-10, 10), M.randomInt(-10, 10));
    };

    ObjectGenerator.prototype.checkIfCollisions = function (newGameObject) {
        for (var gameObject of this.gameObjects) {
            if (newGameObject != gameObject
                && this.physicsEngine.isCollision(gameObject,
                newGameObject)) {
                return true;
            }

            if (!this.physicsEngine.bounds.contains(newGameObject)) {
                return true;
            }
        }

        return false;
    };

    ObjectGenerator.prototype.generatePointObject = function () {
        return new PointObject(this.generatePoint(), this.generateSpeed(),
            this.getColor());
	};

    ObjectGenerator.prototype.generateCircleObject = function () {
        return new CircleObject(this.generatePoint(),
            M.randomInt(20, 100), 0, Math.PI * 2, true,
            this.generateSpeed(), this.getColor());
	};

    ObjectGenerator.prototype.generateAABBObject = function () {
        var point = this.generatePoint();

        return new AABBObject(point, new P(point.x + this.generateLength(),
            point.y + this.generateLength()), this.generateSpeed(),this.getColor());
	};

    ObjectGenerator.prototype.generateOBBObject = function () {
        return new OBBObject(this.generatePoint(), new V(M.randomInt(0, 20),
            M.randomInt(0, 20)), this.generateLength(), this.generateLength(),
            this.generateSpeed(), this.getColor());
	};

    ObjectGenerator.prototype.generateKDopObject = function () {
        var maxLength = 250;
        var minx = M.randomInt(0, maxLength);
        var maxx = M.randomInt(minx, minx+maxLength);
        var miny = M.randomInt(0, maxLength);
        var maxy = M.randomInt(miny, miny+maxLength);
        var dif = Math.min(maxx-minx, maxy-miny)
        var mina = M.randomInt(minx+miny, minx+miny+dif);
        var maxa = M.randomInt(maxx+maxy-dif, maxx+maxy);
        var minb = M.randomInt(minx-maxy, Math.min(2*minx-mina, -2*maxy+maxa));
        var maxb = M.randomInt(Math.max(2*maxx-maxa, mina-2*miny), maxx-miny);
        var min = [minb, minx, mina, miny];
        var max = [maxb, maxx, maxa, maxy];

        return new KDopObject(null, [new V(1, -1),
            new V(1, 0),
            new V(1, 1),
            new V(0, 1)], this.generateSpeed(), this.getColor(), min, max);
	};

    ObjectGenerator.prototype.createObjectsHashmap = function () {
        this.objectGenerators = [];
        this.objectGenerators['PointObject']
            = this.generatePointObject.bind(this);
        this.objectGenerators['CircleObject']
            = this.generateCircleObject.bind(this);
        this.objectGenerators['AABBObject']
            = this.generateAABBObject.bind(this);
        this.objectGenerators['OBBObject'] = this.generateOBBObject.bind(this);
        this.objectGenerators['KDopObject']
            = this.generateKDopObject.bind(this);
    };

    ObjectGenerator.prototype.createColorBank = function () {
        this.colorBank = ['#3d5afe', '#ff5722', '#ff9800', '#ff1744',
            '#ba68C8', '#f06292', '#2196f3', '#006064', '#009688', '#00c853',
            '#8bc34a', '#cddc39', '#ffeb3b', '#ffc107', '#ffa000', '#ff5722',
            '#795548', '#bcaaa4', '#a1887f', '#4e342e', '#9e9e9e', '#607d8b',
            '#b0bec5'];
    };

    ObjectGenerator.prototype.getColor = function () {
        return this.colorBank[M.randomInt(0, this.colorBank.length-1)];
    };

    ObjectGenerator.prototype.generateLength = function () {
        return M.randomInt(10, 200);
    };

	return ObjectGenerator;
});
<|endoftext|>


<commit_before>'use strict';

const expect = require('chai').expect,
    fail = expect.fail,
    JDLUnaryOption = require('../../../lib/core/jdl_unary_option'),
    JDLEntity = require('../../../lib/core/jdl_entity'),
    UNARY_OPTIONS = require('../../../lib/core/jhipster/unary_options').UNARY_OPTIONS;

describe('JDLUnaryOption', function () {
  describe('::new', function () {
    describe('when passing no argument', function () {
      it('fails', function () {
        try {
          new JDLUnaryOption();
          fail();
        } catch (error) {
          expect(error.name).to.eq('NullPointerException');
        }
      });
    });
    describe('when passing an invalid name', function () {
      it('fails', function () {
        try {
          new JDLUnaryOption({name: 'IsNotAnOption'});
          fail();
        } catch (error) {
          expect(error.name).to.eq('IllegalArgumentException');
        }
      });
    });
    describe('when passing a name at least', function () {
      it('creates an option', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        expect(option.name).to.eq(UNARY_OPTIONS.SKIP_CLIENT);
      });
    });
    describe('when passing a list of entity names and excluded names with some of them being repeated', function () {
      it('removes the dupes', function () {
        var option = new JDLUnaryOption({
          name: UNARY_OPTIONS.SKIP_CLIENT,
          entityNames: ['A', 'B', 'C', 'A'],
          excludedNames: ['E', 'E', 'D']
        });
        expect(option.entityNames.size()).to.eq(3);
        expect(option.entityNames.has('A')).to.be.true;
        expect(option.entityNames.has('B')).to.be.true;
        expect(option.entityNames.has('C')).to.be.true;
        expect(option.excludedNames.size()).to.eq(2);
        expect(option.excludedNames.has('E')).to.be.true;
        expect(option.excludedNames.has('D')).to.be.true;
      });
    });
  });
  describe('::isValid', function () {
    describe('when passing a nil object', function () {
      it('returns false', function () {
        expect(JDLUnaryOption.isValid()).to.be.false;
      });
    });
  });
  describe('when passing an object with no name', function () {
    it('returns false', function () {
      expect(JDLUnaryOption.isValid({})).to.be.false;
    });
  });
  describe('when passing an object with a name', function () {
    it('returns false', function () {
      expect(JDLUnaryOption.isValid({name: UNARY_OPTIONS.SKIP_CLIENT})).to.be.false;
    });
  });
  describe('when passing an object with a name, entity names and excluded names', function () {
    it('returns true', function () {
      var emptyOption = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      expect(
          JDLUnaryOption.isValid({
            name: UNARY_OPTIONS.SKIP_CLIENT,
            entityNames: emptyOption.entityNames,
            excludedNames: emptyOption.excludedNames
          })
      ).to.be.true;
    });
  });
});
describe('#addEntity', function () {
  describe('when passing a nil entity', function () {
    it('fails', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      try {
        option.addEntity(null);
        fail();
      } catch (error) {
        expect(error.name).to.eq('NullPointerException');
      }
    });
  });
  describe('when passing an invalid entity', function () {
    it('fails', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      try {
        option.addEntity({});
        fail();
      } catch (error) {
        expect(error.name).to.eq('InvalidObjectException');
      }
    });
  });
  describe("when passing a valid entity that hasn't been added yet", function () {
    it('returns true', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      var result = option.addEntity(new JDLEntity({name: 'A'}));
      expect(result).to.be.true;
      expect(option.entityNames.size()).to.eq(1);
    });
  });
  describe('when passing a valid entity that has already been added', function () {
    it('returns false', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      option.addEntity(new JDLEntity({name: 'A'}));
      var result = option.addEntity(new JDLEntity({name: 'A'}));
      expect(result).to.be.false;
      expect(option.entityNames.size()).to.eq(1);
    });
  });
  describe('when passing an excluded entity', function () {
    it('returns false', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      option.addEntity(new JDLEntity({name: 'A'}));
      var result = option.excludeEntity(new JDLEntity({name: 'A'}));
      expect(result).to.be.false;
    });
  });
});
describe('#excludeEntity', function () {
  describe('when passing a nil entity', function () {
    it('fails', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      try {
        option.excludeEntity(null);
        fail();
      } catch (error) {
        expect(error.name).to.eq('NullPointerException');
      }
    });
  });
  describe('when passing an invalid entity', function () {
    it('fails', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      try {
        option.excludeEntity({});
        fail();
      } catch (error) {
        expect(error.name).to.eq('InvalidObjectException');
      }
    });
  });
  describe("when passing a valid entity that hasn't been excluded yet", function () {
    it('returns true', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      var result = option.excludeEntity(new JDLEntity({name: 'A'}));
      expect(result).to.be.true;
      expect(option.excludedNames.size()).to.eq(1);
    });
  });
  describe('when passing a valid entity that has already been excluded', function () {
    it('returns false', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      option.excludeEntity(new JDLEntity({name: 'A'}));
      var result = option.excludeEntity(new JDLEntity({name: 'A'}));
      expect(result).to.be.false;
      expect(option.excludedNames.size()).to.eq(1);
    });
  });
  describe('when passing an added entity', function () {
    it('returns false', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      option.excludeEntity(new JDLEntity({name: 'A'}));
      var result = option.addEntity(new JDLEntity({name: 'A'}));
      expect(result).to.be.false;
    });
  });
});
describe('#toString', function () {
  it('stringifies the option', function () {
    var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
    option.addEntity(new JDLEntity({name: 'D'}));
    option.addEntity(new JDLEntity({name: 'E'}));
    option.addEntity(new JDLEntity({name: 'F'}));
    option.excludeEntity(new JDLEntity({name: 'A'}));
    option.excludeEntity(new JDLEntity({name: 'B'}));
    option.excludeEntity(new JDLEntity({name: 'C'}));
    expect(option.toString()).to.eq(`${UNARY_OPTIONS.SKIP_CLIENT} for D, E, F except A, B, C`);
  });
});
<commit_msg>Fixed the tests for the JDLUnaryOption class<commit_after>'use strict';

const expect = require('chai').expect,
    fail = expect.fail,
    JDLUnaryOption = require('../../../lib/core/jdl_unary_option'),
    JDLEntity = require('../../../lib/core/jdl_entity'),
    UNARY_OPTIONS = require('../../../lib/core/jhipster/unary_options').UNARY_OPTIONS;

describe('JDLUnaryOption', function () {
  describe('::new', function () {
    describe('when passing no argument', function () {
      it('fails', function () {
        try {
          new JDLUnaryOption();
          fail();
        } catch (error) {
          expect(error.name).to.eq('NullPointerException');
        }
      });
    });
    describe('when passing an invalid name', function () {
      it('fails', function () {
        try {
          new JDLUnaryOption({name: 'IsNotAnOption'});
          fail();
        } catch (error) {
          expect(error.name).to.eq('IllegalArgumentException');
        }
      });
    });
    describe('when passing a name at least', function () {
      it('creates an option', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        expect(option.name).to.eq(UNARY_OPTIONS.SKIP_CLIENT);
      });
    });
    describe('when passing a list of entity names and excluded names with some of them being repeated', function () {
      it('removes the dupes', function () {
        var option = new JDLUnaryOption({
          name: UNARY_OPTIONS.SKIP_CLIENT,
          entityNames: ['A', 'B', 'C', 'A'],
          excludedNames: ['E', 'E', 'D']
        });
        expect(option.entityNames.size()).to.eq(3);
        expect(option.entityNames.has('A')).to.be.true;
        expect(option.entityNames.has('B')).to.be.true;
        expect(option.entityNames.has('C')).to.be.true;
        expect(option.excludedNames.size()).to.eq(2);
        expect(option.excludedNames.has('E')).to.be.true;
        expect(option.excludedNames.has('D')).to.be.true;
      });
    });
  });
  describe('::isValid', function () {
    describe('when passing a nil object', function () {
      it('returns false', function () {
        expect(JDLUnaryOption.isValid()).to.be.false;
      });
    });
    describe('when passing an object with no name', function () {
      it('returns false', function () {
        expect(JDLUnaryOption.isValid({})).to.be.false;
      });
    });
    describe('when passing an object with a name', function () {
      it('returns false', function () {
        expect(JDLUnaryOption.isValid({name: UNARY_OPTIONS.SKIP_CLIENT})).to.be.false;
      });
    });
    describe('when passing an object with a name, entity names and excluded names', function () {
      it('returns true', function () {
        var emptyOption = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        expect(
            JDLUnaryOption.isValid({
              name: UNARY_OPTIONS.SKIP_CLIENT,
              entityNames: emptyOption.entityNames,
              excludedNames: emptyOption.excludedNames
            })
        ).to.be.true;
      });
    });
  });
  describe('#addEntity', function () {
    describe('when passing a nil entity', function () {
      it('fails', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        try {
          option.addEntity(null);
          fail();
        } catch (error) {
          expect(error.name).to.eq('NullPointerException');
        }
      });
    });
    describe('when passing an invalid entity', function () {
      it('fails', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        try {
          option.addEntity({});
          fail();
        } catch (error) {
          expect(error.name).to.eq('InvalidObjectException');
        }
      });
    });
    describe("when passing a valid entity that hasn't been added yet", function () {
      it('returns true', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        var result = option.addEntity(new JDLEntity({name: 'A'}));
        expect(result).to.be.true;
        expect(option.entityNames.size()).to.eq(1);
      });
    });
    describe('when passing a valid entity that has already been added', function () {
      it('returns false', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        option.addEntity(new JDLEntity({name: 'A'}));
        var result = option.addEntity(new JDLEntity({name: 'A'}));
        expect(result).to.be.false;
        expect(option.entityNames.size()).to.eq(1);
      });
    });
    describe('when passing an excluded entity', function () {
      it('returns false', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        option.addEntity(new JDLEntity({name: 'A'}));
        var result = option.excludeEntity(new JDLEntity({name: 'A'}));
        expect(result).to.be.false;
      });
    });
  });
  describe('#excludeEntity', function () {
    describe('when passing a nil entity', function () {
      it('fails', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        try {
          option.excludeEntity(null);
          fail();
        } catch (error) {
          expect(error.name).to.eq('NullPointerException');
        }
      });
    });
    describe('when passing an invalid entity', function () {
      it('fails', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        try {
          option.excludeEntity({});
          fail();
        } catch (error) {
          expect(error.name).to.eq('InvalidObjectException');
        }
      });
    });
    describe("when passing a valid entity that hasn't been excluded yet", function () {
      it('returns true', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        var result = option.excludeEntity(new JDLEntity({name: 'A'}));
        expect(result).to.be.true;
        expect(option.excludedNames.size()).to.eq(1);
      });
    });
    describe('when passing a valid entity that has already been excluded', function () {
      it('returns false', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        option.excludeEntity(new JDLEntity({name: 'A'}));
        var result = option.excludeEntity(new JDLEntity({name: 'A'}));
        expect(result).to.be.false;
        expect(option.excludedNames.size()).to.eq(1);
      });
    });
    describe('when passing an added entity', function () {
      it('returns false', function () {
        var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
        option.excludeEntity(new JDLEntity({name: 'A'}));
        var result = option.addEntity(new JDLEntity({name: 'A'}));
        expect(result).to.be.false;
      });
    });
  });
  describe('#toString', function () {
    it('stringifies the option', function () {
      var option = new JDLUnaryOption({name: UNARY_OPTIONS.SKIP_CLIENT});
      option.addEntity(new JDLEntity({name: 'D'}));
      option.addEntity(new JDLEntity({name: 'E'}));
      option.addEntity(new JDLEntity({name: 'F'}));
      option.excludeEntity(new JDLEntity({name: 'A'}));
      option.excludeEntity(new JDLEntity({name: 'B'}));
      option.excludeEntity(new JDLEntity({name: 'C'}));
      expect(option.toString()).to.eq(`${UNARY_OPTIONS.SKIP_CLIENT} for D, E, F except A, B, C`);
    });
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const path = require('path');
const assert = require('assert');
const utils = require('../utils.js');

assert(!module.parent);
assert(__dirname === process.cwd());

let target = process.argv[2] || 'host'; // can not pass 'host' to bitty
if (target === 'host') target = 'node' + process.version[1];

const input = './test-x-index.js';
const output = './run-time/test-output.exe';

// see readFromSnapshot "NODE_VERSION_MAJOR"

function bitty (version) {
  return (2 * (/^(node|v)?4/.test(version))) |
         (2 * (/^(node|v)?5/.test(version))) |
         (4 * (/^(node|v)?6/.test(version))) |
         (4 * (/^(node|v)?7/.test(version)));
}

const version1 = process.version;
const version2 = target;
if (bitty(version1) !== bitty(version2)) return;

let left, right;
utils.mkdirp.sync(path.dirname(output));

left = utils.spawn.sync(
  'node', [ path.basename(input) ],
  { cwd: path.dirname(input) }
);

utils.pkg.sync([
  '--target', target,
  '--output', output, input
]);

right = utils.spawn.sync(
  './' + path.basename(output), [],
  { cwd: path.dirname(output) }
);

assert.equal(left, right);
utils.vacuum.sync(path.dirname(output));
<commit_msg>improvement for test-fs-layer-2<commit_after>#!/usr/bin/env node

'use strict';

const path = require('path');
const assert = require('assert');
const utils = require('../utils.js');

assert(!module.parent);
assert(__dirname === process.cwd());

let target = process.argv[2] || 'host'; // can not pass 'host' to bitty
if (target === 'host') target = 'node' + process.version[1];

const input = './test-x-index.js';
const output = './run-time/test-output.exe';

// see readFromSnapshot "NODE_VERSION_MAJOR"

function bitty (version) {
  return (2 * (/^(node|v)?4/.test(version))) |
         (2 * (/^(node|v)?5/.test(version))) |
         (4 * (/^(node|v)?6/.test(version))) |
         (4 * (/^(node|v)?7/.test(version)));
}

const version1 = process.version;
const version2 = target;
if (bitty(version1) !== bitty(version2)) return;

let left, right;
utils.mkdirp.sync(path.dirname(output));

left = utils.spawn.sync(
  'node', [ path.basename(input) ],
  { cwd: path.dirname(input) }
);

utils.pkg.sync([
  '--target', target,
  '--output', output, input
]);

right = utils.spawn.sync(
  './' + path.basename(output), [],
  { cwd: path.dirname(output) }
);

left = left.split('\n');
right = right.split('\n');
// right may have less lines, premature exit,
// less trused, so using left.length here
for (let i = 0; i < left.length; i += 1) {
  assert.equal(left[i], right[i]);
}

utils.vacuum.sync(path.dirname(output));
<|endoftext|>


<commit_before>"use strict";

require("sockjs");
let Sock = window.SockJS,
    Genfun = require("genfun"),
    can = require("../../shims/can"),
    $ = require("jquery"),
    {addMethod} = Genfun,
    {clone, init} = require("../proto"),
    {partial, forEach, contains, without} = require("lodash"),
    Q = require("q");

let SocketConn = clone(),
    onOpen = new Genfun(),
    onMessage = new Genfun(),
    onClose = new Genfun();

addMethod(init, [SocketConn], function(conn, authUrl) {
  conn.authUrl = authUrl;
  conn.state = can.compute("close");
  conn.observers = {};
  conn.reqNum = 0;
  conn.reqs = {};
  initSock(conn);
});

function initSock(conn) {
  $.get(conn.authUrl, function(resp) {
    conn.url = resp.data.wsUrl;
    conn.auth = resp.data.auth;
    conn.socket = new Sock(conn.url);
    conn.socket.onopen = partial(notifyObservers, conn, onOpen);
    conn.socket.onmessage = partial(notifyObservers, conn, onMessage);
    conn.socket.onclose = partial(notifyObservers, conn, onClose);
  });
}
addMethod(onOpen, [], function() {});
addMethod(onMessage, [], function() {});
addMethod(onClose, [], function() {});

function handleMessage(conn, handler, msg) {
  let data = JSON.parse(msg.data);
  if (data.req) {
    let req = conn.reqs[data.req];
    if (req) {
      req.resolve(data.data);
    }
    delete conn.reqs[data.req];
  } else {
    let observers = conn.observers[data.namespace] ||
          (console.warn("Unknown namespace: ", data.namespace),
           []);
    forEach(observers, function(obs) {
      return handler.call(conn, obs, data.data);
    });
  }
}

function notifyObservers(conn, handler, msg) {
  if (msg.type === "message") {
    return handleMessage(conn, handler, msg);
  } else {
    conn.state(msg.type);
    if (msg.type === "open") {
      conn.socket.send(conn.auth);
    }
    forEach(conn.observers, function(arr) {
      forEach(arr, function(obs) {
        return handler.call(conn, obs);
      });
    });
  }
}

function listen(conn, observer, namespace) {
  if (!conn.observers[namespace]) { conn.observers[namespace] = []; }
  if (!contains(conn.observers[namespace], observer)) {
    conn.observers[namespace].push(observer);
  }
}

function unlisten(conn, observer) {
  conn.observers = without(conn.observers, observer);
}

function send(conn, namespace, data) {
  conn.socket.send(JSON.stringify({namespace: namespace, data: data}));
}

function request(conn, namespace, data) {
  let deferred = Q.defer(),
      req = ++conn.reqNum;
  conn.socket.send(JSON.stringify({
    namespace: namespace,
    req: req,
    data: data
  }));
  conn.reqs[req] = deferred;
  return Q.timeout(deferred.promise, 30000);
}

module.exports = {
  SocketConn: SocketConn,
  onOpen: onOpen,
  onMessage: onMessage,
  onClose: onClose,
  listen: listen,
  unlisten: unlisten,
  send: send,
  request: request
};
<commit_msg>Support passing options down to SockJS<commit_after>"use strict";

require("sockjs");
let Sock = window.SockJS,
    Genfun = require("genfun"),
    can = require("../../shims/can"),
    $ = require("jquery"),
    {addMethod} = Genfun,
    {clone, init} = require("../proto"),
    {partial, forEach, contains, without} = require("lodash"),
    Q = require("q");

let SocketConn = clone(),
    onOpen = new Genfun(),
    onMessage = new Genfun(),
    onClose = new Genfun();

addMethod(init, [SocketConn], function(conn, authUrl, opts) {
  conn.authUrl = authUrl;
  conn.state = can.compute("close");
  conn.observers = {};
  conn.reqNum = 0;
  conn.reqs = {};
  initSock(conn, opts);
});

function initSock(conn, opts) {
  $.get(conn.authUrl, function(resp) {
    conn.url = resp.data.wsUrl;
    conn.auth = resp.data.auth;
    conn.socket = new Sock(conn.url, null, opts);
    conn.socket.onopen = partial(notifyObservers, conn, onOpen);
    conn.socket.onmessage = partial(notifyObservers, conn, onMessage);
    conn.socket.onclose = partial(notifyObservers, conn, onClose);
  });
}
addMethod(onOpen, [], function() {});
addMethod(onMessage, [], function() {});
addMethod(onClose, [], function() {});

function handleMessage(conn, handler, msg) {
  let data = JSON.parse(msg.data);
  if (data.req) {
    let req = conn.reqs[data.req];
    if (req) {
      req.resolve(data.data);
    }
    delete conn.reqs[data.req];
  } else {
    let observers = conn.observers[data.namespace] ||
          (console.warn("Unknown namespace: ", data.namespace),
           []);
    forEach(observers, function(obs) {
      return handler.call(conn, obs, data.data);
    });
  }
}

function notifyObservers(conn, handler, msg) {
  if (msg.type === "message") {
    return handleMessage(conn, handler, msg);
  } else {
    conn.state(msg.type);
    if (msg.type === "open") {
      conn.socket.send(conn.auth);
    }
    forEach(conn.observers, function(arr) {
      forEach(arr, function(obs) {
        return handler.call(conn, obs);
      });
    });
  }
}

function listen(conn, observer, namespace) {
  if (!conn.observers[namespace]) { conn.observers[namespace] = []; }
  if (!contains(conn.observers[namespace], observer)) {
    conn.observers[namespace].push(observer);
  }
}

function unlisten(conn, observer) {
  conn.observers = without(conn.observers, observer);
}

function send(conn, namespace, data) {
  conn.socket.send(JSON.stringify({namespace: namespace, data: data}));
}

function request(conn, namespace, data) {
  let deferred = Q.defer(),
      req = ++conn.reqNum;
  conn.socket.send(JSON.stringify({
    namespace: namespace,
    req: req,
    data: data
  }));
  conn.reqs[req] = deferred;
  return Q.timeout(deferred.promise, 30000);
}

module.exports = {
  SocketConn: SocketConn,
  onOpen: onOpen,
  onMessage: onMessage,
  onClose: onClose,
  listen: listen,
  unlisten: unlisten,
  send: send,
  request: request
};
<|endoftext|>


<commit_before>'use strict';

require('should');
var ss      = require( '../../../../lib/socketstream'),
    Router = require('../../../../lib/http/router').Router,
    options = ss.client.options,
    defineAbcClient = require('../abcClient');

var responseStub = {
  writeHead: function() {},
  end: function(body) {
    this.body = body;
  }
};

describe('production mode asset server', function () {

  var router = new Router();
  ss.root = ss.api.root = path.join(__dirname, '../../../../fixtures/project');

  beforeEach(function() {

    // back to initial client state
    ss.client.assets.unload();
    ss.client.assets.load();
    ss.client.formatters.add('javascript');
    console.log(ss.api.client.root,'is client root');
    console.log(ss.api.root, ss.client.options.dirs.client);
  });

  afterEach(function() {
    ss.client.forget();
  });

  it('should provide a route for serving javascript code', function(){
    defineAbcClient({
      code: './abc/index.a'
    }, function() {
      require('../../../../lib/client/serve/ondemand')(ss.api, router, options);
    });

    // dev time URL
    var req = {url: '/_serve/code?extras/e1.js' };
    router.route(req.url,req,responseStub).should.equal(true);
    responseStub.body.should.equal('var e1 = 1;\n');
  });

  it('should provide a bundle of javascript code for a directory entry');

  it('should provide a route for serving web worker requests', function() {
    defineAbcClient({
      code: './abc/index.a'
    }, function() {
      require('../../../../lib/client/serve/ondemand')(ss.api, router, options);
    });

    // dev time URL
    var req = {url: '/_serve/worker?/pi.js' };
    router.route(req.url,req,responseStub).should.equal(true);
    responseStub.body.should.equal('// calc pi\n');
  });

    it('should serve requests from a cache, rather than reading a file');

    it('should populate the cache for a request, if that request hasn\'t been processed before');

    it('should compress the file, if specified in the packAssets options');

    it('should raise an error if the file is referenced, but missing');

  it('should define modules importedBy correctly with pathPrefix');

});
<commit_msg>test(fix): removed path, putting back<commit_after>'use strict';

require('should');
var path    = require('path'),
    ss      = require( '../../../../lib/socketstream'),
    Router = require('../../../../lib/http/router').Router,
    options = ss.client.options,
    defineAbcClient = require('../abcClient');

var responseStub = {
  writeHead: function() {},
  end: function(body) {
    this.body = body;
  }
};

describe('production mode asset server', function () {

  var router = new Router();
  ss.root = ss.api.root = path.join(__dirname, '../../../../fixtures/project');

  beforeEach(function() {

    // back to initial client state
    ss.client.assets.unload();
    ss.client.assets.load();
    ss.client.formatters.add('javascript');
    console.log(ss.api.client.root,'is client root');
    console.log(ss.api.root, ss.client.options.dirs.client);
  });

  afterEach(function() {
    ss.client.forget();
  });

  it('should provide a route for serving javascript code', function(){
    defineAbcClient({
      code: './abc/index.a'
    }, function() {
      require('../../../../lib/client/serve/ondemand')(ss.api, router, options);
    });

    // dev time URL
    var req = {url: '/_serve/code?extras/e1.js' };
    router.route(req.url,req,responseStub).should.equal(true);
    responseStub.body.should.equal('var e1 = 1;\n');
  });

  it('should provide a bundle of javascript code for a directory entry');

  it('should provide a route for serving web worker requests', function() {
    defineAbcClient({
      code: './abc/index.a'
    }, function() {
      require('../../../../lib/client/serve/ondemand')(ss.api, router, options);
    });

    // dev time URL
    var req = {url: '/_serve/worker?/pi.js' };
    router.route(req.url,req,responseStub).should.equal(true);
    responseStub.body.should.equal('// calc pi\n');
  });

    it('should serve requests from a cache, rather than reading a file');

    it('should populate the cache for a request, if that request hasn\'t been processed before');

    it('should compress the file, if specified in the packAssets options');

    it('should raise an error if the file is referenced, but missing');

  it('should define modules importedBy correctly with pathPrefix');

});
<|endoftext|>


<commit_before>var test = require('tape')
require('rewire-global').enable()
const proxyquire = require('proxyquire')
const sinon = require('sinon')

const consumeMessages = proxyquire('../../../messages/consumeMessages.js', {'node-queue-adapter': sinon.stub()})
const initLogger = consumeMessages.__get__('initLogger')
const log = consumeMessages.__get__('log')

test('should init the logger when an empty message is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  initLogger(message).then(result => {
    t.ok(log.init.calledWith({
      kthid: undefined,
      ug1Name: undefined,
      ugversion: 123,
      messageId: 'abc'
    }))
  })
})

test('should init the logger when an message without a body is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  initLogger(message).then(result => {
    t.ok(log.init.calledWith({
      kthid: undefined,
      ug1Name: undefined,
      ugversion: 123,
      messageId: 'abc'
    }))
  })
})

test('should init the logger when a message with a body, without kthid or ug1name is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    body: {1: 2},
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  initLogger(message).then(result => {
    t.ok(log.init.calledWith({
      kthid: undefined,
      ug1Name: undefined,
      ugversion: 123,
      messageId: 'abc'
    }))
  })
})

test.only('should init the logger when a message with a body, with kthid and ug1name is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    body: {ug1Name: 'someUg1Name', kthid: 'someKthid'},
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  initLogger(message)

  t.ok(log.init.calledWith({
    kthid: 'someKthid',
    ug1Name: 'someUg1Name',
    ugversion: 123,
    messageId: 'abc'
  }))
})

test('should init the logger without any message settings when null message is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const result = initLogger(null)

  t.ok(log.init.calledWith({}))
})
<commit_msg>init logger is no longer promises<commit_after>var test = require('tape')
require('rewire-global').enable()
const proxyquire = require('proxyquire')
const sinon = require('sinon')

const consumeMessages = proxyquire('../../../messages/consumeMessages.js', {'node-queue-adapter': sinon.stub()})
const initLogger = consumeMessages.__get__('initLogger')
const log = consumeMessages.__get__('log')

test('should init the logger when an empty message is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  initLogger(message)

  t.ok(log.init.calledWith({
    kthid: undefined,
    ug1Name: undefined,
    ugversion: 123,
    messageId: 'abc'
  }))
})

test('should init the logger when an message without a body is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  initLogger(message)

  t.ok(log.init.calledWith({
    kthid: undefined,
    ug1Name: undefined,
    ugversion: 123,
    messageId: 'abc'
  }))
})

test('should init the logger when a message with a body, without kthid or ug1name is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    body: {1: 2},
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  const result = initLogger(message)

  t.ok(log.init.calledWith({
    kthid: undefined,
    ug1Name: undefined,
    ugversion: 123,
    messageId: 'abc'
  }))
})

test('should init the logger when a message with a body, with kthid and ug1name is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const message = {
    body: {ug1Name: 'someUg1Name', kthid: 'someKthid'},
    customProperties: {
      ugversion: 123
    },
    brokerProperties: {
      MessageId: 'abc'
    }
  }

  initLogger(message)

  t.ok(log.init.calledWith({
    kthid: 'someKthid',
    ug1Name: 'someUg1Name',
    ugversion: 123,
    messageId: 'abc'
  }))
})

test('should init the logger without any message settings when null message is passed', t => {
  t.plan(1)
  log.init = sinon.stub()

  const result = initLogger(null)

  t.ok(log.init.calledWith({}))
})
<|endoftext|>


<commit_before>P.initialize({

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

"name"                       : "BiB/i Default", // "Name of this preset. As you like."
"description"                : "Default Preset.", // "Description of this preset. As you like."

"bookshelf"                  : "../../bib/bookshelf/", // path from bib/i/index.html or http:// URI

"reader-view-mode"           : "horizontal", // "vertical" or "horizontal" or "paged"

"book-background"            : "transparent", // CSS background value or ""

"spread-gap"                 : 2, // px (if you set odd-number, it will be added 1.)
"spread-margin-start"        : 2, // px
"spread-margin-end"          : 2, // px

"spread-border-radius"       : "2px", // CSS border-radius value or ""
"spread-box-shadow"          : "", // CSS box-shadow value or ""

"item-padding-left"          : 16, // px
"item-padding-right"         : 16, // px
"item-padding-top"           : 36, // px
"item-padding-bottom"        : 12, // px

"item-column-rule"           : "", // CSS column-rule value or ""

"page-breaking"              : true, // true or false (if true, CSS "page-break-before/after: always;" will work, partially)

"epub-additional-stylesheet" : "", // path from spine-item or http:// URI or ""
"epub-additional-script"     : "", // path from spine-item or http:// URI or ""

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

Initialized: true });<commit_msg>Set "false" to default page-breaking setting for CSS "page-break".<commit_after>P.initialize({

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

"name"                       : "BiB/i Default", // "Name of this preset. As you like."
"description"                : "Default Preset.", // "Description of this preset. As you like."

"bookshelf"                  : "../../bib/bookshelf/", // path from bib/i/index.html or http:// URI

"reader-view-mode"           : "horizontal", // "vertical" or "horizontal" or "paged"

"book-background"            : "transparent", // CSS background value or ""

"spread-gap"                 : 2, // px (if you set odd-number, it will be added 1.)
"spread-margin-start"        : 2, // px
"spread-margin-end"          : 2, // px

"spread-border-radius"       : "2px", // CSS border-radius value or ""
"spread-box-shadow"          : "", // CSS box-shadow value or ""

"item-padding-left"          : 16, // px
"item-padding-right"         : 16, // px
"item-padding-top"           : 36, // px
"item-padding-bottom"        : 12, // px

"item-column-rule"           : "", // CSS column-rule value or ""

"page-breaking"              : false, // true or false (if true, CSS "page-break-before/after: always;" will work, partially)

"epub-additional-stylesheet" : "", // path from spine-item or http:// URI or ""
"epub-additional-script"     : "", // path from spine-item or http:// URI or ""

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

Initialized: true });<|endoftext|>


<commit_before>/*
 * The main JavaScript file for the Spiffy UI framework
 */

spiffyui = {

    /*
     * These four functions are for showing different kinds of messages
     * in the general page UI.  They are accessor methods for implementations
     * in MessageUtil.java.  They are bound in that same class.
     */
    showFatalError: null,
    showError: null,
    showWarning: null,
    showMessage: null,

    autoloadCSS: true,
    autoloadHTML: true,

    /**
     * Gets a string of the date formatted into the short date
     * format in the current locale.
     */
    getDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortDate));
    },

    /**
     * Gets a string of the date formatted into the specified format
     */
    getDateString: function(/*int*/ epoch, /*string*/ format) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(format));
    },

    /**
     * Gets a string of the date formatted into the long date
     * format in the current locale.
     */
    getLongDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.longDate));
    },

    /**
     * Gets a string of the date formatted into the month day
     * format in the current locale. If abbrev = true, then use the
     * abbreviation for month.
     */
    getMonthDay: function(/*int*/ epoch, /*boolean*/ abbrev) {
        var dateVal = new Date(epoch);
        var dateFormat = Date.CultureInfo.formatPatterns.monthDay;
        if (abbrev) {
            dateFormat = dateFormat.replace("MMMM", "MMM");
        }
        return spiffyui.chineseAposWorkaround(dateVal.toString(dateFormat));
    },

    /**
     * In zh locales the formatted date strings are
     * surrounding every Chinese character with apostrophes.
     * For example, it is showing 1'月'4'日' but should be  1月4日,
     * so this will remove all the apostrophes.
     */
    chineseAposWorkaround: function(/*String*/ dateString) {
		if (Date.CultureInfo.name.indexOf("zh") === 0) {
			return dateString.replace(/'/g, "");
		}
		return dateString;
    },

    /**
     * Gets a string of the time formatted into the short time
     * format in the current locale.
     */
    getShortTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * Gets a string of the time at the hour or half hour or
     * rounded up to the nearest half hour
     * and formatted into the short time format in the current
     * locale.
     */
    getShortTimeRounded: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        var min = dateVal.getMinutes();
        if (min > 0) {
	        if (min < 30) {
	            dateVal.setMinutes(30);
	        } else if (min > 30) {
	            dateVal.setMinutes(0);
	            dateVal.setHours(dateVal.getHours() + 1);
	        }
        }

        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * 12 AM is showing up as 0 AM, which is a bug in date.js, who is already aware of the problem.
     * http://groups.google.com/group/datejs/browse_thread/thread/2d4f5d46916920a6/5e2106f2f911ea93?lnk=gst&q=0+AM#5e2106f2f911ea93
     * Since we're still seeing the problem, applying hackito.
     */
    midnightWorkaround: function (/*String*/ formattedString) {
        if (formattedString.indexOf("0:") === 0 && formattedString.indexOf("AM") == 5) {
            formattedString = formattedString.substring(2);
            formattedString = "12:" + formattedString;
        }
        return formattedString;
    },

    /**
     * Gets a string of the date time formatted into the full date time
     * format in the current locale.
     */
    getDateTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.fullDateTime));
    },

    /**
     * This is a helper function that gets a Date object from a time
     * string like 11:30pm.  This is just used in JSDateUtil and
     * shouldn't be used anywhere else.
     */
    getDateFromShortTime: function(/*string*/ formattedTime) {

         /*
            The date.js library has a bug where it gives the wrong
            24 hour value for 12AM and 12PM.  I've filed a bug report,
            but we still need to work aorund the issue.  Hackito
            ergo sum.
          */
         if (formattedTime === "12:00 PM") {
             formattedTime = "12:00 AM";
         } else if (formattedTime === "12:30 PM") {
             formattedTime = "12:30 AM";
         } else if (formattedTime === "12:00 AM") {
             formattedTime = "12:00 PM";
         } else if (formattedTime === "12:30 AM") {
             formattedTime = "12:30 PM";
         }

        /*
           We want to make the Date class parse our time, but it does
           like to parse time without the date so we put a bogus date
           in front of it because we are just interested in the hours
           and minutes.
         */
        var date = Date.parseExact(new Date().toString("yyyy-mm-dd") + " " + formattedTime,
                                   "yyyy-mm-dd " + Date.CultureInfo.formatPatterns.shortTime);
        return date;
    },
    /**
     * Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM).
     */

    getToday: function() {
        return Date.today().getTime();
    },
    /**
     * Adds the 1 day to today.
     */
    nextDay: function() {
        return Date.today().add(1).days().getTime();
    },

    /**
     * Adds the specified number of units to the epochDate and returns the new epochDate
     */
    dateAdd: function(/*int*/ epochDate, /*int*/amt, /*String*/unit) {
        var date = new Date(epochDate);
        if (unit == "WEEK") {
            return date.addWeeks(amt).getTime();
        } else if (unit == "MONTH") {
            return date.addMonths(amt).getTime();
        } else if (unit == "HOUR") {
            return date.addHours(amt).getTime();
        } else if (unit == "MINUTE") {
            return date.addMinutes(amt).getTime();
        } else if (unit == "SECOND") {
            return date.addSeconds(amt).getTime();
        } else if (unit == "YEAR") {
            return date.addHours(amt).getTime();
        } else {
            return date.add(amt).days().getTime();
        }
    },
    /**
     * Gets the epoch string (milliseconds since 1970) from a date.
     */
    getEpoch: function(/*date string*/ formattedDate) {
        var epochObj = new Date(formattedDate);
        return epochObj.getTime();
    },

    /**
     * Get the Ordinal day (numeric day number) of the year, adjusted for leap year.
     * Returns 1 through 365 (366 in leap years).
     */
    getOrdinalNumber: function(/*int*/ epochDate) {
        var date = new Date(epochDate);
        return date.getOrdinalNumber();
    },

    /**
     * Format the ID for a JQuery selector.  This function adds a pound
     * sign to the beginning of the string if there isn't on already
     */
    formatId: function(/*string*/ id) {
         if (id.indexOf('#') === 0) {
             return id;
         } else {
             return '#' + id;
         }
    },

    init: function() {

        if (spiffyui.autoloadHTML) {

            /*
             * We start by adding the HTML tags our CSS depends on
             */
            jQuery('body').append(
                '

' +
                '
' +
                    '
' +
                        '

' +
                        '
' +
                            '

' +
                            '
' +
                                '

' +
                            '
' +
                            '

' +
                        '
' +
                        '

' +
                    '
' +
                '
' +
                '

');
        }

        if (spiffyui.autoloadCSS) {
            /*
             * Almost all of our CSS is in spiffyui.css, but there are always a few
             * tweaks you need to add for IE.  This special style sheet is added only
             * if the browser is IE and contains just those tweaks.
             */
            if (navigator.appName == 'Microsoft Internet Explorer') {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.ie.css"
                });
            }

            /*
             * Now we add the spiffyui.min.css file.  If the URL ends with -debug.html
             * then we'll add the uncompressed version.  We add these files dynamically
             * so users of the framework have less to add to their page and because IE8
             * give precedence to files loaded in the page over those added with JavaScript
             * and we can't do that because we override styles in spiffyui.ie.css.
             */
            if (window.location.href.substr(-11) === "-debug.html") {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.css"
                });
            } else {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.min.css"
                });
            }
        }
    }

};

jQuery(document).ready(function() {
    spiffyui.init();
});
<commit_msg>Removed some invalid characters from a comment.<commit_after>/*
 * The main JavaScript file for the Spiffy UI framework
 */

spiffyui = {

    /*
     * These four functions are for showing different kinds of messages
     * in the general page UI.  They are accessor methods for implementations
     * in MessageUtil.java.  They are bound in that same class.
     */
    showFatalError: null,
    showError: null,
    showWarning: null,
    showMessage: null,

    autoloadCSS: true,
    autoloadHTML: true,

    /**
     * Gets a string of the date formatted into the short date
     * format in the current locale.
     */
    getDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortDate));
    },

    /**
     * Gets a string of the date formatted into the specified format
     */
    getDateString: function(/*int*/ epoch, /*string*/ format) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(format));
    },

    /**
     * Gets a string of the date formatted into the long date
     * format in the current locale.
     */
    getLongDate: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.longDate));
    },

    /**
     * Gets a string of the date formatted into the month day
     * format in the current locale. If abbrev = true, then use the
     * abbreviation for month.
     */
    getMonthDay: function(/*int*/ epoch, /*boolean*/ abbrev) {
        var dateVal = new Date(epoch);
        var dateFormat = Date.CultureInfo.formatPatterns.monthDay;
        if (abbrev) {
            dateFormat = dateFormat.replace("MMMM", "MMM");
        }
        return spiffyui.chineseAposWorkaround(dateVal.toString(dateFormat));
    },

    /**
     * In zh locales the formatted date strings are
     * surrounding every Chinese character with apostrophes.
     * For example, it is showing, so this will remove all the
     * apostrophes.
     */
    chineseAposWorkaround: function(/*String*/ dateString) {
		if (Date.CultureInfo.name.indexOf("zh") === 0) {
			return dateString.replace(/'/g, "");
		}
		return dateString;
    },

    /**
     * Gets a string of the time formatted into the short time
     * format in the current locale.
     */
    getShortTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * Gets a string of the time at the hour or half hour or
     * rounded up to the nearest half hour
     * and formatted into the short time format in the current
     * locale.
     */
    getShortTimeRounded: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        var min = dateVal.getMinutes();
        if (min > 0) {
	        if (min < 30) {
	            dateVal.setMinutes(30);
	        } else if (min > 30) {
	            dateVal.setMinutes(0);
	            dateVal.setHours(dateVal.getHours() + 1);
	        }
        }

        return spiffyui.midnightWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.shortTime));
    },

    /**
     * 12 AM is showing up as 0 AM, which is a bug in date.js, who is already aware of the problem.
     * http://groups.google.com/group/datejs/browse_thread/thread/2d4f5d46916920a6/5e2106f2f911ea93?lnk=gst&q=0+AM#5e2106f2f911ea93
     * Since we're still seeing the problem, applying hackito.
     */
    midnightWorkaround: function (/*String*/ formattedString) {
        if (formattedString.indexOf("0:") === 0 && formattedString.indexOf("AM") == 5) {
            formattedString = formattedString.substring(2);
            formattedString = "12:" + formattedString;
        }
        return formattedString;
    },

    /**
     * Gets a string of the date time formatted into the full date time
     * format in the current locale.
     */
    getDateTime: function(/*int*/ epoch) {
        var dateVal = new Date(epoch);
        return spiffyui.chineseAposWorkaround(dateVal.toString(Date.CultureInfo.formatPatterns.fullDateTime));
    },

    /**
     * This is a helper function that gets a Date object from a time
     * string like 11:30pm.  This is just used in JSDateUtil and
     * shouldn't be used anywhere else.
     */
    getDateFromShortTime: function(/*string*/ formattedTime) {

         /*
            The date.js library has a bug where it gives the wrong
            24 hour value for 12AM and 12PM.  I've filed a bug report,
            but we still need to work aorund the issue.  Hackito
            ergo sum.
          */
         if (formattedTime === "12:00 PM") {
             formattedTime = "12:00 AM";
         } else if (formattedTime === "12:30 PM") {
             formattedTime = "12:30 AM";
         } else if (formattedTime === "12:00 AM") {
             formattedTime = "12:00 PM";
         } else if (formattedTime === "12:30 AM") {
             formattedTime = "12:30 PM";
         }

        /*
           We want to make the Date class parse our time, but it does
           like to parse time without the date so we put a bogus date
           in front of it because we are just interested in the hours
           and minutes.
         */
        var date = Date.parseExact(new Date().toString("yyyy-mm-dd") + " " + formattedTime,
                                   "yyyy-mm-dd " + Date.CultureInfo.formatPatterns.shortTime);
        return date;
    },
    /**
     * Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM).
     */

    getToday: function() {
        return Date.today().getTime();
    },
    /**
     * Adds the 1 day to today.
     */
    nextDay: function() {
        return Date.today().add(1).days().getTime();
    },

    /**
     * Adds the specified number of units to the epochDate and returns the new epochDate
     */
    dateAdd: function(/*int*/ epochDate, /*int*/amt, /*String*/unit) {
        var date = new Date(epochDate);
        if (unit == "WEEK") {
            return date.addWeeks(amt).getTime();
        } else if (unit == "MONTH") {
            return date.addMonths(amt).getTime();
        } else if (unit == "HOUR") {
            return date.addHours(amt).getTime();
        } else if (unit == "MINUTE") {
            return date.addMinutes(amt).getTime();
        } else if (unit == "SECOND") {
            return date.addSeconds(amt).getTime();
        } else if (unit == "YEAR") {
            return date.addHours(amt).getTime();
        } else {
            return date.add(amt).days().getTime();
        }
    },
    /**
     * Gets the epoch string (milliseconds since 1970) from a date.
     */
    getEpoch: function(/*date string*/ formattedDate) {
        var epochObj = new Date(formattedDate);
        return epochObj.getTime();
    },

    /**
     * Get the Ordinal day (numeric day number) of the year, adjusted for leap year.
     * Returns 1 through 365 (366 in leap years).
     */
    getOrdinalNumber: function(/*int*/ epochDate) {
        var date = new Date(epochDate);
        return date.getOrdinalNumber();
    },

    /**
     * Format the ID for a JQuery selector.  This function adds a pound
     * sign to the beginning of the string if there isn't on already
     */
    formatId: function(/*string*/ id) {
         if (id.indexOf('#') === 0) {
             return id;
         } else {
             return '#' + id;
         }
    },

    init: function() {

        if (spiffyui.autoloadHTML) {

            /*
             * We start by adding the HTML tags our CSS depends on
             */
            jQuery('body').append(
                '

' +
                '
' +
                    '
' +
                        '

' +
                        '
' +
                            '

' +
                            '
' +
                                '

' +
                            '
' +
                            '

' +
                        '
' +
                        '

' +
                    '
' +
                '
' +
                '

');
        }

        if (spiffyui.autoloadCSS) {
            /*
             * Almost all of our CSS is in spiffyui.css, but there are always a few
             * tweaks you need to add for IE.  This special style sheet is added only
             * if the browser is IE and contains just those tweaks.
             */
            if (navigator.appName == 'Microsoft Internet Explorer') {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.ie.css"
                });
            }

            /*
             * Now we add the spiffyui.min.css file.  If the URL ends with -debug.html
             * then we'll add the uncompressed version.  We add these files dynamically
             * so users of the framework have less to add to their page and because IE8
             * give precedence to files loaded in the page over those added with JavaScript
             * and we can't do that because we override styles in spiffyui.ie.css.
             */
            if (window.location.href.substr(-11) === "-debug.html") {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.css"
                });
            } else {
                jQuery("head").prepend("<link>");
                css = $("head").children(":first");
                css.attr({
                    rel:  "stylesheet",
                    type: "text/css",
                    href: "spiffyui.min.css"
                });
            }
        }
    }

};

jQuery(document).ready(function() {
    spiffyui.init();
});
<|endoftext|>


<commit_before>/**
 * Provide class for getting value by key
 *
 * @version r6
 * @author Viacheslav Lotsmanov
 * @license GNU/GPLv3 by Free Software Foundation (https://github.com/unclechu/js-useful-amd-modules/blob/master/GPLv3-LICENSE)
 * @see {@link https://github.com/unclechu/js-useful-amd-modules/|GitHub}
 */

(function (factory) {
	if (typeof define === 'function' && define.amd)
		define(factory); // AMD (RequireJS)
	else if (typeof module === 'object' && typeof module.exports === 'object')
		module.exports = factory(); // CommonJS (Browserify)
	else
		throw new Error('Unsupported architecture');
})(function () {

	'use strict';

	// helpers {{{1

	/**
	 * @private
	 * @inner
	 */
	function inherit(proto) {
		if (Object.create) return Object.create(proto);
		function F() {}
		F.prototype = proto;
		return new F();
	}

	// helpers }}}1

	/**
	 * @class
	 * @public
	 * @param {Object} values - Key-value object of values
	 * @param {Object} [required] - Key-value object to set required values
	 * @returns {function} getWrapper
	 */
	var exports = function (values, required) { // {{{1
		self = this;

		// validation of arguments {{{2

		// values
		if (typeof values !== 'object')
			throw new self.exceptions.IncorrectArgument(
				null, 'values', typeof(values), 'object');
		if (typeof values.values !== 'object')
			throw new self.exceptions.RequiredArgumentKey(
				null, 'values', 'values', typeof(values.values), 'object');
		if (typeof values.required !== 'object')
			throw new self.exceptions.RequiredArgumentKey(
				null, 'values', 'required', typeof(values.required), 'object');

		// required
		if (required && typeof required !== 'object')
			throw new self.exceptions.IncorrectArgument(
				null, 'required', typeof(required), 'object');

		// validation of arguments }}}2

		/** @private */ self._values = values.values;
		/** @private */ self._required = values.required;

		if (required)
			for (var key in required)
				self.set.call(self, key, required[key]);

		/** @public */
		function getWrapper() {
			// delegate to "get" method
			return self.get.apply(self, arguments);
		}

		/** @public */ getWrapper.super = self;

		return getWrapper;
	}; // constructor to exports }}}1

	/** @private */
	exports.prototype._checkRequired = function () { // {{{1

		for (var i=0; i<this._required.length; i++)
			if (!(this._required[i] in this._values))
				throw new exports.exceptions.RequiredIsNotSet(null, this._required[i]);

	}; // "_checkRequired" method }}}1

	/**
	 * Only for "required" keys
	 *
	 * @public
	 */
	exports.prototype.set = function (key, val) { // {{{1

		var found = false;

		if (typeof key !== 'string')
			throw new exports.exceptions.IncorrectKey(null, typeof(key));

		for (var i=0; i<this._required.length; i++)
			if (this._required[i] === key) found = true;

		if (!found)
			throw new exports.exceptions.NoKeyInRequiredList(null, key);

		this._values[key] = val;

	}; // "set" method }}}1

	/** @public */
	exports.prototype.get = function (key, ignoreRequired) { // {{{1

		if (!ignoreRequired) this._checkRequired();

		if (typeof key !== 'string')
			throw new exports.exceptions.IncorrectKey(null, typeof(key));

		if (!(key in this._values))
			throw new exports.exceptions.KeyIsNotExists(null, key);

		return this._values[key];

	}; // "get" method }}}1

	/* exceptions {{{1 */

	/**
	 * @static
	 * @public
	 */
	exports.exceptions = exports.prototype.exceptions = {};

	exports.exceptions.IncorrectArgument = // {{{2
	function (message, name, type, mustBe) {
		Error.call(this);
		this.name = 'IncorrectArgument';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect';
			if (name) this.message += ' "'+ name +'"';
			this.message += ' argument type';
			if (type) this.message += ': "'+ type +'"';
			if (mustBe) this.message += ', must be a(n) "'+ mustBe +'"';
		}
	}; // }}}2

	exports.exceptions.RequiredArgumentKey = // {{{2
	function (message, argName, keyName, keyType, keyMustBe) {
		Error.call(this);
		this.name = 'RequiredArgumentKey';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect';
			if (argName) this.message += ' "'+ argName +'"';
			this.message += ' argument key';
			if (keyName) this.message += ' "'+ keyName +'"';
			this.message += ' type';
			if (keyType) this.message += ': "'+ keyType +'"';
			if (keyMustBe) this.message += ', must be a(n) "'+ keyMustBe +'"';
		}
	}; // }}}2

	exports.exceptions.IncorrectKey = function (message, keyType) { // {{{2
		Error.call(this);
		this.name = 'IncorrectKey';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect key type';
			if (keyType) this.message += ' ("'+ keyType +'")';
			this.message += ', must be a string';
		}
	}; // }}}2

	exports.exceptions.KeyIsNotExists = function (message, key) { // {{{2
		Error.call(this);
		this.name = 'KeyIsNotExists';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Key';
			if (key) this.message += ' "'+ key +'"';
			this.message += ' is not exists';
		}
	}; // }}}2

	exports.exceptions.RequiredIsNotSet = function (message, key) { // {{{2
		Error.call(this);
		this.name = 'RequiredIsNotSet';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Required key is not set';
			if (key) this.message += ': "'+ key +'"';
		}
	}; // }}}2

	exports.exceptions.NoKeyInRequiredList = function (message, key) { // {{{2
		Error.call(this);
		this.name = 'NoKeyInRequiredList';
		if (message) {
			this.message = message;
		} else {
			this.message = 'No key';
			if (key) this.message += ' "'+ key +'"';
			this.message += ' in required list';
		}
	}; // }}}2

	for (var key in exports.exceptions) {
		exports.exceptions[key].prototype = inherit(Error.prototype);
	}

	/* exceptions }}}1 */

	return exports;

}); // factory()
<commit_msg>fixed grammar in "get_val" comment (r6)<commit_after>/**
 * Provides class for getting value by key
 *
 * @version r6
 * @author Viacheslav Lotsmanov
 * @license GNU/GPLv3 by Free Software Foundation (https://github.com/unclechu/js-useful-amd-modules/blob/master/GPLv3-LICENSE)
 * @see {@link https://github.com/unclechu/js-useful-amd-modules/|GitHub}
 */

(function (factory) {
	if (typeof define === 'function' && define.amd)
		define(factory); // AMD (RequireJS)
	else if (typeof module === 'object' && typeof module.exports === 'object')
		module.exports = factory(); // CommonJS (Browserify)
	else
		throw new Error('Unsupported architecture');
})(function () {

	'use strict';

	// helpers {{{1

	/**
	 * @private
	 * @inner
	 */
	function inherit(proto) {
		if (Object.create) return Object.create(proto);
		function F() {}
		F.prototype = proto;
		return new F();
	}

	// helpers }}}1

	/**
	 * @class
	 * @public
	 * @param {Object} values - Key-value object of values
	 * @param {Object} [required] - Key-value object to set required values
	 * @returns {function} getWrapper
	 */
	var exports = function (values, required) { // {{{1
		self = this;

		// validation of arguments {{{2

		// values
		if (typeof values !== 'object')
			throw new self.exceptions.IncorrectArgument(
				null, 'values', typeof(values), 'object');
		if (typeof values.values !== 'object')
			throw new self.exceptions.RequiredArgumentKey(
				null, 'values', 'values', typeof(values.values), 'object');
		if (typeof values.required !== 'object')
			throw new self.exceptions.RequiredArgumentKey(
				null, 'values', 'required', typeof(values.required), 'object');

		// required
		if (required && typeof required !== 'object')
			throw new self.exceptions.IncorrectArgument(
				null, 'required', typeof(required), 'object');

		// validation of arguments }}}2

		/** @private */ self._values = values.values;
		/** @private */ self._required = values.required;

		if (required)
			for (var key in required)
				self.set.call(self, key, required[key]);

		/** @public */
		function getWrapper() {
			// delegate to "get" method
			return self.get.apply(self, arguments);
		}

		/** @public */ getWrapper.super = self;

		return getWrapper;
	}; // constructor to exports }}}1

	/** @private */
	exports.prototype._checkRequired = function () { // {{{1

		for (var i=0; i<this._required.length; i++)
			if (!(this._required[i] in this._values))
				throw new exports.exceptions.RequiredIsNotSet(null, this._required[i]);

	}; // "_checkRequired" method }}}1

	/**
	 * Only for "required" keys
	 *
	 * @public
	 */
	exports.prototype.set = function (key, val) { // {{{1

		var found = false;

		if (typeof key !== 'string')
			throw new exports.exceptions.IncorrectKey(null, typeof(key));

		for (var i=0; i<this._required.length; i++)
			if (this._required[i] === key) found = true;

		if (!found)
			throw new exports.exceptions.NoKeyInRequiredList(null, key);

		this._values[key] = val;

	}; // "set" method }}}1

	/** @public */
	exports.prototype.get = function (key, ignoreRequired) { // {{{1

		if (!ignoreRequired) this._checkRequired();

		if (typeof key !== 'string')
			throw new exports.exceptions.IncorrectKey(null, typeof(key));

		if (!(key in this._values))
			throw new exports.exceptions.KeyIsNotExists(null, key);

		return this._values[key];

	}; // "get" method }}}1

	/* exceptions {{{1 */

	/**
	 * @static
	 * @public
	 */
	exports.exceptions = exports.prototype.exceptions = {};

	exports.exceptions.IncorrectArgument = // {{{2
	function (message, name, type, mustBe) {
		Error.call(this);
		this.name = 'IncorrectArgument';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect';
			if (name) this.message += ' "'+ name +'"';
			this.message += ' argument type';
			if (type) this.message += ': "'+ type +'"';
			if (mustBe) this.message += ', must be a(n) "'+ mustBe +'"';
		}
	}; // }}}2

	exports.exceptions.RequiredArgumentKey = // {{{2
	function (message, argName, keyName, keyType, keyMustBe) {
		Error.call(this);
		this.name = 'RequiredArgumentKey';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect';
			if (argName) this.message += ' "'+ argName +'"';
			this.message += ' argument key';
			if (keyName) this.message += ' "'+ keyName +'"';
			this.message += ' type';
			if (keyType) this.message += ': "'+ keyType +'"';
			if (keyMustBe) this.message += ', must be a(n) "'+ keyMustBe +'"';
		}
	}; // }}}2

	exports.exceptions.IncorrectKey = function (message, keyType) { // {{{2
		Error.call(this);
		this.name = 'IncorrectKey';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Incorrect key type';
			if (keyType) this.message += ' ("'+ keyType +'")';
			this.message += ', must be a string';
		}
	}; // }}}2

	exports.exceptions.KeyIsNotExists = function (message, key) { // {{{2
		Error.call(this);
		this.name = 'KeyIsNotExists';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Key';
			if (key) this.message += ' "'+ key +'"';
			this.message += ' is not exists';
		}
	}; // }}}2

	exports.exceptions.RequiredIsNotSet = function (message, key) { // {{{2
		Error.call(this);
		this.name = 'RequiredIsNotSet';
		if (message) {
			this.message = message;
		} else {
			this.message = 'Required key is not set';
			if (key) this.message += ': "'+ key +'"';
		}
	}; // }}}2

	exports.exceptions.NoKeyInRequiredList = function (message, key) { // {{{2
		Error.call(this);
		this.name = 'NoKeyInRequiredList';
		if (message) {
			this.message = message;
		} else {
			this.message = 'No key';
			if (key) this.message += ' "'+ key +'"';
			this.message += ' in required list';
		}
	}; // }}}2

	for (var key in exports.exceptions) {
		exports.exceptions[key].prototype = inherit(Error.prototype);
	}

	/* exceptions }}}1 */

	return exports;

}); // factory()
<|endoftext|>


<commit_before>var dnnCountryRegionService;

function CountryRegionService($) {
	var baseServicepath = $.dnnSF(-1).getServiceRoot('InternalServices') + 'CountryRegion/';

	this.listCountries = function (searchString, success) {
		$.ajax({
			type: "GET",
			url: baseServicepath + 'Countries',
			data: { searchString: searchString }
		}).done(function (data) {
			if (success != undefined) {
				success(data);
			}
		}).fail(function (xhr, status) {
			alert(eval("(" + xhr.responseText + ")").ExceptionMessage);
		});
	};

	this.listRegions = function (country, success) {
		$.ajax({
			type: "GET",
			url: baseServicepath + 'Regions',
			data: { country: country }
		}).done(function (data) {
			if (success != undefined) {
				success(data);
			}
		}).fail(function (xhr, status) {
			alert(eval("(" + xhr.responseText + ")").ExceptionMessage);
		});
	};

}

function setupRegionLists() {
	$('div[data-list="Region"]').each(function (index, value) {
		var stringValue = $(value).children('input[data-editor="DNNRegionEditControl_Hidden"]').val();
		var $row = $(value);
		var $label = $row.prev().find('label');
		var $textControl = $row.children('input[data-editor="DNNRegionEditControl_Text"]');
		var $selectControl = $row.children('select');
		if ($selectControl.children('option').length < 2) {
			$selectControl.hide();
			$textControl.show();
			$textControl.val(stringValue);

			$label.attr('for', $textControl.attr('id'));
		} else {
			$selectControl.show();
			$textControl.hide();
			$selectControl.children('option[value="' + stringValue + '"]').prop('selected', true);

			$label.attr('for', $selectControl.attr('id'));
		};
	});
	$('select[data-editor="DNNRegionEditControl_DropDown"]').change(function () {
		$(this).parent().children('input[data-editor="DNNRegionEditControl_Hidden"]').val($(this).val());
	});
}

function loadRegionList(category, country) {
	var selector = category ? 'div[data-list="Region"][data-category="' + category + '"]' : 'div[data-list="Region"]';
	$(selector).each(function (index, value) {
		var dd = $(value).children('select');
		$(dd).children().not(':first').remove();
		if (country != '') {
			if (dnnCountryRegionService == undefined) { dnnCountryRegionService = new CountryRegionService($) };
			dnnCountryRegionService.listRegions(country, function (data) {
				$.each(data, function (index, value) {
					$(dd).append($('<option>').text(value.Text).attr('value', value.Value));
				});
				setupRegionLists();
			});
		}
	});
}

function clearCountryValue(countryControl) {
	$('#' + $(countryControl).attr('id').replace('_name', '') + '_id').val('');
	$(countryControl).attr('data-value', '');
	$(countryControl).attr('value', '');
	loadRegionList($(countryControl).attr('data-category'), '');
	setupRegionLists();
}

function setupCountryAutoComplete() {
	$('input[data-editor="DnnCountryAutocompleteControl"]').autocomplete({
		minLength: 2,
		source: function (request, response) {
			if (dnnCountryRegionService == undefined) { dnnCountryRegionService = new CountryRegionService($) };
			dnnCountryRegionService.listCountries(request.term, function (data) {
				if (data.length == 0) {
					clearCountryValue(this);
				};
				response($.map(data, function (item) {
					return {
						label: item.FullName,
						id: item.Id,
						value: item.Id,
						name: item.Name
					};
				}))
			})
		},
		select: function (event, ui) {
			$('#' + $(this).attr('id').replace('_name', '') + '_id').val(ui.item.id);
			$(this).attr('data-value', ui.item.id);
			$(this).attr('data-text', ui.item.name);
		},
		close: function () {
			if ($(this).attr('data-text') != undefined) {
				$(this).val($(this).attr('data-text'));
				loadRegionList($(this).attr('data-category'), $(this).attr('data-value'));
			} else {
				clearCountryValue(this);
			}
		}
	});
	$('input[data-editor="DnnCountryAutocompleteControl"]').change(function () {
		if ($(this).val().length < 2) {
			clearCountryValue(this);
		}
	});
}

function initCountryRegionControls() {
	setupCountryAutoComplete();
	setupRegionLists();
}

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initCountryRegionControls);

(function ($) {
	$(document).ready(function () {
		initCountryRegionControls();
	});
})(jQuery);<commit_msg>DNN-7059: pass correct parameter.<commit_after>var dnnCountryRegionService;

function CountryRegionService($) {
	var baseServicepath = $.dnnSF(-1).getServiceRoot('InternalServices') + 'CountryRegion/';

	this.listCountries = function (searchString, success) {
		$.ajax({
			type: "GET",
			url: baseServicepath + 'Countries',
			data: { searchString: searchString }
		}).done(function (data) {
			if (success != undefined) {
				success(data);
			}
		}).fail(function (xhr, status) {
			alert(eval("(" + xhr.responseText + ")").ExceptionMessage);
		});
	};

	this.listRegions = function (country, success) {
		$.ajax({
			type: "GET",
			url: baseServicepath + 'Regions',
			data: { country: country }
		}).done(function (data) {
			if (success != undefined) {
				success(data);
			}
		}).fail(function (xhr, status) {
			alert(eval("(" + xhr.responseText + ")").ExceptionMessage);
		});
	};

}

function setupRegionLists() {
	$('div[data-list="Region"]').each(function (index, value) {
		var stringValue = $(value).children('input[data-editor="DNNRegionEditControl_Hidden"]').val();
		var $row = $(value);
		var $label = $row.prev().find('label');
		var $textControl = $row.children('input[data-editor="DNNRegionEditControl_Text"]');
		var $selectControl = $row.children('select');
		if ($selectControl.children('option').length < 2) {
			$selectControl.hide();
			$textControl.show();
			$textControl.val(stringValue);

			$label.attr('for', $textControl.attr('id'));
		} else {
			$selectControl.show();
			$textControl.hide();
			$selectControl.children('option[value="' + stringValue + '"]').prop('selected', true);

			$label.attr('for', $selectControl.attr('id'));
		};
	});
	$('select[data-editor="DNNRegionEditControl_DropDown"]').change(function () {
		$(this).parent().children('input[data-editor="DNNRegionEditControl_Hidden"]').val($(this).val());
	});
}

function loadRegionList(category, country) {
	var selector = category ? 'div[data-list="Region"][data-category="' + category + '"]' : 'div[data-list="Region"]';
	$(selector).each(function (index, value) {
		var dd = $(value).children('select');
		$(dd).children().not(':first').remove();
		if (country != '') {
			if (dnnCountryRegionService == undefined) { dnnCountryRegionService = new CountryRegionService($) };
			dnnCountryRegionService.listRegions(country, function (data) {
				$.each(data, function (index, value) {
					$(dd).append($('<option>').text(value.Text).attr('value', value.Value));
				});
				setupRegionLists();
			});
		}
	});
}

function clearCountryValue(countryControl) {
	$('#' + $(countryControl).attr('id').replace('_name', '') + '_id').val('');
	$(countryControl).attr('data-value', '');
	$(countryControl).attr('value', '');
	loadRegionList($(countryControl).attr('data-category'), '');
	setupRegionLists();
}

function setupCountryAutoComplete() {
	$('input[data-editor="DnnCountryAutocompleteControl"]').autocomplete({
		minLength: 2,
		source: function (request, response) {
			var control = this.element;
			if (dnnCountryRegionService == undefined) { dnnCountryRegionService = new CountryRegionService($) };
			dnnCountryRegionService.listCountries(request.term, function (data) {
				if (data.length == 0) {
					clearCountryValue(control);
				};
				response($.map(data, function (item) {
					return {
						label: item.FullName,
						id: item.Id,
						value: item.Id,
						name: item.Name
					};
				}))
			})
		},
		select: function (event, ui) {
			$('#' + $(this).attr('id').replace('_name', '') + '_id').val(ui.item.id);
			$(this).attr('data-value', ui.item.id);
			$(this).attr('data-text', ui.item.name);
		},
		close: function () {
			if ($(this).attr('data-text') != undefined) {
				$(this).val($(this).attr('data-text'));
				loadRegionList($(this).attr('data-category'), $(this).attr('data-value'));
			} else {
				clearCountryValue(this);
			}
		}
	});
	$('input[data-editor="DnnCountryAutocompleteControl"]').change(function () {
		if ($(this).val().length < 2) {
			clearCountryValue(this);
		}
	});
}

function initCountryRegionControls() {
	setupCountryAutoComplete();
	setupRegionLists();
}

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initCountryRegionControls);

(function ($) {
	$(document).ready(function () {
		initCountryRegionControls();
	});
})(jQuery);<|endoftext|>