<commit_before>module.exports = {
  'env': {
    'es6': true
  },
  'parserOptions': {
    'ecmaVersion': 6,
    'sourceType': 'module',
    'ecmaFeatures': {
      'generators': false,
      'objectLiteralDuplicateProperties': false
    }
  },
  'plugins': [
    'import'
  ],
  'rules': {
    // enforces no braces where they can be omitted
    // http://eslint.org/docs/rules/arrow-body-style
    'arrow-body-style': [2, 'as-needed'],
    // require parens in arrow function arguments
    'arrow-parens': 0,
    // require space before/after arrow function's arrow
    // http://eslint.org/docs/rules/arrow-spacing
    'arrow-spacing': [2, { 'before': true, 'after': true }],
    // require trailing commas in multiline object literals
    'comma-dangle': [2, 'always-multiline'],
    // verify super() callings in constructors
    'constructor-super': 0,
    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,
    // disallow modifying variables of class declarations
    // http://eslint.org/docs/rules/no-class-assign
    'no-class-assign': 2,
    // disallow arrow functions where they could be confused with comparisons
    // http://eslint.org/docs/rules/no-confusing-arrow
    'no-confusing-arrow': [2, {
      'allowParens': true,
    }],
    // disallow modifying variables that are declared using const
    'no-const-assign': 2,
    // disallow duplicate class members
    // http://eslint.org/docs/rules/no-dupe-class-members
    'no-dupe-class-members': 2,
    // disallow importing from the same path more than once
    // http://eslint.org/docs/rules/no-duplicate-imports
    'no-duplicate-imports': 2,
    // disallow symbol constructor
    // http://eslint.org/docs/rules/no-new-symbol
    'no-new-symbol': 2,
    // disallow specific globals
    'no-restricted-globals': 0,
    // disallow specific imports
    // http://eslint.org/docs/rules/no-restricted-imports
    'no-restricted-imports': 0,
    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,
    // require let or const instead of var
    'no-var': 2,
    // disallow useless computed property keys
    // http://eslint.org/docs/rules/no-useless-computed-key
    'no-useless-computed-key': 2,
    // disallow unnecessary constructor
    // http://eslint.org/docs/rules/no-useless-constructor
    'no-useless-constructor': 2,
    // require method and property shorthand syntax for object literals
    // http://eslint.org/docs/rules/object-shorthand
    'object-shorthand': [2, 'always'],
    // suggest using arrow functions as callbacks
    'prefer-arrow-callback': [2, {
      'allowNamedFunctions': false,
      'allowUnboundThis': true,
    }],
    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': 2,
    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,
    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,
    // use rest parameters instead of arguments
    // http://eslint.org/docs/rules/prefer-rest-params
    'prefer-rest-params': 2,
    // suggest using template literals instead of string concatenation
    // http://eslint.org/docs/rules/prefer-template
    'prefer-template': 2,
    // disallow generator functions that do not have yield
    'require-yield': 0,
    // import sorting
    // http://eslint.org/docs/rules/sort-imports
    'sort-imports': 0,
    // enforce usage of spacing in template strings
    // http://eslint.org/docs/rules/template-curly-spacing
    'template-curly-spacing': 2,
    // enforce spacing around the * in yield* expressions
    // http://eslint.org/docs/rules/yield-star-spacing
    'yield-star-spacing': [2, 'after'],
    // disallow invalid exports, e.g. multiple defaults
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md
    'import/export': 2,
    // ensure default import coupled with default export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
    'import/default': 0,
    // Ensure consistent use of file extension within the import path
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
    // TODO: enable
    'import/extensions': [0, 'never'],
    // ensure named imports coupled with named exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
    'import/named': 0,
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md
    'import/namespace': 0,
    // Forbid the use of extraneous packages
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md
    // TODO: enable
    'import/no-extraneous-dependencies': [0, {
      'devDependencies': false,
      'optionalDependencies': false,
    }],
    // ensure imports point to files/modules that can be resolved
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
    'import/no-unresolved': [2, { 'commonjs': true }],
    // do not allow a default import name to match a named export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md
    // TODO: enable
    'import/no-named-as-default': 0,
    // disallow require()
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md
    'import/no-commonjs': 0,
    // disallow AMD require/define
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md
    // TODO: enable
    'import/no-amd': 0,
    // disallow non-import statements appearing before import statements
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md
    // TODO: enable?
    'import/imports-first': [0, 'absolute-first'],
    // disallow duplicate imports
    // TODO: enable
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
    'import/no-duplicates': 0,
    // disallow use of jsdoc-marked-deprecated imports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    'import/no-deprecated': 0,
    // disallow namespace imports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
    'import/no-namespace': 0,
    // warn on accessing default export property names that are also named exports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md
    'import/no-named-as-default-member': 0,
    // No Node.js builtin modules
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md
    'import/no-nodejs-modules': 0,
    // Enforce a convention in module import order
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
    // TODO: enable?
    'import/order': [0, {
      'groups': ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
      'newlines-between': 'never',
    }],
    // Require a newline after the last import/require in a group
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md
    // TODO: enable
    'import/newline-after-import': 0,
    // Forbid mutable exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md
    // TODO: enable
    'import/no-mutable-exports': 0,
  },
  'settings': {
    'import/resolver': {
      'node': {
        'extensions': ['.js', '.json']
      }
    }
  }
};
<commit_msg>[eslint config] [base] [minor] enable `import/no-amd`<commit_after>module.exports = {
  'env': {
    'es6': true
  },
  'parserOptions': {
    'ecmaVersion': 6,
    'sourceType': 'module',
    'ecmaFeatures': {
      'generators': false,
      'objectLiteralDuplicateProperties': false
    }
  },
  'plugins': [
    'import'
  ],
  'rules': {
    // enforces no braces where they can be omitted
    // http://eslint.org/docs/rules/arrow-body-style
    'arrow-body-style': [2, 'as-needed'],
    // require parens in arrow function arguments
    'arrow-parens': 0,
    // require space before/after arrow function's arrow
    // http://eslint.org/docs/rules/arrow-spacing
    'arrow-spacing': [2, { 'before': true, 'after': true }],
    // require trailing commas in multiline object literals
    'comma-dangle': [2, 'always-multiline'],
    // verify super() callings in constructors
    'constructor-super': 0,
    // enforce the spacing around the * in generator functions
    'generator-star-spacing': 0,
    // disallow modifying variables of class declarations
    // http://eslint.org/docs/rules/no-class-assign
    'no-class-assign': 2,
    // disallow arrow functions where they could be confused with comparisons
    // http://eslint.org/docs/rules/no-confusing-arrow
    'no-confusing-arrow': [2, {
      'allowParens': true,
    }],
    // disallow modifying variables that are declared using const
    'no-const-assign': 2,
    // disallow duplicate class members
    // http://eslint.org/docs/rules/no-dupe-class-members
    'no-dupe-class-members': 2,
    // disallow importing from the same path more than once
    // http://eslint.org/docs/rules/no-duplicate-imports
    'no-duplicate-imports': 2,
    // disallow symbol constructor
    // http://eslint.org/docs/rules/no-new-symbol
    'no-new-symbol': 2,
    // disallow specific globals
    'no-restricted-globals': 0,
    // disallow specific imports
    // http://eslint.org/docs/rules/no-restricted-imports
    'no-restricted-imports': 0,
    // disallow to use this/super before super() calling in constructors.
    'no-this-before-super': 0,
    // require let or const instead of var
    'no-var': 2,
    // disallow useless computed property keys
    // http://eslint.org/docs/rules/no-useless-computed-key
    'no-useless-computed-key': 2,
    // disallow unnecessary constructor
    // http://eslint.org/docs/rules/no-useless-constructor
    'no-useless-constructor': 2,
    // require method and property shorthand syntax for object literals
    // http://eslint.org/docs/rules/object-shorthand
    'object-shorthand': [2, 'always'],
    // suggest using arrow functions as callbacks
    'prefer-arrow-callback': [2, {
      'allowNamedFunctions': false,
      'allowUnboundThis': true,
    }],
    // suggest using of const declaration for variables that are never modified after declared
    'prefer-const': 2,
    // suggest using the spread operator instead of .apply()
    'prefer-spread': 0,
    // suggest using Reflect methods where applicable
    'prefer-reflect': 0,
    // use rest parameters instead of arguments
    // http://eslint.org/docs/rules/prefer-rest-params
    'prefer-rest-params': 2,
    // suggest using template literals instead of string concatenation
    // http://eslint.org/docs/rules/prefer-template
    'prefer-template': 2,
    // disallow generator functions that do not have yield
    'require-yield': 0,
    // import sorting
    // http://eslint.org/docs/rules/sort-imports
    'sort-imports': 0,
    // enforce usage of spacing in template strings
    // http://eslint.org/docs/rules/template-curly-spacing
    'template-curly-spacing': 2,
    // enforce spacing around the * in yield* expressions
    // http://eslint.org/docs/rules/yield-star-spacing
    'yield-star-spacing': [2, 'after'],
    // disallow invalid exports, e.g. multiple defaults
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md
    'import/export': 2,
    // ensure default import coupled with default export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
    'import/default': 0,
    // Ensure consistent use of file extension within the import path
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
    // TODO: enable
    'import/extensions': [0, 'never'],
    // ensure named imports coupled with named exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
    'import/named': 0,
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md
    'import/namespace': 0,
    // Forbid the use of extraneous packages
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md
    // TODO: enable
    'import/no-extraneous-dependencies': [0, {
      'devDependencies': false,
      'optionalDependencies': false,
    }],
    // ensure imports point to files/modules that can be resolved
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
    'import/no-unresolved': [2, { 'commonjs': true }],
    // do not allow a default import name to match a named export
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md
    // TODO: enable
    'import/no-named-as-default': 0,
    // disallow require()
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md
    'import/no-commonjs': 0,
    // disallow AMD require/define
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md
    'import/no-amd': 2,
    // disallow non-import statements appearing before import statements
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md
    // TODO: enable?
    'import/imports-first': [0, 'absolute-first'],
    // disallow duplicate imports
    // TODO: enable
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
    'import/no-duplicates': 0,
    // disallow use of jsdoc-marked-deprecated imports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
    'import/no-deprecated': 0,
    // disallow namespace imports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
    'import/no-namespace': 0,
    // warn on accessing default export property names that are also named exports
    // TODO: enable?
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md
    'import/no-named-as-default-member': 0,
    // No Node.js builtin modules
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md
    'import/no-nodejs-modules': 0,
    // Enforce a convention in module import order
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
    // TODO: enable?
    'import/order': [0, {
      'groups': ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
      'newlines-between': 'never',
    }],
    // Require a newline after the last import/require in a group
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md
    // TODO: enable
    'import/newline-after-import': 0,
    // Forbid mutable exports
    // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md
    // TODO: enable
    'import/no-mutable-exports': 0,
  },
  'settings': {
    'import/resolver': {
      'node': {
        'extensions': ['.js', '.json']
      }
    }
  }
};
<|endoftext|>


