<commit_before>Travis.Build = Travis.Record.extend(Travis.Helpers.Urls, Travis.Helpers.Common, {
  repositoryId:   SC.Record.attr(Number, { key: 'repository_id' }),
  parentId:       SC.Record.attr(Number, { key: 'parent_id' }),
  config:         SC.Record.attr(Object),
  state:          SC.Record.attr(String),
  number:         SC.Record.attr(String),
  commit:         SC.Record.attr(String),
  branch:         SC.Record.attr(String),
  message:        SC.Record.attr(String),
  result:         SC.Record.attr(Number, { key: 'status' }), // status is reserved by SC
  startedAt:      SC.Record.attr(String, { key: 'started_at' }), // use DateTime?
  finishedAt:     SC.Record.attr(String, { key: 'finished_at' }),
  committedAt:    SC.Record.attr(String, { key: 'committed_at' }),
  committerName:  SC.Record.attr(String, { key: 'committer_name' }),
  committerEmail: SC.Record.attr(String, { key: 'committer_email' }),
  authorName:     SC.Record.attr(String, { key: 'author_name' }),
  authorEmail:    SC.Record.attr(String, { key: 'author_email' }),
  compareUrl:     SC.Record.attr(String, { key: 'compare_url' }),
  log:            SC.Record.attr(String),

  matrix: SC.Record.toMany('Travis.Build', { nested: true }), // TODO should be Travis.Test!

  parent: function() {
    return this.get('parentId') ? Travis.Build.find(this.get('parentId')) : null;
  }.property('parentId', 'status'),

  repository: function() {
    return Travis.Repository.find(this.get('repositoryId'));
  }.property('repositoryId'),

  isMatrix: function() {
    return this.getPath('matrix.length') > 1;
  }.property('matrix.status'),

  color: function() {
    return this.colorForStatus(this.get('result'));
  }.property('status', 'result'),

  duration: function() {
    return this.durationFrom(this.get('startedAt'), this.get('finishedAt'));
  }.property('startedAt', 'finishedAt'),

  configDimensions: function() {
    return $.map($.keys($.only(this.get('config'), 'rvm', 'gemfile', 'env')), function(value) { return $.camelize(value) });
  }.property('config'),

  configValues: function() {
    return $.values($.only(this.get('config'), 'rvm', 'gemfile', 'env'));
  }.property('config'),

  // TODO the following display logic all seems to belong to a controller or helper module

  formattedCommit: function() {
    return (this.get('commit') || '').substr(0, 7) + (this.get('branch') ? ' (%@)'.fmt(this.get('branch')) : '');
  }.property('commit', 'branch'),

  formattedDuration: function() {
    return this.readableTime(this.get('duration'));
  }.property('status', 'duration'),

  formattedFinishedAt: function() {
    return this.timeAgoInWords(this.get('finishedAt')) || '-';
  }.property('status', 'finishedAt'),

  formattedConfig: function() {
    if(this.get('isMatrix')) return;
    var config = $.only(this.get('config'), 'rvm', 'gemfile', 'env');
    var values = $.map(config, function(value, key) { return '%@: %@'.fmt($.camelize(key), value.join ? value.join(', ') : value); });
    return values.length == 0 ? '-' : values.join(', ');
  }.property('config'),

  formattedLog: function() {
    return this.get('log'); // fold log etc. here
  }.property('log'),

  // updateRepository: function() {
  //   var repository = this.get('repository');
  //   if(repository.get('lastBuildStartedAt') < this.get('startedAt') || repository.get('lastBuildFinishedAt') < this.get('finishedAt')) {
  //     repository.update({
  //       lastBuildNumber:     this.get('number'),
  //       lastBuildStatus:     this.get('result'),
  //       lastBuildStartedAt:  this.get('startedAt'),
  //       lastBuildFinishedAt: this.get('finishedAt'),
  //     });
  //   }
  // },

  // updateObserver: function() {
  //   this.updateRepository();
  // }.observes('startedAt', 'finishedAt', 'result'),
});

Travis.Build.reopenClass({
  resource: 'builds',
  byRepositoryId: function(id, parameters) {
    return this.all({ url: '/repositories/%@/builds.json?parent_id='.fmt(id), parentId: null, orderBy: 'number DESC' })
  },
});
<commit_msg>Displaying build log for regular and matrix builds.<commit_after>Travis.Build = Travis.Record.extend(Travis.Helpers.Urls, Travis.Helpers.Common, {
  repositoryId:   SC.Record.attr(Number, { key: 'repository_id' }),
  parentId:       SC.Record.attr(Number, { key: 'parent_id' }),
  config:         SC.Record.attr(Object),
  state:          SC.Record.attr(String),
  number:         SC.Record.attr(String),
  commit:         SC.Record.attr(String),
  branch:         SC.Record.attr(String),
  message:        SC.Record.attr(String),
  result:         SC.Record.attr(Number, { key: 'status' }), // status is reserved by SC
  startedAt:      SC.Record.attr(String, { key: 'started_at' }), // use DateTime?
  finishedAt:     SC.Record.attr(String, { key: 'finished_at' }),
  committedAt:    SC.Record.attr(String, { key: 'committed_at' }),
  committerName:  SC.Record.attr(String, { key: 'committer_name' }),
  committerEmail: SC.Record.attr(String, { key: 'committer_email' }),
  authorName:     SC.Record.attr(String, { key: 'author_name' }),
  authorEmail:    SC.Record.attr(String, { key: 'author_email' }),
  compareUrl:     SC.Record.attr(String, { key: 'compare_url' }),
  log:            SC.Record.attr(String),

  matrix: SC.Record.toMany('Travis.Build', { nested: true }), // TODO should be Travis.Test!

  parent: function() {
    return this.get('parentId') ? Travis.Build.find(this.get('parentId')) : null;
  }.property('parentId', 'status'),

  repository: function() {
    return Travis.Repository.find(this.get('repositoryId'));
  }.property('repositoryId'),

  isMatrix: function() {
    return this.getPath('matrix.length') > 1;
  }.property('matrix.status'),

  color: function() {
    return this.colorForStatus(this.get('result'));
  }.property('status', 'result'),

  duration: function() {
    return this.durationFrom(this.get('startedAt'), this.get('finishedAt'));
  }.property('startedAt', 'finishedAt'),

  configDimensions: function() {
    return $.map($.keys($.only(this.get('config'), 'rvm', 'gemfile', 'env')), function(value) { return $.camelize(value) });
  }.property('config'),

  configValues: function() {
    return $.values($.only(this.get('config'), 'rvm', 'gemfile', 'env'));
  }.property('config'),

  // TODO the following display logic all seems to belong to a controller or helper module

  formattedCommit: function() {
    return (this.get('commit') || '').substr(0, 7) + (this.get('branch') ? ' (%@)'.fmt(this.get('branch')) : '');
  }.property('commit', 'branch'),

  formattedDuration: function() {
    return this.readableTime(this.get('duration'));
  }.property('status', 'duration'),

  formattedFinishedAt: function() {
    return this.timeAgoInWords(this.get('finishedAt')) || '-';
  }.property('status', 'finishedAt'),

  formattedConfig: function() {
    if(this.get('isMatrix')) return;
    var config = $.only(this.get('config'), 'rvm', 'gemfile', 'env');
    var values = $.map(config, function(value, key) { return '%@: %@'.fmt($.camelize(key), value.join ? value.join(', ') : value); });
    return values.length == 0 ? '-' : values.join(', ');
  }.property('config'),
  // TODO: Add log folding and line numbers here
  formattedLog: function() {
    if (this.get('matrix').objectAt(0) !== undefined)
      return this.get('matrix').objectAt(0).get('log');
    else
      return this.get('log')
  }.property('matrix', 'log'),

  build: function() {
    return this.get('matrix').objectAt(0);
  }.property('build'),

  // updateRepository: function() {
  //   var repository = this.get('repository');
  //   if(repository.get('lastBuildStartedAt') < this.get('startedAt') || repository.get('lastBuildFinishedAt') < this.get('finishedAt')) {
  //     repository.update({
  //       lastBuildNumber:     this.get('number'),
  //       lastBuildStatus:     this.get('result'),
  //       lastBuildStartedAt:  this.get('startedAt'),
  //       lastBuildFinishedAt: this.get('finishedAt'),
  //     });
  //   }
  // },

  // updateObserver: function() {
  //   this.updateRepository();
  // }.observes('startedAt', 'finishedAt', 'result'),
});

