<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Polltag = mongoose.model('Polltag'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll.save()
    .then(_poll => {
      poll = _poll;
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner = req.user && poll.user && poll.user._id.toString() === req.user._id.toString();
  poll.canEdit = req.user && req.user.roles && req.user.roles.length && req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll.save()
    .then(_poll => {
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        if (opt._id) {
          promises.push(() => {
            Opt.findById(opt._id).exec((err, _opt) => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll.remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find().sort('-created').populate('user', 'displayName').exec(function(err, polls) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polls);
    }
  });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id).populate('user', 'displayName').exec(function(err, opts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(opts);
    }
  });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  Poll.findCmts(req.poll._id).populate('user', 'displayName profileImageURL').exec(function(err, cmts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(cmts);
    }
  });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip = req.headers["X-Forwarded-For"] || req.headers["x-forwarded-for"] || req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {};
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      _votes.forEach(vote => {
        Vote.findOpts(vote._id).exec(function(err, opts) {
          if (err) {
            handleError(err);
          } else {
            rs.voteopts.push(opts);
          }
        });
      });
      res.jsonp(rs);
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id).populate('user', 'displayName profileImageURL').exec(function(err, poll) {
    if (err) {
      return next(err);
    } else if (!poll) {
      return res.status(404).send({
        message: 'No Poll with that identifier has been found'
      });
    }
    req.poll = poll;
    next();
  });
};
<commit_msg>Commited from lenh at 2017年 6月 21日 水曜日 10:57:36<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Polltag = mongoose.model('Polltag'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll.save()
    .then(_poll => {
      poll = _poll;
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner = req.user && poll.user && poll.user._id.toString() === req.user._id.toString();
  poll.canEdit = req.user && req.user.roles && req.user.roles.length && req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll.save()
    .then(_poll => {
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        if (opt._id) {
          promises.push(() => {
            Opt.findById(opt._id).exec((err, _opt) => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll.remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find().sort('-created').populate('user', 'displayName').exec(function(err, polls) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polls);
    }
  });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id).populate('user', 'displayName').exec(function(err, opts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(opts);
    }
  });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  Poll.findCmts(req.poll._id).populate('user', 'displayName profileImageURL').exec(function(err, cmts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(cmts);
    }
  });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip = req.headers["X-Forwarded-For"] || req.headers["x-forwarded-for"] || req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {};
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      _votes.forEach(vote => {
        console.log(vote);
        Vote.findOpts(vote._id).exec(function(err, opts) {
          if (err) {
            handleError(err);
          } else {
            rs.voteopts.push(opts);
          }
        });
      });
      res.jsonp(rs);
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id).populate('user', 'displayName profileImageURL').exec(function(err, poll) {
    if (err) {
      return next(err);
    } else if (!poll) {
      return res.status(404).send({
        message: 'No Poll with that identifier has been found'
      });
    }
    req.poll = poll;
    next();
  });
};
<|endoftext|>


<commit_before>'use strict';

process.env.testing = true;

var expect = require('chai').expect;
var watcher = require('../lib/watcher').test;

describe('Command parsing', function() {
    describe('parseCommands(pm2 startOrRestart test.json && pm2 logs; pm2 kill)', function() {
        var parsedCommands = watcher.parseCommands('pm2 startOrRestart test.json && pm2 logs; pm2 kill');

        it('should return an array', function() {
            expect(parsedCommands).is.an('array');
        });

        describe('the contents of it should be', function() {
            it('[0] === { command: pm2, arguments: [ startOrRestart, test.json ] }', function() {
                expect(parsedCommands[0].command).to.equal('pm2');
                expect(parsedCommands[0].arguments).to.have.all.members(['startOrRestart', 'test.json']);
            });

            it('[1] === { command: pm2, arguments: [ logs ] }', function() {
                expect(parsedCommands[1].command).to.equal('pm2');
                expect(parsedCommands[1].arguments).to.have.all.members(['logs']);
            });

            it('[2] === { command: pm2, arguments: [ kill ] }', function() {
                expect(parsedCommands[2].command).to.equal('pm2');
                expect(parsedCommands[2].arguments).to.have.all.members(['kill']);
            });
        });
    });

    describe('parseCommand(pm2 logs)', function() {
        var parsedCommand = watcher.parseCommand('pm2 logs');

        it('should return an object', function() {
            expect(parsedCommand).is.an('object');
        });

        it('the command string should be equal to »pm2«', function() {
            expect(parsedCommand.command).is.a('string').and.equal('pm2');
        });

        it('the arguments should be [ \'logs\' ]', function() {
            expect(parsedCommand.arguments).is.an('array').which.have.all.members(['logs']);
        });

        it('the remainingString should equal »«', function() {
            expect(parsedCommand.remainingString).is.a('string').which.equal('');
        });
    });
});
<commit_msg>Fixed path<commit_after>'use strict';

process.env.testing = true;

var expect = require('chai').expect;
var watcher = require('../lib/node-watcher').test;

describe('Command parsing', function() {
    describe('parseCommands(pm2 startOrRestart test.json && pm2 logs; pm2 kill)', function() {
        var parsedCommands = watcher.parseCommands('pm2 startOrRestart test.json && pm2 logs; pm2 kill');

        it('should return an array', function() {
            expect(parsedCommands).is.an('array');
        });

        describe('the contents of it should be', function() {
            it('[0] === { command: pm2, arguments: [ startOrRestart, test.json ] }', function() {
                expect(parsedCommands[0].command).to.equal('pm2');
                expect(parsedCommands[0].arguments).to.have.all.members(['startOrRestart', 'test.json']);
            });

            it('[1] === { command: pm2, arguments: [ logs ] }', function() {
                expect(parsedCommands[1].command).to.equal('pm2');
                expect(parsedCommands[1].arguments).to.have.all.members(['logs']);
            });

            it('[2] === { command: pm2, arguments: [ kill ] }', function() {
                expect(parsedCommands[2].command).to.equal('pm2');
                expect(parsedCommands[2].arguments).to.have.all.members(['kill']);
            });
        });
    });

    describe('parseCommand(pm2 logs)', function() {
        var parsedCommand = watcher.parseCommand('pm2 logs');

        it('should return an object', function() {
            expect(parsedCommand).is.an('object');
        });

        it('the command string should be equal to »pm2«', function() {
            expect(parsedCommand.command).is.a('string').and.equal('pm2');
        });

        it('the arguments should be [ \'logs\' ]', function() {
            expect(parsedCommand.arguments).is.an('array').which.have.all.members(['logs']);
        });

        it('the remainingString should equal »«', function() {
            expect(parsedCommand.remainingString).is.a('string').which.equal('');
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

describe("state", function() {
  var mockConfigurator = {
    configurationFor: function(name) {
      return {};
    },
    getRetrievers: function(name) {
      return {};
    }
  };

  var createTokens = function() {
    return {
      '01': {
        id: '01',
        string: 'Arma',
        head: {
          id: '03'
        }
      },
      '02': {
        id: '02',
        string: 'virum',
        head: {
          id: '03',
        }
      },
      '03': {
        id: '03',
        string: '-que',
        head: {
          id: '04'
        }
      },
      '04': {
        id: '04',
        string: 'cano',
        head: {
          id: '00'
        }
      }
    };
  };

  beforeEach(module("arethusa.core", function($provide) {
    $provide.value('configurator', mockConfigurator);
  }));

  var state;
  beforeEach(inject(function(_state_) {
    state = _state_;
    state.tokens = createTokens();
  }));

  describe("this.countTotalTokens", function() {
    it('counts the total number of tokens, exposed through this.totalTokens', function() {
      state.countTotalTokens();
      expect(state.totalTokens).toEqual(4);
    });
  });

  describe('this.countTokens', function() {
    it('returns a count of tokens for which the given function is true', function() {
      var fn = function(token) {
        return token.string == "cano";
      };
      expect(state.countTokens(fn)).toEqual(1);
    });
  });

  describe('this.getToken', function() {
    it('returns a token by id', function() {
      var res = state.tokens['01'];
      expect(state.getToken('01')).toBe(res);
    });
  });

  describe('this.asString', function() {
    it('returns the string of a token identified by id', function() {
      expect(state.asString('01')).toEqual('Arma');
    });
  });

  describe('this.selectToken()', function() {
    it('selects the clicked token', function() {
      state.selectToken('03', 'click');

      expect(state.selectedTokens).toEqual({'03': 'click'});
    });

    it('deselects all tokens after head change', function() {
      state.selectToken('01', 'click');
      state.selectToken('03', 'click');

      expect(state.selectedTokens).toEqual({});
    });

    it('selects multiple tokens with ctrl', function() {
      state.selectToken('01', 'ctrl-click');
      state.selectToken('03', 'ctrl-click');

      expect(state.selectedTokens).toEqual({'01': 'ctrl-click', '03': 'ctrl-click'});
    });
  });

  describe('this.deselectToken', function() {
    it('deselects a token', function() {
      state.selectToken('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
      state.deselectToken('01', 'click');
      expect(state.isSelected('01')).toBeFalsy();
    });

    it('selection type has to be the same to do a proper deselect', function() {
      state.selectToken('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
      state.deselectToken('01', 'hover');
      expect(state.isSelected('01')).toBeTruthy();
    });
  });

  describe('this.deselectAll', function() {
    it('deselects all selected tokens, no matter the selection type', function() {
      state.selectToken('01', 'ctrl-click');
      state.selectToken('03', 'ctrl-click');
      expect(state.isSelected('01')).toBeTruthy();
      expect(state.isSelected('03')).toBeTruthy();
      state.deselectAll();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('03')).toBeFalsy();
    });
  });

  describe('this.toggleSelection', function() {
    it('toggles the selection of a token', function() {
      state.toggleSelection('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
      state.toggleSelection('01', 'click');
      expect(state.isSelected('01')).toBeFalsy();
    });

    it('takes hover and click differences into account', function() {
      state.toggleSelection('01', 'hover');
      expect(state.isSelected('01')).toBeTruthy();
      state.toggleSelection('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
    });
  });

  /* Default tree:
   *     04:cano
   *        |
   *     03:-que
   *      /   \
   *  01:Arma 02:virum
   */
  describe('this.handleChangeHead', function() {
    /*
     *     04:cano
     *     /    \
     * 03:-que 01:Arma
     *     |
     *  02:virum
     */
    it('parents a leaf node to the root', function() {
      state.selectToken('01', 'click');

      state.selectToken('04', 'click');

      expect(state.getToken('01').head.id).toBe('04');
    });

    /*
     *     04:cano
     *        |
     *     03:-que
     *        |
     *    02:virum
     *        |
     *     01:Arma
     */
    it('parents a leaf node to another leaf node', function() {
      state.selectToken('01', 'click');

      state.selectToken('02', 'click');

      expect(state.getToken('01').head.id).toBe('02');
    });

    /*
     *     04:cano
     *        |
     *     01:Arma
     *        |
     *     03:-que
     *        |
     *    02:virum
     */
    it('parents an inner node to a leaf node', function() {
      state.selectToken('03', 'click');

      state.selectToken('01', 'click');

      expect(state.getToken('03').head.id).toBe('01');
      expect(state.getToken('02').head.id).toBe('03');
      expect(state.getToken('01').head.id).toBe('04');
    });

    describe('with multiple selection', function() {
      /*
       *         04:cano
       *      /     |     \
       * 01:Arma 02:virum 03:-que
       */
      it('parents two leaf nodes to an inner node', function() {
        state.selectToken('01', 'click');
        state.selectToken('02', 'ctrl-click');

        state.selectToken('04', 'click');

        expect(state.getToken('01').head.id).toBe('04');
        expect(state.getToken('02').head.id).toBe('04');
        expect(state.getToken('03').head.id).toBe('04');
      });

      /*
       *     04:cano
       *        |
       *     03:-que
       *        |
       *    02:virum
       *        |
       *     01:Arma
       */
      it('ignores node in multiselection if it becomes head', function() {
        state.selectToken('01', 'click');
        state.selectToken('02', 'ctrl-click');

        state.selectToken('02', 'click');

        expect(state.getToken('01').head.id).toBe('02');
        expect(state.getToken('02').head.id).toBe('03');
      });
    });
  });

  describe('this.headsFor', function() {
    it('returns an empty array for the root', function() {
      expect(state.headsFor('00')).toEqual([]);
    });

    it('returns an array of head ids', function() {
      expect(state.headsFor('01')).toEqual(['03', '04', '00']);
    });
  });
});
<commit_msg>Add specs for state.selectNextToken()<commit_after>"use strict";

describe("state", function() {
  var mockConfigurator = {
    configurationFor: function(name) {
      return {};
    },
    getRetrievers: function(name) {
      return {};
    }
  };

  var createTokens = function() {
    return {
      '01': {
        id: '01',
        string: 'Arma',
        head: {
          id: '03'
        }
      },
      '02': {
        id: '02',
        string: 'virum',
        head: {
          id: '03',
        }
      },
      '03': {
        id: '03',
        string: '-que',
        head: {
          id: '04'
        }
      },
      '04': {
        id: '04',
        string: 'cano',
        head: {
          id: '00'
        }
      }
    };
  };

  beforeEach(module("arethusa.core", function($provide) {
    $provide.value('configurator', mockConfigurator);
  }));

  var state;
  beforeEach(inject(function(_state_) {
    state = _state_;
    state.tokens = createTokens();
  }));

  describe("this.countTotalTokens", function() {
    it('counts the total number of tokens, exposed through this.totalTokens', function() {
      state.countTotalTokens();
      expect(state.totalTokens).toEqual(4);
    });
  });

  describe('this.countTokens', function() {
    it('returns a count of tokens for which the given function is true', function() {
      var fn = function(token) {
        return token.string == "cano";
      };
      expect(state.countTokens(fn)).toEqual(1);
    });
  });

  describe('this.getToken', function() {
    it('returns a token by id', function() {
      var res = state.tokens['01'];
      expect(state.getToken('01')).toBe(res);
    });
  });

  describe('this.asString', function() {
    it('returns the string of a token identified by id', function() {
      expect(state.asString('01')).toEqual('Arma');
    });
  });

  describe('this.selectToken()', function() {
    it('selects the clicked token', function() {
      state.selectToken('03', 'click');

      expect(state.selectedTokens).toEqual({'03': 'click'});
    });

    it('deselects all tokens after head change', function() {
      state.selectToken('01', 'click');
      state.selectToken('03', 'click');

      expect(state.selectedTokens).toEqual({});
    });

    it('selects multiple tokens with ctrl', function() {
      state.selectToken('01', 'ctrl-click');
      state.selectToken('03', 'ctrl-click');

      expect(state.selectedTokens).toEqual({'01': 'ctrl-click', '03': 'ctrl-click'});
    });
  });

  describe('this.deselectToken', function() {
    it('deselects a token', function() {
      state.selectToken('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
      state.deselectToken('01', 'click');
      expect(state.isSelected('01')).toBeFalsy();
    });

    it('selection type has to be the same to do a proper deselect', function() {
      state.selectToken('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
      state.deselectToken('01', 'hover');
      expect(state.isSelected('01')).toBeTruthy();
    });
  });

  describe('this.deselectAll', function() {
    it('deselects all selected tokens, no matter the selection type', function() {
      state.selectToken('01', 'ctrl-click');
      state.selectToken('03', 'ctrl-click');
      expect(state.isSelected('01')).toBeTruthy();
      expect(state.isSelected('03')).toBeTruthy();
      state.deselectAll();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('03')).toBeFalsy();
    });
  });

  describe('this.toggleSelection', function() {
    it('toggles the selection of a token', function() {
      state.toggleSelection('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
      state.toggleSelection('01', 'click');
      expect(state.isSelected('01')).toBeFalsy();
    });

    it('takes hover and click differences into account', function() {
      state.toggleSelection('01', 'hover');
      expect(state.isSelected('01')).toBeTruthy();
      state.toggleSelection('01', 'click');
      expect(state.isSelected('01')).toBeTruthy();
    });
  });

  describe('this.selectNextToken', function() {
    it('watches the first active selection and selects the next token', function() {
      state.selectToken('01', 'click');
      state.selectNextToken();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('02')).toBeTruthy();
    });

    it('always takes the first - even if there is more than one selection', function() {
      state.selectToken('01', 'ctrl-click');
      state.selectToken('03', 'ctrl-click');
      state.selectNextToken();
      expect(state.isSelected('01')).toBeFalsy();
      expect(state.isSelected('03')).toBeFalsy();
      expect(state.isSelected('02')).toBeTruthy();
    });

    it('selects the first token if no selection was made before', function() {
      state.selectNextToken();
      expect(state.isSelected('01')).toBeTruthy();
    });

    it('starts at the top when current selection is the last token', function() {
      state.selectToken('04');
      state.selectNextToken();
      expect(state.isSelected('01')).toBeTruthy();
    });
  });

  /* Default tree:
   *     04:cano
   *        |
   *     03:-que
   *      /   \
   *  01:Arma 02:virum
   */
  describe('this.handleChangeHead', function() {
    /*
     *     04:cano
     *     /    \
     * 03:-que 01:Arma
     *     |
     *  02:virum
     */
    it('parents a leaf node to the root', function() {
      state.selectToken('01', 'click');

      state.selectToken('04', 'click');

      expect(state.getToken('01').head.id).toBe('04');
    });

    /*
     *     04:cano
     *        |
     *     03:-que
     *        |
     *    02:virum
     *        |
     *     01:Arma
     */
    it('parents a leaf node to another leaf node', function() {
      state.selectToken('01', 'click');

      state.selectToken('02', 'click');

      expect(state.getToken('01').head.id).toBe('02');
    });

    /*
     *     04:cano
     *        |
     *     01:Arma
     *        |
     *     03:-que
     *        |
     *    02:virum
     */
    it('parents an inner node to a leaf node', function() {
      state.selectToken('03', 'click');

      state.selectToken('01', 'click');

      expect(state.getToken('03').head.id).toBe('01');
      expect(state.getToken('02').head.id).toBe('03');
      expect(state.getToken('01').head.id).toBe('04');
    });

    describe('with multiple selection', function() {
      /*
       *         04:cano
       *      /     |     \
       * 01:Arma 02:virum 03:-que
       */
      it('parents two leaf nodes to an inner node', function() {
        state.selectToken('01', 'click');
        state.selectToken('02', 'ctrl-click');

        state.selectToken('04', 'click');

        expect(state.getToken('01').head.id).toBe('04');
        expect(state.getToken('02').head.id).toBe('04');
        expect(state.getToken('03').head.id).toBe('04');
      });

      /*
       *     04:cano
       *        |
       *     03:-que
       *        |
       *    02:virum
       *        |
       *     01:Arma
       */
      it('ignores node in multiselection if it becomes head', function() {
        state.selectToken('01', 'click');
        state.selectToken('02', 'ctrl-click');

        state.selectToken('02', 'click');

        expect(state.getToken('01').head.id).toBe('02');
        expect(state.getToken('02').head.id).toBe('03');
      });
    });
  });

  describe('this.headsFor', function() {
    it('returns an empty array for the root', function() {
      expect(state.headsFor('00')).toEqual([]);
    });

    it('returns an array of head ids', function() {
      expect(state.headsFor('01')).toEqual(['03', '04', '00']);
    });
  });
});
<|endoftext|>


<commit_before>import test from 'ava';
import fs from 'fs';
import px2rem from '../';

let css;

test.before('setup', t => {
    css = fs.readFileSync('./data/styles.css', 'utf8');
});

test('processed #1', t => {
    const validProcessedCSS = fs.readFileSync('./valid/styles.css', 'utf8');
    const processedCSS = px2rem.process(css);

    t.is(processedCSS, validProcessedCSS);
});

test('processed #2', t => {
    const validProcessedCSS = fs.readFileSync('./valid/styles.css', 'utf8');
    const pxToRem = px2rem();
    const processedCSS = pxToRem.process(css);

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `mediaQuery`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/media-query.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        mediaQuery: true
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/root-value.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: 12
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with percent `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/root-value-percent.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: '10%'
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with rem `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/root-value-rem.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: '10rem'
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with pt `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/root-value-pt.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: '1pt'
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `unitPrecision`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/unit-precision.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        unitPrecision: 2
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `propertyBlackList`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/property-blacklist.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        propertyBlackList: [
            'font-size'
        ]
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `propertyWhiteList`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/property-whitelist.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        propertyWhiteList: [
            'font-size'
        ]
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `replace`', t => {
    const validProcessedCSS = fs.readFileSync('./valid/replace.css', 'utf8');
    const processedCSS = px2rem.process(css, {
        replace: true
    });

    t.is(processedCSS, validProcessedCSS);
});
<commit_msg>fix test<commit_after>import test from 'ava';
import fs from 'fs';
import path from 'path';
import px2rem from '../';

let css;

test.before('setup', t => {
    css = fs.readFileSync(`${__dirname}/data/styles.css`, 'utf8');
});

test('processed #1', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/styles.css`, 'utf8');
    const processedCSS = px2rem.process(css);

    t.is(processedCSS, validProcessedCSS);
});

test('processed #2', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/styles.css`, 'utf8');
    const pxToRem = px2rem();
    const processedCSS = pxToRem.process(css);

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `mediaQuery`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/media-query.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        mediaQuery: true
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/root-value.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: 12
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with percent `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/root-value-percent.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: '10%'
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with rem `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/root-value-rem.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: '10rem'
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with pt `rootValue`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/root-value-pt.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        rootValue: '1pt'
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `unitPrecision`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/unit-precision.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        unitPrecision: 2
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `propertyBlackList`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/property-blacklist.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        propertyBlackList: [
            'font-size'
        ]
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `propertyWhiteList`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/property-whitelist.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        propertyWhiteList: [
            'font-size'
        ]
    });

    t.is(processedCSS, validProcessedCSS);
});

test('processed with `replace`', t => {
    const validProcessedCSS = fs.readFileSync(`${__dirname}/valid/replace.css`, 'utf8');
    const processedCSS = px2rem.process(css, {
        replace: true
    });

    t.is(processedCSS, validProcessedCSS);
});
<|endoftext|>


<commit_before>// Copyright 2015 Fabian Dietenberger

var should = require('chai').should(),
    hypemResolver = require('../hypem-resolver');

describe('Use the hypem link to get the songs url', function () {
    describe('if the song is hosted on soundcloud', function () {
        it('should return a soundcloud url', function (done) {
            var soundcloudUrl = hypemResolver.getUrl('adad');
            soundcloudUrl.should.be.a('string');
            done();
        })
    });
});<commit_msg>Add tests for the async methods<commit_after>// Copyright 2015 Fabian Dietenberger

var should = require('chai').should(),
    hypemResolver = require('../hypem-resolver');

var grizHypemId = "2c87x",
    grizHypemUrl = "http://hypem.com/track/2c87x",
    grizSoundcloudUrl = "https://soundcloud.com/griz/summer-97-ft-muzzy-bearr";

describe('Get the songs URL with the hypem URL', function () {
    describe('if the song is hosted on soundcloud', function () {
        it('should return a soundcloud url', function (done) {
            var soundcloudUrl = hypemResolver.getByUrl(grizHypemUrl);
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        })
    });
});

describe('Get the songs URL with the hypem URL async', function () {
    describe('if the song is hosted on soundcloud', function () {
        it('should return a soundcloud url', function (done) {
            hypemResolver.getByUrlAsync(grizHypemUrl, function (soundcloudUrl) {
                soundcloudUrl.should.be.a('string');
                soundcloudUrl.should.equal(grizSoundcloudUrl);
                done();
            });
        })
    });
});

describe('Get the songs URL with the hypem ID', function () {
    describe('if the song is hosted on soundcloud', function () {
        it('should return a soundcloud url', function (done) {
            var soundcloudUrl = hypemResolver.getById(grizHypemId);
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        })
    });
});

describe('Get the songs URL with the hypem ID async', function () {
    describe('if the song is hosted on soundcloud', function () {
        it('should return a soundcloud url', function (done) {
            hypemResolver.getByIdAsync(grizHypemId, function (soundcloudUrl) {
                soundcloudUrl.should.be.a('string');
                soundcloudUrl.should.equal(grizSoundcloudUrl);
                done();
            });
        })
    });
});<|endoftext|>


<commit_before>import * as _ from 'lodash';
import { ConstantPool } from '../jvm/ConstantPool';

_.mixin({
  toMap: function (map) {
    let m = {};
    for (var k of map) {
      let [key, value] = k;
      m[key] = value;
    }
    return m;
  }
});

export class ClassFile {
  constructor(name) {
    this.name = name;
    this.props = new Map();
    this.constantPool = new ConstantPool();
    this.interfaces = [];
    this.fields = [];
    this.methods = [];
    this.attributes = [];
  }

  property(prop, value = null) {
    if (value === null) {
      return this.props.get(prop);
    }

    this.props.set(prop, value);
  }

  string(idx) {
    return this.constantPool.at(idx).bytes.toString('UTF8');
  }

  dump() {
    let struct = {
      'interfaces': [],
      'strings': [],
      'fields': [],
      'methods': [],
      'attributes': [],
    };

    let _clone = (obj) => {
      return JSON.parse(JSON.stringify(obj));
    };

    let resolveAttribute = (attr) => {
      let clone = _clone(attr);

      clone['decoded'] = {
        name: this.string(clone.attribute_name_index)
      };

      return clone;
    };

    _.each(this.fields, field => {
      let clone = _clone(field);

      _.map(clone.attribute_info, (attrInfo) => {
        attrInfo['name'] = this.string(attrInfo.attribute_name_index);
      });

      clone['decoded'] = {
        name: this.string(clone.name_index),
        descriptor: this.string(clone.descriptor_index)
      };

      struct.fields.push(clone);
    });

    _.each(this.methods, method => {
      let clone = _clone(method);

      _.map(clone.attribute_info, (attrInfo) => {
        attrInfo['name'] = this.string(attrInfo.attribute_name_index);
      });

      clone['decoded'] = {
        name: this.string(clone.name_index),
        descriptor: this.string(clone.descriptor_index)
      };

      struct.methods.push(clone);
    });

    _.each(this.attributes, attribute => {
      // let clone = JSON.parse(JSON.stringify(attribute));

      // clone['decoded'] = {
      //   name: this.string(clone.attribute_name_index)
      // };

      struct.attributes.push(resolveAttribute(attribute));
    });

    _.each(_.filter(this.constantPool.pool, { tag: 1 }), (val) => {
      struct.strings.push(val.bytes.toString('UTF8'));
    });

    _.each(this.interfaces, (idx) => {
      struct.interfaces.push(this.constantPool.at(idx))
    });

    return {
      properties: _.toMap(this.props),
      debug: struct
    };
  }
}
<commit_msg>add shortened getter for ConstantPool instant in ClassFile<commit_after>import * as _ from 'lodash';
import { ConstantPool } from '../jvm/ConstantPool';

_.mixin({
  toMap: function (map) {
    let m = {};
    for (var k of map) {
      let [key, value] = k;
      m[key] = value;
    }
    return m;
  }
});

export class ClassFile {
  constructor(name) {
    this.name = name;
    this.props = new Map();
    this.constantPool = new ConstantPool();
    this.interfaces = [];
    this.fields = [];
    this.methods = [];
    this.attributes = [];
  }

  get pool() {
    return this.constantPool;
  }

  property(prop, value = null) {
    if (value === null) {
      return this.props.get(prop);
    }

    this.props.set(prop, value);
  }

  string(idx) {
    return this.constantPool.at(idx).bytes.toString('UTF8');
  }

  dump() {
    let struct = {
      'interfaces': [],
      'strings': [],
      'fields': [],
      'methods': [],
      'attributes': [],
    };

    let _clone = (obj) => {
      return JSON.parse(JSON.stringify(obj));
    };

    let resolveAttribute = (attr) => {
      let clone = _clone(attr);

      clone['decoded'] = {
        name: this.string(clone.attribute_name_index)
      };

      return clone;
    };

    _.each(this.fields, field => {
      let clone = _clone(field);

      _.map(clone.attribute_info, (attrInfo) => {
        attrInfo['name'] = this.string(attrInfo.attribute_name_index);
      });

      clone['decoded'] = {
        name: this.string(clone.name_index),
        descriptor: this.string(clone.descriptor_index)
      };

      struct.fields.push(clone);
    });

    _.each(this.methods, method => {
      let clone = _clone(method);

      _.map(clone.attribute_info, (attrInfo) => {
        attrInfo['name'] = this.string(attrInfo.attribute_name_index);
      });

      clone['decoded'] = {
        name: this.string(clone.name_index),
        descriptor: this.string(clone.descriptor_index)
      };

      struct.methods.push(clone);
    });

    _.each(this.attributes, attribute => {
      // let clone = JSON.parse(JSON.stringify(attribute));

      // clone['decoded'] = {
      //   name: this.string(clone.attribute_name_index)
      // };

      struct.attributes.push(resolveAttribute(attribute));
    });

    _.each(_.filter(this.constantPool.pool, { tag: 1 }), (val) => {
      struct.strings.push(val.bytes.toString('UTF8'));
    });

    _.each(this.interfaces, (idx) => {
      struct.interfaces.push(this.constantPool.at(idx))
    });

    return {
      properties: _.toMap(this.props),
      debug: struct
    };
  }
}
<|endoftext|>


<commit_before>var should = require('chai').should(),
  assert = require('assert'),
  expect = require('chai').expect;
nmap = require('../index');

describe('NmapScan', function () {

  it('runs NMAP', function (done) {

    this.timeout(10000);
    var scan = nmap.NmapScan("127.0.0.1");
    scan.on('complete', function (data) {
      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[0]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();
    });
    scan.startScan();
  });

  it('accepts space separated command', function (done) {

    this.timeout(10000);
    var scan = nmap.NmapScan("-sn 127.0.0.1");
    scan.on('complete', function (data) {

      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[0]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();
    });
    scan.startScan();
  });

  it('accepts multiple hosts', function (done) {

    this.timeout(10000);
    var scan = nmap.NmapScan("-sn 127.0.0.1 google.com");
    scan.on('complete', function (data) {

      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[1]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();
    });
    scan.startScan();
  });
  it('returns failure data for bad requests', function (done) {

    this.timeout(10000);
    var scan = nmap.NmapScan("127.0.0.");
    scan.on('error', function (err) {
      expect(err).to.be.a('string');
      done();
    });
    scan.startScan();
  });

});

describe('quickScan', function () {

  it('scans range of hosts', function (done) {

    this.timeout(10000);
    var scan = nmap.quickScan("127.0.0.1 google.com");
    scan.on('complete', function (data) {

      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[1]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();

    });
    scan.startScan();
  });
  it('returns failure data for bad requests', function (done) {

    this.timeout(10000);
    var scan = nmap.quickScan("127.0.0.");
    scan.on('error', function (err) {
      expect(err).to.be.a('string');
      done();
    });
    scan.startScan();

  });

});

describe('osAndPortScan', function () {

  it('scans hosts for open ports and OS data', function (done) {

    this.timeout(20000);
    var scan = nmap.osAndPortScan("google.com");
    scan.on('complete', function (data) {
      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[0]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      expect(data[0].openPorts).to.be.instanceOf(Array);
      expect(data[0].openPorts[0].port).to.exist;
      done();

    });
    scan.startScan();
  });
  it('returns failure data for bad requests', function (done) {

    this.timeout(10000);
    var scan = nmap.osAndPortScan("127.0.0.");
    scan.on('error', function (err) {
      expect(err).to.be.a('string');
      done();
    });
    scan.startScan();

  });

});<commit_msg>Fix tests<commit_after>var should = require('chai').should(),
  assert = require('assert'),
  expect = require('chai').expect,
nmap = require('../index');

describe('NmapScan', function () {

  it('runs NMAP', function (done) {

    this.timeout(10000);
    var scan = new nmap.nodenmap.NmapScan("google.com");
    scan.on('complete', function (data) {
      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[0]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();
    });
    scan.startScan();
  });

  it('accepts space separated command', function (done) {

    this.timeout(10000);
    var scan = new nmap.nodenmap.NmapScan("-sn 127.0.0.1");
    scan.on('complete', function (data) {

      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[0]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();
    });
    scan.startScan();
  });

  it('accepts multiple hosts', function (done) {

    this.timeout(10000);
    var scan = new nmap.nodenmap.NmapScan("-sn 127.0.0.1 google.com");
    scan.on('complete', function (data) {

      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[1]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();
    });
    scan.startScan();
  });
  it('returns failure data for bad requests', function (done) {

    this.timeout(10000);
    var scan = new nmap.nodenmap.NmapScan("127.0.0.");
    scan.on('error', function (err) {
      expect(err).to.be.a('string');
      done();
    });
    scan.startScan();
  });

});

describe('quickScan', function () {

  it('scans range of hosts', function (done) {

    this.timeout(10000);
    var scan = new nmap.nodenmap.QuickScan("127.0.0.1 google.com");
    scan.on('complete', function (data) {

      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[1]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      done();

    });
    scan.startScan();
  });
  it('returns failure data for bad requests', function (done) {

    this.timeout(10000);
    var scan = new nmap.nodenmap.QuickScan("127.0.0.");
    scan.on('error', function (err) {
      expect(err).to.be.a('string');
      done();
    });
    scan.startScan();

  });

});

describe('osAndPortScan', function () {

  it('scans hosts for open ports and OS data', function (done) {

    this.timeout(20000);
    var scan = new nmap.nodenmap.OsAndPortScan("google.com");
    scan.on('complete', function (data) {
      expect(data).to.be.instanceOf(Array);
      expect(data).to.not.be.empty;
      expect(data[0]).to.include.keys('hostname', 'ip', 'mac', 'openPorts', 'osNmap');
      expect(data[0].openPorts).to.be.instanceOf(Array);
      expect(data[0].openPorts[0].port).to.exist;
      done();

    });
    scan.startScan();
  });
  it('returns failure data for bad requests', function (done) {

    this.timeout(10000);
    var scan = new nmap.nodenmap.OsAndPortScan("127.0.0.");
    scan.on('error', function (err) {
      expect(err).to.be.a('string');
      done();
    });
    scan.startScan();

  });

});<|endoftext|>


<commit_before>define(['backbone','./FrameView'],
function(Backbone, FrameView) {
  /**
   * @class CanvasView
   * */
  return Backbone.View.extend({

    initialize: function(o) {
      _.bindAll(this, 'renderBody', 'onFrameScroll', 'clearOff');
      this.config = o.config || {};
      this.em = this.config.em || {};
      this.ppfx  = this.config.pStylePrefix || '';
      this.className  = this.config.stylePrefix + 'canvas';
      this.listenTo(this.em, 'change:canvasOffset', this.clearOff);
      this.frame = new FrameView({
        model: this.model.get('frame'),
        config: this.config
      });
    },

    /**
     * Update tools position
     * @private
     */
    onFrameScroll: function(){
      var u = 'px';
      var body = this.frame.el.contentDocument.body;
      this.toolsEl.style.top = '-' + body.scrollTop + u;
      this.toolsEl.style.left = '-' + body.scrollLeft + u;
      this.em.trigger('canvasScroll');
    },

    /**
     * Insert scripts into head, it will call renderBody after all scripts loaded or failed
     * @private
     */
    renderScripts: function () {
        var frame = this.frame;
        var that = this;

        frame.el.onload = function () {
          var scripts = that.config.scripts.slice(0),  // clone
              counter = 0;

          function appendScript(scripts) {
            if (scripts.length > 0) {
              var script = document.createElement('script');
              script.type = 'text/javascript';
              script.src = scripts.shift();
              script.onerror = script.onload = appendScript.bind(null, scripts);
              frame.el.contentDocument.head.appendChild(script);
            } else {
              that.renderBody();
            }
          }
          appendScript(scripts);
        };
    },

    /**
     * Render inside frame's body
     * @private
     */
    renderBody: function(){
      var wrap = this.model.get('frame').get('wrapper');
      var em = this.config.em;
      if(wrap) {
        var ppfx = this.ppfx;
        var body = this.frame.$el.contents().find('body');
        var cssc = em.get('CssComposer');
        var conf = em.get('Config');
        body.append(wrap.render()).append(cssc.render());
        var protCss = conf.protectedCss;
        var frameCss = '.' + ppfx + 'dashed :not([contenteditable]) > *{outline: 1px dashed rgba(170,170,170,0.7); outline-offset: -2px}' +
                       '.' + ppfx + 'comp-selected{outline: 3px solid #3b97e3 !important}' +
                       '.' + ppfx + 'no-select{user-select: none; -webkit-user-select:none; -moz-user-select: none}'+
                       '.' + ppfx + 'freezed{opacity: 0.5; pointer-events: none}' +
                       '.' + ppfx + 'no-pointer{pointer-events: none}' +
                       '.' + ppfx + 'plh-image{background:#f5f5f5; border:none; height:50px; width:50px; display:block; outline:3px solid #ffca6f; cursor:pointer}' +
                       '.' + ppfx + 'grabbing{cursor: grabbing; cursor: -webkit-grabbing}' +
                       '* ::-webkit-scrollbar-track {background: rgba(0, 0, 0, 0.1)}' +
                       '* ::-webkit-scrollbar-thumb {background: rgba(255, 255, 255, 0.2)}' +
                       '* ::-webkit-scrollbar {width: 10px}' +
                       (conf.canvasCss || '');
        if(protCss)
          body.append('<style>' + frameCss + protCss + '</style>');
        body.append(this.getJsContainer());
        em.trigger('loaded');
        this.frame.el.contentWindow.onscroll = this.onFrameScroll;
        this.frame.udpateOffset();

        // When the iframe is focused the event dispatcher is not the same so
        // I need to delegate all events to the parent document
        var doc = document;
        var fdoc = this.frame.el.contentDocument;
        fdoc.addEventListener('keydown', function(e){
          doc.dispatchEvent(new KeyboardEvent(e.type, e));
        });
        fdoc.addEventListener('keyup', function(e){
          doc.dispatchEvent(new KeyboardEvent(e.type, e));
        });
      }
    },

    /**
     * Get the offset of the element
     * @param  {HTMLElement} el
     * @return {Object}
     */
    offset: function(el){
      var rect = el.getBoundingClientRect();
      var docBody = el.ownerDocument.body;
      return {
        top: rect.top + docBody.scrollTop,
        left: rect.left + docBody.scrollLeft
      };
    },

    /**
     * Cleare cached offsets
     * @private
     */
    clearOff: function(){
      this.frmOff = null;
      this.cvsOff = null;
    },

    /**
     * Return frame offset
     * @return {Object}
     * @private
     */
    getFrameOffset: function () {
      if(!this.frmOff)
        this.frmOff = this.offset(this.frame.el);
      return this.frmOff;
    },

    /**
     * Return canvas offset
     * @return {Object}
     * @private
     */
    getCanvasOffset: function () {
      if(!this.cvsOff)
        this.cvsOff = this.offset(this.el);
      return this.cvsOff;
    },

    /**
     * Returns element's data info
     * @param {HTMLElement} el
     * @return {Object}
     * @private
     */
    getElementPos: function(el) {
      var frmOff = this.getFrameOffset();
      var cvsOff = this.getCanvasOffset();
      var eo = this.offset(el);
      var top = eo.top + frmOff.top - cvsOff.top;
      var left = eo.left + frmOff.left - cvsOff.left;
      return {
        top: top,
        left: left,
        height: el.offsetHeight,
        width: el.offsetWidth
      };
    },

    /**
     * Returns position data of the canvas element
     * @return {Object} obj Position object
     * @private
     */
    getPosition: function() {
      var bEl = this.frame.el.contentDocument.body;
      var fo = this.getFrameOffset();
      var co = this.getCanvasOffset();
      return {
        top: fo.top + bEl.scrollTop - co.top,
        left: fo.left + bEl.scrollLeft - co.left
      };
    },

    /**
     * Update javascript of a specific component passed by its View
     * @param {View} view Component's View
     * @private
     */
    updateScript: function(view) {
      if(!view.scriptContainer) {
        view.scriptContainer = $('<div>');
        this.getJsContainer().append(view.scriptContainer.get(0));
      }

      var id = view.model.cid;
      var script = view.model.get('script');
      var scrStr = 'function(){' + script + '}';
      scrStr = typeof script == 'function' ? script.toString() : scrStr;

      view.el.id = id;
      view.scriptContainer.html('');

      view.scriptContainer.append('<script>' +
        'var item = document.getElementById("'+id+'");' +
        '(' + scrStr + '.bind(item))()</script>');
    },

    /**
     * Get javascript container
     * @private
     */
    getJsContainer: function () {
      if (!this.jsContainer) {
        this.jsContainer = $('<div>', {class: this.ppfx + 'js-cont'}).get(0);
      }
      return this.jsContainer;
    },

    render: function() {
      this.wrapper  = this.model.get('wrapper');

      if(this.wrapper && typeof this.wrapper.render == 'function'){
        this.model.get('frame').set('wrapper', this.wrapper);
        this.$el.append(this.frame.render().el);
        var frame = this.frame;
        if (this.config.scripts.length === 0) {
          frame.el.onload = this.renderBody;
        } else {
          this.renderScripts(); // will call renderBody later
        }
      }
      var ppfx = this.ppfx;
      toolsEl = $('<div>', { id: ppfx + 'tools' }).get(0);
      this.hlEl = $('<div>', { class: ppfx + 'highlighter' }).get(0);
      this.badgeEl = $('<div>', {class: ppfx + 'badge'}).get(0);
      this.placerEl = $('<div>', {class: ppfx + 'placeholder'}).get(0);
      this.placerIntEl = $('<div>', {class: ppfx + 'placeholder-int'}).get(0);
      this.ghostEl = $('<div>', {class: ppfx + 'ghost'}).get(0);
      this.toolbarEl = $('<div>', {class: ppfx + 'toolbar'}).get(0);
      this.resizerEl = $('<div>', {class: ppfx + 'resizer'}).get(0);
      this.offsetEl = $('<div>', {class: ppfx + 'offset-v'}).get(0);
      this.fixedOffsetEl = $('<div>', {class: ppfx + 'offset-fixed-v'}).get(0);
      this.placerEl.appendChild(this.placerIntEl);
      toolsEl.appendChild(this.hlEl);
      toolsEl.appendChild(this.badgeEl);
      toolsEl.appendChild(this.placerEl);
      toolsEl.appendChild(this.ghostEl);
      toolsEl.appendChild(this.toolbarEl);
      toolsEl.appendChild(this.resizerEl);
      toolsEl.appendChild(this.offsetEl);
      toolsEl.appendChild(this.fixedOffsetEl);
      this.$el.append(toolsEl);
      var rte = this.em.get('rte');

      if(rte)
        toolsEl.appendChild(rte.render());

      this.toolsEl = toolsEl;
      this.$el.attr({class: this.className});
      return this;
    },

  });
});
<commit_msg>Move essential styles inside Canvas<commit_after>define(['backbone','./FrameView'],
function(Backbone, FrameView) {
  /**
   * @class CanvasView
   * */
  return Backbone.View.extend({

    initialize: function(o) {
      _.bindAll(this, 'renderBody', 'onFrameScroll', 'clearOff');
      this.config = o.config || {};
      this.em = this.config.em || {};
      this.ppfx  = this.config.pStylePrefix || '';
      this.className  = this.config.stylePrefix + 'canvas';
      this.listenTo(this.em, 'change:canvasOffset', this.clearOff);
      this.frame = new FrameView({
        model: this.model.get('frame'),
        config: this.config
      });
    },

    /**
     * Update tools position
     * @private
     */
    onFrameScroll: function(){
      var u = 'px';
      var body = this.frame.el.contentDocument.body;
      this.toolsEl.style.top = '-' + body.scrollTop + u;
      this.toolsEl.style.left = '-' + body.scrollLeft + u;
      this.em.trigger('canvasScroll');
    },

    /**
     * Insert scripts into head, it will call renderBody after all scripts loaded or failed
     * @private
     */
    renderScripts: function () {
        var frame = this.frame;
        var that = this;

        frame.el.onload = function () {
          var scripts = that.config.scripts.slice(0),  // clone
              counter = 0;

          function appendScript(scripts) {
            if (scripts.length > 0) {
              var script = document.createElement('script');
              script.type = 'text/javascript';
              script.src = scripts.shift();
              script.onerror = script.onload = appendScript.bind(null, scripts);
              frame.el.contentDocument.head.appendChild(script);
            } else {
              that.renderBody();
            }
          }
          appendScript(scripts);
        };
    },

    /**
     * Render inside frame's body
     * @private
     */
    renderBody: function() {
      var wrap = this.model.get('frame').get('wrapper');
      var em = this.config.em;
      if(wrap) {
        var ppfx = this.ppfx;
        var body = this.frame.$el.contents().find('body');
        var cssc = em.get('CssComposer');
        var conf = em.get('Config');
        body.append(wrap.render()).append(cssc.render());
        var protCss = conf.protectedCss;

        // I need all this styles to make the editor work properly
        var frameCss = '* {box-sizing: border-box;} body{margin:0;height:auto;background-color:#fff} #wrapper{min-height:100%; overflow:auto}' +
          '.' + ppfx + 'dashed :not([contenteditable]) > *{outline: 1px dashed rgba(170,170,170,0.7); outline-offset: -2px}' +
          '.' + ppfx + 'comp-selected{outline: 3px solid #3b97e3 !important}' +
          '.' + ppfx + 'no-select{user-select: none; -webkit-user-select:none; -moz-user-select: none}'+
          '.' + ppfx + 'freezed{opacity: 0.5; pointer-events: none}' +
          '.' + ppfx + 'no-pointer{pointer-events: none}' +
          '.' + ppfx + 'plh-image{background:#f5f5f5; border:none; height:50px; width:50px; display:block; outline:3px solid #ffca6f; cursor:pointer}' +
          '.' + ppfx + 'grabbing{cursor: grabbing; cursor: -webkit-grabbing}' +
          '* ::-webkit-scrollbar-track {background: rgba(0, 0, 0, 0.1)}' +
          '* ::-webkit-scrollbar-thumb {background: rgba(255, 255, 255, 0.2)}' +
          '* ::-webkit-scrollbar {width: 10px}' +
          (conf.canvasCss || '');
        frameCss += protCss || '';
        body.append('<style>' + frameCss + '</style>');
        body.append(this.getJsContainer());
        em.trigger('loaded');
        this.frame.el.contentWindow.onscroll = this.onFrameScroll;
        this.frame.udpateOffset();

        // When the iframe is focused the event dispatcher is not the same so
        // I need to delegate all events to the parent document
        var doc = document;
        var fdoc = this.frame.el.contentDocument;
        fdoc.addEventListener('keydown', function(e){
          doc.dispatchEvent(new KeyboardEvent(e.type, e));
        });
        fdoc.addEventListener('keyup', function(e){
          doc.dispatchEvent(new KeyboardEvent(e.type, e));
        });
      }
    },

    /**
     * Get the offset of the element
     * @param  {HTMLElement} el
     * @return {Object}
     */
    offset: function(el){
      var rect = el.getBoundingClientRect();
      var docBody = el.ownerDocument.body;
      return {
        top: rect.top + docBody.scrollTop,
        left: rect.left + docBody.scrollLeft
      };
    },

    /**
     * Cleare cached offsets
     * @private
     */
    clearOff: function(){
      this.frmOff = null;
      this.cvsOff = null;
    },

    /**
     * Return frame offset
     * @return {Object}
     * @private
     */
    getFrameOffset: function () {
      if(!this.frmOff)
        this.frmOff = this.offset(this.frame.el);
      return this.frmOff;
    },

    /**
     * Return canvas offset
     * @return {Object}
     * @private
     */
    getCanvasOffset: function () {
      if(!this.cvsOff)
        this.cvsOff = this.offset(this.el);
      return this.cvsOff;
    },

    /**
     * Returns element's data info
     * @param {HTMLElement} el
     * @return {Object}
     * @private
     */
    getElementPos: function(el) {
      var frmOff = this.getFrameOffset();
      var cvsOff = this.getCanvasOffset();
      var eo = this.offset(el);
      var top = eo.top + frmOff.top - cvsOff.top;
      var left = eo.left + frmOff.left - cvsOff.left;
      return {
        top: top,
        left: left,
        height: el.offsetHeight,
        width: el.offsetWidth
      };
    },

    /**
     * Returns position data of the canvas element
     * @return {Object} obj Position object
     * @private
     */
    getPosition: function() {
      var bEl = this.frame.el.contentDocument.body;
      var fo = this.getFrameOffset();
      var co = this.getCanvasOffset();
      return {
        top: fo.top + bEl.scrollTop - co.top,
        left: fo.left + bEl.scrollLeft - co.left
      };
    },

    /**
     * Update javascript of a specific component passed by its View
     * @param {View} view Component's View
     * @private
     */
    updateScript: function(view) {
      if(!view.scriptContainer) {
        view.scriptContainer = $('<div>');
        this.getJsContainer().append(view.scriptContainer.get(0));
      }

      var id = view.model.cid;
      var script = view.model.get('script');
      var scrStr = 'function(){' + script + '}';
      scrStr = typeof script == 'function' ? script.toString() : scrStr;

      view.el.id = id;
      view.scriptContainer.html('');

      view.scriptContainer.append('<script>' +
        'var item = document.getElementById("'+id+'");' +
        '(' + scrStr + '.bind(item))()</script>');
    },

    /**
     * Get javascript container
     * @private
     */
    getJsContainer: function () {
      if (!this.jsContainer) {
        this.jsContainer = $('<div>', {class: this.ppfx + 'js-cont'}).get(0);
      }
      return this.jsContainer;
    },

    render: function() {
      this.wrapper  = this.model.get('wrapper');

      if(this.wrapper && typeof this.wrapper.render == 'function'){
        this.model.get('frame').set('wrapper', this.wrapper);
        this.$el.append(this.frame.render().el);
        var frame = this.frame;
        if (this.config.scripts.length === 0) {
          frame.el.onload = this.renderBody;
        } else {
          this.renderScripts(); // will call renderBody later
        }
      }
      var ppfx = this.ppfx;
      toolsEl = $('<div>', { id: ppfx + 'tools' }).get(0);
      this.hlEl = $('<div>', { class: ppfx + 'highlighter' }).get(0);
      this.badgeEl = $('<div>', {class: ppfx + 'badge'}).get(0);
      this.placerEl = $('<div>', {class: ppfx + 'placeholder'}).get(0);
      this.placerIntEl = $('<div>', {class: ppfx + 'placeholder-int'}).get(0);
      this.ghostEl = $('<div>', {class: ppfx + 'ghost'}).get(0);
      this.toolbarEl = $('<div>', {class: ppfx + 'toolbar'}).get(0);
      this.resizerEl = $('<div>', {class: ppfx + 'resizer'}).get(0);
      this.offsetEl = $('<div>', {class: ppfx + 'offset-v'}).get(0);
      this.fixedOffsetEl = $('<div>', {class: ppfx + 'offset-fixed-v'}).get(0);
      this.placerEl.appendChild(this.placerIntEl);
      toolsEl.appendChild(this.hlEl);
      toolsEl.appendChild(this.badgeEl);
      toolsEl.appendChild(this.placerEl);
      toolsEl.appendChild(this.ghostEl);
      toolsEl.appendChild(this.toolbarEl);
      toolsEl.appendChild(this.resizerEl);
      toolsEl.appendChild(this.offsetEl);
      toolsEl.appendChild(this.fixedOffsetEl);
      this.$el.append(toolsEl);
      var rte = this.em.get('rte');

      if(rte)
        toolsEl.appendChild(rte.render());

      this.toolsEl = toolsEl;
      this.$el.attr({class: this.className});
      return this;
    },

  });
});
<|endoftext|>


<commit_before>'use strict'

const repeat=require('lodash.repeat')

class CodeOutput {
	constructor(generateCode,i18n) {
		let code=generateCode()
		const $sectionCode={}, $sectionModeInput={}
		let $indentCheckbox, $indentNumber, $jsSemicolonsCheckbox
		const getHtmlDataUri=(html)=>'data:text/html;charset=utf-8,'+encodeURIComponent(html)
		const getFormatting=()=>{
			let indent='\t'
			if (!$indentCheckbox.prop('checked')) {
				let n=4
				if ($indentNumber[0].checkValidity()) {
					n=Number($indentNumber.val())
				}
				indent=repeat(' ',n)
			}
			return {
				refs: this.refs,
				indent,
				jsSemicolons: $jsSemicolonsCheckbox.prop('checked'),
			}
		}
		const writeControls=()=>{
			return $("
").append(
				$("<button type='button'>"+i18n('code-output.run')+"</button>").click(function(){
					/*
					// doesn't work in IE
					window.open(getHtmlDataUri(
						code.get(this.formatting).join("\n")
					),"generatedCode")
					*/
					const w=window.open("","generatedCode")
					w.document.open()
					w.document.write(
						code.get(getFormatting()).join("\n")
					)
					w.document.close()
				})
			).append(" ").append(
				$("<button type='button'>Open in CodePen</button>").click(function(){
					// http://blog.codepen.io/documentation/api/prefill/
					const sections=code.extractSections({html:'body',css:'paste',js:'paste'})
					const getSection=sectionName=>
						sections[sectionName].get(getFormatting()).join("\n")
					$("<form method='post' action='http://codepen.io/pen/define/'>")
						.append($("<input type='hidden' name='data'>").val(JSON.stringify({
							html: getSection('html'),
							css: getSection('css'),
							js: getSection('js'),
							title: code.title,
						})))
						.appendTo('body')
						.submit()
				})
			).append(" ").append(
				$("<button type='button'>Open in JSFiddle</button>").click(function(){
					// http://doc.jsfiddle.net/api/post.html
					const sections=code.extractSections({html:'body',css:'paste',js:'paste'})
					const writeSection=sectionName=>
						$("<input type='hidden'>")
							.attr('name',sectionName)
							.val(sections[sectionName].get(getFormatting()).join("\n"))
					$("<form method='post' action='http://jsfiddle.net/api/post/library/pure/'>")
						.append(writeSection('html'))
						.append(writeSection('css'))
						.append(writeSection('js'))
						.append($("<input type='hidden' name='title'>").val(code.title))
						.append("<input type='hidden' name='wrap' value='b'>")
						.appendTo('body')
						.submit()
				})
			).append(" "+i18n('code-output.warning.jsfiddle-run')+"")
		}
		const getSectionModes=()=>({
			html: $sectionModeInput['html'].val(),
			css:  $sectionModeInput['css' ].val(),
			js:   $sectionModeInput['js'  ].val(),
		})
		const extractCode=()=>{
			const sectionModes=getSectionModes()
			const sections=code.extractSections(sectionModes)
			for (let sectionName in sections) {
				if (sectionModes[sectionName]=='embed') {
					$sectionCode[sectionName].empty().append(
						"
"+i18n('code-output.embedded')+"
"
					)
				} else {
					let $code
					$sectionCode[sectionName].empty().append(
						$("
").append(
							$code=$("")
						)
					)
					$code.html(
						sections[sectionName].getHtml(getFormatting()).join("\n")
					)
					if (window.hljs) {
						hljs.highlightBlock($code[0])
					}
				}
			}
		}
		const writeFormattingControls=()=>{
			return $("")
				.append("Formatting")
				.append($("
")
					.append($("")
						.append($indentCheckbox=$("<input type='checkbox' checked>").change(extractCode))
						.append(" indent with tabs")
					)
				)
				.append($("
")
					.append($("")
						.append($indentNumber=$("<input type='number' min='0' max='32' value='4' required>").on('input change',extractCode))
						.append(" spaces per indent")
					)
				)
				.append($("
")
					.append($("")
						.append($jsSemicolonsCheckbox=$("<input type='checkbox'>").change(extractCode))
						.append(" JavaScript semicolons")
					)
				)
		}
		const writeSection=(sectionName)=>{
			const extractable=sectionName!='html'
			const $summary=$(""+i18n('code-output.section.'+sectionName)+"")
			let $saveButton
			$summary.append(" ").append(
				$sectionModeInput[sectionName]=$("<select>").append(
					(sectionName=='html'
						? ['full','body']
						: ['embed','paste','file']
					).map(mode=>
						$("<option>").val(mode).html(i18n('code-output.mode.'+mode))
					)
				).change(function(){
					if (extractable) {
						$saveButton.prop('disabled',this.value=='embed')
					}
					extractCode()
				})
			)
			$summary.append(" ").append(
				/*
				// doesn't work in IE
				$("<button type='button'>"+i18n('code-output.save')+"</button>").click(function(){
					// yes I want a button, but download attr is only available for links
					$(this).attr('href',getHtmlDataUri(
						section.get(this.formatting).join("\n")
					))
				})
				*/
				$saveButton=$("<button type='button'>"+i18n('code-output.save')+"</button>").click(function(){
					const section=code.extractSections(getSectionModes())[sectionName]
					// http://stackoverflow.com/a/24354303
					const blob=new Blob(
						[section.get(getFormatting()).join("\n")],
						{type:section.mimeType}
					)
					if (navigator.msSaveOrOpenBlob) {
						navigator.msSaveOrOpenBlob(blob,section.filename)
					} else {
						const $a=$("")
							.attr('download',section.filename)
							.attr('href',URL.createObjectURL(blob))
							.appendTo('body')
						$a.get(0).click()
						$a.remove()
					}
				})
			)
			if (extractable) {
				$saveButton.prop('disabled',$sectionModeInput[sectionName].val()=='embed')
			}
			return $("")
				.append($summary)
				.append($sectionCode[sectionName]=$("
"))
		}
		const $output=$("
").append(writeControls())
			.append(writeFormattingControls())
			.append(writeSection('html'))
			.append(writeSection('css'))
			.append(writeSection('js'))
		if (!window.hljs) {
			$output.append("
"+i18n('code-output.warning.no-hljs')+"
")
		}
		$output.append(writeControls())
		extractCode()

		const delay=200
		let timeoutId=null
		const update=()=>{
			clearTimeout(timeoutId)
			timeoutId=setTimeout(()=>{
				code=generateCode()
				extractCode()
			},delay)
		}

		// public props:
		this.$output=$output
		this.update=update
	}

	// private interface:
	get refs() {
		return {}
	}
}

module.exports=CodeOutput
<commit_msg>open source code details by default<commit_after>'use strict'

const repeat=require('lodash.repeat')

class CodeOutput {
	constructor(generateCode,i18n) {
		let code=generateCode()
		const $sectionCode={}, $sectionModeInput={}
		let $indentCheckbox, $indentNumber, $jsSemicolonsCheckbox
		const getHtmlDataUri=(html)=>'data:text/html;charset=utf-8,'+encodeURIComponent(html)
		const getFormatting=()=>{
			let indent='\t'
			if (!$indentCheckbox.prop('checked')) {
				let n=4
				if ($indentNumber[0].checkValidity()) {
					n=Number($indentNumber.val())
				}
				indent=repeat(' ',n)
			}
			return {
				refs: this.refs,
				indent,
				jsSemicolons: $jsSemicolonsCheckbox.prop('checked'),
			}
		}
		const writeControls=()=>{
			return $("
").append(
				$("<button type='button'>"+i18n('code-output.run')+"</button>").click(function(){
					/*
					// doesn't work in IE
					window.open(getHtmlDataUri(
						code.get(this.formatting).join("\n")
					),"generatedCode")
					*/
					const w=window.open("","generatedCode")
					w.document.open()
					w.document.write(
						code.get(getFormatting()).join("\n")
					)
					w.document.close()
				})
			).append(" ").append(
				$("<button type='button'>Open in CodePen</button>").click(function(){
					// http://blog.codepen.io/documentation/api/prefill/
					const sections=code.extractSections({html:'body',css:'paste',js:'paste'})
					const getSection=sectionName=>
						sections[sectionName].get(getFormatting()).join("\n")
					$("<form method='post' action='http://codepen.io/pen/define/'>")
						.append($("<input type='hidden' name='data'>").val(JSON.stringify({
							html: getSection('html'),
							css: getSection('css'),
							js: getSection('js'),
							title: code.title,
						})))
						.appendTo('body')
						.submit()
				})
			).append(" ").append(
				$("<button type='button'>Open in JSFiddle</button>").click(function(){
					// http://doc.jsfiddle.net/api/post.html
					const sections=code.extractSections({html:'body',css:'paste',js:'paste'})
					const writeSection=sectionName=>
						$("<input type='hidden'>")
							.attr('name',sectionName)
							.val(sections[sectionName].get(getFormatting()).join("\n"))
					$("<form method='post' action='http://jsfiddle.net/api/post/library/pure/'>")
						.append(writeSection('html'))
						.append(writeSection('css'))
						.append(writeSection('js'))
						.append($("<input type='hidden' name='title'>").val(code.title))
						.append("<input type='hidden' name='wrap' value='b'>")
						.appendTo('body')
						.submit()
				})
			).append(" "+i18n('code-output.warning.jsfiddle-run')+"")
		}
		const getSectionModes=()=>({
			html: $sectionModeInput['html'].val(),
			css:  $sectionModeInput['css' ].val(),
			js:   $sectionModeInput['js'  ].val(),
		})
		const extractCode=()=>{
			const sectionModes=getSectionModes()
			const sections=code.extractSections(sectionModes)
			for (let sectionName in sections) {
				if (sectionModes[sectionName]=='embed') {
					$sectionCode[sectionName].empty().append(
						"
"+i18n('code-output.embedded')+"
"
					)
				} else {
					let $code
					$sectionCode[sectionName].empty().append(
						$("
").append(
							$code=$("")
						)
					)
					$code.html(
						sections[sectionName].getHtml(getFormatting()).join("\n")
					)
					if (window.hljs) {
						hljs.highlightBlock($code[0])
					}
				}
			}
		}
		const writeFormattingControls=()=>{
			return $("")
				.append("Formatting")
				.append($("
")
					.append($("")
						.append($indentCheckbox=$("<input type='checkbox' checked>").change(extractCode))
						.append(" indent with tabs")
					)
				)
				.append($("
")
					.append($("")
						.append($indentNumber=$("<input type='number' min='0' max='32' value='4' required>").on('input change',extractCode))
						.append(" spaces per indent")
					)
				)
				.append($("
")
					.append($("")
						.append($jsSemicolonsCheckbox=$("<input type='checkbox'>").change(extractCode))
						.append(" JavaScript semicolons")
					)
				)
		}
		const writeSection=(sectionName)=>{
			const extractable=sectionName!='html'
			const $summary=$(""+i18n('code-output.section.'+sectionName)+"")
			let $saveButton
			$summary.append(" ").append(
				$sectionModeInput[sectionName]=$("<select>").append(
					(sectionName=='html'
						? ['full','body']
						: ['embed','paste','file']
					).map(mode=>
						$("<option>").val(mode).html(i18n('code-output.mode.'+mode))
					)
				).change(function(){
					if (extractable) {
						$saveButton.prop('disabled',this.value=='embed')
					}
					extractCode()
				})
			)
			$summary.append(" ").append(
				/*
				// doesn't work in IE
				$("<button type='button'>"+i18n('code-output.save')+"</button>").click(function(){
					// yes I want a button, but download attr is only available for links
					$(this).attr('href',getHtmlDataUri(
						section.get(this.formatting).join("\n")
					))
				})
				*/
				$saveButton=$("<button type='button'>"+i18n('code-output.save')+"</button>").click(function(){
					const section=code.extractSections(getSectionModes())[sectionName]
					// http://stackoverflow.com/a/24354303
					const blob=new Blob(
						[section.get(getFormatting()).join("\n")],
						{type:section.mimeType}
					)
					if (navigator.msSaveOrOpenBlob) {
						navigator.msSaveOrOpenBlob(blob,section.filename)
					} else {
						const $a=$("")
							.attr('download',section.filename)
							.attr('href',URL.createObjectURL(blob))
							.appendTo('body')
						$a.get(0).click()
						$a.remove()
					}
				})
			)
			if (extractable) {
				$saveButton.prop('disabled',$sectionModeInput[sectionName].val()=='embed')
			}
			return $("")
				.append($summary)
				.append($sectionCode[sectionName]=$("
"))
		}
		const $output=$("
").append(writeControls())
			.append(writeFormattingControls())
			.append(writeSection('html'))
			.append(writeSection('css'))
			.append(writeSection('js'))
		if (!window.hljs) {
			$output.append("
"+i18n('code-output.warning.no-hljs')+"
")
		}
		$output.append(writeControls())
		extractCode()

		const delay=200
		let timeoutId=null
		const update=()=>{
			clearTimeout(timeoutId)
			timeoutId=setTimeout(()=>{
				code=generateCode()
				extractCode()
			},delay)
		}

		// public props:
		this.$output=$output
		this.update=update
	}

	// private interface:
	get refs() {
		return {}
	}
}

module.exports=CodeOutput
<|endoftext|>


<commit_before>/**
 * drop-down menus
 * TODO transform in jQuery Plugin style
 **/
$(document).delegate('.js_dropdown .selected', 'click', function(e) {
	$(".js_dropdown-list").hide();
	$(this).parents(".js_dropdown").find(".js_dropdown-list").toggle();
	e.stopPropagation();
	return false;
});
$(".js_dropdown .js_dropdown-link").bind('click', function(e) {
	reset(e.target);
	$(this).parents('.js_dropdown').find('.js_dropdown-list').toggle();
	$(this).parents('.js_dropdown').find('a').toggleClass('dropdown-selected');
	if ($(this).attr('href') == '#') return false;
});
$(document).bind('click', function(e) {
	if (!$(e.target).hasClass('js_dropdown-ignore')) {
		reset(e.target)
	}
});

function reset(clicked) {
	$(".js_dropdown a.js_dropdown-link").each(function(){
		if (clicked != this) {
			$(this).parents(".js_dropdown").find("div.js_dropdown-list").hide();
			$(this).parents(".js_dropdown").find(".dropdown-selected").removeClass('dropdown-selected');
		}
	});
//	return false;
}

// Check all / Uncheck all
$('#js_uncheckall').click(function() {
	$('#js_location-type-filter input').prop('checked', false);
	return false;
});
$('#js_checkall').click(function() {
	$('#js_location-type-filter input').prop('checked', true);
	return false;
});
<commit_msg>fixed bug where filter would not close if clicking on it<commit_after>/**
 * drop-down menus
 * TODO transform in jQuery Plugin style
 **/

$(document).delegate(".js_dropdown a.js_dropdown-link").bind('click', function(e) {
	if ($(e.target).hasClass('dropdown-selected')) {
		reset(null);
	}
	else {
		reset(e.target);
		$(e.target).addClass('dropdown-selected');
		$(e.target).parents('.js_dropdown').find('.js_dropdown-list').show();
		if ($(e.target).attr('href') == '#') return false;
	}
});
$(document).bind('click', function(e) {
	if (!$(e.target).hasClass('js_dropdown-ignore')) {
		//reset(e.target)
	}
});

function reset(clicked) {
	$(".js_dropdown .js_dropdown-link").each(function(){
		if (clicked != this) {
			$(this).parents(".js_dropdown").find(".js_dropdown-list").hide();
			$(this).parents(".js_dropdown").find(".dropdown-selected").removeClass('dropdown-selected');
		}
	});
//	return false;
}

// Check all / Uncheck all
$('#js_uncheckall').click(function() {
	$('#js_location-type-filter input').prop('checked', false);
	return false;
});
$('#js_checkall').click(function() {
	$('#js_location-type-filter input').prop('checked', true);
	return false;
});
<|endoftext|>


<commit_before>/**
 * Created by Ben on 11/8/14.
 */

//set the default vars
var EncEnabled = false;
var Cipher = "0";

//get their chrome values
chrome.storage.sync.get('EncEnabled', function (result) {
    EncEnabled = result.EncEnabled;
});

chrome.storage.sync.get('CurrentCy', function(result) {
    Cipher = result.CurrentCy;
});

//get the start item
var currentItem = $(".userContent")[0];

//when the page loads
$(document).ready(function () {

    //run main to start
    main();
});

//when someone clicks something
$(document).on("click", function() {

    //wait two seconds
    window.setTimeout(function () {

        //if the items has changed
        if ($(".userContent")[0] != currentItem) {

            //debugging log
            console.log("change url");

            //change the start text
            currentItem = $(".userContent")[0]

            //run main again
            main();
        }
    }, 2000);
});

//main function
function main() {

    //get the amount of entrees
    var entries = $(".userContent").length;

    //loop through the items
    for (var i = 0; i < entries; i++) {

        //slice up the items
        var dataDom = $(".userContent").slice(i, i + 1);
        var dataText = dataDom.text();

        //check the encryption flag
        var encyt_flag = dataText.slice(0, 5);

        //debugging log
        console.log("flag:", encyt_flag);

        //if the flag is valid, change the message
        if (encyt_flag == "<enc>") {

            //temp message change
            dataDom.html("new secret message");
        }
    }
};

function cipher(plainText){
    var cValue = createCipher();

    //Cipher the text
    var len = plainText.length;

    var out = "";
    for (var i = 0; i < len; i++) {
        if ((plainText.charCodeAt(i) + cValue) < 127) {
            out = out.concat(String.fromCharCode(plainText.charCodeAt(i) + cValue));
        }
        else {
            out = out.concat(String.fromCharCode(plainText.charCodeAt(i) + cValue - 127));
        }
    }
    return out;
}

function decipher(encryptedText){

    var cValue = createCipher();

    //Decipher the text
    var len = encryptedText.length;

    var out = "";
    for (var i = 0; i < len; i++) {
        if ((encryptedText.charCodeAt(i) - cValue) > 31) {
            out = out.concat(String.fromCharCode(encryptedText.charCodeAt(i) - cValue));
        }
        else {
            out = out.concat(String.fromCharCode(encryptedText.charCodeAt(i) - cValue + 127));
        }
    }
    return out;
}<commit_msg>Merging<commit_after>/**
 * Created by Ben on 11/8/14.
 */

//set the default vars
var EncEnabled = false;
var Cipher = "0";

//get their chrome values
chrome.storage.sync.get('EncEnabled', function (result) {
    EncEnabled = result.EncEnabled;
});

chrome.storage.sync.get('CurrentCy', function(result) {
    Cipher = result.CurrentCy;
});

//get the start item
var currentItem = $(".userContent")[0];

//when the page loads
$(document).ready(function () {

    //run main to start
    main();
});

//when someone clicks something
$(document).on("click", function() {

    //wait two seconds
    window.setTimeout(function () {

        //if the items has changed
        if ($(".userContent")[0] != currentItem) {

            //debugging log
            console.log("change url");

            //change the start text
            currentItem = $(".userContent")[0]

            //run main again
            main();
        }
    }, 2000);
});

//main function
function main() {

    //get the amount of entrees
    var entries = $(".userContent").length;

    //loop through the items
    for (var i = 0; i < entries; i++) {

        //slice up the items
        var dataDom = $(".userContent").slice(i, i + 1);
        var dataText = dataDom.text();

        //check the encryption flag
        var encyt_flag = dataText.slice(0, 5);
        var message = dataText.slice(6);

        //debugging log
        console.log("flag:", encyt_flag);

        //if the flag is valid, change the message
        if (encyt_flag == "<enc>") {

            var out = decipher(message, Cipher);

            //temp message change
            dataDom.html(out);
        }
    }
};

function cipher(plainText, code){
    var cValue = createCipher(code);

    //Cipher the text
    var len = plainText.length;

    var out = "";
    for (var i = 0; i < len; i++) {
        if ((plainText.charCodeAt(i) + cValue) < 127) {
            out = out.concat(String.fromCharCode(plainText.charCodeAt(i) + cValue));
        }
        else {
            out = out.concat(String.fromCharCode(plainText.charCodeAt(i) + cValue - 127));
        }
    }
    return out;
}

function decipher(encryptedText, code){

    var cValue = createCipher(code);

    //Decipher the text
    var len = encryptedText.length;

    var out = "";
    for (var i = 0; i < len; i++) {
        if ((encryptedText.charCodeAt(i) - cValue) > 31) {
            out = out.concat(String.fromCharCode(encryptedText.charCodeAt(i) - cValue));
        }
        else {
            out = out.concat(String.fromCharCode(encryptedText.charCodeAt(i) - cValue + 127));
        }
    }
    return out;
}

function createCipher(code) {
    var j = code.length;
    var cipherVal = 0;

    while(j--){
        cipherVal += code.charCodeAt(j);
    }
    return cipherVal % 94;
}<|endoftext|>


<commit_before>'use strict';
/* jshint node: true */
/* jshint esnext: true */
/* global jasmine, describe, it, expect, beforeEach, spyOn */

const crypto = require('crypto');
const config = require('config');

describe('editUrlHelper', () => {

  const editUrlHelper = require('../../domain/editUrlHelper.js');

  describe('generateSecureID', () => {

    it('should generate a cryptographically secure id', () => {
      spyOn(crypto, 'randomBytes').and.returnValue("testID");

      const secureID = editUrlHelper.generateSecureID();
      expect(crypto.randomBytes.calls.count()).toEqual(1);
      expect(crypto.randomBytes).toHaveBeenCalledWith(32);

      expect(secureID).toBe("testID");

    });
  });

  describe('generateUrl', () => {
    it('should produce absolute URI', () => {
      const secureID = editUrlHelper.generateUrl('secureId');

      expect(secureID).toBe(`${config.get('pace-url')}/editparticipant/secureId`);
    });
  });

  describe('generateUrlForAdmin', () => {
    it('should produce absolute URI', () => {
      const secureID = editUrlHelper.generateUrlForAdmin('secureId');

      expect(secureID).toBe(`${config.get('pace-url')}/admin/editparticipant/secureId`);
    });
  });

});
<commit_msg>Absolute edit URI.<commit_after>'use strict';
/* jshint node: true */
/* jshint esnext: true */
/* global jasmine, describe, it, expect, beforeEach, spyOn */

const crypto = require('crypto');
const config = require('config');

describe('editUrlHelper', () => {

  const editUrlHelper = require('../../domain/editUrlHelper.js');

  describe('generateSecureID', () => {

    it('should generate a cryptographically secure id', () => {
      spyOn(crypto, 'randomBytes').and.returnValue("testID");

      const secureID = editUrlHelper.generateSecureID();
      expect(crypto.randomBytes.calls.count()).toEqual(1);
      expect(crypto.randomBytes).toHaveBeenCalledWith(32);

      expect(secureID).toBe("testID");

    });
  });

  describe('generateUrl', () => {
    it('should produce absolute URI', () => {
      const secureID = editUrlHelper.generateUrl('secureId');

      expect(secureID).toBe(`${config.get('pace-url')}/editparticipant/?edit=secureId`);
    });
  });

  describe('generateUrl', () => {
    it('should produce absolute URI', () => {
      const secureID = editUrlHelper.generateUrl('secureId');

      expect(secureID).toBe(`${config.get('pace-url')}/editparticipant/secureId`);
    });
  });

  describe('generateUrlForAdmin', () => {
    it('should produce absolute URI', () => {
      const secureID = editUrlHelper.generateUrlForAdmin('secureId');

      expect(secureID).toBe(`${config.get('pace-url')}/admin/editparticipant/secureId`);
    });
  });

});
<|endoftext|>