<commit_before>var AuthenticationInitializer = {

    name: 'authentication',
    before: 'simple-auth',
    after: 'registerTrailingLocationHistory',

    initialize: function (container) {
        window.ENV = window.ENV || {};
        window.ENV['simple-auth'] = {
            authenticationRoute: 'signin',
            routeAfterAuthentication: 'content',
            authorizer: 'simple-auth-authorizer:oauth2-bearer'
        };
        SimpleAuth.Session.reopen({
            user: function () {
                return container.lookup('store:main').find('user', 'me');
            }.property()
        });
        SimpleAuth.Authenticators.OAuth2.reopen({
            serverTokenEndpoint: '/ghost/api/v0.1/authentication/token',
            refreshAccessTokens: true,
            makeRequest: function (url, data) {
                data.client_id = 'ghost-admin';
                return this._super(url, data);
            }
        });
    }
};

export default AuthenticationInitializer;
<commit_msg>Update authentication endpoint for subdirectory<commit_after>import ghostPaths from 'ghost/utils/ghost-paths';

var Ghost = ghostPaths();

var AuthenticationInitializer = {

    name: 'authentication',
    before: 'simple-auth',
    after: 'registerTrailingLocationHistory',

    initialize: function (container) {
        window.ENV = window.ENV || {};
        window.ENV['simple-auth'] = {
            authenticationRoute: 'signin',
            routeAfterAuthentication: 'content',
            authorizer: 'simple-auth-authorizer:oauth2-bearer'
        };
        SimpleAuth.Session.reopen({
            user: function () {
                return container.lookup('store:main').find('user', 'me');
            }.property()
        });
        SimpleAuth.Authenticators.OAuth2.reopen({
            serverTokenEndpoint: Ghost.apiRoot + '/authentication/token',
            refreshAccessTokens: true,
            makeRequest: function (url, data) {
                data.client_id = 'ghost-admin';
                return this._super(url, data);
            }
        });
    }
};

export default AuthenticationInitializer;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var kanye = require("../../kanye");
var request = require("request");

// The main app can hit this when an SMS is received
app.get('/sms', function(req, res) {
    if (req.query.message.toLowerCase() != "reddit") {
        res.status(400).end();
        return;
    }

    request("http://reddit.com/top.json?limit=5", function(error, response, body) {
        console.log(body);
        var json = JSON.parse(body);

        var response = "";
        for (var x in json.data.children) {
            var child = json.data.children[x].data;
            var title = child.title;
            response += title + "\n";
        }

        console.log(response.length);
        kanye.sendMessage(req.query.number, response);
        res.status(200).end();
    });

    // kanye.sendMessage(req.query.number, "You're now browsing reddit!");
});

app.listen(3002);
<commit_msg>Add numbers to reddit posts<commit_after>var express = require('express');
var app = express();
var kanye = require("../../kanye");
var request = require("request");

// The main app can hit this when an SMS is received
app.get('/sms', function(req, res) {
    if (req.query.message.toLowerCase() != "reddit") {
        res.status(400).end();
        return;
    }

    request("http://reddit.com/top.json?limit=5", function(error, response, body) {
        console.log(body);
        var json = JSON.parse(body);

        var response = "";
        var num = 1;
        for (var x in json.data.children) {
            var child = json.data.children[x].data;
            var title = child.title;
            response += (num++) + ".) " + title + "\n";
        }

        console.log(response.length);
        kanye.sendMessage(req.query.number, response);
        res.status(200).end();
    });

    // kanye.sendMessage(req.query.number, "You're now browsing reddit!");
});

app.listen(3002);
<|endoftext|>


<commit_before>var path = require('path');
var argv = require('yargs').argv;

const coverage_reporters = [
  { type: 'text-summary' },
];
const reporters = [
 'spec',
 'coverage',
];
if (process.env.COVERALLS_REPO_TOKEN) {
  console.log('coveralls found');
  coverage_reporters.push( { type : 'lcov', dir : 'coverage' } );
  reporters.push('coveralls');
} else {
  console.log('coveralls NOT found');
  coverage_reporters.push( { type : 'html', dir : 'coverage', 'subdir' : '.' } );
}

module.exports = function (config) {
  config.set({
    browsers: ['PhantomJS'],
    coverageReporter: {
      reporters: coverage_reporters,
    },
    files: [
      './node_modules/phantomjs-polyfill/bind-polyfill.js',
      './node_modules/babel-polyfill/dist/polyfill.js',
      'tests.webpack.js',
    ],
    singleRun: !argv.watch,
    frameworks: [
      'mocha',
      'chai-sinon',
      'chai-as-promised',
      'chai'
    ],
    preprocessors: {
      'tests.webpack.js': ['webpack', 'sourcemap'],
    },
    reporters: reporters,
    webpack: {
      cache: true,
      devtool: 'inline-source-map',
      module: {
        preLoaders: [
          {
            test: /spec\.js$/,
            include: /src/,
            exclude: /(bower_components|node_modules)/,
            loader: 'babel',
            query: {
              cacheDirectory: true,
            },
          },
          {
            test: /\.js?$/,
            include: /src/,
            exclude: /(node_modules|bower_components|spec)/,
            loader: 'babel-istanbul',
            query: {
              cacheDirectory: true,
            },
          },
        ],
        loaders: [
          {
            test: /\.js$/,
            include: path.resolve(__dirname, '../src'),
            exclude: /(bower_components|node_modules|spec)/,
            loader: 'babel',
            query: {
              cacheDirectory: true,
            },
          },
        ],
      },
    },
  });
};
<commit_msg>Working with coveralls<commit_after>var path = require('path');
var argv = require('yargs').argv;

const coverage_reporters = [
  { type: 'text-summary' },
];
const reporters = [
 'spec',
 'coverage',
];
if (process.env.TRAVIS) {
  console.log('On Travis sending coveralls');
  coverage_reporters.push( { type : 'lcov', dir : 'coverage' } );
  reporters.push('coveralls');
} else {
  console.log('Not on Travis so not sending coveralls');
  coverage_reporters.push( { type : 'html', dir : 'coverage', 'subdir' : '.' } );
}

module.exports = function (config) {
  config.set({
    browsers: ['PhantomJS'],
    coverageReporter: {
      reporters: coverage_reporters,
    },
    files: [
      './node_modules/phantomjs-polyfill/bind-polyfill.js',
      './node_modules/babel-polyfill/dist/polyfill.js',
      'tests.webpack.js',
    ],
    singleRun: !argv.watch,
    frameworks: [
      'mocha',
      'chai-sinon',
      'chai-as-promised',
      'chai'
    ],
    preprocessors: {
      'tests.webpack.js': ['webpack', 'sourcemap'],
    },
    reporters: reporters,
    webpack: {
      cache: true,
      devtool: 'inline-source-map',
      module: {
        preLoaders: [
          {
            test: /spec\.js$/,
            include: /src/,
            exclude: /(bower_components|node_modules)/,
            loader: 'babel',
            query: {
              cacheDirectory: true,
            },
          },
          {
            test: /\.js?$/,
            include: /src/,
            exclude: /(node_modules|bower_components|spec)/,
            loader: 'babel-istanbul',
            query: {
              cacheDirectory: true,
            },
          },
        ],
        loaders: [
          {
            test: /\.js$/,
            include: path.resolve(__dirname, '../src'),
            exclude: /(bower_components|node_modules|spec)/,
            loader: 'babel',
            query: {
              cacheDirectory: true,
            },
          },
        ],
      },
    },
  });
};
<|endoftext|>


<commit_before>import { ReactiveVar } from 'meteor/reactive-var';
import { Session } from 'meteor/session';
import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/tap:i18n';
import _ from 'underscore';
import s from 'underscore.string';
import moment from 'moment';

import { DateFormat } from '../../../lib';
import { popover } from '../../../ui-utils';
import { templateVarHandler } from '../../../utils';
import { RoomRoles, UserRoles, Roles } from '../../../models';
import { settings } from '../../../settings';
import FullUser from '../../../models/client/models/FullUser';
import { getActions } from './userActions';
import './userInfo.html';

const shownActionsCount = 2;

const moreActions = function() {
	return (
		Template.instance().actions.get()
			.map((action) => (typeof action === 'function' ? action.call(this) : action))
			.filter((action) => action && (!action.condition || action.condition.call(this)))
			.slice(shownActionsCount)
	);
};

Template.userInfo.helpers({
	hideHeader() {
		return ['Template.adminUserInfo', 'adminUserInfo'].includes(Template.parentData(2).viewName);
	},

	moreActions,

	actions() {
		return Template.instance().actions.get()
			.map((action) => (typeof action === 'function' ? action.call(this) : action))
			.filter((action) => action && (!action.condition || action.condition.call(this)))
			.slice(0, shownActionsCount);
	},

	customField() {
		const sCustomFieldsToShow = settings.get('Accounts_CustomFieldsToShowInUserInfo').trim();
		const customFields = [];

		if (sCustomFieldsToShow) {
			const user = Template.instance().user.get();
			const userCustomFields = (user && user.customFields) || {};
			const listOfCustomFieldsToShow = JSON.parse(sCustomFieldsToShow);

			_.map(listOfCustomFieldsToShow, (el) => {
				let content = '';
				if (_.isObject(el)) {
					_.map(el, (key, label) => {
						const value = templateVarHandler(key, userCustomFields);
						if (value) {
							content = { label, value };
						}
					});
				} else {
					content = templateVarHandler(el, userCustomFields);
				}
				if (content) {
					customFields.push(content);
				}
			});
		}
		return customFields;
	},

	name() {
		const user = Template.instance().user.get();
		return user && user.name ? user.name : TAPi18n.__('Unnamed');
	},

	username() {
		const user = Template.instance().user.get();
		return user && user.username;
	},

	userStatus() {
		const user = Template.instance().user.get();
		const userStatus = Session.get(`user_${ user.username }_status`);
		return userStatus;
	},

	email() {
		const user = Template.instance().user.get();
		return user && user.emails && user.emails[0] && user.emails[0].address;
	},

	utc() {
		const user = Template.instance().user.get();
		if (user && user.utcOffset != null) {
			if (user.utcOffset > 0) {
				return `+${ user.utcOffset }`;
			}
			return user.utcOffset;
		}
	},

	lastLogin() {
		const user = Template.instance().user.get();
		if (user && user.lastLogin) {
			return moment(user.lastLogin).format('LLL');
		}
	},

	createdAt() {
		const user = Template.instance().user.get();
		if (user && user.createdAt) {
			return moment(user.createdAt).format('LLL');
		}
	},
	linkedinUsername() {
		const user = Template.instance().user.get();
		if (user && user.services && user.services.linkedin && user.services.linkedin.publicProfileUrl) {
			return s.strRight(user.services.linkedin.publicProfileUrl, '/in/');
		}
	},

	servicesMeteor() {
		const user = Template.instance().user.get();
		return user && user.services && user.services['meteor-developer'];
	},

	userTime() {
		const user = Template.instance().user.get();
		if (user && user.utcOffset != null) {
			return DateFormat.formatTime(Template.instance().now.get().utcOffset(user.utcOffset));
		}
	},

	user() {
		return Template.instance().user.get();
	},

	hasEmails() {
		return _.isArray(this.emails);
	},

	hasPhone() {
		return _.isArray(this.phone);
	},

	isLoading() {
		return Template.instance().loadingUserInfo.get();
	},

	editingUser() {
		return Template.instance().editingUser.get();
	},

	userToEdit() {
		const instance = Template.instance();
		const data = Template.currentData();
		return {
			user: instance.user.get(),
			back(username) {
				instance.editingUser.set();

				if (username != null) {
					const user = instance.user.get();
					if ((user != null ? user.username : undefined) !== username) {
						data.username = username;
						return instance.loadedUsername.set(username);
					}
				}
			},
		};
	},

	roleTags() {
		const user = Template.instance().user.get();
		if (!user || !user._id) {
			return;
		}
		const userRoles = UserRoles.findOne(user._id) || {};
		const roomRoles = RoomRoles.findOne({ 'u._id': user._id, rid: Session.get('openedRoom') }) || {};
		const roles = _.union(userRoles.roles || [], roomRoles.roles || []);
		return roles.length && Roles.find({ _id: { $in: roles }, description: { $exists: 1 } }, { fields: { description: 1 } });
	},

	shouldDisplayReason() {
		const user = Template.instance().user.get();
		return settings.get('Accounts_ManuallyApproveNewUsers') && user.active === false && user.reason;
	},
});