Travis.Build.reopenClass({
  resource: 'builds',
  byRepositoryId: function(id, parameters) {
    return this.all({ url: '/repositories/%@/builds.json?parent_id='.fmt(id), parentId: null, orderBy: 'number DESC' })
  },
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { getDateLocalizer } from 'redux-autoform-utils';
import FormGroup from '../common/FormGroup';
import { DatePicker, TimePicker, TextField } from 'material-ui';

class DateTimePicker extends Component {

    getFormat = (format, type, formats) => {
        if (!type) {
            throw Error('\'type\' should be truthy');
        }

        if (!formats) {
            throw Error('\'localizer\' should be truthy');
        }

        if (format) {
            return format;
        }

        switch(type) {
            case 'datetime':
                return formats.default;
            case 'date':
                return formats.date;
            case 'time':
                return formats.time;
            default:
                throw Error(`Invalid type. Type: ${type}`);
        }
    };

    onChange = (date, dateAsString) => {
        let { onChange } = this.props;
        onChange(dateAsString);
    };

    render() {
        let { value, name, displayName, help, error, active, touched, onBlur, format, type, fieldLayout, placeholder } = this.props;
	    let errors = (touched || active)? error : null;
	    let localizer = getDateLocalizer();

        if (typeof value == 'string') {
            if(value == '') {
                value = undefined;
            } else {
                format = this.getFormat(format, type, localizer.formats);
                value = localizer.parse(value, format);
            }
        }

        let reactWidgetsProps = { value, displayName, onChange: this.onChange, onBlur, format };
        let formGroupProps = { error, touched, displayName, name, help, fieldLayout };

	    switch (type) {
		    case 'date':
			    return (
				    <FormGroup>
					    <TextField
						    name={name}
						    value={value}
						    errorText={errors}
						    hintText={placeholder}
						    floatingLabelText={displayName}
						    onChange={this.onChange}
						    onBlur={onBlur}
						    fullWidth
						    type={type}
					    />
				    </FormGroup>
			    );

		    case 'time':
			    return (
				    <FormGroup>
					    <TextField
						    name={name}
						    value={value}
						    errorText={errors}
						    hintText={placeholder}
						    floatingLabelText={displayName}
						    onChange={this.onChange}
						    onBlur={onBlur}
						    fullWidth
						    type={type}
					    />
				    </FormGroup>
			    );

		    default:
			    return false;
	    }
    }
}

DateTimePicker.propTypes = {
    value: PropTypes.any,
    onChange: PropTypes.func.isRequired,
    displayName: PropTypes.string,
    name: PropTypes.string.isRequired,
    error: PropTypes.string,
    format: PropTypes.string
};

export default DateTimePicker;<commit_msg>#5 DateTimePicker now is working<commit_after>import React, { Component, PropTypes } from 'react';
import { getDateLocalizer } from 'redux-autoform-utils';
import FormGroup from '../common/FormGroup';
import { DatePicker, TimePicker } from 'material-ui';

class DateTimePicker extends Component {

    getFormat = (format, type, formats) => {
        if (!type) {
            throw Error('\'type\' should be truthy');
        }

        if (!formats) {
            throw Error('\'localizer\' should be truthy');
        }

        if (format) {
            return format;
        }

        switch(type) {
            case 'datetime':
                return formats.default;
            case 'date':
                return formats.date;
            case 'time':
                return formats.time;
            default:
                throw Error(`Invalid type. Type: ${type}`);
        }
    };

    onChange = (event, date) => {
        let { onChange } = this.props;
        onChange(date);
    };

    render() {
        let { value, name, displayName, help, error, active, touched, onBlur, format, type, fieldLayout, placeholder } = this.props;
	    let errors = (touched || active)? error : null;
	    let localizer = getDateLocalizer();

        if (typeof value == 'string') {
            if(value == '') {
                value = undefined;
            } else {
                format = this.getFormat(format, type, localizer.formats);
                value = localizer.parse(value, format);
            }
        }
        //
        // let reactWidgetsProps = { value, displayName, onChange: this.onChange, onBlur, format };
        // let formGroupProps = { error, touched, displayName, name, help, fieldLayout };

	    switch (type) {
		    case 'date':
			    return (
				    <FormGroup>
					    <DatePicker
						    name={name}
						    value={value}
						    mode="landscape"
						    container="inline"
						    errorText={errors}
						    hintText={placeholder}
						    floatingLabelText={displayName}
						    onChange={this.onChange}
						    onBlur={onBlur}
						    fullWidth
						    type={type}
					    />
				    </FormGroup>
			    );

		    case 'time':
			    return (
				    <FormGroup>
					    <TimePicker
						    format="24hr"
						    name={name}
						    value={value}
						    errorText={errors}
						    hintText={placeholder}
						    floatingLabelText={displayName}
						    onChange={this.onChange}
						    onBlur={onBlur}
						    fullWidth
						    type={type}
					    />
				    </FormGroup>
			    );

		    default:
			    return false;
	    }
    }
}

DateTimePicker.propTypes = {
    value: PropTypes.any,
    onChange: PropTypes.func.isRequired,
    displayName: PropTypes.string,
    name: PropTypes.string.isRequired,
    error: PropTypes.string,
    format: PropTypes.string
};

export default DateTimePicker;<|endoftext|>


<commit_before>// Load in modules
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var async = require('async');
var concat = require('concat-stream');
var getPixels = require('get-pixels');
var Vinyl = require('vinyl');
var spritesmith = require('../src/smith.js');

// Set up paths
var spriteDir = path.join(__dirname, 'test_sprites');
var expectedDir = __dirname + '/expected_files';

// DEV: These were unsorted for testing `sort: false` but these work for all tests as is =D
var multipleSprites = [
  path.join(spriteDir, 'sprite1.png'),
  path.join(spriteDir, 'sprite3.png'),
  path.join(spriteDir, 'sprite2.jpg')
];

// Define common utilities
var spritesmithUtils = {
  run: function (params) {
    before(function runFn (done) {
      // Attempt to spritesmith out the sprites
      var that = this;
      var spriteData = spritesmith(params);
      async.parallel([
        function handleInfoStream (cb) {
          var errEncountered = false;
          spriteData.info.on('error', function saveInfoError (err) {
            errEncountered = true;
            that.infoErr = err;
            cb();
          });
          spriteData.info.pipe(concat({encoding: 'object'}, function saveInfo (infoArr) {
            that.infoArr = infoArr;
            if (!errEncountered) {
              cb();
            }
          }));
        },
        function handleImgStream (cb) {
          var errEncountered = false;
          spriteData.img.on('error', function saveImgError (err) {
            errEncountered = true;
            that.imgErr = err;
            cb();
          });
          spriteData.img.pipe(concat({encoding: 'buffer'}, function saveImg (buff) {
            that.img = buff;
            if (!errEncountered) {
              cb();
            }
          }));
        }
      ], done);
    });
    after(function cleanupResult () {
      delete this.infoErr;
      delete this.infoArr;
      delete this.imgErr;
      delete this.img;
    });
  },

  assertNoError: function () {
    return function assertNoErrorFn () {
      assert.strictEqual(this.imgErr, undefined);
      assert.strictEqual(this.infoErr, undefined);
    };
  },

  assertCoordinates: function (filename) {
    return function assertCoordinatesFn () {
      // Load in the coordinates
      assert.strictEqual(this.infoArr.length, 1);
      var result = this.infoArr[0];

      // DEV: Write out to actual_files
      if (process.env.TEST_DEBUG) {
        try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
        fs.writeFileSync(__dirname + '/actual_files/' + filename, JSON.stringify(result.coordinates, null, 4));
      }

      // Normalize the actual coordinates
      var expectedCoords = require(expectedDir + '/' + filename);
      var actualCoords = result.coordinates;
      var normCoords = {};
      assert(actualCoords, 'Result does not have a coordinates property');

      Object.getOwnPropertyNames(actualCoords).forEach(function (filepath) {
        var file = path.relative(spriteDir, filepath);
        normCoords[file] = actualCoords[filepath];
      });

      // Assert that the returned coordinates deep equal those in the coordinates.json
      assert.deepEqual(expectedCoords, normCoords, 'Actual coordinates do not match expected coordinates');
    };
  },

  assertProps: function (filename) {
    return function assertPropsFn () {
      // Load in the properties
      assert.strictEqual(this.infoArr.length, 1);
      var result = this.infoArr[0];

      // DEV: Write out to actual_files
      if (process.env.TEST_DEBUG) {
        try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
        fs.writeFileSync(__dirname + '/actual_files/' + filename, JSON.stringify(result.properties, null, 4));
      }

      // Assert that the returned properties equals the expected properties
      var actualProps = result.properties;
      var expectedProps = require(expectedDir + '/' + filename);
      assert.deepEqual(expectedProps, actualProps, 'Actual properties do not match expected properties');
    };
  },

  assertSpritesheet: function (filename) {
    return function assertSpritesheetFn (done) {
      // Load our variables
      var actualImageBuff = this.img;
      var expectedFilepath = path.join(expectedDir, filename);

      // DEV: Write out to actual_files
      if (process.env.TEST_DEBUG) {
        try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
        fs.writeFileSync(__dirname + '/actual_files/' + filename, actualImageBuff);
      }

      // Assert the actual image is the same expected
      // DEV: We are using pngjs for decoding/encoding in the library but this is testing one more cycle
      getPixels(actualImageBuff, 'image/png', function handleActualPixels (err, actualImage) {
        if (err) { return done(err); }
        getPixels(expectedFilepath, function handleExpectedPixels (err, expectedImage) {
          if (err) { return done(err); }
          assert.deepEqual(actualImage, expectedImage, 'Actual image does not match expected image');
          done();
        });
      });
    };
  }
};

// Start our tests
describe('An array of sprites', function () {
  describe('when processed via spritesmith', function () {
    spritesmithUtils.run({
      src: multipleSprites
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a binary-tree spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('binaryTree.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('binaryTree.properties.json'));
  });

  describe('when converted from left to right', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      algorithm: 'left-right'
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a left-right spritesheet', spritesmithUtils.assertSpritesheet('leftRight.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('leftRight.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('leftRight.properties.json'));
  });

  describe('when provided with a padding parameter', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      algorithm: 'binary-tree',
      padding: 2
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a padded spritesheet', spritesmithUtils.assertSpritesheet('padding.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('padding.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('padding.properties.json'));
  });

  describe('when told not to sort', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      algorithm: 'top-down',
      algorithmOpts: {sort: false}
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders an unsorted spritesheet', spritesmithUtils.assertSpritesheet('unsorted.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('unsorted.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('unsorted.properties.json'));
  });
});

describe('An array of vinyl object sprites', function () {
  describe('when processed via spritesmith', function () {
    spritesmithUtils.run({
      src: multipleSprites.map(function createVinylObject (filepath) {
        return new Vinyl({
          path: filepath,
          contents: fs.readFileSync(filepath)
        });
      })
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a binary-tree spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('binaryTree.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('binaryTree.properties.json'));
  });
});

describe('An empty array', function () {
  var emptySprites = [];

  describe('when processed via spritesmith', function () {
    spritesmithUtils.run({
      src: emptySprites
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders an empty spritesheet', function () {
      assert.deepEqual(this.img, new Buffer(0));
    });
    it('returns an empty coordinate mapping', function () {
      assert.strictEqual(this.infoArr.length, 1);
      assert.deepEqual(this.infoArr[0].coordinates, {});
    });
    it('has the proper properties', spritesmithUtils.assertProps('empty.properties.json'));
  });
});

describe('`spritesmith` using a custom engine via string', function () {
  describe('processing a set of images', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      engine: 'phantomjssmith'
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.phantomjs.png'));
  });
});

describe('`spritesmith` using a custom engine via an object', function () {
  describe('processing a set of images', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      engine: require('phantomjssmith')
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.phantomjs.png'));
  });
});

// Edge cases
// Test for https://github.com/twolfson/gulp.spritesmith/issues/22
var canvassmith;
try {
  canvassmith = require('canvassmith');
} catch (err) {}
var describeIfCanvassmithExists = canvassmith ? describe : describe.skip;
describeIfCanvassmithExists('`spritesmith` using `canvassmith`', function () {
  describe('processing a bad image', function () {
    spritesmithUtils.run({
      src: [path.join(spriteDir, 'malformed.png')],
      engine: 'canvassmith'
    });

    it('calls back with an error', function () {
      assert.notEqual(this.imgErr, undefined);
      assert.notEqual(this.infoErr, undefined);
    });
  });
});
<commit_msg>Fixed up failing edge case<commit_after>// Load in modules
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var async = require('async');
var concat = require('concat-stream');
var getPixels = require('get-pixels');
var Vinyl = require('vinyl');
var spritesmith = require('../src/smith.js');

// Set up paths
var spriteDir = path.join(__dirname, 'test_sprites');
var expectedDir = __dirname + '/expected_files';

// DEV: These were unsorted for testing `sort: false` but these work for all tests as is =D
var multipleSprites = [
  path.join(spriteDir, 'sprite1.png'),
  path.join(spriteDir, 'sprite3.png'),
  path.join(spriteDir, 'sprite2.jpg')
];

// Define common utilities
var spritesmithUtils = {
  run: function (params) {
    before(function runFn (done) {
      // Attempt to spritesmith out the sprites
      var that = this;
      var spriteData = spritesmith(params);
      async.parallel([
        function handleInfoStream (cb) {
          var errEncountered = false;
          spriteData.info.on('error', function saveInfoError (err) {
            errEncountered = true;
            that.infoErr = err;
            cb();
          });
          spriteData.info.pipe(concat({encoding: 'object'}, function saveInfo (infoArr) {
            that.infoArr = infoArr;
            if (!errEncountered) {
              cb();
            }
          }));
        },
        function handleImgStream (cb) {
          var errEncountered = false;
          spriteData.img.on('error', function saveImgError (err) {
            errEncountered = true;
            that.imgErr = err;
            cb();
          });
          spriteData.img.pipe(concat({encoding: 'buffer'}, function saveImg (buff) {
            that.img = buff;
            if (!errEncountered) {
              cb();
            }
          }));
        }
      ], done);
    });
    after(function cleanupResult () {
      delete this.infoErr;
      delete this.infoArr;
      delete this.imgErr;
      delete this.img;
    });
  },

  assertNoError: function () {
    return function assertNoErrorFn () {
      assert.strictEqual(this.imgErr, undefined);
      assert.strictEqual(this.infoErr, undefined);
    };
  },

  assertCoordinates: function (filename) {
    return function assertCoordinatesFn () {
      // Load in the coordinates
      assert.strictEqual(this.infoArr.length, 1);
      var result = this.infoArr[0];

      // DEV: Write out to actual_files
      if (process.env.TEST_DEBUG) {
        try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
        fs.writeFileSync(__dirname + '/actual_files/' + filename, JSON.stringify(result.coordinates, null, 4));
      }

      // Normalize the actual coordinates
      var expectedCoords = require(expectedDir + '/' + filename);
      var actualCoords = result.coordinates;
      var normCoords = {};
      assert(actualCoords, 'Result does not have a coordinates property');

      Object.getOwnPropertyNames(actualCoords).forEach(function (filepath) {
        var file = path.relative(spriteDir, filepath);
        normCoords[file] = actualCoords[filepath];
      });

      // Assert that the returned coordinates deep equal those in the coordinates.json
      assert.deepEqual(expectedCoords, normCoords, 'Actual coordinates do not match expected coordinates');
    };
  },

  assertProps: function (filename) {
    return function assertPropsFn () {
      // Load in the properties
      assert.strictEqual(this.infoArr.length, 1);
      var result = this.infoArr[0];

      // DEV: Write out to actual_files
      if (process.env.TEST_DEBUG) {
        try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
        fs.writeFileSync(__dirname + '/actual_files/' + filename, JSON.stringify(result.properties, null, 4));
      }

      // Assert that the returned properties equals the expected properties
      var actualProps = result.properties;
      var expectedProps = require(expectedDir + '/' + filename);
      assert.deepEqual(expectedProps, actualProps, 'Actual properties do not match expected properties');
    };
  },

  assertSpritesheet: function (filename) {
    return function assertSpritesheetFn (done) {
      // Load our variables
      var actualImageBuff = this.img;
      var expectedFilepath = path.join(expectedDir, filename);

      // DEV: Write out to actual_files
      if (process.env.TEST_DEBUG) {
        try { fs.mkdirSync(__dirname + '/actual_files'); } catch (e) {}
        fs.writeFileSync(__dirname + '/actual_files/' + filename, actualImageBuff);
      }

      // Assert the actual image is the same expected
      // DEV: We are using pngjs for decoding/encoding in the library but this is testing one more cycle
      getPixels(actualImageBuff, 'image/png', function handleActualPixels (err, actualImage) {
        if (err) { return done(err); }
        getPixels(expectedFilepath, function handleExpectedPixels (err, expectedImage) {
          if (err) { return done(err); }
          assert.deepEqual(actualImage, expectedImage, 'Actual image does not match expected image');
          done();
        });
      });
    };
  }
};

// Start our tests
describe('An array of sprites', function () {
  describe('when processed via spritesmith', function () {
    spritesmithUtils.run({
      src: multipleSprites
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a binary-tree spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('binaryTree.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('binaryTree.properties.json'));
  });

  describe('when converted from left to right', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      algorithm: 'left-right'
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a left-right spritesheet', spritesmithUtils.assertSpritesheet('leftRight.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('leftRight.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('leftRight.properties.json'));
  });

  describe('when provided with a padding parameter', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      algorithm: 'binary-tree',
      padding: 2
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a padded spritesheet', spritesmithUtils.assertSpritesheet('padding.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('padding.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('padding.properties.json'));
  });

  describe('when told not to sort', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      algorithm: 'top-down',
      algorithmOpts: {sort: false}
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders an unsorted spritesheet', spritesmithUtils.assertSpritesheet('unsorted.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('unsorted.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('unsorted.properties.json'));
  });
});

describe('An array of vinyl object sprites', function () {
  describe('when processed via spritesmith', function () {
    spritesmithUtils.run({
      src: multipleSprites.map(function createVinylObject (filepath) {
        return new Vinyl({
          path: filepath,
          contents: fs.readFileSync(filepath)
        });
      })
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a binary-tree spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.pixelsmith.png'));
    it('has the proper coordinates', spritesmithUtils.assertCoordinates('binaryTree.coordinates.json'));
    it('has the proper properties', spritesmithUtils.assertProps('binaryTree.properties.json'));
  });
});

describe('An empty array', function () {
  var emptySprites = [];

  describe('when processed via spritesmith', function () {
    spritesmithUtils.run({
      src: emptySprites
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders an empty spritesheet', function () {
      assert.deepEqual(this.img, new Buffer(0));
    });
    it('returns an empty coordinate mapping', function () {
      assert.strictEqual(this.infoArr.length, 1);
      assert.deepEqual(this.infoArr[0].coordinates, {});
    });
    it('has the proper properties', spritesmithUtils.assertProps('empty.properties.json'));
  });
});

describe('`spritesmith` using a custom engine via string', function () {
  describe('processing a set of images', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      engine: 'phantomjssmith'
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.phantomjs.png'));
  });
});

describe('`spritesmith` using a custom engine via an object', function () {
  describe('processing a set of images', function () {
    spritesmithUtils.run({
      src: multipleSprites,
      engine: require('phantomjssmith')
    });

    it('has no errors', spritesmithUtils.assertNoError());
    it('renders a spritesheet', spritesmithUtils.assertSpritesheet('binaryTree.phantomjs.png'));
  });
});

// Edge cases
// Test for https://github.com/twolfson/gulp.spritesmith/issues/22
var canvassmith;
try {
  canvassmith = require('canvassmith');
} catch (err) {}
var describeIfCanvassmithExists = canvassmith ? describe : describe.skip;
describeIfCanvassmithExists('`spritesmith` using `canvassmith`', function () {
  describe('processing a bad image', function () {
    spritesmithUtils.run({
      src: [path.join(spriteDir, 'malformed.png')],
      engine: 'canvassmith'
    });

    it('calls back with an error', function () {
      assert.notEqual(this.imgErr, undefined);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

describe("Search controller: ", function () {
    var searchController, $scope, $controller, $httpBackend, $injector, $templateCache, $rootScope;

    beforeEach(function() {
        module('owh');

        inject(function (_$controller_, _$rootScope_, _$injector_, _$templateCache_) {
            // The injector unwraps the underscores (_) from around the parameter names when matching
            $rootScope = _$rootScope_;
            $controller = _$controller_;
            $injector   = _$injector_;
            $scope= _$rootScope_.$new();
            $httpBackend = $injector.get('$httpBackend');
            $templateCache = _$templateCache_;

            searchController= $controller('SearchController',{$scope:$scope});
            $httpBackend.whenGET('app/i18n/messages-en.json').respond({ hello: 'World' });
            $httpBackend.whenGET('app/partials/marker-template.html').respond( $templateCache.get('app/partials/marker-template.html'));
            $httpBackend.whenGET('app/partials/home/home.html').respond( $templateCache.get('app/partials/home/home.html'));
            $httpBackend.whenPOST('/search').respond( $templateCache.get('app/partials/marker-template.html'))
        });
    });

    it("Should execute showFbDialog",function() {
        var shareUtilService= {
            shareOnFb: function(){}
        };
        var searchController= $controller('SearchController',{$scope:$scope, shareUtilService:shareUtilService});
        searchController.showFbDialog([],"graphTitle","graph subtitle");
    });

    it("Should execute showExpandedGraph",function() {
        var chartUtilService= {
            showExpandedGraph: function(){}
        };
        var searchController= $controller('SearchController',{$scope:$scope, chartUtilService:chartUtilService});
        searchController.showExpandedGraph([]);
    });

    //TODO: ignoring for now, but eventually we should re-write this test
    xit("With selectedPrimaryfilter as disease ",function(){

        var stateparams = { primaryFilterKey: "deaths", queryId: "", allFilters: null, selectedFilters: null };
        var primaryFilterChangedFn, searchResultThenFn;
        var allFilters = [
            /*Demographics*/
            {key: 'race', title: 'label.filter.race', queryKey:"race", primary: false, value: [], groupBy: 'row',
                type:"label.filter.group.demographics", showChart: true, defaultGroup:"column",
                autoCompleteOptions: []},
            {key: 'gender', title: 'label.filter.gender', queryKey:"sex", primary: false, value: [], groupBy: 'column',
                type:"label.filter.group.demographics", groupByDefault: 'column', showChart: true,
                autoCompleteOptions: [], defaultGroup:"column"},

            /*Year and Month*/
            {key: 'year', title: 'label.filter.year', queryKey:"current_year",primary: false, value: ['2014'],
                groupBy: false,type:"label.filter.group.year.month", defaultGroup:"row",autoCompleteOptions:[
                    { "key": "2014", "title": "2014" },
                    { "key": "2013", "title": "2013" },
                    { "key": "2012", "title": "2012" }
                ]}
        ];

        function searchResultFn() {
            return {then:function(func){
                searchResultThenFn = func;
            }}
        }
        var maps = {"states":[
            {"name":"NY","deaths":53107,"sex":[{"name":"Male","deaths":27003},{"name":"Female","deaths":26104}]},
            {"name":"MT","deaths":53060,"sex":[{"name":"Male","deaths":26800},{"name":"Female","deaths":26260}]},
            {"name":"WA","deaths":53057,"sex":[{"name":"Male","deaths":26955},{"name":"Female","deaths":26102}]}
        ]};

        //mock searchFactory object
        var searchFactory= {
            updateFilterValues: function(){

            },
            addCountsToAutoCompleteOptions: function(){
                return {then: function(func) {
                    primaryFilterChangedFn= func;
                }};
            },
            getAllFilters:function () {
                return {search:[{
                    key: 'deaths', title: 'label.filter.mortality', primary: true, value: [], header:"Mortality",
                    allFilters: allFilters, searchResults: searchResultFn, showMap:true, chartAxisLabel:'Deaths',
                    countLabel: 'Number of Deaths', mapData:{}, searchCount:30032, maps: maps,
                    sideFilters:[
                        {
                            filterGroup: false, collapse: false, allowGrouping: true,
                            filters: allFilters[0]
                        },
                        {
                            filterGroup: false, collapse: true, allowGrouping: true,
                            filters: allFilters[1]
                        }
                    ]
                },
                    {
                        key: 'mental_health',title: 'label.risk.behavior',primary: true,value: [],
                        header: "Youth risk behavior",allFilters: [],searchResults: searchResultFn,
                        dontShowInlineCharting: true,additionalHeaders: [], countLabel: 'Total',
                        sideFilters: [
                            {
                                filterGroup: false, collapse: false, allowGrouping: false, dontShowCounts: true,
                                filters: allFilters[2]
                            }
                        ]
                    }
                ]}
            },
            showPhaseTwoModal:function (text) {
                return text;
            }
        };

        var searchController= $controller('SearchController',{$scope: $scope, searchFactory:searchFactory, $stateParams:stateparams});
        expect(searchController.filters).toBeDefined();
        expect(searchController.selectedMapSize).toEqual("small");

        //change map size to big
        searchController.selectedMapSize = "big";

        //Call primaryFilterChanged
        // primaryFilterChangedFn();
        // primaryFilterChangedFn();

        // $rootScope.$digest();

        //Call SearchResultFn
        // searchResultThenFn();

        //show phase two graphs
        searchController.showPhaseTwoGraphs("show next graph modal");

        var dummyFeatureObj = {
            properties: {
                totalCount:53100
            }
        };
        //call map style method of map to get the legend colors
        var styleObj = searchController.filters.selectedPrimaryFilter.mapData.geojson.style(dummyFeatureObj);
        expect(styleObj.weight).toBe(2);
        expect(styleObj.color).toEqual("white");

        /*getSelectedYears */
        //getSelectedYears
        var selectedYear = searchController.getSelectedYears();
        expect(selectedYear.length).toEqual(1);

        //If selected year has no value
        searchController.filters.selectedPrimaryFilter.allFilters[2].value="";
        selectedYear = searchController.getSelectedYears();
        expect(selectedYear.length).toEqual(3);

        //yearFilter is empty
        searchController.filters.selectedPrimaryFilter.allFilters=[];
        searchController.getSelectedYears();
        /*getSelectedYears */

        ////Changes the key values from deaths to yrbs
        //// make an initial selection
        //$scope.$apply('sc.filters.selectedPrimaryFilter.key="deaths"');
        //
        //// make another one
        //$scope.$apply('sc.filters.selectedPrimaryFilter.key="mental_health"');

        //on event
        //var args = {leafletEvent:{leafEvent:{latlng:{lat:3434,lng:42234}, target:{feature: {properties:{}}}, _map:{}}}}
        //$rootScope.$broadcast('leafletDirectiveGeoJson.click',event, args);

        //Verify queryID has not empty value
        var queryIdForIntialCall = searchController.queryId;
        expect(queryIdForIntialCall).not.toEqual("");
        //Call search method with filter params
        stateparams.allFilters = searchController.filters;
        stateparams.selectedFilters = searchController.filters.selectedPrimaryFilter;
        var searchController= $controller('SearchController',{$scope: $scope, searchFactory:searchFactory, $stateParams:stateparams});
        expect(searchController.filters).toBeDefined();
        expect(queryIdForIntialCall).not.toEqual("");
        expect(searchController.queryId).not.toEqual(queryIdForIntialCall);
    });

    it("downloadCSV should prepare mixedTable and call out to xlsService",inject(function(utilService, xlsService) {
        spyOn(utilService, 'prepareMixedTableData').and.returnValue({});
        spyOn(xlsService, 'exportCSVFromMixedTable');
        var searchController= $controller('SearchController',{$scope:$scope});
        searchController.filters = {selectedPrimaryFilter: {data: {}, value: []} };
        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable).toHaveBeenCalled();
        expect(utilService.prepareMixedTableData).toHaveBeenCalled();
    }));

    it('downloadCSV should call out with the proper filename', inject(function(utilService, xlsService) {
        spyOn(utilService, 'prepareMixedTableData').and.returnValue({});
        spyOn(xlsService, 'exportCSVFromMixedTable');
        var searchController= $controller('SearchController',{$scope:$scope});
        searchController.filters = {selectedPrimaryFilter: {data: {}, value: [], header: 'Mortality', allFilters: [
            {
                key: 'year',
                value: ['2014']
            }
        ]} };

        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable.calls.argsFor(0)).toContain('Mortality_2014_Filtered');

        searchController.filters.selectedPrimaryFilter.allFilters = [{key: 'year', value: ['2013', '2014']}];
        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable.calls.argsFor(1)).toContain('Mortality_2013-2014_Filtered');

        searchController.filters.selectedPrimaryFilter.allFilters = [{key: 'year', value: []}];
        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable.calls.argsFor(2)).toContain('Mortality_All_Filtered');
    }));

    it('downloadXLS should prepare mixedTable and call out to xlsService', inject(function(utilService, xlsService) {
        spyOn(utilService, 'prepareMixedTableData').and.returnValue({});
        spyOn(xlsService, 'exportXLSFromMixedTable');
        var searchController= $controller('SearchController',{$scope:$scope});
        searchController.filters = {selectedPrimaryFilter: {data: {}} };
        searchController.downloadXLS();

        expect(xlsService.exportXLSFromMixedTable).toHaveBeenCalled();
        expect(utilService.prepareMixedTableData).toHaveBeenCalled();
    }));

    it('changeViewFilter should set the tableView and call out to search', function() {
        var searchController= $controller('SearchController',{$scope:$scope});
        spyOn(searchController, 'search');
        searchController.filters = {selectedPrimaryFilter: {data: {}, allFilters: [], sideFilters: []}};
        searchController.changeViewFilter({key: 'number_of_deaths'});

        expect(searchController.tableView).toEqual('number_of_deaths');
        expect(searchController.search).toHaveBeenCalled();
    });

    it('changeViewFilter should replace ethnicity queryKey and options for crude_death_rates', function() {
        var searchController= $controller('SearchController',{$scope:$scope});
        spyOn(searchController, 'search');

        var ethnicityFilter = {
            query_key: 'hispanicOrigin',
            key: 'hispanicOrigin'
        };

        searchController.filters = {selectedPrimaryFilter: {data: {}, allFilters: [ethnicityFilter], sideFilters: [{filters: ethnicityFilter}]}};
        searchController.filters.ethnicityGroupOptions = [
            {"key": 'hispanic', "title": 'Hispanic'},
            {"key": 'non', "title": "Non-Hispanic"}
        ];
        searchController.filters.hispanicOptions = [
            {
                key: 'Cuban'
            },
            {
                key: 'Dominican'
            }
        ];

        searchController.changeViewFilter({key: 'crude_death_rates'});

        expect(searchController.tableView).toEqual('crude_death_rates');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].queryKey).toEqual('ethnicity_group');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[0].key).toEqual('hispanic');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[1].key).toEqual('non');

        searchController.changeViewFilter({key: 'number_of_deaths'});

        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].queryKey).toEqual('hispanicOrigin');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[0].key).toEqual('Cuban');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[1].key).toEqual('Dominican');
    });

});
<commit_msg>OWH-222: add unit test<commit_after>'use strict';

describe("Search controller: ", function () {
    var searchController, $scope, $controller, $httpBackend, $injector, $templateCache, $rootScope;

    beforeEach(function() {
        module('owh');

        inject(function (_$controller_, _$rootScope_, _$injector_, _$templateCache_) {
            // The injector unwraps the underscores (_) from around the parameter names when matching
            $rootScope = _$rootScope_;
            $controller = _$controller_;
            $injector   = _$injector_;
            $scope= _$rootScope_.$new();
            $httpBackend = $injector.get('$httpBackend');
            $templateCache = _$templateCache_;

            searchController= $controller('SearchController',{$scope:$scope});
            $httpBackend.whenGET('app/i18n/messages-en.json').respond({ hello: 'World' });
            $httpBackend.whenGET('app/partials/marker-template.html').respond( $templateCache.get('app/partials/marker-template.html'));
            $httpBackend.whenGET('app/partials/home/home.html').respond( $templateCache.get('app/partials/home/home.html'));
            $httpBackend.whenPOST('/search').respond( $templateCache.get('app/partials/marker-template.html'))
        });
    });

    it("Should execute showFbDialog",function() {
        var shareUtilService= {
            shareOnFb: function(){}
        };
        var searchController= $controller('SearchController',{$scope:$scope, shareUtilService:shareUtilService});
        searchController.showFbDialog([],"graphTitle","graph subtitle");
    });

    it("Should execute showExpandedGraph",function() {
        var chartUtilService= {
            showExpandedGraph: function(){}
        };
        var searchController= $controller('SearchController',{$scope:$scope, chartUtilService:chartUtilService});
        searchController.showExpandedGraph([]);
    });

    //TODO: ignoring for now, but eventually we should re-write this test
    xit("With selectedPrimaryfilter as disease ",function(){

        var stateparams = { primaryFilterKey: "deaths", queryId: "", allFilters: null, selectedFilters: null };
        var primaryFilterChangedFn, searchResultThenFn;
        var allFilters = [
            /*Demographics*/
            {key: 'race', title: 'label.filter.race', queryKey:"race", primary: false, value: [], groupBy: 'row',
                type:"label.filter.group.demographics", showChart: true, defaultGroup:"column",
                autoCompleteOptions: []},
            {key: 'gender', title: 'label.filter.gender', queryKey:"sex", primary: false, value: [], groupBy: 'column',
                type:"label.filter.group.demographics", groupByDefault: 'column', showChart: true,
                autoCompleteOptions: [], defaultGroup:"column"},

            /*Year and Month*/
            {key: 'year', title: 'label.filter.year', queryKey:"current_year",primary: false, value: ['2014'],
                groupBy: false,type:"label.filter.group.year.month", defaultGroup:"row",autoCompleteOptions:[
                    { "key": "2014", "title": "2014" },
                    { "key": "2013", "title": "2013" },
                    { "key": "2012", "title": "2012" }
                ]}
        ];

        function searchResultFn() {
            return {then:function(func){
                searchResultThenFn = func;
            }}
        }
        var maps = {"states":[
            {"name":"NY","deaths":53107,"sex":[{"name":"Male","deaths":27003},{"name":"Female","deaths":26104}]},
            {"name":"MT","deaths":53060,"sex":[{"name":"Male","deaths":26800},{"name":"Female","deaths":26260}]},
            {"name":"WA","deaths":53057,"sex":[{"name":"Male","deaths":26955},{"name":"Female","deaths":26102}]}
        ]};

        //mock searchFactory object
        var searchFactory= {
            updateFilterValues: function(){

            },
            addCountsToAutoCompleteOptions: function(){
                return {then: function(func) {
                    primaryFilterChangedFn= func;
                }};
            },
            getAllFilters:function () {
                return {search:[{
                    key: 'deaths', title: 'label.filter.mortality', primary: true, value: [], header:"Mortality",
                    allFilters: allFilters, searchResults: searchResultFn, showMap:true, chartAxisLabel:'Deaths',
                    countLabel: 'Number of Deaths', mapData:{}, searchCount:30032, maps: maps,
                    sideFilters:[
                        {
                            filterGroup: false, collapse: false, allowGrouping: true,
                            filters: allFilters[0]
                        },
                        {
                            filterGroup: false, collapse: true, allowGrouping: true,
                            filters: allFilters[1]
                        }
                    ]
                },
                    {
                        key: 'mental_health',title: 'label.risk.behavior',primary: true,value: [],
                        header: "Youth risk behavior",allFilters: [],searchResults: searchResultFn,
                        dontShowInlineCharting: true,additionalHeaders: [], countLabel: 'Total',
                        sideFilters: [
                            {
                                filterGroup: false, collapse: false, allowGrouping: false, dontShowCounts: true,
                                filters: allFilters[2]
                            }
                        ]
                    }
                ]}
            },
            showPhaseTwoModal:function (text) {
                return text;
            }
        };

        var searchController= $controller('SearchController',{$scope: $scope, searchFactory:searchFactory, $stateParams:stateparams});
        expect(searchController.filters).toBeDefined();
        expect(searchController.selectedMapSize).toEqual("small");

        //change map size to big
        searchController.selectedMapSize = "big";

        //Call primaryFilterChanged
        // primaryFilterChangedFn();
        // primaryFilterChangedFn();

        // $rootScope.$digest();

        //Call SearchResultFn
        // searchResultThenFn();

        //show phase two graphs
        searchController.showPhaseTwoGraphs("show next graph modal");

        var dummyFeatureObj = {
            properties: {
                totalCount:53100
            }
        };
        //call map style method of map to get the legend colors
        var styleObj = searchController.filters.selectedPrimaryFilter.mapData.geojson.style(dummyFeatureObj);
        expect(styleObj.weight).toBe(2);
        expect(styleObj.color).toEqual("white");

        /*getSelectedYears */
        //getSelectedYears
        var selectedYear = searchController.getSelectedYears();
        expect(selectedYear.length).toEqual(1);

        //If selected year has no value
        searchController.filters.selectedPrimaryFilter.allFilters[2].value="";
        selectedYear = searchController.getSelectedYears();
        expect(selectedYear.length).toEqual(3);

        //yearFilter is empty
        searchController.filters.selectedPrimaryFilter.allFilters=[];
        searchController.getSelectedYears();
        /*getSelectedYears */

        ////Changes the key values from deaths to yrbs
        //// make an initial selection
        //$scope.$apply('sc.filters.selectedPrimaryFilter.key="deaths"');
        //
        //// make another one
        //$scope.$apply('sc.filters.selectedPrimaryFilter.key="mental_health"');

        //on event
        //var args = {leafletEvent:{leafEvent:{latlng:{lat:3434,lng:42234}, target:{feature: {properties:{}}}, _map:{}}}}
        //$rootScope.$broadcast('leafletDirectiveGeoJson.click',event, args);

        //Verify queryID has not empty value
        var queryIdForIntialCall = searchController.queryId;
        expect(queryIdForIntialCall).not.toEqual("");
        //Call search method with filter params
        stateparams.allFilters = searchController.filters;
        stateparams.selectedFilters = searchController.filters.selectedPrimaryFilter;
        var searchController= $controller('SearchController',{$scope: $scope, searchFactory:searchFactory, $stateParams:stateparams});
        expect(searchController.filters).toBeDefined();
        expect(queryIdForIntialCall).not.toEqual("");
        expect(searchController.queryId).not.toEqual(queryIdForIntialCall);
    });

    it("downloadCSV should prepare mixedTable and call out to xlsService",inject(function(utilService, xlsService) {
        spyOn(utilService, 'prepareMixedTableData').and.returnValue({});
        spyOn(xlsService, 'exportCSVFromMixedTable');
        var searchController= $controller('SearchController',{$scope:$scope});
        searchController.filters = {selectedPrimaryFilter: {data: {}, value: []} };
        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable).toHaveBeenCalled();
        expect(utilService.prepareMixedTableData).toHaveBeenCalled();
    }));

    it('downloadCSV should call out with the proper filename', inject(function(utilService, xlsService) {
        spyOn(utilService, 'prepareMixedTableData').and.returnValue({});
        spyOn(xlsService, 'exportCSVFromMixedTable');
        var searchController= $controller('SearchController',{$scope:$scope});
        searchController.filters = {selectedPrimaryFilter: {data: {}, value: [], header: 'Mortality', allFilters: [
            {
                key: 'year',
                value: ['2014']
            }
        ]} };

        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable.calls.argsFor(0)).toContain('Mortality_2014_Filtered');

        searchController.filters.selectedPrimaryFilter.allFilters = [{key: 'year', value: ['2013', '2014']}];
        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable.calls.argsFor(1)).toContain('Mortality_2013-2014_Filtered');

        searchController.filters.selectedPrimaryFilter.allFilters = [{key: 'year', value: []}];
        searchController.downloadCSV();

        expect(xlsService.exportCSVFromMixedTable.calls.argsFor(2)).toContain('Mortality_All_Filtered');
    }));

    it('downloadXLS should prepare mixedTable and call out to xlsService', inject(function(utilService, xlsService) {
        spyOn(utilService, 'prepareMixedTableData').and.returnValue({});
        spyOn(xlsService, 'exportXLSFromMixedTable');
        var searchController= $controller('SearchController',{$scope:$scope});
        searchController.filters = {selectedPrimaryFilter: {data: {}} };
        searchController.downloadXLS();

        expect(xlsService.exportXLSFromMixedTable).toHaveBeenCalled();
        expect(utilService.prepareMixedTableData).toHaveBeenCalled();
    }));

    it('changeViewFilter should set the tableView and call out to search', function() {
        var searchController= $controller('SearchController',{$scope:$scope});
        spyOn(searchController, 'search');
        searchController.filters = {selectedPrimaryFilter: {data: {}, allFilters: [], sideFilters: []}};
        searchController.changeViewFilter({key: 'number_of_deaths'});

        expect(searchController.tableView).toEqual('number_of_deaths');
        expect(searchController.search).toHaveBeenCalled();
    });

    it('changeViewFilter should replace ethnicity queryKey and options for crude_death_rates', function() {
        var searchController= $controller('SearchController',{$scope:$scope});
        spyOn(searchController, 'search');

        var ethnicityFilter = {
            query_key: 'hispanicOrigin',
            key: 'hispanicOrigin'
        };

        searchController.filters = {selectedPrimaryFilter: {data: {}, allFilters: [ethnicityFilter], sideFilters: [{filters: ethnicityFilter}]}};
        searchController.filters.ethnicityGroupOptions = [
            {"key": 'hispanic', "title": 'Hispanic'},
            {"key": 'non', "title": "Non-Hispanic"}
        ];
        searchController.filters.hispanicOptions = [
            {
                key: 'Cuban'
            },
            {
                key: 'Dominican'
            }
        ];

        searchController.changeViewFilter({key: 'crude_death_rates'});

        expect(searchController.tableView).toEqual('crude_death_rates');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].queryKey).toEqual('ethnicity_group');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[0].key).toEqual('hispanic');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[1].key).toEqual('non');

        searchController.changeViewFilter({key: 'number_of_deaths'});

        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].queryKey).toEqual('hispanicOrigin');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[0].key).toEqual('Cuban');
        expect(searchController.filters.selectedPrimaryFilter.allFilters[0].autoCompleteOptions[1].key).toEqual('Dominican');
    });

    it('filterUtilities for yrbs should perform proper functions', function() {
        var searchController= $controller('SearchController',{$scope:$scope});

        searchController.filterUtilities['mental_health'][0].options[0].onChange(true);

        expect(searchController.showConfidenceIntervals).toBeTruthy();

        searchController.filterUtilities['mental_health'][0].options[0].onChange(false);

        expect(searchController.showConfidenceIntervals).toBeFalsy();

        searchController.filterUtilities['mental_health'][0].options[1].onChange(true);

        expect(searchController.showUnweightedFrequency).toBeTruthy();

        searchController.filterUtilities['mental_health'][0].options[1].onChange(false);

        expect(searchController.showUnweightedFrequency).toBeFalsy();
    });

});
<|endoftext|>