Template.userInfo.events({
	'click .js-more'(e, instance) {
		const actions = moreActions.call(this);
		const groups = [];
		const columns = [];
		const admin = actions.filter((actions) => actions.group === 'admin');
		const others = actions.filter((action) => !action.group);
		const channel = actions.filter((actions) => actions.group === 'channel');
		if (others.length) {
			groups.push({ items: others });
		}
		if (channel.length) {
			groups.push({ items: channel });
		}

		if (admin.length) {
			groups.push({ items: admin });
		}
		columns[0] = { groups };

		$(e.currentTarget).blur();
		e.preventDefault();
		e.stopPropagation();
		const config = {
			columns,
			data: {
				rid: this._id,
				username: instance.data.username,
				instance,
			},
			currentTarget: e.currentTarget,
			offsetVertical: e.currentTarget.clientHeight + 10,
		};
		popover.open(config);
	},
	'click .js-action'(e) {
		return this.action && this.action.apply(this, [e, { instance: Template.instance() }]);
	},
	'click .js-close-info'(e, instance) {
		return instance.clear();
	},
	'click .js-back'(e, instance) {
		return instance.clear();
	},
});

Template.userInfo.onCreated(function() {
	this.now = new ReactiveVar(moment());
	this.user = new ReactiveVar();
	this.actions = new ReactiveVar();

	this.autorun(() => {
		const user = this.user.get();
		if (!user) {
			this.actions.set([]);
			return;
		}
		const actions = getActions({
			user,
			hideAdminControls: this.data.hideAdminControls,
			directActions: this.data.showAll,
		});
		this.actions.set(actions);
	});
	this.editingUser = new ReactiveVar();
	this.loadingUserInfo = new ReactiveVar(true);
	this.loadedUsername = new ReactiveVar();
	this.tabBar = Template.currentData().tabBar;
	this.nowInterval = setInterval(() => this.now.set(moment()), 30000);

	this.autorun(() => {
		const username = this.loadedUsername.get();

		if (username == null) {
			this.loadingUserInfo.set(false);
			return;
		}

		this.loadingUserInfo.set(true);

		return this.subscribe('fullUserData', username, 1, () => this.loadingUserInfo.set(false));
	});

	this.autorun(() => {
		const data = Template.currentData();
		if (data.clear != null) {
			this.clear = data.clear;
		}
	});

	this.autorun(() => {
		const data = Template.currentData();
		const user = this.user.get();
		return this.loadedUsername.set((user != null ? user.username : undefined) || (data != null ? data.username : undefined));
	});

	return this.autorun(() => {
		let filter;
		const data = Template.currentData();
		if (data && data.username != null) {
			filter = { username: data.username };
		} else if (data && data._id != null) {
			filter = { _id: data._id };
		}
		const user = FullUser.findOne(filter);

		return this.user.set(user);
	});
});

Template.userInfo.onDestroyed(function() {
	clearInterval(this.nowInterval);
});
<commit_msg>[FIX] User status information on User Info panel (#14763)<commit_after>import { ReactiveVar } from 'meteor/reactive-var';
import { Session } from 'meteor/session';
import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/tap:i18n';
import _ from 'underscore';
import s from 'underscore.string';
import moment from 'moment';

import { DateFormat } from '../../../lib';
import { popover } from '../../../ui-utils';
import { templateVarHandler } from '../../../utils';
import { RoomRoles, UserRoles, Roles } from '../../../models';
import { settings } from '../../../settings';
import FullUser from '../../../models/client/models/FullUser';
import { getActions } from './userActions';
import './userInfo.html';

const shownActionsCount = 2;

const moreActions = function() {
	return (
		Template.instance().actions.get()
			.map((action) => (typeof action === 'function' ? action.call(this) : action))
			.filter((action) => action && (!action.condition || action.condition.call(this)))
			.slice(shownActionsCount)
	);
};

Template.userInfo.helpers({
	hideHeader() {
		return ['Template.adminUserInfo', 'adminUserInfo'].includes(Template.parentData(2).viewName);
	},

	moreActions,

	actions() {
		return Template.instance().actions.get()
			.map((action) => (typeof action === 'function' ? action.call(this) : action))
			.filter((action) => action && (!action.condition || action.condition.call(this)))
			.slice(0, shownActionsCount);
	},

	customField() {
		const sCustomFieldsToShow = settings.get('Accounts_CustomFieldsToShowInUserInfo').trim();
		const customFields = [];

		if (sCustomFieldsToShow) {
			const user = Template.instance().user.get();
			const userCustomFields = (user && user.customFields) || {};
			const listOfCustomFieldsToShow = JSON.parse(sCustomFieldsToShow);

			_.map(listOfCustomFieldsToShow, (el) => {
				let content = '';
				if (_.isObject(el)) {
					_.map(el, (key, label) => {
						const value = templateVarHandler(key, userCustomFields);
						if (value) {
							content = { label, value };
						}
					});
				} else {
					content = templateVarHandler(el, userCustomFields);
				}
				if (content) {
					customFields.push(content);
				}
			});
		}
		return customFields;
	},

	name() {
		const user = Template.instance().user.get();
		return user && user.name ? user.name : TAPi18n.__('Unnamed');
	},

	username() {
		const user = Template.instance().user.get();
		return user && user.username;
	},

	userStatus() {
		const user = Template.instance().user.get();
		const userStatus = Session.get(`user_${ user.username }_status`);
		return userStatus || 'offline';
	},

	email() {
		const user = Template.instance().user.get();
		return user && user.emails && user.emails[0] && user.emails[0].address;
	},

	utc() {
		const user = Template.instance().user.get();
		if (user && user.utcOffset != null) {
			if (user.utcOffset > 0) {
				return `+${ user.utcOffset }`;
			}
			return user.utcOffset;
		}
	},

	lastLogin() {
		const user = Template.instance().user.get();
		if (user && user.lastLogin) {
			return moment(user.lastLogin).format('LLL');
		}
	},

	createdAt() {
		const user = Template.instance().user.get();
		if (user && user.createdAt) {
			return moment(user.createdAt).format('LLL');
		}
	},
	linkedinUsername() {
		const user = Template.instance().user.get();
		if (user && user.services && user.services.linkedin && user.services.linkedin.publicProfileUrl) {
			return s.strRight(user.services.linkedin.publicProfileUrl, '/in/');
		}
	},

	servicesMeteor() {
		const user = Template.instance().user.get();
		return user && user.services && user.services['meteor-developer'];
	},

	userTime() {
		const user = Template.instance().user.get();
		if (user && user.utcOffset != null) {
			return DateFormat.formatTime(Template.instance().now.get().utcOffset(user.utcOffset));
		}
	},

	user() {
		return Template.instance().user.get();
	},

	hasEmails() {
		return _.isArray(this.emails);
	},

	hasPhone() {
		return _.isArray(this.phone);
	},

	isLoading() {
		return Template.instance().loadingUserInfo.get();
	},

	editingUser() {
		return Template.instance().editingUser.get();
	},

	userToEdit() {
		const instance = Template.instance();
		const data = Template.currentData();
		return {
			user: instance.user.get(),
			back(username) {
				instance.editingUser.set();

				if (username != null) {
					const user = instance.user.get();
					if ((user != null ? user.username : undefined) !== username) {
						data.username = username;
						return instance.loadedUsername.set(username);
					}
				}
			},
		};
	},

	roleTags() {
		const user = Template.instance().user.get();
		if (!user || !user._id) {
			return;
		}
		const userRoles = UserRoles.findOne(user._id) || {};
		const roomRoles = RoomRoles.findOne({ 'u._id': user._id, rid: Session.get('openedRoom') }) || {};
		const roles = _.union(userRoles.roles || [], roomRoles.roles || []);
		return roles.length && Roles.find({ _id: { $in: roles }, description: { $exists: 1 } }, { fields: { description: 1 } });
	},

	shouldDisplayReason() {
		const user = Template.instance().user.get();
		return settings.get('Accounts_ManuallyApproveNewUsers') && user.active === false && user.reason;
	},
});

Template.userInfo.events({
	'click .js-more'(e, instance) {
		const actions = moreActions.call(this);
		const groups = [];
		const columns = [];
		const admin = actions.filter((actions) => actions.group === 'admin');
		const others = actions.filter((action) => !action.group);
		const channel = actions.filter((actions) => actions.group === 'channel');
		if (others.length) {
			groups.push({ items: others });
		}
		if (channel.length) {
			groups.push({ items: channel });
		}

		if (admin.length) {
			groups.push({ items: admin });
		}
		columns[0] = { groups };

		$(e.currentTarget).blur();
		e.preventDefault();
		e.stopPropagation();
		const config = {
			columns,
			data: {
				rid: this._id,
				username: instance.data.username,
				instance,
			},
			currentTarget: e.currentTarget,
			offsetVertical: e.currentTarget.clientHeight + 10,
		};
		popover.open(config);
	},
	'click .js-action'(e) {
		return this.action && this.action.apply(this, [e, { instance: Template.instance() }]);
	},
	'click .js-close-info'(e, instance) {
		return instance.clear();
	},
	'click .js-back'(e, instance) {
		return instance.clear();
	},
});

Template.userInfo.onCreated(function() {
	this.now = new ReactiveVar(moment());
	this.user = new ReactiveVar();
	this.actions = new ReactiveVar();

	this.autorun(() => {
		const user = this.user.get();
		if (!user) {
			this.actions.set([]);
			return;
		}
		const actions = getActions({
			user,
			hideAdminControls: this.data.hideAdminControls,
			directActions: this.data.showAll,
		});
		this.actions.set(actions);
	});
	this.editingUser = new ReactiveVar();
	this.loadingUserInfo = new ReactiveVar(true);
	this.loadedUsername = new ReactiveVar();
	this.tabBar = Template.currentData().tabBar;
	this.nowInterval = setInterval(() => this.now.set(moment()), 30000);

	this.autorun(() => {
		const username = this.loadedUsername.get();

		if (username == null) {
			this.loadingUserInfo.set(false);
			return;
		}

		this.loadingUserInfo.set(true);

		return this.subscribe('fullUserData', username, 1, () => this.loadingUserInfo.set(false));
	});

	this.autorun(() => {
		const data = Template.currentData();
		if (data.clear != null) {
			this.clear = data.clear;
		}
	});

	this.autorun(() => {
		const data = Template.currentData();
		const user = this.user.get();
		return this.loadedUsername.set((user != null ? user.username : undefined) || (data != null ? data.username : undefined));
	});

	return this.autorun(() => {
		let filter;
		const data = Template.currentData();
		if (data && data.username != null) {
			filter = { username: data.username };
		} else if (data && data._id != null) {
			filter = { _id: data._id };
		}
		const user = FullUser.findOne(filter);

		return this.user.set(user);
	});
});

Template.userInfo.onDestroyed(function() {
	clearInterval(this.nowInterval);
});
<|endoftext|>


<commit_before>var Logger = require('js-logger'),
    extend = require('underscore').extend,
    clone  = require('underscore').clone,
    EventEmitter  = require('events').EventEmitter,
    AppDispatcher = require('../dispatcher/dispatcher'),
    CurrentServiceStore = require('../stores/current-service'),
    Payload   = require('../constants/constants').Payload,
    ActionTypes   = require('../constants/constants').ActionTypes;

var state = {};

function update(id, data) {
  Logger.debug('NowPlaying update', id, data)
  state[id] = data;
}

var Store = extend(new EventEmitter(), {
  get: function (id) {
    if (state[id]) {
      return clone(state[id]);
    }
  },
  emitChange: function (id) {
    this.emit('change', id);
  },
  addChangeListener: function (callback) {
    this.on('change', callback);
  }
});

Store.dispatchToken = AppDispatcher.register(function (payload) {
  var source = payload.source,
      action = payload.action;

  switch(action.type) {
    case ActionTypes.RECEIVE_INITIAL_STATE:
      AppDispatcher.waitFor([CurrentServiceStore.dispatchToken]);
      Logger.debug('NowPlaying', action.type, action.state);
      if (action.state.current && action.state.current.nowPlaying) {
        update(action.state.current.id, action.state.current.nowPlaying);
        Store.emitChange(action.state.current.id);
      }
      break;
    case ActionTypes.SERVICE:
      Logger.debug('NowPlaying: ', action.type, action.state);
      if (source === Payload.SERVER_ACTION && action.state.topic === 'service.changed') {
        AppDispatcher.waitFor([CurrentServiceStore.dispatchToken]);
        Logger.debug('NowPlaying: SERVER', action.type, action.state);
        if (action.state.data && action.state.data.nowPlaying) {
          update(action.state.data.id, action.state.data.nowPlaying);
          Store.emitChange(action.state.data.id);
        }
      }
      break;
    case ActionTypes.NOW_PLAYING:
      Logger.debug('NowPlaying: ', action.type, action.state);
      if (source === Payload.SERVER_ACTION) {
        Logger.debug('NowPlaying: SERVER', action.type, action.state);
        if (action.state.service && action.state.data) {
          update(action.state.service, action.state.data);
          Store.emitChange(action.state.service);
        }
      }
      break;
  }
});

module.exports = Store;<commit_msg>Ensure NowPlaying {} is converted to null<commit_after>var Logger = require('js-logger'),
    extend = require('underscore').extend,
    clone  = require('underscore').clone,
    isEmpty = require('underscore').isEmpty,
    EventEmitter  = require('events').EventEmitter,
    AppDispatcher = require('../dispatcher/dispatcher'),
    CurrentServiceStore = require('../stores/current-service'),
    Payload   = require('../constants/constants').Payload,
    ActionTypes   = require('../constants/constants').ActionTypes;

var state = {};

function update(id, data) {
  Logger.debug('NowPlaying update', id, data);
  state[id] = isEmpty(data) ? null : data;
}

var Store = extend(new EventEmitter(), {
  get: function (id) {
    if (state[id]) {
      return clone(state[id]);
    }
  },
  emitChange: function (id) {
    this.emit('change', id);
  },
  addChangeListener: function (callback) {
    this.on('change', callback);
  }
});

Store.dispatchToken = AppDispatcher.register(function (payload) {
  var source = payload.source,
      action = payload.action;

  switch(action.type) {
    case ActionTypes.RECEIVE_INITIAL_STATE:
      AppDispatcher.waitFor([CurrentServiceStore.dispatchToken]);
      Logger.debug('NowPlaying', action.type, action.state);
      if (action.state.current && action.state.current.nowPlaying) {
        update(action.state.current.id, action.state.current.nowPlaying);
        Store.emitChange(action.state.current.id);
      }
      break;
    case ActionTypes.SERVICE:
      Logger.debug('NowPlaying: ', action.type, action.state);
      if (source === Payload.SERVER_ACTION && action.state.topic === 'service.changed') {
        AppDispatcher.waitFor([CurrentServiceStore.dispatchToken]);
        Logger.debug('NowPlaying: SERVER', action.type, action.state);
        if (action.state.data && action.state.data.nowPlaying) {
          update(action.state.data.id, action.state.data.nowPlaying);
          Store.emitChange(action.state.data.id);
        }
      }
      break;
    case ActionTypes.NOW_PLAYING:
      Logger.debug('NowPlaying: ', action.type, action.state);
      if (source === Payload.SERVER_ACTION) {
        Logger.debug('NowPlaying: SERVER', action.type, action.state);
        if (action.state.service && action.state.data) {
          update(action.state.service, action.state.data);
          Store.emitChange(action.state.service);
        }
      }
      break;
  }
});

module.exports = Store;<|endoftext|>


<commit_before>(function ($) {

  // this 'complete' function is not currently used
  Drupal.behaviors.ows_civi_complete = {
    attach: function (context, settings) {
      $('#civi_email_result > span').html('Thanks for signing up!').css({padding: '5px', backgroundColor: '#2F5', borderRadius: '10px', marginTop: '5px', textAlign: 'center'});
      setTimeout(function() {
        $('#civi_email_result > span').fadeOut('slow');
      }, 5000);
    }
  };

  // send an email address to civi
  Drupal.behaviors.ows_civi_post = {
    attach: function (context, settings) {
      $('div.newsletter-email-submit-button input.form-submit', context).click(function() {
        var email = $('div.newsletter-email input#email-Primary').val();
        if (email) {
          // send the data to civi
          var profileId = 26;
          var groupId = 14;
          var url = 'http://contribute.occupywallstreet.net/civicrm/profile/create?gid=' + profileId + '&reset=1';

          var data = {
            'postURL': '',
            'cancelURL': '',
            'add_to_group' : groupId,
            'email-Primary' : email,
            '_qf_default' : '',
            '_qf_Edit_next' : ''
          };
          $.ajax({
            'url': url,
            'data': data,
            'type': 'POST',
            //'complete': ows_civi_complete
          });

          $('div.newsletter-email input#email-Primary').val('Thanks!');

          return false;
        }
      });
    }
  };
})(jQuery);
<commit_msg>added email validation to civi form, need to test<commit_after>(function ($) {

  // this 'complete' function is not currently used
  Drupal.behaviors.ows_civi_complete = {
    attach: function (context, settings) {
      $('#civi_email_result > span').html('Thanks for signing up!').css({padding: '5px', backgroundColor: '#2F5', borderRadius: '10px', marginTop: '5px', textAlign: 'center'});
      setTimeout(function() {
        $('#civi_email_result > span').fadeOut('slow');
      }, 5000);
    }
  };

  // send an email address to civi
  Drupal.behaviors.ows_civi_post = {
    attach: function (context, settings) {
      $('div.newsletter-email-submit-button input.form-submit', context).click(function() {
        var email = $('div.newsletter-email input#email-Primary').val();

				//validate
				if( !email.test( /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i ) ){
					alert("Please enter a valid email address.");
					return false;
				}

				if (email) {
          // send the data to civi
          var profileId = 26;
          var groupId = 14;
          var url = 'http://contribute.occupywallstreet.net/civicrm/profile/create?gid=' + profileId + '&reset=1';

          var data = {
            'postURL': '',
            'cancelURL': '',
            'add_to_group' : groupId,
            'email-Primary' : email,
            '_qf_default' : '',
            '_qf_Edit_next' : ''
          };
          $.ajax({
            'url': url,
            'data': data,
            'type': 'POST',
            //'complete': ows_civi_complete
          });

          $('div.newsletter-email input#email-Primary').val('Thanks for signing up!');

          return false;
        }
      });
    }
  };
})(jQuery);
<|endoftext|>


<commit_before>// Sample app.
console.log("Sample App");
console.log("process.argv", process.argv);
console.log("");
<commit_msg>Express app example<commit_after>// Sample app.
console.log("Sample App");
console.log("process.argv", process.argv);
console.log("");

var express = require("express");
var app = express();

app.get("/", function(req, res) {
  res.send("Hello World!");
});

const PORT = 5000;
app.listen(PORT, function() {
  console.log("PORT", PORT);
})
<|endoftext|>


<commit_before>import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SPELLS from 'common/SPELLS';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import StatisticBox from "Main/StatisticBox";
import SpellIcon from "common/SpellIcon";
import SpellLink from "common/SpellLink";

const debug = false;

const TITANS_THUNDER_USE_REGARDLESS_THRESHHOLD = 30;

class TitansThunder extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    spellUsable: SpellUsable,
  };

  goodTTCasts = 0;
  badTTCasts = 0;
  _currentStacks = 0;
  totalTTCasts = 0;
  stacksOnTTCast = 0;
  shouldHaveSavedTT = 0;
  weirdCast = 0;
  damage = 0;

  on_initialized() {
    this.active = this.combatants.selected.traitsBySpellId[SPELLS.TITANS_THUNDER.id];
  }

  on_initialized() {
    this.active = this.combatants.selected.traitsBySpellId[SPELLS.TITANS_THUNDER.id] > 0;
  }

  on_toPlayer_applybuff(event) {
    const buffId = event.ability.guid;
    if (buffId !== SPELLS.DIRE_BEAST_BUFF.id) {
      return;
    }
    this._currentStacks += 1;
  }

  on_toPlayer_removebuff(event) {
    const buffId = event.ability.guid;
    if (buffId !== SPELLS.DIRE_BEAST_BUFF.id) {
      return;
    }
    this._currentStacks -= 1;
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.TITANS_THUNDER.id) {
      return;
    }
    debug && console.log(`stacks:`, this._currentStacks);
    this.totalTTCasts += 1;
    const bestialWrathIsOnCooldown = this.spellUsable.isOnCooldown(SPELLS.BESTIAL_WRATH.id);
    if (bestialWrathIsOnCooldown) {
      if (!this.combatants.selected.hasBuff(SPELLS.BESTIAL_WRATH.id) && this.spellUsable.cooldownRemaining(SPELLS.BESTIAL_WRATH.id) < TITANS_THUNDER_USE_REGARDLESS_THRESHHOLD) {
        this.shouldHaveSavedTT += 1;
        return;
      } else if (!this.combatants.selected.hasBuff(SPELLS.BESTIAL_WRATH.id) && (this.spellUsable.cooldownRemaining(SPELLS.BESTIAL_WRATH.id) > TITANS_THUNDER_USE_REGARDLESS_THRESHHOLD)) {
        this.goodTTCasts += 1;
        return;
      }
    }
    if (!this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id)) {
      if (this.combatants.selected.hasBuff(SPELLS.DIRE_BEAST_BUFF.id)) {
        this.goodTTCasts += 1;
        this.stacksOnTTCast += this._currentStacks;
      } else {
        this.badTTCasts += 1;
      }
    } else {
      if (this.combatants.selected.hasBuff(SPELLS.BESTIAL_WRATH.id)) {
        debug && console.log(`in good tt casts`);
        this.goodTTCasts += 1;
      } else {
        this.badTTCasts += 1;
      }
    }

    debug && console.log('good tt casts:', this.goodTTCasts, ' and bad tt casts: ', this.badTTCasts, ' and total casts is: ', this.totalTTCasts, ' and weird casts: ', this.weirdCast);
  }

  on_byPlayerPet_damage(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.TITANS_THUNDER_DAMAGE.id) {
      return;
    }
    this.damage += event.amount;
  }

  statistic() {
    let tooltipText = `You cast Titan's Thunder a total of ${this.totalTTCasts} times.`;
    tooltipText += this.badTTCasts + this.shouldHaveSavedTT > 0 ? `<ul>` : ``;
    tooltipText += this.badTTCasts > 0 && !this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id) ? `<li>You had ${this.badTTCasts} bad cast(s) of Titan's Thunder. Bad casts indicate that Titan's Thunder was used without any Dire Beasts up.</li>` : ``;
    tooltipText += this.badTTCasts > 0 && this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id) ? `<li>You had ${this.badTTCasts} bad cast(s) of Titan's Thunder. Bad casts indicate that Titan's Thunder was used without Bestial Wrath up.</li>` : ``;
    tooltipText += this.shouldHaveSavedTT > 0 ? `
You cast Titan's Thunder ${this.shouldHaveSavedTT} times where you should have delayed casting it, this occurs when you cast Titan's Thunder when there is less than 30 seconds remaning on Bestial Wrath cooldown.
` : ``;
    tooltipText += this.badTTCasts + this.shouldHaveSavedTT > 0 ? `</ul>` : ``;

    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.TITANS_THUNDER.id} />}
        value={(

            {this.goodTTCasts}{'  '}
            <SpellIcon
              id={SPELLS.TITANS_THUNDER.id}
              style={{
                height: '1.3em',
                marginTop: '-.1em',
              }}
            />

            {this.badTTCasts + this.shouldHaveSavedTT}{'  '}
            <SpellIcon
              id={SPELLS.TITANS_THUNDER.id}
              style={{
                height: '1.3em',
                marginTop: '-.1em',
                filter: 'grayscale(100%)',
              }}
            />

        )}
        label={`Titan's Thunder`}
        tooltip={tooltipText}
      />
    );
  }
  subStatistic() {
    return (

          <SpellLink id={SPELLS.TITANS_THUNDER.id}>
            <SpellIcon id={SPELLS.TITANS_THUNDER.id} noLink /> Titan's Thunder
          </SpellLink>

          {(this.owner.formatItemDamageDone(this.damage))}

    );
  }
  suggestions(when) {
    when(this.badTTCasts).isGreaterThan(0)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(Don't cast <SpellLink id={SPELLS.TITANS_THUNDER.id} /> without <SpellLink id={SPELLS.DIRE_BEAST.id} /> up, or if using <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id} /> without <SpellLink id={SPELLS.BESTIAL_WRATH.id} /> up.)
          .icon(SPELLS.TITANS_THUNDER.icon)
          .actual(`You cast Titan's Thunder ${this.badTTCasts} times without Dire Beasts up, or if using Dire Frenzy without Bestial Wrath up.`)
          .recommended(`${recommended} is recommended`)
          .major(recommended);
      });
    when(this.shouldHaveSavedTT).isGreaterThan(0)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(Don't cast <SpellLink id={SPELLS.TITANS_THUNDER.id} /> when there is less than 30 seconds cooldown remaining on <SpellLink id={SPELLS.BESTIAL_WRATH.id} />.)
          .icon(SPELLS.TITANS_THUNDER.icon)
          .actual(`You cast Titan's Thunder ${this.badTTCasts} times when there was less than 30 seconds cooldown on Bestial Wrath`)
          .recommended(`${recommended} is recommended`)
          .major(recommended);
      });
  }

}