<commit_before>import axios from 'axios';

import Auth from './auth';

const apiBaseURI = 'http://localhost:8080';

function getChannels() {
  return axios.get(`${apiBaseURI}/api/channels`).then(resp => {
    if (resp.status >= 200 && resp.status < 300) {
      return resp.data;
    } else {
      throw new Error(resp.statusText);
    }
  });
}

function createUser(body) {
  return axios.post(`${apiBaseURI}/api/users`, body).then(resp => {
    if (resp.status >= 200 && resp.status < 300) {
      return resp.data;
    } else {
      throw new Error(resp.statusText);
    }
  });
}

function getPendingUsers() {
  const token = Auth.getToken();
  var config = {
    headers: {
      Authorization: token
    }
  };
  return axios
    .get(`${apiBaseURI}/api/admins?filter=pending`, config)
    .then(resp => {
      console.log(resp);
      if (resp.status >= 200 && resp.status < 300) {
        return resp.data;
      } else {
        throw new Error(resp.statusText);
      }
    });
}

function applyPermissions(userId, body) {
  const token = Auth.getToken();
  var config = {
    headers: {
      Authorization: token
    }
  };
  return axios
    .post(`${apiBaseURI}/api/users/${userId}/convertInAdmin`, body, config)
    .then(resp => {
      console.log(resp);
      if (resp.status >= 200 && resp.status < 300) {
        return resp.data;
      } else {
        throw new Error(resp.data.message);
      }
    });
}