export default TitansThunder;
<commit_msg>fixes double init<commit_after>import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SPELLS from 'common/SPELLS';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import StatisticBox from "Main/StatisticBox";
import SpellIcon from "common/SpellIcon";
import SpellLink from "common/SpellLink";

const debug = false;

const TITANS_THUNDER_USE_REGARDLESS_THRESHHOLD = 30;

class TitansThunder extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    spellUsable: SpellUsable,
  };

  goodTTCasts = 0;
  badTTCasts = 0;
  _currentStacks = 0;
  totalTTCasts = 0;
  stacksOnTTCast = 0;
  shouldHaveSavedTT = 0;
  weirdCast = 0;
  damage = 0;

  on_initialized() {
    this.active = this.combatants.selected.traitsBySpellId[SPELLS.TITANS_THUNDER.id];
  }

  on_toPlayer_applybuff(event) {
    const buffId = event.ability.guid;
    if (buffId !== SPELLS.DIRE_BEAST_BUFF.id) {
      return;
    }
    this._currentStacks += 1;
  }

  on_toPlayer_removebuff(event) {
    const buffId = event.ability.guid;
    if (buffId !== SPELLS.DIRE_BEAST_BUFF.id) {
      return;
    }
    this._currentStacks -= 1;
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.TITANS_THUNDER.id) {
      return;
    }
    debug && console.log(`stacks:`, this._currentStacks);
    this.totalTTCasts += 1;
    const bestialWrathIsOnCooldown = this.spellUsable.isOnCooldown(SPELLS.BESTIAL_WRATH.id);
    if (bestialWrathIsOnCooldown) {
      if (!this.combatants.selected.hasBuff(SPELLS.BESTIAL_WRATH.id) && this.spellUsable.cooldownRemaining(SPELLS.BESTIAL_WRATH.id) < TITANS_THUNDER_USE_REGARDLESS_THRESHHOLD) {
        this.shouldHaveSavedTT += 1;
        return;
      } else if (!this.combatants.selected.hasBuff(SPELLS.BESTIAL_WRATH.id) && (this.spellUsable.cooldownRemaining(SPELLS.BESTIAL_WRATH.id) > TITANS_THUNDER_USE_REGARDLESS_THRESHHOLD)) {
        this.goodTTCasts += 1;
        return;
      }
    }
    if (!this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id)) {
      if (this.combatants.selected.hasBuff(SPELLS.DIRE_BEAST_BUFF.id)) {
        this.goodTTCasts += 1;
        this.stacksOnTTCast += this._currentStacks;
      } else {
        this.badTTCasts += 1;
      }
    } else {
      if (this.combatants.selected.hasBuff(SPELLS.BESTIAL_WRATH.id)) {
        debug && console.log(`in good tt casts`);
        this.goodTTCasts += 1;
      } else {
        this.badTTCasts += 1;
      }
    }

    debug && console.log('good tt casts:', this.goodTTCasts, ' and bad tt casts: ', this.badTTCasts, ' and total casts is: ', this.totalTTCasts, ' and weird casts: ', this.weirdCast);
  }

  on_byPlayerPet_damage(event) {
    const spellId = event.ability.guid;
    if (spellId !== SPELLS.TITANS_THUNDER_DAMAGE.id) {
      return;
    }
    this.damage += event.amount;
  }

  statistic() {
    let tooltipText = `You cast Titan's Thunder a total of ${this.totalTTCasts} times.`;
    tooltipText += this.badTTCasts + this.shouldHaveSavedTT > 0 ? `<ul>` : ``;
    tooltipText += this.badTTCasts > 0 && !this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id) ? `<li>You had ${this.badTTCasts} bad cast(s) of Titan's Thunder. Bad casts indicate that Titan's Thunder was used without any Dire Beasts up.</li>` : ``;
    tooltipText += this.badTTCasts > 0 && this.combatants.selected.hasTalent(SPELLS.DIRE_FRENZY_TALENT.id) ? `<li>You had ${this.badTTCasts} bad cast(s) of Titan's Thunder. Bad casts indicate that Titan's Thunder was used without Bestial Wrath up.</li>` : ``;
    tooltipText += this.shouldHaveSavedTT > 0 ? `
You cast Titan's Thunder ${this.shouldHaveSavedTT} times where you should have delayed casting it, this occurs when you cast Titan's Thunder when there is less than 30 seconds remaning on Bestial Wrath cooldown.
` : ``;
    tooltipText += this.badTTCasts + this.shouldHaveSavedTT > 0 ? `</ul>` : ``;

    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.TITANS_THUNDER.id} />}
        value={(

            {this.goodTTCasts}{'  '}
            <SpellIcon
              id={SPELLS.TITANS_THUNDER.id}
              style={{
                height: '1.3em',
                marginTop: '-.1em',
              }}
            />

            {this.badTTCasts + this.shouldHaveSavedTT}{'  '}
            <SpellIcon
              id={SPELLS.TITANS_THUNDER.id}
              style={{
                height: '1.3em',
                marginTop: '-.1em',
                filter: 'grayscale(100%)',
              }}
            />

        )}
        label={`Titan's Thunder`}
        tooltip={tooltipText}
      />
    );
  }
  subStatistic() {
    return (

          <SpellLink id={SPELLS.TITANS_THUNDER.id}>
            <SpellIcon id={SPELLS.TITANS_THUNDER.id} noLink /> Titan's Thunder
          </SpellLink>

          {(this.owner.formatItemDamageDone(this.damage))}

    );
  }
  suggestions(when) {
    when(this.badTTCasts).isGreaterThan(0)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(Don't cast <SpellLink id={SPELLS.TITANS_THUNDER.id} /> without <SpellLink id={SPELLS.DIRE_BEAST.id} /> up, or if using <SpellLink id={SPELLS.DIRE_FRENZY_TALENT.id} /> without <SpellLink id={SPELLS.BESTIAL_WRATH.id} /> up.)
          .icon(SPELLS.TITANS_THUNDER.icon)
          .actual(`You cast Titan's Thunder ${this.badTTCasts} times without Dire Beasts up, or if using Dire Frenzy without Bestial Wrath up.`)
          .recommended(`${recommended} is recommended`)
          .major(recommended);
      });
    when(this.shouldHaveSavedTT).isGreaterThan(0)
      .addSuggestion((suggest, actual, recommended) => {
        return suggest(Don't cast <SpellLink id={SPELLS.TITANS_THUNDER.id} /> when there is less than 30 seconds cooldown remaining on <SpellLink id={SPELLS.BESTIAL_WRATH.id} />.)
          .icon(SPELLS.TITANS_THUNDER.icon)
          .actual(`You cast Titan's Thunder ${this.badTTCasts} times when there was less than 30 seconds cooldown on Bestial Wrath`)
          .recommended(`${recommended} is recommended`)
          .major(recommended);
      });
  }

}