export default {
  getChannels,
  createUser,
  getPendingUsers,
  applyPermissions
};
<commit_msg>Refacor request and add function to fetch peding admins<commit_after>import axios from 'axios';

import Auth from './auth';

const apiBaseURI = 'http://localhost:8080';

function checkStatusCode(resp) {
  if (resp.status >= 200 && resp.status < 300) {
    return resp.data;
  } else {
    throw new Error(resp.statusText);
  }
}

function getChannels() {
  return axios.get(`${apiBaseURI}/api/channels`).then(checkStatusCode);
}

function createUser(body) {
  return axios.post(`${apiBaseURI}/api/users`, body).then(checkStatusCode);
}

function getPendingUsers() {
  const token = Auth.getToken();
  var config = {
    headers: {
      Authorization: token
    }
  };
  return axios
    .get(`${apiBaseURI}/api/admins?filter=pending`, config)
    .then(checkStatusCode);
}

function applyPermissions(userId, body) {
  const token = Auth.getToken();
  var config = {
    headers: {
      Authorization: token
    }
  };
  return axios
    .post(`${apiBaseURI}/api/users/${userId}/convertInAdmin`, body, config)
    .then(checkStatusCode);
}

function getAllAdmins() {
  const token = Auth.getToken();
  var config = {
    headers: {
      Authorization: token
    }
  };
  return axios.get(`${apiBaseURI}/api/admins`, config).then(checkStatusCode);
}