export default TitansThunder;
<|endoftext|>


<commit_before>import React from 'react';

import Module from 'Parser/Core/Module';
import Enemies from 'Parser/Core/Modules/Enemies';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Combatants from "../../../Core/Modules/Combatants";

class PatientSniper extends Module {

  static dependencies = {
    enemies: Enemies,
    combatants: Combatants,
  }

  /*
  A module to track the effectiveness of the Patient Sniper talent
  > Apply Vulnerable
  > 0-0.99seconds passed = 0%
  > 1-1.99seconds passed = 6%
  > 2-2.99seconds passed = 12%
  > 3-3.99seconds passed = 18%
  > 4-4.99seconds passed = 24%
  > 5-5.99seconds passed = 30%
  > 6-6.99seconds passed = 36%
  > Vulnerable fades from the target
  */

  //The various levels of patient sniper
  zeroSecondsIntoVulnerable = 0;
  oneSecondIntoVulnerable = 0;
  twoSecondsIntoVulnerable = 0;
  threeSecondsIntoVulnerable = 0;
  fourSecondsIntoVulnerable = 0;
  fiveSecondsIntoVulnerable = 0;
  sixSecondsIntoVulnerable = 0;

  on_initialized() {
    this.active = this.combatants.selected.hasTalent(SPELLS.PATIENT_SNIPER_TALENT.id);
  }

  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    const eventTimestamp = event.timestamp;
    const enemy = this.enemies.getEntity(event);

    if (spellId !== SPELLS.WINDBURST.id || spellId !== SPELLS.MARKED_SHOT.id) {
      return;
    }

  }

}

export default PatientSniper;
<commit_msg>second pass<commit_after>import React from 'react';

import Module from 'Parser/Core/Module';
import Enemies from 'Parser/Core/Modules/Enemies';

import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Combatants from "../../../Core/Modules/Combatants";
import StatisticBox from "../../../../Main/StatisticBox";

class PatientSniper extends Module {

  static dependencies = {
    enemies: Enemies,
    combatants: Combatants,
  };

  /*
  A module to track the effectiveness of the Patient Sniper talent
  > Apply Vulnerable
  > 0-0.99seconds passed = 0%
  > 1-1.99seconds passed = 6%
  > 2-2.99seconds passed = 12%
  > 3-3.99seconds passed = 18%
  > 4-4.99seconds passed = 24%
  > 5-5.99seconds passed = 30%
  > 6-6.99seconds passed = 36%
  > Vulnerable fades from the target
  */

  //The various levels of patient sniper
  nonVulnerableAimedShots = 0;
  zeroSecondsIntoVulnerable = 0;
  oneSecondIntoVulnerable = 0;
  twoSecondsIntoVulnerable = 0;
  threeSecondsIntoVulnerable = 0;
  fourSecondsIntoVulnerable = 0;
  fiveSecondsIntoVulnerable = 0;
  sixSecondsIntoVulnerable = 0;
  lastVulnerableTimestamp = null;
  timeIntoVulnerable = 0;

  on_initialized() {
    this.active = this.combatants.selected.hasTalent(SPELLS.PATIENT_SNIPER_TALENT.id);
  }

  on_byPlayer_cast(event) {
    const spellId = event.ability.guid;
    const eventTimestamp = event.timestamp;
    const enemy = this.enemies.getEntity(event);

    if (spellId !== SPELLS.AIMED_SHOT.id || spellId !== SPELLS.MARKED_SHOT.id) {
      return;
    }
    if (spellId === SPELLS.MARKED_SHOT.id) {
      //vulnerable is reset, so we get new timestamp
      this.lastVulnerableTimestamp = eventTimestamp;
    }
    if (spellId === SPELLS.AIMED_SHOT.id) {
      if (enemy.hasBuff(SPELLS.VULNERABLE.id, event.timestamp)) {
        this.timeIntoVulnerable = eventTimestamp - this.lastVulnerableTimestamp;
        switch (this.timeIntoVulnerable / 1000) {
          case 0:
            this.zeroSecondsIntoVulnerable += 1;
            break;
          case 1:
            this.oneSecondIntoVulnerable += 1;
            break;
          case 2:
            this.twoSecondsIntoVulnerable += 1;
            break;
          case 3:
            this.threeSecondsIntoVulnerable += 1;
            break;
          case 4:
            this.fourSecondsIntoVulnerable += 1;
            break;
          case 5:
            this.fiveSecondsIntoVulnerable += 1;
            break;
          case 6:
            this.sixSecondsIntoVulnerable += 1;
            break;
          default:
            break;
        }
      }
      else {
        this.nonVulnerableAimedShots += 1;
      }
    }
  }
  on_byPlayer_damage(event) {
    const spellId = event.ability.guid;
    const eventTimestamp = event.timestamp;

    //we're only interested in windburst here
    if (spellId !== SPELLS.WINDBURST.id) {
      return;
    }
    else {
      //vulnerable is reset, so we get new timestamp
      this.lastVulnerableTimestamp = eventTimestamp;
    }
    return this.lastVulnerableTimestamp;
  }

  statistic() {
    return (
      <StatisticBox
        icon={<SpellIcon id={SPELLS.PATIENT_SNIPER_TALENT.id} />}
        value={`}
        label={}/>
    )
  }

}

export default PatientSniper;
<|endoftext|>


<commit_before>import React from 'react';
import { Doughnut as DoughnutChart } from 'react-chartjs-2';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';

import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';

import StatisticsListBox, { STATISTIC_ORDER } from 'Main/StatisticsListBox';

const CHART_SIZE = 75;

class CastBehavior extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    abilityTracker: AbilityTracker,
  };

  legend(items, total) {
    const numItems = items.length;
    return items.map(({ color, label, tooltip, value, spellId }, index) => {
      label = tooltip ? (
        <dfn data-tip={tooltip}>{label}</dfn>
      ) : label;
      label = spellId ? (
        <SpellLink id={spellId}>{label}</SpellLink>
      ) : label;
      return (

            {label}

            <dfn data-tip={value}>
              {formatPercentage(value / total, 0)}%
            </dfn>

      );
    });
  }
  chart(items) {
    return (
      <DoughnutChart
        data={{
          datasets: [{
            data: items.map(item => item.value),
            backgroundColor: items.map(item => item.color),
            borderColor: '#666',
            borderWidth: 1.5,
          }],
          labels: items.map(item => item.label),
        }}
        options={{
          legend: {
            display: false,
          },
          tooltips: {
            bodyFontSize: 8,
          },
          cutoutPercentage: 45,
          animation: false,
          responsive: false,
        }}
        width={CHART_SIZE}
        height={CHART_SIZE}
      />
    );
  }

  twUsageRatioChart() {
    const riptide = this.abilityTracker.getAbility(SPELLS.RIPTIDE.id);
    const healingWave = this.abilityTracker.getAbility(SPELLS.HEALING_WAVE.id);
    const healingSurge = this.abilityTracker.getAbility(SPELLS.HEALING_SURGE_RESTORATION.id);
    const chainHeal = this.abilityTracker.getAbility(SPELLS.CHAIN_HEAL.id);

    const chainHealCasts = chainHeal.casts || 0;
    const riptideCasts = riptide.casts || 0;
    const twPerRiptide = this.combatants.selected.hasTalent(SPELLS.CRASHING_WAVES_TALENT.id) ? 2 : 1;
    const totalTwGenerated = twPerRiptide * riptideCasts + chainHealCasts;
    const twHealingWaves = healingWave.healingTwHits || 0;
    const twHealingSurges = healingSurge.healingTwHits || 0;

    const totalTwUsed = twHealingWaves + twHealingSurges;
    const unusedTw = totalTwGenerated - totalTwUsed;

    const items = [
      {
        color: '#009688',
        label: 'Healing Wave',
        spellId: SPELLS.HEALING_WAVE.id,
        value: twHealingWaves,
      },
      {
        color: '#ecd1b6',
        label: 'Healing Surge',
        spellId: SPELLS.HEALING_SURGE_RESTORATION.id,
        value: twHealingSurges,
      },
      {
        color: '#f44336',
        label: 'Wasted Tidal Waves',
        tooltip: `The amount of Tidal Waves you did not use out of the total available. You cast ${riptideCasts} Riptides and ${chainHealCasts} Chain Heals which gave you ${totalTwGenerated} Tidal Waves charges, of which you used ${totalTwUsed}.`,
        value: unusedTw,
      },
    ];

    return (

          {this.chart(items)}

          {this.legend(items, totalTwGenerated)}

    );
  }

  fillerCastRatioChart() {
    const healingWave = this.abilityTracker.getAbility(SPELLS.HEALING_WAVE.id);
    const healingSurge = this.abilityTracker.getAbility(SPELLS.HEALING_SURGE_RESTORATION.id);
    const twHealingWaves = healingWave.healingTwHits || 0;
    const twHealingSurges = healingSurge.healingTwHits || 0;

    const healingWaveHeals = healingWave.casts || 0;
    const healingSurgeHeals = healingSurge.casts || 0;
    const fillerHealingWaves = healingWaveHeals - twHealingWaves;
    const fillerHealingSurges = healingSurgeHeals - twHealingSurges;
    const totalFillers = fillerHealingWaves + fillerHealingSurges;

    const items = [
      {
        color: '#009688',
        label: 'Healing Wave',
        spellId: SPELLS.HEALING_WAVE.id,
        value: fillerHealingWaves,
      },
      {
        color: '#ecd1b6',
        label: 'Healing Surge',
        spellId: SPELLS.HEALING_SURGE_RESTORATION.id,
        value: fillerHealingSurges,
      },
    ];

    return (

          {this.chart(items)}

          {this.legend(items, totalFillers)}

    );
  }

  statistic() {
    return (

          <StatisticsListBox
            title={<SpellLink id={SPELLS.TIDAL_WAVES_BUFF.id}/> usage}
            containerProps={{ className: 'col-xs-12' }}
          >
            {this.twUsageRatioChart()}
          </StatisticsListBox>

          <StatisticsListBox
            title="Fillers"
            containerProps={{ className: 'col-xs-12' }}
          >
            {this.fillerCastRatioChart()}
          </StatisticsListBox>

    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(40);
}

export default CastBehavior;
<commit_msg>changed chart colors<commit_after>import React from 'react';
import { Doughnut as DoughnutChart } from 'react-chartjs-2';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';

import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';

import StatisticsListBox, { STATISTIC_ORDER } from 'Main/StatisticsListBox';

const CHART_SIZE = 75;

class CastBehavior extends Analyzer {
  static dependencies = {
    combatants: Combatants,
    abilityTracker: AbilityTracker,
  };

  legend(items, total) {
    const numItems = items.length;
    return items.map(({ color, label, tooltip, value, spellId }, index) => {
      label = tooltip ? (
        <dfn data-tip={tooltip}>{label}</dfn>
      ) : label;
      label = spellId ? (
        <SpellLink id={spellId}>{label}</SpellLink>
      ) : label;
      return (

            {label}

            <dfn data-tip={value}>
              {formatPercentage(value / total, 0)}%
            </dfn>

      );
    });
  }
  chart(items) {
    return (
      <DoughnutChart
        data={{
          datasets: [{
            data: items.map(item => item.value),
            backgroundColor: items.map(item => item.color),
            borderColor: '#666',
            borderWidth: 1.5,
          }],
          labels: items.map(item => item.label),
        }}
        options={{
          legend: {
            display: false,
          },
          tooltips: {
            bodyFontSize: 8,
          },
          cutoutPercentage: 45,
          animation: false,
          responsive: false,
        }}
        width={CHART_SIZE}
        height={CHART_SIZE}
      />
    );
  }

  twUsageRatioChart() {
    const riptide = this.abilityTracker.getAbility(SPELLS.RIPTIDE.id);
    const healingWave = this.abilityTracker.getAbility(SPELLS.HEALING_WAVE.id);
    const healingSurge = this.abilityTracker.getAbility(SPELLS.HEALING_SURGE_RESTORATION.id);
    const chainHeal = this.abilityTracker.getAbility(SPELLS.CHAIN_HEAL.id);

    const chainHealCasts = chainHeal.casts || 0;
    const riptideCasts = riptide.casts || 0;
    const twPerRiptide = this.combatants.selected.hasTalent(SPELLS.CRASHING_WAVES_TALENT.id) ? 2 : 1;
    const totalTwGenerated = twPerRiptide * riptideCasts + chainHealCasts;
    const twHealingWaves = healingWave.healingTwHits || 0;
    const twHealingSurges = healingSurge.healingTwHits || 0;

    const totalTwUsed = twHealingWaves + twHealingSurges;
    const unusedTw = totalTwGenerated - totalTwUsed;

    const items = [
      {
        color: '#2055CC',
        label: 'Healing Wave',
        spellId: SPELLS.HEALING_WAVE.id,
        value: twHealingWaves,
      },
      {
        color: '#42E0FF',
        label: 'Healing Surge',
        spellId: SPELLS.HEALING_SURGE_RESTORATION.id,
        value: twHealingSurges,
      },
      {
        color: '#CC3D20',
        label: 'Wasted Tidal Waves',
        tooltip: `The amount of Tidal Waves you did not use out of the total available. You cast ${riptideCasts} Riptides and ${chainHealCasts} Chain Heals which gave you ${totalTwGenerated} Tidal Waves charges, of which you used ${totalTwUsed}.`,
        value: unusedTw,
      },
    ];

    return (

          {this.chart(items)}

          {this.legend(items, totalTwGenerated)}

    );
  }

  fillerCastRatioChart() {
    const healingWave = this.abilityTracker.getAbility(SPELLS.HEALING_WAVE.id);
    const healingSurge = this.abilityTracker.getAbility(SPELLS.HEALING_SURGE_RESTORATION.id);
    const twHealingWaves = healingWave.healingTwHits || 0;
    const twHealingSurges = healingSurge.healingTwHits || 0;

    const healingWaveHeals = healingWave.casts || 0;
    const healingSurgeHeals = healingSurge.casts || 0;
    const fillerHealingWaves = healingWaveHeals - twHealingWaves;
    const fillerHealingSurges = healingSurgeHeals - twHealingSurges;
    const totalFillers = fillerHealingWaves + fillerHealingSurges;

    const items = [
      {
        color: '#2055CC',
        label: 'Healing Wave',
        spellId: SPELLS.HEALING_WAVE.id,
        value: fillerHealingWaves,
      },
      {
        color: '#42E0FF',
        label: 'Healing Surge',
        spellId: SPELLS.HEALING_SURGE_RESTORATION.id,
        value: fillerHealingSurges,
      },
    ];

    return (

          {this.chart(items)}

          {this.legend(items, totalFillers)}

    );
  }

  statistic() {
    return (

          <StatisticsListBox
            title={<SpellLink id={SPELLS.TIDAL_WAVES_BUFF.id}/> usage}
            containerProps={{ className: 'col-xs-12' }}
          >
            {this.twUsageRatioChart()}
          </StatisticsListBox>

          <StatisticsListBox
            title="Fillers"
            containerProps={{ className: 'col-xs-12' }}
          >
            {this.fillerCastRatioChart()}
          </StatisticsListBox>

    );
  }
  statisticOrder = STATISTIC_ORDER.CORE(40);
}

export default CastBehavior;
<|endoftext|>


<commit_before>import React from 'react';
import {
	View,
	Text,
	StyleSheet,
} from 'react-native';
import { Actions } from 'react-native-router-flux';

import Card from '../card/Card';
import BannerCard from '../common/BannerCard';
import ConferenceListView from './ConferenceListView';
import { getMaxCardWidth, getCampusPrimary } from '../../util/general';
import Touchable from '../common/Touchable';

const ConferenceCard = ({ conference, saved }) => (
	<View>
		{ (saved.length < 1) ?
			(
				<BannerCard
					image={conference['conference-logo-lg']}
					onPress={() => Actions.ConferenceView()}
				/>
			) :
			(
				<Card
					title={conference.name}
					header={conference['conference-logo-lg']}
				>
					<View
						style={{ flex: 1, width: getMaxCardWidth() }}
					>
						<ConferenceListView
							scrollEnabled={false}
							personal={true}
							rows={4}
							disabled={true}
						/>
						<Touchable
							onPress={() => Actions.ConferenceView()}
						>
							<View style={styles.more}>
								<Text style={styles.more_label}>
									See Full Schedule
								</Text>
							</View>
						</Touchable>
					</View>
				</Card>
			)
		}
	</View>
);

const styles = StyleSheet.create({
	more: { alignItems: 'center', justifyContent: 'center', padding: 6 },
	more_label: { fontSize: 20, color: getCampusPrimary(), fontWeight: '300' },
});

export default ConferenceCard;
<commit_msg>Add border to conference card list<commit_after>import React from 'react';
import {
	View,
	Text,
	StyleSheet,
} from 'react-native';
import { Actions } from 'react-native-router-flux';

import Card from '../card/Card';
import BannerCard from '../common/BannerCard';
import ConferenceListView from './ConferenceListView';
import { getMaxCardWidth, getCampusPrimary } from '../../util/general';
import Touchable from '../common/Touchable';

const ConferenceCard = ({ conference, saved }) => (
	<View>
		{ (saved.length < 1) ?
			(
				<BannerCard
					image={conference['conference-logo-lg']}
					onPress={() => Actions.ConferenceView()}
				/>
			) :
			(
				<Card
					title={conference.name}
					header={conference['conference-logo-lg']}
				>
					<View
						style={{ flex: 1, width: getMaxCardWidth() }}
					>
						<ConferenceListView
							scrollEnabled={false}
							personal={true}
							rows={4}
							disabled={true}
							style={styles.conferenceListView}
						/>
						<Touchable
							onPress={() => Actions.ConferenceView()}
						>
							<View style={styles.more}>
								<Text style={styles.more_label}>
									See Full Schedule
								</Text>
							</View>
						</Touchable>
					</View>
				</Card>
			)
		}
	</View>
);

const styles = StyleSheet.create({
	more: { alignItems: 'center', justifyContent: 'center', padding: 6 },
	more_label: { fontSize: 20, color: getCampusPrimary(), fontWeight: '300' },
	conferenceListView: { borderBottomWidth: 1, borderBottomColor: '#DDD' },
});

export default ConferenceCard;
<|endoftext|>


<commit_before>window.addEventListener("load", function () {
    var pk = new Piklor(".color-picker", [
            "#f44336"
          , "#e91e63"
          , "#3f51b5"
          , "#4caf50"
          , "#ffc107"
          , "#795548"
        ], {
            open: ".picker-wrapper .btn"
          , position: "auto"
        })
      , wrapperEl = pk.getElm(".picker-wrapper")
      , header = pk.getElm("header")
      , footer = pk.getElm("footer")
      ;

    pk.colorChosen(function (col) {
        wrapperEl.style.backgroundColor = col;
        header.style.backgroundColor = col;
        footer.style.backgroundColor = col;
    });
});
<commit_msg>More colors! :art:<commit_after>window.addEventListener("load", function () {
    var pk = new Piklor(".color-picker", [
            "#1abc9c"
          , "#2ecc71"
          , "#3498db"
          , "#9b59b6"
          , "#34495e"
          , "#16a085"
          , "#27ae60"
          , "#2980b9"
          , "#8e44ad"
          , "#2c3e50"
          , "#f1c40f"
          , "#e67e22"
          , "#e74c3c"
          , "#ecf0f1"
          , "#95a5a6"
          , "#f39c12"
          , "#d35400"
          , "#c0392b"
          , "#bdc3c7"
          , "#7f8c8d"
        ], {
            open: ".picker-wrapper .btn"
          , position: "auto"
        })
      , wrapperEl = pk.getElm(".picker-wrapper")
      , header = pk.getElm("header")
      , footer = pk.getElm("footer")
      ;

    pk.colorChosen(function (col) {
        wrapperEl.style.backgroundColor = col;
        header.style.backgroundColor = col;
        footer.style.backgroundColor = col;
    });
});
<|endoftext|>


<commit_before>
/*
 * SmilePlease v1.0 - a lightweight library for taking screenshots of the current state of DOM
 * Author: Venkat Subramanian (https://github.com/Venkatb4U)
 *
 * Copyright (c) 2016 Venkat Subramanian (https://github.com/Venkatb4U)
 * Licence: MIT
 */

 /*
  USAGE:
  -----
	smilePlease(dom, [optional callback]);
 */

var smilePlease = function (target, callback) {

	(function (tg, cb) {
	 	"use strict";

	 	var DOMURL = window.URL || window.webkitURL || window;

		function sp () {
			(function init(sp) {
				sp.target = tg;

				// cloning the target to avoid polluting the original reference
				sp.targetClone = tg.cloneNode(true);

				// sp.createCanvas();
				sp.render();
				// sp.applyStyles();
			})(this);
		};

		sp.prototype = {

			createCanvas: function () {
				// var canvas = document.createElement('canvas');
				var canvas = document.getElementById('canvas');
				canvas.setAttribute('width', this.target.offsetWidth + 'px');
				canvas.setAttribute('height', this.target.offsetHeight + 'px');
				this.canvas = canvas;
				this.ctx = canvas.getContext('2d');

			},

			getStyles: function (elem, prop) {
				var cs = window.getComputedStyle(elem,null);
			  	if (prop) {
				  // console.log(prop+" : "+cs.getPropertyValue(prop));
				  return prop + ":" + cs.getPropertyValue(prop) + ";";
				}
				var len = cs.length;
				var inlStyles = "";
				for (var i=0;i<len;i++) {

				  var style = cs[i];
				  inlStyles += (style + ":" + cs.getPropertyValue(style) + ";");
				  // console.log(style+" : "+cs.getPropertyValue(style));
				}
				return inlStyles;
			},

			applyStyles: function (target) {
				var nodeList = target ? target.getElementsByTagName('*') : this.target.getElementsByTagName('*'),
					nodeListLen = nodeList.length;
				var nodeCloneList = this.targetClone.getElementsByTagName('*');

				for (var i=0; i<nodeListLen; i++) {
					nodeCloneList[i].style = this.getStyles(nodeList[i]);
				}
				this.targetClone.style = this.getStyles(this.target); // target tag style apply

				return nodeCloneList;
			},

			cookBlob: function (target) {
				var target = target || this.targetClone;

				this.applyStyles();

				var xmlSer = new XMLSerializer();
				var serialisedDom = xmlSer.serializeToString(target);

				var svgScaffold = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" id="sp_svg">' +
							           '<foreignObject width="100%" height="100%">' +
								           '
' +
								           		serialisedDom +
								           '
' +
							           '</foreignObject>' +
						          '</svg>';
			    // console.log(serialisedDom);
				// var xmlParser = new DOMParser();
				// var xmlDoc = xmlParser.parseFromString(svgScaffold, "text/xml");

				// xmlDoc.getElementById('sp_root').appendChild(domExtract);
				return svgScaffold;
			},

			render: function () {
				var self = this;
				var img = new Image();
				var cookedBlob = this.cookBlob();
				// console.log(cookedBlob);
				var svg = new Blob([cookedBlob], {type: 'image/svg+xml'});
				var url = DOMURL.createObjectURL(svg);

				this.createCanvas();

				img.src = url;
				img.setAttribute('width', this.canvas.width + 'px');
				img.setAttribute('height', this.canvas.height + 'px');

				img.onload = function () {
					var imgWidth = img.width;
					var imgHeight = img.height;

					self.canvas.width = imgWidth;
					self.canvas.height = imgHeight;

				  	// self.ctx.drawImage(img, 0, 0, 500, 300, 0, 0, 500, 300);
				  	self.ctx.drawImage(img, 0, 0);
				  	DOMURL.revokeObjectURL(url);
				}

				// document.body.appendChild(img);
				document.body.appendChild(this.canvas);

			}

		};

		return new sp();

	}(function(target) {
		return typeof target === 'string' ? document.querySelector(target) : target;
	}(target), callback));
}

__ = smilePlease; // short-hand alias.

__('#test');

<commit_msg>svg width height alter<commit_after>
/*
 * SmilePlease v1.0 - a lightweight library for taking screenshots of the current state of DOM
 * Author: Venkat Subramanian (https://github.com/Venkatb4U)
 *
 * Copyright (c) 2016 Venkat Subramanian (https://github.com/Venkatb4U)
 * Licence: MIT
 */

 /*
  USAGE:
  -----
	smilePlease(dom, [optional callback]);
 */

var smilePlease = function (target, callback) {

	(function (tg, cb) {
	 	"use strict";

	 	var DOMURL = window.URL || window.webkitURL || window;

		function sp () {
			(function init(sp) {
				sp.target = tg;

				// cloning the target to avoid polluting the original reference
				sp.targetClone = tg.cloneNode(true);

				// sp.createCanvas();
				sp.render();
				// sp.applyStyles();
			})(this);
		};

		sp.prototype = {

			createCanvas: function () {
				// var canvas = document.createElement('canvas');
				var canvas = document.getElementById('canvas');
				canvas.setAttribute('width', this.target.offsetWidth + 'px');
				canvas.setAttribute('height', this.target.offsetHeight + 'px');
				this.canvas = canvas;
				this.ctx = canvas.getContext('2d');

			},

			getStyles: function (elem, prop) {
				var cs = window.getComputedStyle(elem,null);
			  	if (prop) {
				  // console.log(prop+" : "+cs.getPropertyValue(prop));
				  return prop + ":" + cs.getPropertyValue(prop) + ";";
				}
				var len = cs.length;
				var inlStyles = "";
				for (var i=0;i<len;i++) {

				  var style = cs[i];
				  inlStyles += (style + ":" + cs.getPropertyValue(style) + ";");
				  // console.log(style+" : "+cs.getPropertyValue(style));
				}
				return inlStyles;
			},

			applyStyles: function (target) {
				var nodeList = target ? target.getElementsByTagName('*') : this.target.getElementsByTagName('*'),
					nodeListLen = nodeList.length;
				var nodeCloneList = this.targetClone.getElementsByTagName('*');

				for (var i=0; i<nodeListLen; i++) {
					nodeCloneList[i].style = this.getStyles(nodeList[i]);
				}
				this.targetClone.style = this.getStyles(this.target); // target tag style apply

				return nodeCloneList;
			},

			cookBlob: function (target) {
				var target = target || this.targetClone;

				this.applyStyles();

				var xmlSer = new XMLSerializer();
				var serialisedDom = xmlSer.serializeToString(target);

				var svgScaffold = '<svg xmlns="http://www.w3.org/2000/svg" id="sp_svg">' +
							           '<foreignObject width="100%" height="100%">' +
								           '
' +
								           		serialisedDom +
								           '
' +
							           '</foreignObject>' +
						          '</svg>';
			    // console.log(serialisedDom);
				// var xmlParser = new DOMParser();
				// var xmlDoc = xmlParser.parseFromString(svgScaffold, "text/xml");

				// xmlDoc.getElementById('sp_root').appendChild(domExtract);
				return svgScaffold;
			},

			render: function () {
				var self = this;
				var img = new Image();
				var cookedBlob = this.cookBlob();
				// console.log(cookedBlob);
				var svg = new Blob([cookedBlob], {type: 'image/svg+xml'});
				var url = DOMURL.createObjectURL(svg);

				this.createCanvas();

				img.src = url;
				img.setAttribute('width', this.canvas.width + 'px');
				img.setAttribute('height', this.canvas.height + 'px');

				img.onload = function () {
					var imgWidth = img.width;
					var imgHeight = img.height;

					self.canvas.width = imgWidth;
					self.canvas.height = imgHeight;

				  	// self.ctx.drawImage(img, 0, 0, 500, 300, 0, 0, 500, 300);
				  	self.ctx.drawImage(img, 0, 0);
				  	// document.body.appendChild(img);
				  	DOMURL.revokeObjectURL(url);
				}

				// document.body.appendChild(img);
				document.body.appendChild(this.canvas);

			}

		};

		return new sp();

	}(function(target) {
		return typeof target === 'string' ? document.querySelector(target) : target;
	}(target), callback));
}

__ = smilePlease; // short-hand alias.

__('#test');

<|endoftext|>


<commit_before>module.exports = function (grunt) {
    return {
        main: {
            options: {
                add    : (grunt.option('cleanup') ? false : true),
                base   : 'dist',
                branch : 'gh-pages',
                message: global.is_release ? `Release to ${global.release_target}` : `Deploy to ${global.branch || 'gh-pages'}`,
                ...(global.is_release && {
                    repo: global.release_info.target_repo || global.release_info.origin,
                }),
            },
            src: global.branch ? [global.branch_prefix + global.branch + '/**'] : ['**', '!' + (global.branch_prefix || 'br_') + '*/**']
        },
        trigger_tests: {
            options: {
                add    : true,
                base   : 'dist',
                branch : 'master',
                repo   : 'git@github.com:binary-com/robot-framework.git',
                message: 'Trigger tests',
            },
            src: grunt.option('staging') ? 'version' : '',
        },
    }
};
<commit_msg>Prevent the gh-pages local cache problems<commit_after>module.exports = function (grunt) {
    return {
        main: {
            options: {
                add    : (grunt.option('cleanup') ? false : true),
                base   : 'dist',
                branch : 'gh-pages',
                message: global.is_release ? `Release to ${global.release_target}` : `Deploy to ${global.branch || 'gh-pages'}`,
                ...(global.is_release && {
                    repo: global.release_info.target_repo || global.release_info.origin,
                    get clone() { // clone each repo to a unique folder to prevent local cache issues
                        return `.grunt/grunt-gh-pages/gh-pages/${/^.*:(.*)\.git$/g.exec(this.repo)[1].replace(/\//g, '__')}`;
                    },
                }),
            },
            src: global.branch ? [global.branch_prefix + global.branch + '/**'] : ['**', '!' + (global.branch_prefix || 'br_') + '*/**']
        },
        trigger_tests: {
            options: {
                add    : true,
                base   : 'dist',
                branch : 'master',
                repo   : 'git@github.com:binary-com/robot-framework.git',
                message: 'Trigger tests',
            },
            src: grunt.option('staging') ? 'version' : '',
        },
    }
};
<|endoftext|>