export default {
  getChannels,
  createUser,
  getPendingUsers,
  getAllAdmins,
  applyPermissions
};
<|endoftext|>


<commit_before>/*jshint bitwise: false*/
/*globals define*/
define([
  'box2d',
  'entities/explosion',
  'entities/physics-entity',
  'entities/player',
  'config/colors',
  'config/material',
  'config/settings',
  'utils',
  'world'
], function( Box2D, Explosion, PhysicsEntity, Player, Colors, Material, Settings, Utils, world ) {
  'use strict';

  var PI2 = Utils.PI2;

  var Vec2 = Box2D.Common.Math.b2Vec2;

  function Laser( x, y, material ) {
    PhysicsEntity.call( this, {
      fixture: {
        isSensor: true,
        filter: {
          categoryBits: material
        }
      },
      body: {
        position: {
          x: x,
          y: y
        }
      }
    });

    this.target = null;
    this.endpoint = null;
    this.normal = null;
    this.fraction = Number.POSITIVE_INFINITY;
  }

  Laser.prototype = new PhysicsEntity();
  Laser.prototype.constructor = Laser;

  Laser.prototype.update = function( dt ) {
    PhysicsEntity.prototype.update.call( this, dt );

    var cos = 1,
        sin = 0;

    if ( this.angle ) {
      cos = Math.cos( -this.angle );
      sin = Math.sin( -this.angle );
    }

    this.target = null;
    this.endpoint = null;
    this.fraction = Number.POSITIVE_INFINITY;

    world.RayCast(
      function( fixture, point, normal, fraction ) {
        var target = fixture.GetBody().GetUserData();
        if ( !( target.material & this.material ) ) {
          return -1;
        }

        if ( fraction < this.fraction ) {
          this.target = target;
          this.normal = normal;
          this.endpoint = point;
          this.fraction = fraction;
        }

        return fraction;
      }.bind( this ),
      new Vec2( this.x + cos, this.y + sin ),
      new Vec2( this.x + 1e4 * cos, this.y + 1e4 * sin )
    );

    if ( !this.target ) {
      return;
    }

    // Delete target.
    var target = this.target;
    if ( target !== this &&
         target.material !== Material.BIMATTER &&
         !( target instanceof Player ) &&
         target.game ) {
      this.game.removed.push( target );

      if ( Settings.explosions ) {
        var explosion, fill;
        fill = Colors.Explosion[ Material.type( target.material ) ];

        if ( fill ) {
          explosion = new Explosion( target.x, target.y );
          explosion.fill.set( fill );
          this.game.add( explosion );
        }
      }
    }
  };

  Laser.prototype.drawPath = function( ctx ) {
    // Draw laser source.
    ctx.beginPath();

    // The laser starts at a radius of 1.
    ctx.rect( -1, -0.5, 2, 1 );
    ctx.fillStyle = '#000';
    ctx.fill();

    PhysicsEntity.prototype.drawPath.call( this, ctx );
  };

  Laser.prototype.draw = function( ctx ) {
    PhysicsEntity.prototype.draw.call( this, ctx );

    // Only render beam if there is no endpoint and target,
    // or if the target has not been removed from the game.
    if ( !this.endpoint || !this.target ||
        ( this.target && !this.target.game ) ) {
      return;
    }

    if ( Settings.glow ) {
      ctx.globalCompositeOperation = 'lighter';
    }

    var cos = Math.cos( -this.angle ),
        sin = Math.sin( -this.angle );

    var x0 = this.x + cos,
        y0 = this.y + sin,
        x1 = this.endpoint.x,
        y1 = this.endpoint.y;

    ctx.beginPath();
    ctx.moveTo( x0, y0 );
    ctx.lineTo( x1, y1 );

    var outerWidth = 0.4 + Math.random() * 0.2,
        innerWidth = 0.1 + Math.random() * 0.1;

    // Draw beam.
    var glowColor = Colors.Glow[ Material.type( this.material ) ];

    if ( glowColor ) {
      ctx.lineWidth = outerWidth;
      ctx.strokeStyle = glowColor;
      ctx.stroke();
    }

    ctx.lineWidth = innerWidth;
    ctx.strokeStyle = '#fff';
    ctx.stroke();

    // Draw endpoint glows.
    ctx.beginPath();
    ctx.arc( x0, y0, innerWidth * 2, 0, PI2 );
    ctx.moveTo( x1, y1 );
    ctx.arc( x1, y1, innerWidth * 2, 0, PI2 );

    if ( glowColor ) {
      ctx.lineWidth = outerWidth;
      ctx.strokeStyle = glowColor;
      ctx.stroke();
    }

    ctx.fillStyle = '#fff';
    ctx.fill();

    if ( Settings.glow ) {
      ctx.globalCompositeOperation = 'source-over';
    }
  };

  Laser.prototype.drawNormals = function( ctx ) {
    if ( !this.endpoint || !this.normal ) {
      return;
    }

    ctx.save();

    // Counteract transofmrs in draw.
    ctx.rotate( this.angle );
    ctx.translate( -this.x, -this.y );

    ctx.beginPath();
    ctx.moveTo( this.endpoint.x, this.endpoint.y );
    ctx.lineTo( this.endpoint.x + this.normal.x, this.endpoint.y + this.normal.y );
    ctx.lineWidth = 0.2;
    ctx.strokeStyle = '#fff';
    ctx.stroke();

    ctx.restore();
  };

  return Laser;
});
<commit_msg>Add Laser .aabb().<commit_after>/*jshint bitwise: false*/
/*globals define*/
define([
  'box2d',
  'entities/explosion',
  'entities/physics-entity',
  'entities/player',
  'config/colors',
  'config/material',
  'config/settings',
  'utils',
  'world'
], function( Box2D, Explosion, PhysicsEntity, Player, Colors, Material, Settings, Utils, world ) {
  'use strict';

  var PI2 = Utils.PI2;

  var Vec2 = Box2D.Common.Math.b2Vec2;

  function Laser( x, y, material ) {
    PhysicsEntity.call( this, {
      fixture: {
        isSensor: true,
        filter: {
          categoryBits: material
        }
      },
      body: {
        position: {
          x: x,
          y: y
        }
      }
    });

    this.target = null;
    this.endpoint = null;
    this.normal = null;
    this.fraction = Number.POSITIVE_INFINITY;
  }

  Laser.prototype = new PhysicsEntity();
  Laser.prototype.constructor = Laser;

  Laser.prototype.update = function( dt ) {
    PhysicsEntity.prototype.update.call( this, dt );

    var cos = 1,
        sin = 0;

    if ( this.angle ) {
      cos = Math.cos( -this.angle );
      sin = Math.sin( -this.angle );
    }

    this.target = null;
    this.endpoint = null;
    this.fraction = Number.POSITIVE_INFINITY;

    world.RayCast(
      function( fixture, point, normal, fraction ) {
        var target = fixture.GetBody().GetUserData();
        if ( !( target.material & this.material ) ) {
          return -1;
        }

        if ( fraction < this.fraction ) {
          this.target = target;
          this.normal = normal;
          this.endpoint = point;
          this.fraction = fraction;
        }

        return fraction;
      }.bind( this ),
      new Vec2( this.x + cos, this.y + sin ),
      new Vec2( this.x + 1e4 * cos, this.y + 1e4 * sin )
    );

    if ( !this.target ) {
      return;
    }

    // Delete target.
    var target = this.target;
    if ( target !== this &&
         target.material !== Material.BIMATTER &&
         !( target instanceof Player ) &&
         target.game ) {
      this.game.removed.push( target );

      if ( Settings.explosions ) {
        var explosion, fill;
        fill = Colors.Explosion[ Material.type( target.material ) ];

        if ( fill ) {
          explosion = new Explosion( target.x, target.y );
          explosion.fill.set( fill );
          this.game.add( explosion );
        }
      }
    }
  };

  Laser.prototype.drawPath = function( ctx ) {
    // Draw laser source.
    ctx.beginPath();

    // The laser starts at a radius of 1.
    ctx.rect( -1, -0.5, 2, 1 );
    ctx.fillStyle = '#000';
    ctx.fill();

    PhysicsEntity.prototype.drawPath.call( this, ctx );
  };

  Laser.prototype.draw = function( ctx ) {
    PhysicsEntity.prototype.draw.call( this, ctx );

    // Only render beam if there is no endpoint and target,
    // or if the target has not been removed from the game.
    if ( !this.endpoint || !this.target ||
        ( this.target && !this.target.game ) ) {
      return;
    }

    if ( Settings.glow ) {
      ctx.globalCompositeOperation = 'lighter';
    }

    var cos = Math.cos( -this.angle ),
        sin = Math.sin( -this.angle );

    var x0 = this.x + cos,
        y0 = this.y + sin,
        x1 = this.endpoint.x,
        y1 = this.endpoint.y;

    ctx.beginPath();
    ctx.moveTo( x0, y0 );
    ctx.lineTo( x1, y1 );

    var outerWidth = 0.4 + Math.random() * 0.2,
        innerWidth = 0.1 + Math.random() * 0.1;

    // Draw beam.
    var glowColor = Colors.Glow[ Material.type( this.material ) ];

    if ( glowColor ) {
      ctx.lineWidth = outerWidth;
      ctx.strokeStyle = glowColor;
      ctx.stroke();
    }

    ctx.lineWidth = innerWidth;
    ctx.strokeStyle = '#fff';
    ctx.stroke();

    // Draw endpoint glows.
    ctx.beginPath();
    ctx.arc( x0, y0, innerWidth * 2, 0, PI2 );
    ctx.moveTo( x1, y1 );
    ctx.arc( x1, y1, innerWidth * 2, 0, PI2 );

    if ( glowColor ) {
      ctx.lineWidth = outerWidth;
      ctx.strokeStyle = glowColor;
      ctx.stroke();
    }

    ctx.fillStyle = '#fff';
    ctx.fill();

    if ( Settings.glow ) {
      ctx.globalCompositeOperation = 'source-over';
    }
  };

  Laser.prototype.drawNormals = function( ctx ) {
    if ( !this.endpoint || !this.normal ) {
      return;
    }

    ctx.save();

    // Counteract transofmrs in draw.
    ctx.rotate( this.angle );
    ctx.translate( -this.x, -this.y );

    ctx.beginPath();
    ctx.moveTo( this.endpoint.x, this.endpoint.y );
    ctx.lineTo( this.endpoint.x + this.normal.x, this.endpoint.y + this.normal.y );
    ctx.lineWidth = 0.2;
    ctx.strokeStyle = '#fff';
    ctx.stroke();

    ctx.restore();
  };

  Laser.prototype.aabb = function() {
    var aabb;
    if ( !this.endpoint ) {
      aabb = PhysicsEntity.prototype.aabb();
      return Utils.expandAABB( aabb, 1, 1 );
    }

    var x0 = this.x,
        y0 = this.y;

    var x1 = this.endpoint.x,
        y1 = this.endpoint.y;

    aabb = {
      xmin: Math.min( x0, x1 ),
      ymin: Math.min( y0, y1 ),
      xmax: Math.max( x0, x1 ),
      ymax: Math.max( y0, y1 )
    };

    // 1 is the pointer radius. 0.6 is the maximum glow radius.
    var radius = 1.6;
    return Utils.relativeExpandAABB( aabb, radius, radius );
  };

  return Laser;
});
<|endoftext|>


<commit_before>/* global describe, it */

'use strict';

(function () {

  var expect = require('chai').expect;

  var index = require('../src/index');

  describe('index.js', function () {

    it('should export some stuff', function () {
      var keyTypeMap = {
        collect: 'function',
        Program: 'function',
        Command: 'function',
        KWArg: 'function',
        Flag: 'function',
        Arg: 'function',
        Required: 'function',
        RequireAll: 'function',
        RequireAny: 'function'
      };

      expect(index).to.be.ok;

      for (var key in index) {
        expect(key in keyTypeMap).to.be.true;
        expect(typeof index[key]).to.equal(keyTypeMap[key]);
      }
    });

  });

})();
<commit_msg>Update index tests<commit_after>/* global describe, it */

'use strict';

(function () {

  var expect = require('chai').expect;

  var index = require('../src/index');

  describe('index.js', function () {

    it('should export some stuff', function () {
      var keyTypeMap = {
        collect: 'function',
        Help: 'function',
        Program: 'function',
        Command: 'function',
        KWArg: 'function',
        Flag: 'function',
        Arg: 'function',
        Required: 'function',
        RequireAll: 'function',
        RequireAny: 'function'
      };

      expect(index).to.be.ok;

      for (var key in index) {
        expect(key in keyTypeMap).to.be.true;
        expect(typeof index[key]).to.equal(keyTypeMap[key]);
      }
    });

  });

})();
<|endoftext|>


<commit_before>/* -*- coding: utf-8 -*- */
/* global cforum, t, Dropzone */

cforum.cf_messages = {
  initMarkdown: function(elem_id) {
    var elem = $("#" + elem_id);

    if(elem.length) {
      cforum.markdown_buttons.l10n();

      elem.markdown({autofocus: false, savable: false, iconlibrary: 'fa',
                     language: 'de', hiddenButtons: 'cmdPreview',
                     disabledButtons: 'cmdPreview', resize: 'both',
                     additionalButtons: [
                       {
                         name: 'groupCustom',
                         data: [
                           cforum.markdown_buttons.noMarkdown,
                           cforum.markdown_buttons.tab,
                           cforum.markdown_buttons.hellip,
                           cforum.markdown_buttons.mdash,
                           cforum.markdown_buttons.almostEqualTo,
                           cforum.markdown_buttons.unequal,
                           cforum.markdown_buttons.times,
                           cforum.markdown_buttons.arrowRight,
                           cforum.markdown_buttons.arrowUp,
                           cforum.markdown_buttons.blackUpPointingTriangle,
                           cforum.markdown_buttons.rightwardsDoubleArrow,
                           cforum.markdown_buttons.trademark,
                           cforum.markdown_buttons.doublePunctuationMarks,
                           cforum.markdown_buttons.singlePunctuationMarks
                         ]
                       }
                     ]});

      var usg = $('#forum-usage');
      if(usg.length > 0) {
        elem.prev().append(usg);
      }
    }
  },

  maxLen: function(text) {
    var newlines = 0;

    for(var i = 0; i < text.length; ++i) {
      if(text.charAt(i) == "\n") {
        newlines++;

        if(newlines >= 3 && i >= 100) {
          return text.substr(0, i);
        }
      }

      if(i > 300) {
        return text.substr(0, i);
      }
    }

    return null;
  },

  initQuotes: function() {
    if(uconf('fold_quotes') != 'yes') {
      return;
    }

    $(".posting-content blockquote").each(function() {
      var $this = $(this);
      var txt = cforum.cf_messages.maxLen($this.text());

      if(txt) {
        $this.css('display', 'none');
        $this.before('

\n' + t('unfold_quote') + '
');
        $this.prev().prepend(document.createTextNode(txt));
      }
    });

    $(".posting-content").click(function(ev) {
      var trg = $(ev.target);
      if(trg.hasClass('unfold')) {
        trg.parent().next().fadeIn('fast');
        trg.parent().remove();
      }
    });
  },

  init: function() {
    var action = $('body').attr('data-action');
    cforum.tags.initTags();
    cforum.cf_messages.initQuotes();

    if(action != 'create' && action != 'update') {
      cforum.cf_messages.initCursor();
    }

    cforum.cf_messages.initMarkdown("message_input");
    cforum.cf_messages.initUpload();
    $("#message_input").mentions();
  },

  new: function() {
    if(cforum.cf_messages.quotedMessage) {
      $(".form-actions").append("<button class=\"cf-btn quote-message\">" + t('add_quote') + "</button>");
      $('.form-actions .quote-message').on('click', cforum.cf_messages.quoteMessage);
    }
  },

  quoteMessage: function(ev) {
    ev.preventDefault();
    $("#message_input").val($("#message_input").val() + cforum.cf_messages.quotedMessage);
    $(".form-actions .quote-message").fadeOut('fast', function() { $(this).remove(); });
  },

  initCursor: function() {
    var content = $("#message_input");
    var subj = $("#cf_message_subject");
    var author = $("#cf_message_author");

    cforum.cf_threads.setCursor(author, subj, content);
  },

  initUpload: function() {
    if($("#message_input").length > 0 && window.Dropzone) {
      $("#message_input").after('
' + t('upload.image_area') + '
');
      $(".image-upload").dropzone({
        createImageThumbnails: false,
        maxFilesize: 2, // 2mb max filesize
        url: cforum.baseUrl + 'images.json',
        clickable: true,
        acceptedFiles: 'image/*',
        previewTemplate : '

',
        fallback: function() { },
        init: function() {
          this.on("success", function(file, rsp) {
            var $msg = $("#message_input");
            var selection = $msg.getSelection();
            var md = '![' + t('upload.alternative_text') + '](' + cforum.basePath + 'images/' + rsp.path + ')';

            var imgup = $('.image-upload');
            imgup.removeClass('loading');
            imgup.html(t('upload.image_area'));

            $msg.replaceSelection(md);

            window.setTimeout(function() {
              $msg.focus();
              $msg.setSelection(selection.start + 2, selection.start + 17);
            }, 0);
          });

          this.on('error', function(file, response) {
            var imgup = $('.image-upload');
            imgup.removeClass('loading');
            imgup.html(t('upload.image_area'));
            cforum.alert.error(response.error || t('internal_error'));
          });

          this.on('sending', function(file, xhr, formData) {
            var imgup = $('.image-upload');
            imgup.addClass('loading');
            imgup.html("");

            xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
          });
        }
      });
    }
  }
};

/* eof */
<commit_msg>ref: code formatting<commit_after>/* -*- coding: utf-8 -*- */
/* global cforum, t, uconf */

cforum.cf_messages = {
  initMarkdown: function(elem_id) {
    var elem = $("#" + elem_id);

    if(elem.length) {
      cforum.markdown_buttons.l10n();

      elem.markdown({autofocus: false, savable: false, iconlibrary: 'fa',
                     language: 'de', hiddenButtons: 'cmdPreview',
                     disabledButtons: 'cmdPreview', resize: 'both',
                     additionalButtons: [
                       {
                         name: 'groupCustom',
                         data: [
                           cforum.markdown_buttons.noMarkdown,
                           cforum.markdown_buttons.tab,
                           cforum.markdown_buttons.hellip,
                           cforum.markdown_buttons.mdash,
                           cforum.markdown_buttons.almostEqualTo,
                           cforum.markdown_buttons.unequal,
                           cforum.markdown_buttons.times,
                           cforum.markdown_buttons.arrowRight,
                           cforum.markdown_buttons.arrowUp,
                           cforum.markdown_buttons.blackUpPointingTriangle,
                           cforum.markdown_buttons.rightwardsDoubleArrow,
                           cforum.markdown_buttons.trademark,
                           cforum.markdown_buttons.doublePunctuationMarks,
                           cforum.markdown_buttons.singlePunctuationMarks
                         ]
                       }
                     ]});

      var usg = $('#forum-usage');
      if(usg.length > 0) {
        elem.prev().append(usg);
      }
    }
  },

  maxLen: function(text) {
    var newlines = 0;

    for(var i = 0; i < text.length; ++i) {
      if(text.charAt(i) == "\n") {
        newlines++;

        if(newlines >= 3 && i >= 100) {
          return text.substr(0, i);
        }
      }

      if(i > 300) {
        return text.substr(0, i);
      }
    }

    return null;
  },

  initQuotes: function() {
    if(uconf('fold_quotes') != 'yes') {
      return;
    }

    $(".posting-content blockquote").each(function() {
      var $this = $(this);
      var txt = cforum.cf_messages.maxLen($this.text());

      if(txt) {
        $this.css('display', 'none');
        $this.before('

\n' + t('unfold_quote') + '
');
        $this.prev().prepend(document.createTextNode(txt));
      }
    });

    $(".posting-content").click(function(ev) {
      var trg = $(ev.target);
      if(trg.hasClass('unfold')) {
        trg.parent().next().fadeIn('fast');
        trg.parent().remove();
      }
    });
  },

  init: function() {
    var action = $('body').attr('data-action');
    cforum.tags.initTags();
    cforum.cf_messages.initQuotes();

    if(action != 'create' && action != 'update') {
      cforum.cf_messages.initCursor();
    }

    cforum.cf_messages.initMarkdown("message_input");
    cforum.cf_messages.initUpload();
    $("#message_input").mentions();
  },

  new: function() {
    if(cforum.cf_messages.quotedMessage) {
      $(".form-actions").append("<button class=\"cf-btn quote-message\">" + t('add_quote') + "</button>");
      $('.form-actions .quote-message').on('click', cforum.cf_messages.quoteMessage);
    }
  },

  quoteMessage: function(ev) {
    ev.preventDefault();
    $("#message_input").val($("#message_input").val() + cforum.cf_messages.quotedMessage);
    $(".form-actions .quote-message").fadeOut('fast', function() { $(this).remove(); });
  },

  initCursor: function() {
    var content = $("#message_input");
    var subj = $("#cf_message_subject");
    var author = $("#cf_message_author");

    cforum.cf_threads.setCursor(author, subj, content);
  },

  initUpload: function() {
    if($("#message_input").length > 0 && window.Dropzone) {
      $("#message_input").after('
' + t('upload.image_area') + '
');
      $(".image-upload").dropzone({
        createImageThumbnails: false,
        maxFilesize: 2, // 2mb max filesize
        url: cforum.baseUrl + 'images.json',
        clickable: true,
        acceptedFiles: 'image/*',
        previewTemplate : '

',
        fallback: function() { },
        init: function() {
          this.on("success", function(file, rsp) {
            var $msg = $("#message_input");
            var selection = $msg.getSelection();
            var md = '![' + t('upload.alternative_text') + '](' + cforum.basePath + 'images/' + rsp.path + ')';

            var imgup = $('.image-upload');
            imgup.removeClass('loading');
            imgup.html(t('upload.image_area'));

            $msg.replaceSelection(md);

            window.setTimeout(function() {
              $msg.focus();
              $msg.setSelection(selection.start + 2, selection.start + 17);
            }, 0);
          });

          this.on('error', function(file, response) {
            var imgup = $('.image-upload');
            imgup.removeClass('loading');
            imgup.html(t('upload.image_area'));
            cforum.alert.error(response.error || t('internal_error'));
          });

          this.on('sending', function(file, xhr, formData) {
            var imgup = $('.image-upload');
            imgup.addClass('loading');
            imgup.html("");

            xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
          });
        }
      });
    }
  }
};

/* eof */
<|endoftext|>


<commit_before>'use strict';
/*jshint bitwise: false*/

function generateUUID(){
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c==='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
}

angular.module('chkrApp')
  .controller('ToDoCtrl', function ($scope, $http, Auth) {
    $scope.isLoggedIn = Auth.isLoggedIn;
    $scope.isAdmin = Auth.isAdmin;
    $scope.getCurrentUser = Auth.getCurrentUser;
    // $scope.todos = Auth.getCurrentUser().todos || [];
    // $scope.settings = Auth.getCurrentUser().settings || {};

    $http.get('/api/users/me').success(function(user){
        var todos = user.todos || [];
        $scope.settings = user.settings || {};
        for (var i=0;i< todos.length;i++){
            todos[i].editable = false;
            todos[i].calOpen = false;
        }
        // Make sure we start sorted
        if ($scope.settings.sortTasks) {$scope.sortTodos(todos, function(sorted){
            $scope.todos = sorted;
        });}
    });

    $scope.addTodo = function() {
    	if($scope.newTodo === ''){
    		return;
    	}
    	var nt = { name: $scope.newTodo, id: generateUUID(), done: false, color: '', date: new Date()};
        if ($scope.todos === undefined){
            $scope.todos = [];
        }
    	$scope.todos.push(nt);
        if ($scope.settings.sortTasks) {$scope.sortTodos(angular.noop);}
        $scope.newTodo = '';
    	$http.post('/api/users/' + Auth.getCurrentUser()._id + '/todos', {todos: $scope.todos})
    		.success(function(){
    			console.log('Added todo ' + nt.id);
    		});
    };

    $scope.removeTodo = function(todo) {
    	$scope.todos = $scope.todos.filter(function(e){
			return e.id !== todo.id;
		});
		if ($scope.todos === undefined){
			$scope.todos = [];
		}
		$http.post('api/users/' + Auth.getCurrentUser()._id + '/todos', {todos: $scope.todos})
			.success(function() {
				console.log('Removed Todo ' + todo.id);
			});
    };

    $scope.updateTodos = function() {

        $http.post('/api/users/' + Auth.getCurrentUser()._id + '/todos', {todos: $scope.todos})
            .success(function() {
                console.log('Updated todos.');
            });
    };

    $scope.sortTodos = function(todos, cb) {
        var dones = [];
        var undones = [];
        for(var i=0;i<todos.length;i++){
            if (todos[i].done) {
                dones.push(todos[i]);
            }
            else {
                undones.push(todos[i]);
            }
        }
        cb(undones.concat(dones));
    };

    $scope.today = function() {
        $scope.dt = new Date();
    };
    $scope.today();

    $scope.clear = function () {
        $scope.dt = null;
    };

    $scope.toggleMin = function() {
        $scope.minDate = $scope.minDate ? null : new Date();
    };
    $scope.toggleMin();

    $scope.dateOptions = {
        formatYear: 'yy',
        startingDay: 1
    };

    $scope.format = 'shortDate';

    $scope.sortableOptions = {
    	handle: '.handle',
    	containment: 'parent',
    	axis: 'y',
    	cursor: 'move',
    	opacity: 1,
    	revert: 150,
    	stop: $scope.updateTodos
    };

  });
<commit_msg>promise resolution for dailies<commit_after>'use strict';
/*jshint bitwise: false*/

function generateUUID(){
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c==='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
}

angular.module('chkrApp')
  .controller('ToDoCtrl', function ($scope, $http, Auth) {
    $scope.isLoggedIn = Auth.isLoggedIn;
    $scope.isAdmin = Auth.isAdmin;
    $scope.currentUser = Auth.getCurrentUser();

    $scope.currentUser.$promise.then(function(user){
        var todos = user.todos || [];
        $scope.settings = user.settings || {};
        for (var i=0;i< todos.length;i++){
            todos[i].editable = false;
            todos[i].calOpen = false;
        }
        // Make sure we start sorted
        if ($scope.settings.sortTasks) {$scope.sortTodos(todos, function(sorted){
            $scope.todos = sorted;
        });}
    });

    $scope.addTodo = function() {
    	if($scope.newTodo === ''){
    		return;
    	}
    	var nt = { name: $scope.newTodo, id: generateUUID(), done: false, color: '', date: new Date()};
        if ($scope.todos === undefined){
            $scope.todos = [];
        }
    	$scope.todos.push(nt);
        if ($scope.settings.sortTasks) {$scope.sortTodos(angular.noop);}
        $scope.newTodo = '';
    	$http.post('/api/users/' + Auth.getCurrentUser()._id + '/todos', {todos: $scope.todos})
    		.success(function(){
    			console.log('Added todo ' + nt.id);
    		});
    };

    $scope.removeTodo = function(todo) {
    	$scope.todos = $scope.todos.filter(function(e){
			return e.id !== todo.id;
		});
		if ($scope.todos === undefined){
			$scope.todos = [];
		}
		$http.post('api/users/' + Auth.getCurrentUser()._id + '/todos', {todos: $scope.todos})
			.success(function() {
				console.log('Removed Todo ' + todo.id);
			});
    };

    $scope.updateTodos = function() {

        $http.post('/api/users/' + Auth.getCurrentUser()._id + '/todos', {todos: $scope.todos})
            .success(function() {
                console.log('Updated todos.');
            });
    };

    $scope.sortTodos = function(todos, cb) {
        var dones = [];
        var undones = [];
        for(var i=0;i<todos.length;i++){
            if (todos[i].done) {
                dones.push(todos[i]);
            }
            else {
                undones.push(todos[i]);
            }
        }
        cb(undones.concat(dones));
    };

    $scope.today = function() {
        $scope.dt = new Date();
    };
    $scope.today();

    $scope.clear = function () {
        $scope.dt = null;
    };

    $scope.toggleMin = function() {
        $scope.minDate = $scope.minDate ? null : new Date();
    };
    $scope.toggleMin();

    $scope.dateOptions = {
        formatYear: 'yy',
        startingDay: 1
    };

    $scope.format = 'shortDate';

    $scope.sortableOptions = {
    	handle: '.handle',
    	containment: 'parent',
    	axis: 'y',
    	cursor: 'move',
    	opacity: 1,
    	revert: 150,
    	stop: $scope.updateTodos
    };

  });
<|endoftext|>