<commit_before>'use strict';

var mongoose = require('mongoose');
var Defaults    = mongoose.model('_Defaults');
var Prom = require('promise');

module.exports = function () {
	Defaults.find({}).remove ();
	return new Prom (function (resolve, reject) {
		var promiseArray = [];
		//
		// default project permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'project',
			level    : 'global',
			type     : 'default-permissions',
			defaults : {
				roles: {
					'eao-admin':['eao-admin', 'eao-member', 'eao-invitee', 'epd', 'intake', 'lead', 'team', 'assistant-dm', 'assistant-dm-office', 'associate-dm', 'associate-dmo', 'minister', 'minister-office', 'qa-officer', 'ce-lead', 'ce-officer', 'aboriginal-consultant', 'aboriginal-subconsultant', 'ceaa', 'local-gov', 'working-group', 'technical-working-group'],
					'pro-admin':['pro-admin', 'pro-member', 'pro-subconsultant', 'pro-invitee']
				},
				permissions: {
					'viewSchedule'            : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listEnforcements'        : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'editSchedule'            : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listCommentPeriods'      : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listDocuments'           : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectInvitations'  : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectComplaints'   : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectConditions'   : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listInspectionReports'   : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectRoles'        : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listValuedComponents'    : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listArtifacts'           : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listUsers'               : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'viewEAOTombstone'        : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'uploadDocument'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'createProjectInvitation' : ['eao-admin',               'pro-admin', 'pro-member'],
					'createProjectRole'       : ['eao-admin',               'pro-admin', 'pro-member'],
					'createValuedComponent'   : ['eao-admin',               'pro-admin', 'pro-member'],
					'createArtifact'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'editProject'             : ['eao-admin',               'pro-admin', 'pro-member'],
					'createEnforcement'       : ['eao-admin'                                         ],
					'createCommentPeriod'     : ['eao-admin'                                         ],
					'createProjectComplaint'  : ['eao-admin'                                         ],
					'createProjectCondition'  : ['eao-admin'                                         ],
					'createInspectionReport'  : ['eao-admin'                                         ],
					'publish'                 : ['eao-admin'                                         ],
					'unPublish'               : ['eao-admin'                                         ],
				}
			}
		})).save ());
		//
		// default document permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'document',
			level    : 'global',
			type     : 'default-permissions',
			defaults : {
				roles: {
					'eao-admin':['eao-admin', 'eao-member', 'eao-invitee', 'epd', 'intake', 'lead', 'team', 'assistant-dm', 'assistant-dm-office', 'associate-dm', 'associate-dmo', 'minister', 'minister-office', 'qa-officer', 'ce-lead', 'ce-officer', 'aboriginal-consultant', 'aboriginal-subconsultant', 'ceaa', 'local-gov', 'working-group', 'technical-working-group'],
					'pro-admin':['pro-admin', 'pro-member', 'pro-subconsultant', 'pro-invitee']
				},
				permissions: {
					'listDocuments'           : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'uploadDocument'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'createArtifact'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'publish'                 : ['eao-admin'                                         ],
					'unPublish'               : ['eao-admin'                                         ],
				}
			}
		})).save ());
		//
		// default application permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'application',
			resource : 'application',
			level    : 'global',
			type     : 'default-permissions',
			//
			// this goes owner, role, permissions
			//
			defaults : {
				roles: {
					'application:sysadmin':['sysadmin', 'eao', 'proponent', 'invitee']
				},
				permissions: {
					'viewConfiguration'   : ['sysadmin','proponent','eao'],
					'viewSchedule'        : ['sysadmin','proponent','eao'],
					'listConditions'      : ['sysadmin','proponent','eao'],
					'listEmailTemplates'  : ['sysadmin','proponent','eao'],
					'listOrganizations'   : ['sysadmin','proponent','eao'],
					'listNews'            : ['sysadmin','proponent','eao'],
					'listRoles'           : ['sysadmin','proponent','eao'],
					'listTemplates'       : ['sysadmin','proponent','eao'],
					'listTopics'          : ['sysadmin','proponent','eao'],
					'listUsers'           : ['sysadmin','proponent','eao'],
					'createProject'       : ['sysadmin','proponent'],
					'createCondition'     : ['sysadmin'],
					'createEmailTemplate' : ['sysadmin'],
					'createOrganization'  : ['sysadmin'],
					'createNews'          : ['sysadmin'],
					'createRole'          : ['sysadmin'],
					'createTemplate'      : ['sysadmin'],
					'createTopic'         : ['sysadmin'],
					'createUser'          : ['sysadmin']
				}
			}
		})).save ());

		console.log ('Seeding defaults');
		var allProjectPermissions = [
			'viewSchedule',
			'editSchedule',
			'listEnforcements',
			'createEnforcement',
			'listCommentPeriods',
			'createCommentPeriod',
			'listDocuments',
			'uploadDocument',
			'listProjectInvitations',
			'createProjectInvitation',
			'listProjectComplaints',
			'createProjectComplaint',
			'listProjectConditions',
			'createProjectCondition',
			'listInspectionReports',
			'createInspectionReport',
			'listProjectRoles',
			'createProjectRole',
			'listValuedComponents',
			'createValuedComponent',
			'listArtifacts',
			'createArtifact',
			'publish',
			'unPublish',
			'listUsers',
			'viewEAOTombstone',
			'editProject'
		];
		var readProjectPermissions = [
			'viewSchedule',
			'listEnforcements',
			'listCommentPeriods',
			'listDocuments',
			'listProjectInvitations',
			'listProjectComplaints',
			'listProjectConditions',
			'listInspectionReports',
			'listProjectRoles',
			'listValuedComponents',
			'listArtifacts',
			'listUsers'
		];
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'project',
			level    : 'global',
			type     : 'rolePermissions',
			//
			// this goes owner, role, permissions
			//
			defaults : {
				'eao-admin' : {
					'eao-admin' : allProjectPermissions,
					'eao-member' : readProjectPermissions,
					'eao-invitee' : [],
					'epd' : [],
					'intake' : [],
					'lead' : [],
					'team' : [],
					'assistant-dm' : [],
					'assistant-dm-office' : [],
					'associate-dm' : [],
					'associate-dmo' : [],
					'minister' : [],
					'minister-office' : [],
					'qa-officer' : [],
					'ce-lead' : [],
					'ce-officer' : [],
					'aboriginal-consultant' : [],
					'aboriginal-subconsultant' : [],
					'ceaa' : [],
					'local-gov' : [],
					'working-group' : [],
					'technical-working-group' : [],
				},
				'pro-admin' : {
					'pro-admin' : readProjectPermissions.concat ([
						'uploadDocument',
						'createProjectInvitation',
						'createProjectRole',
						'createValuedComponent',
						'createArtifact',
						'editProject'
					]),
					'pro-member' : readProjectPermissions.concat ([
						'uploadDocument',
						'createProjectInvitation',
						'createProjectRole',
						'createValuedComponent',
						'createArtifact',
						'editProject'
					]),
					'pro-subconsultant' : [],
					'pro-invitee' : []
				}
			}
		})).save ());
		var allApplicationPermissions = [
			'viewConfiguration',
			'viewSchedule',
			'listConditions',
			'listEmailTemplates',
			'listOrganizations',
			'listNews',
			'listRoles',
			'listTemplates',
			'listTopics',
			'listUsers',
			'createCondition',
			'createEmailTemplate',
			'createOrganization',
			'createNews',
			'createRole',
			'createTemplate',
			'createTopic',
			'createUser',
			'createProject',
		];
		var readApplicationPermissions = [
			'viewConfiguration',
			'viewSchedule',
			'listConditions',
			'listEmailTemplates',
			'listOrganizations',
			'listNews',
			'listRoles',
			'listTemplates',
			'listTopics',
			'listUsers'
		];

		promiseArray.push ((new Defaults ({
			context  : 'application',
			resource : 'application',
			level    : 'global',
			type     : 'rolePermissions',
			//
			// this goes owner, role, permissions
			//
			defaults : {
				'application:sysadmin' : {
					'sysadmin' : allApplicationPermissions,
					'eao' : readApplicationPermissions,
					'proponent' : readApplicationPermissions.concat (['createProject']),
					'invitee': [],
				}
			}
		})).save ());
	});
};
<commit_msg>Adding seed data for comment and commentperiod.<commit_after>'use strict';

var mongoose = require('mongoose');
var Defaults    = mongoose.model('_Defaults');
var Prom = require('promise');

module.exports = function () {
	Defaults.find({}).remove ();
	return new Prom (function (resolve, reject) {
		var promiseArray = [];
		//
		// default project permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'project',
			level    : 'global',
			type     : 'default-permissions',
			defaults : {
				roles: {
					'eao-admin':['eao-admin', 'eao-member', 'eao-invitee', 'epd', 'intake', 'lead', 'team', 'assistant-dm', 'assistant-dm-office', 'associate-dm', 'associate-dmo', 'minister', 'minister-office', 'qa-officer', 'ce-lead', 'ce-officer', 'aboriginal-consultant', 'aboriginal-subconsultant', 'ceaa', 'local-gov', 'working-group', 'technical-working-group'],
					'pro-admin':['pro-admin', 'pro-member', 'pro-subconsultant', 'pro-invitee']
				},
				permissions: {
					'viewSchedule'            : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listEnforcements'        : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'editSchedule'            : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listCommentPeriods'      : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listDocuments'           : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectInvitations'  : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectComplaints'   : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectConditions'   : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listInspectionReports'   : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listProjectRoles'        : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listValuedComponents'    : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listArtifacts'           : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'listUsers'               : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'viewEAOTombstone'        : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'uploadDocument'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'createProjectInvitation' : ['eao-admin',               'pro-admin', 'pro-member'],
					'createProjectRole'       : ['eao-admin',               'pro-admin', 'pro-member'],
					'createValuedComponent'   : ['eao-admin',               'pro-admin', 'pro-member'],
					'createArtifact'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'editProject'             : ['eao-admin',               'pro-admin', 'pro-member'],
					'createEnforcement'       : ['eao-admin'                                         ],
					'createCommentPeriod'     : ['eao-admin'                                         ],
					'createProjectComplaint'  : ['eao-admin'                                         ],
					'createProjectCondition'  : ['eao-admin'                                         ],
					'createInspectionReport'  : ['eao-admin'                                         ],
					'publish'                 : ['eao-admin'                                         ],
					'unPublish'               : ['eao-admin'                                         ],
				}
			}
		})).save ());
		//
		// default document permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'document',
			level    : 'global',
			type     : 'default-permissions',
			defaults : {
				roles: {
					'eao-admin':['eao-admin', 'eao-member', 'eao-invitee', 'epd', 'intake', 'lead', 'team', 'assistant-dm', 'assistant-dm-office', 'associate-dm', 'associate-dmo', 'minister', 'minister-office', 'qa-officer', 'ce-lead', 'ce-officer', 'aboriginal-consultant', 'aboriginal-subconsultant', 'ceaa', 'local-gov', 'working-group', 'technical-working-group'],
					'pro-admin':['pro-admin', 'pro-member', 'pro-subconsultant', 'pro-invitee']
				},
				permissions: {
					'listDocuments'           : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
					'uploadDocument'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'createArtifact'          : ['eao-admin',               'pro-admin', 'pro-member'],
					'publish'                 : ['eao-admin'                                         ],
					'unPublish'               : ['eao-admin'                                         ],
				}
			}
		})).save ());
		//
		// default document permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'commentperiod',
			level    : 'global',
			type     : 'default-permissions',
			defaults : {
				roles: {
					'eao-admin':['eao-admin', 'eao-member', 'eao-invitee', 'epd', 'intake', 'lead', 'team', 'assistant-dm', 'assistant-dm-office', 'associate-dm', 'associate-dmo', 'minister', 'minister-office', 'qa-officer', 'ce-lead', 'ce-officer', 'aboriginal-consultant', 'aboriginal-subconsultant', 'ceaa', 'local-gov', 'working-group', 'technical-working-group'],
					'pro-admin':['pro-admin', 'pro-member', 'pro-subconsultant', 'pro-invitee']
				},
				permissions: {
					'createCommentPeriod'     : ['eao-admin'                                         ],
					'publish'                 : ['eao-admin'                                         ],
					'unPublish'               : ['eao-admin'                                         ],
					'listCommentPeriods'      : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
				}
			}
		})).save ());
		//
		// default document permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'comment',
			level    : 'global',
			type     : 'default-permissions',
			defaults : {
				roles: {
					'eao-admin':['eao-admin', 'eao-member', 'eao-invitee', 'epd', 'intake', 'lead', 'team', 'assistant-dm', 'assistant-dm-office', 'associate-dm', 'associate-dmo', 'minister', 'minister-office', 'qa-officer', 'ce-lead', 'ce-officer', 'aboriginal-consultant', 'aboriginal-subconsultant', 'ceaa', 'local-gov', 'working-group', 'technical-working-group'],
					'pro-admin':['pro-admin', 'pro-member', 'pro-subconsultant', 'pro-invitee']
				},
				permissions: {
					'createCommentPeriod'     : ['eao-admin'                                         ],
					'publish'                 : ['eao-admin'                                         ],
					'unPublish'               : ['eao-admin'                                         ],
					'listCommentPeriods'      : ['eao-admin', 'eao-member', 'pro-admin', 'pro-member'],
				}
			}
		})).save ());
		//
		// default application permissions
		//
		promiseArray.push ((new Defaults ({
			context  : 'application',
			resource : 'application',
			level    : 'global',
			type     : 'default-permissions',
			//
			// this goes owner, role, permissions
			//
			defaults : {
				roles: {
					'application:sysadmin':['sysadmin', 'eao', 'proponent', 'invitee']
				},
				permissions: {
					'viewConfiguration'   : ['sysadmin','proponent','eao'],
					'viewSchedule'        : ['sysadmin','proponent','eao'],
					'listConditions'      : ['sysadmin','proponent','eao'],
					'listEmailTemplates'  : ['sysadmin','proponent','eao'],
					'listOrganizations'   : ['sysadmin','proponent','eao'],
					'listNews'            : ['sysadmin','proponent','eao'],
					'listRoles'           : ['sysadmin','proponent','eao'],
					'listTemplates'       : ['sysadmin','proponent','eao'],
					'listTopics'          : ['sysadmin','proponent','eao'],
					'listUsers'           : ['sysadmin','proponent','eao'],
					'createProject'       : ['sysadmin','proponent'],
					'createCondition'     : ['sysadmin'],
					'createEmailTemplate' : ['sysadmin'],
					'createOrganization'  : ['sysadmin'],
					'createNews'          : ['sysadmin'],
					'createRole'          : ['sysadmin'],
					'createTemplate'      : ['sysadmin'],
					'createTopic'         : ['sysadmin'],
					'createUser'          : ['sysadmin']
				}
			}
		})).save ());

		console.log ('Seeding defaults');
		var allProjectPermissions = [
			'viewSchedule',
			'editSchedule',
			'listEnforcements',
			'createEnforcement',
			'listCommentPeriods',
			'createCommentPeriod',
			'listDocuments',
			'uploadDocument',
			'listProjectInvitations',
			'createProjectInvitation',
			'listProjectComplaints',
			'createProjectComplaint',
			'listProjectConditions',
			'createProjectCondition',
			'listInspectionReports',
			'createInspectionReport',
			'listProjectRoles',
			'createProjectRole',
			'listValuedComponents',
			'createValuedComponent',
			'listArtifacts',
			'createArtifact',
			'publish',
			'unPublish',
			'listUsers',
			'viewEAOTombstone',
			'editProject'
		];
		var readProjectPermissions = [
			'viewSchedule',
			'listEnforcements',
			'listCommentPeriods',
			'listDocuments',
			'listProjectInvitations',
			'listProjectComplaints',
			'listProjectConditions',
			'listInspectionReports',
			'listProjectRoles',
			'listValuedComponents',
			'listArtifacts',
			'listUsers'
		];
		promiseArray.push ((new Defaults ({
			context  : 'project',
			resource : 'project',
			level    : 'global',
			type     : 'rolePermissions',
			//
			// this goes owner, role, permissions
			//
			defaults : {
				'eao-admin' : {
					'eao-admin' : allProjectPermissions,
					'eao-member' : readProjectPermissions,
					'eao-invitee' : [],
					'epd' : [],
					'intake' : [],
					'lead' : [],
					'team' : [],
					'assistant-dm' : [],
					'assistant-dm-office' : [],
					'associate-dm' : [],
					'associate-dmo' : [],
					'minister' : [],
					'minister-office' : [],
					'qa-officer' : [],
					'ce-lead' : [],
					'ce-officer' : [],
					'aboriginal-consultant' : [],
					'aboriginal-subconsultant' : [],
					'ceaa' : [],
					'local-gov' : [],
					'working-group' : [],
					'technical-working-group' : [],
				},
				'pro-admin' : {
					'pro-admin' : readProjectPermissions.concat ([
						'uploadDocument',
						'createProjectInvitation',
						'createProjectRole',
						'createValuedComponent',
						'createArtifact',
						'editProject'
					]),
					'pro-member' : readProjectPermissions.concat ([
						'uploadDocument',
						'createProjectInvitation',
						'createProjectRole',
						'createValuedComponent',
						'createArtifact',
						'editProject'
					]),
					'pro-subconsultant' : [],
					'pro-invitee' : []
				}
			}
		})).save ());
		var allApplicationPermissions = [
			'viewConfiguration',
			'viewSchedule',
			'listConditions',
			'listEmailTemplates',
			'listOrganizations',
			'listNews',
			'listRoles',
			'listTemplates',
			'listTopics',
			'listUsers',
			'createCondition',
			'createEmailTemplate',
			'createOrganization',
			'createNews',
			'createRole',
			'createTemplate',
			'createTopic',
			'createUser',
			'createProject',
		];
		var readApplicationPermissions = [
			'viewConfiguration',
			'viewSchedule',
			'listConditions',
			'listEmailTemplates',
			'listOrganizations',
			'listNews',
			'listRoles',
			'listTemplates',
			'listTopics',
			'listUsers'
		];

		promiseArray.push ((new Defaults ({
			context  : 'application',
			resource : 'application',
			level    : 'global',
			type     : 'rolePermissions',
			//
			// this goes owner, role, permissions
			//
			defaults : {
				'application:sysadmin' : {
					'sysadmin' : allApplicationPermissions,
					'eao' : readApplicationPermissions,
					'proponent' : readApplicationPermissions.concat (['createProject']),
					'invitee': [],
				}
			}
		})).save ());
	});
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Text, View, TouchableHighlight } from 'react-native';
import { FormattedMessage, intlShape } from 'react-intl';

// app
import styles from './Counter.styles';
import { toJS, injectIntl } from '../../Shared/utils';

@toJS()
@injectIntl()
/** A Counter with increment and decrement buttons */
class CounterComponent extends Component {
  /**
   * @namespace
   * @property {function} increment - Increment action
   * @property {function} incrementIfOdd - Increment If Odd action
   * @property {function} incrementAsync - Increment Async action
   * @property {function} decrement - Decrement action
   * @property {Object} counter - Counter state
   * @property {Object} intl - React Intl API object
   */
  static propTypes = {
    increment: PropTypes.func.isRequired,
    incrementIfOdd: PropTypes.func.isRequired,
    incrementAsync: PropTypes.func.isRequired,
    decrement: PropTypes.func.isRequired,
    counter: PropTypes.object.isRequired,
    intl: intlShape.isRequired
  };

  /**
   * render
   * @return {ViewComponent} - View that represents the Counter
   */
  render() {
    const { increment, incrementIfOdd, incrementAsync, decrement, counter, intl } = this.props;
    const incrementAsyncMsg = intl.formatMessage({ id: 'incrementLabel' }, { type: 'async' }); // example of using formatMessage API
    return (
      <View style={styles.container}>
        <Text style={styles.text}>
          <FormattedMessage id="clickedMessage" values={{ count: counter.counter }} />
        </Text>
        <TouchableHighlight onPress={increment}>
          <Text style={styles.text}>+</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={decrement}>
          <Text style={styles.text}>-</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={incrementIfOdd}>
          <Text style={styles.text}><FormattedMessage id="incrementLabel" values={{ type: 'odd' }} /></Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={incrementAsync}>
          <Text style={styles.text}>{incrementAsyncMsg}</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

export default CounterComponent;
<commit_msg>Add example tag for Counter<commit_after>import React, { Component, PropTypes } from 'react';
import { Text, View, TouchableHighlight } from 'react-native';
import { FormattedMessage, intlShape } from 'react-intl';

// app
import styles from './Counter.styles';
import { toJS, injectIntl } from '../../Shared/utils';

@toJS()
@injectIntl()
/**
 * A Counter with increment and decrement buttons
 * @example
 * <Counter {...props} />
 * */
class CounterComponent extends Component {
  /**
   * @namespace
   * @property {function} increment - Increment action
   * @property {function} incrementIfOdd - Increment If Odd action
   * @property {function} incrementAsync - Increment Async action
   * @property {function} decrement - Decrement action
   * @property {Object} counter - Counter state
   * @property {Object} intl - React Intl API object
   */
  static propTypes = {
    increment: PropTypes.func.isRequired,
    incrementIfOdd: PropTypes.func.isRequired,
    incrementAsync: PropTypes.func.isRequired,
    decrement: PropTypes.func.isRequired,
    counter: PropTypes.object.isRequired,
    intl: intlShape.isRequired
  };

  /**
   * render
   * @return {ViewComponent} - View that represents the Counter
   */
  render() {
    const { increment, incrementIfOdd, incrementAsync, decrement, counter, intl } = this.props;
    const incrementAsyncMsg = intl.formatMessage({ id: 'incrementLabel' }, { type: 'async' }); // example of using formatMessage API
    return (
      <View style={styles.container}>
        <Text style={styles.text}>
          <FormattedMessage id="clickedMessage" values={{ count: counter.counter }} />
        </Text>
        <TouchableHighlight onPress={increment}>
          <Text style={styles.text}>+</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={decrement}>
          <Text style={styles.text}>-</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={incrementIfOdd}>
          <Text style={styles.text}><FormattedMessage id="incrementLabel" values={{ type: 'odd' }} /></Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={incrementAsync}>
          <Text style={styles.text}>{incrementAsyncMsg}</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

export default CounterComponent;
<|endoftext|>


<commit_before>const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const paths = require('./paths')
const postcssConfig = require('./postcss.config.dev')

module.exports = {
  entry: [
    paths.appIndexJs
  ],
  output: {
    path: paths.appBuild,
    pathinfo: true,
    filename: 'static/js/bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [{ loader: 'eslint-loader' }],
        include: paths.appSrc,
        enforce: 'pre'
      },
      {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.css$/,
          /\.json$/,
          /\.svg$/
        ],
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(js|jsx)$/,
        use: [{ loader: 'babel-loader', options: { cacheDirectory: true } }],
        include: paths.appSrc,
      },
      {
        test: /\.json$/,
        use: [{ loader: 'json-loader' }]
      },
      {
        test: /\.css$/,
        include: paths.appSrc,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              module: true
            }
          },
          {
            loader: 'postcss-loader',
            options: postcssConfig
          }
        ]
      },
      {
        test: /\.css$/,
        exclude: paths.appSrc,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' }
        ]
      },
      {
        test: /\.svg$/,
        use: [{ loader: 'file-loader', options: { name: 'static/media/[name].[hash:8].[ext]' } }]
      }
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    // prints more readable module names in the browser console on HMR updates
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
    })
  ],
  devtool: 'cheap-module-source-map'
}<commit_msg>update<commit_after>const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const paths = require('./paths')
const postcssConfig = require('./postcss.config.dev')

module.exports = {
  entry: [
    paths.appIndexJs
  ],
  output: {
    path: paths.appBuild,
    publicPath: '/',
    pathinfo: true,
    filename: 'static/js/bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: [{ loader: 'eslint-loader' }],
        include: paths.appSrc,
        enforce: 'pre'
      },
      {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.css$/,
          /\.json$/,
          /\.svg$/
        ],
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(js|jsx)$/,
        use: [{ loader: 'babel-loader', options: { cacheDirectory: true } }],
        include: paths.appSrc,
      },
      {
        test: /\.json$/,
        use: [{ loader: 'json-loader' }]
      },
      {
        test: /\.css$/,
        include: paths.appSrc,
        use: [
          { loader: 'style-loader' },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              module: true
            }
          },
          {
            loader: 'postcss-loader',
            options: postcssConfig
          }
        ]
      },
      {
        test: /\.css$/,
        exclude: paths.appSrc,
        use: [
          { loader: 'style-loader' },
          { loader: 'css-loader' }
        ]
      },
      {
        test: /\.svg$/,
        use: [{ loader: 'file-loader', options: { name: 'static/media/[name].[hash:8].[ext]' } }]
      }
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    // prints more readable module names in the browser console on HMR updates
    new webpack.NamedModulesPlugin(),
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
    })
  ],
  devtool: 'cheap-module-source-map'
}<|endoftext|>


<commit_before>process.env.NODE_ENV = process.env.NODE_ENV || 'production';

const environment = require('./environment');

module.exports = environment.toWebpackConfig();
module.exports.devtool = 'none';
<commit_msg>change devtool level<commit_after>process.env.NODE_ENV = process.env.NODE_ENV || 'production';

const environment = require('./environment');

module.exports = environment.toWebpackConfig();
module.exports.devtool = 'source-map';
<|endoftext|>


<commit_before>'use strict';

/* global Connector */

if (location.href === 'http://bandzone.cz/' || location.href === 'https://bandzone.cz/') {
	Connector.playerSelector = '#stats';

	Connector.getArtist = function () {
		var text = $('.stat:has(.ui-miniaudioplayer-state-playing) h4').text().trim();
		return text || null;
	};

	Connector.getTrack = function () {
		var text = $('.stat:has(.ui-miniaudioplayer-state-playing) .songTitle').text().trim();
		return text || null;
	};

	Connector.isPlaying = function () {
		return $('.ui-miniaudioplayer-state-playing').length;
	};
} else {
	Connector.playerSelector = '#playerWidget';

	Connector.getArtist = function () {
		var text = $('.profile-name h1').text().replace($('.profile-name span').text(), '').trim();
		return text || null;
	};

	Connector.trackSelector = '.ui-state-active .ui-audioplayer-song-title';

	Connector.isPlaying = function () {
		return $('ui-audioplayer-button').text() === 'stop';
	};
}
<commit_msg>Fix Bandzone playing state recognition<commit_after>'use strict';

/* global Connector */

if (location.href === 'http://bandzone.cz/' || location.href === 'https://bandzone.cz/') {
	Connector.playerSelector = '#stats';

	Connector.getArtist = function () {
		var text = $('.stat:has(.ui-miniaudioplayer-state-playing) h4').text().trim();
		return text || null;
	};

	Connector.getTrack = function () {
		var text = $('.stat:has(.ui-miniaudioplayer-state-playing) .songTitle').text().trim();
		return text || null;
	};

	Connector.isPlaying = function () {
		return $('.ui-miniaudioplayer-state-playing').length;
	};
} else {
	Connector.playerSelector = '#playerWidget';

	Connector.getArtist = function () {
		var text = $('.profile-name h1').text().replace($('.profile-name span').text(), '').trim();
		return text || null;
	};

	Connector.trackSelector = '.ui-state-active .ui-audioplayer-song-title';

	Connector.isPlaying = function () {
		return $('.ui-audioplayer-button').text() === 'stop';
	};
}
<|endoftext|>


<commit_before>'use strict';

Meteor.publish('contactList', function() {
  return Meteor.Contact.find({});
});

Meteor.methods({
  'insertContact': function(contact) {
    Meteor.Contact.insert({
      name: contact.name,
      email: contact.email,
      age: contact.age
    });
  }
});
<commit_msg>Add update contact and rename to Contacts<commit_after>'use strict';

Meteor.publish('contactList', function() {
  return Contacts.find({});
});

Meteor.methods({
  'insertContact': function(contact) {
    Contacts.insert({
      name: contact.name,
      email: contact.email,
      age: contact.age
    });
  },
  'updateContact': function(contact) {
    Contacts.update(contact.id, {
        $set: {
          name: contact.name,
          email: contact.email,
          age: contact.age
        }
      });
    }
});
<|endoftext|>


<commit_before>'use strict';
var turf = require('turf');
var _ = require('underscore');
var rbush = require('rbush');

module.exports = function(tileLayers, tile, writeData, done) {
  var layer = tileLayers.osm.osm;
  var highways = {};
  var bboxes = [];
  var preserveType = {
    'motorway': true,
    'primary': true,
    'secondary': true,
    'tertiary': true,
    'trunk': true,
    'residential': true,
    'unclassified': true,
    'living_street': true,
    'service': true,
    'road': true
  };
  var osmlint = 'overlaphighways';

  for (var i = 0; i < layer.features.length; i++) {
    var val = layer.features[i];
    if (preserveType[val.properties.highway] && (val.geometry.type === 'LineString' || val.geometry.type === 'MultiLineString') && val.properties.layer === undefined) {
      var bboxHighway = turf.extent(val);
      bboxHighway.push(val.properties._osm_way_id);
      bboxes.push(bboxHighway);
      highways[val.properties._osm_way_id] = val;
    }
  }
  var traceTree = rbush(bboxes.length);
  traceTree.load(bboxes);
  var output = {};
  for (var j = 0; j < bboxes.length; j++) {
    var bbox = bboxes[j];
    var overlaps = traceTree.search(bbox);
    for (var k = 0; k < overlaps.length; k++) {
      var overlap = overlaps[k];
      if (bbox[4] !== overlap[4]) {
        var intersect = turf.intersect(highways[overlap[4]], highways[bbox[4]]);
        if (intersect !== undefined && (intersect.geometry.type === 'LineString')) {
          var coordinates = intersect.geometry.coordinates;
          output[bbox[4] + 'p'] = turf.point(coordinates[0], {
            _osmlint: osmlint
          });
          output[overlap[4] + 'p'] = turf.point(coordinates[coordinates.length - 1], {
            _osmlint: osmlint
          });
          highways[bbox[4]].properties._osmlint = osmlint;
          highways[overlap[4]].properties._osmlint = osmlint;
          output[bbox[4]] = highways[bbox[4]];
          output[overlap[4]] = highways[overlap[4]];
        }
      }
    }
  }
  var result = _.values(output);

  if (result.length > 0) {
    var fc = turf.featurecollection(result);
    writeData(JSON.stringify(fc) + '\n');
  }

  done(null, null);

};
<commit_msg>update for MultiLineString<commit_after>'use strict';
var turf = require('turf');
var _ = require('underscore');
var rbush = require('rbush');

module.exports = function(tileLayers, tile, writeData, done) {
  var layer = tileLayers.osm.osm;
  var highways = {};
  var bboxes = [];
  var preserveType = {
    'motorway': true,
    'primary': true,
    'secondary': true,
    'tertiary': true,
    'trunk': true,
    'residential': true,
    'unclassified': true,
    'living_street': true,
    'service': true,
    'road': true
  };
  var osmlint = 'overlaphighways';

  for (var i = 0; i < layer.features.length; i++) {
    var val = layer.features[i];
    if (preserveType[val.properties.highway] && (val.geometry.type === 'LineString' || val.geometry.type === 'MultiLineString') && val.properties.layer === undefined) {
      var bboxHighway = turf.extent(val);
      bboxHighway.push(val.properties._osm_way_id);
      bboxes.push(bboxHighway);
      highways[val.properties._osm_way_id] = val;
    }
  }
  var traceTree = rbush(bboxes.length);
  traceTree.load(bboxes);
  var output = {};
  for (var j = 0; j < bboxes.length; j++) {
    var bbox = bboxes[j];
    var overlaps = traceTree.search(bbox);
    for (var k = 0; k < overlaps.length; k++) {
      var overlap = overlaps[k];
      if (bbox[4] !== overlap[4]) {
        var intersect = turf.intersect(highways[overlap[4]], highways[bbox[4]]);
        if (intersect !== undefined && (intersect.geometry.type === 'LineString' || intersect.geometry.type === 'MultiLineString')) {
          var coordinates = intersect.geometry.coordinates;
          output[bbox[4] + 'p'] = turf.point(coordinates[0], {
            _osmlint: osmlint
          });
          output[overlap[4] + 'p'] = turf.point(coordinates[coordinates.length - 1], {
            _osmlint: osmlint
          });
          highways[bbox[4]].properties._osmlint = osmlint;
          highways[overlap[4]].properties._osmlint = osmlint;
          output[bbox[4]] = highways[bbox[4]];
          output[overlap[4]] = highways[overlap[4]];
        }
      }
    }
  }
  var result = _.values(output);

  if (result.length > 0) {
    var fc = turf.featurecollection(result);
    writeData(JSON.stringify(fc) + '\n');
  }

  done(null, null);

};<|endoftext|>


<commit_before>import { CODE_VARIANTS } from 'docs/src/modules/constants';
import { getDependencies } from 'docs/src/modules/utils/helpers';

function jsDemo(demoData, options) {
  return {
    dependencies: getDependencies(demoData.raw, {
      codeLanguage: CODE_VARIANTS.JS,
      muiCommitRef:
        process.env.PULL_REQUEST && options.previewPackage ? process.env.COMMIT_REF : undefined,
    }),
    files: {
      'demo.js': demoData.raw,
      'index.js': `
import * as React from 'react';
import ReactDOM from 'react-dom';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './demo';

ReactDOM.render(
  ,
  document.querySelector("#root")
);
    `.trim(),
    },
  };
}

function tsDemo(demoData, options) {
  return {
    dependencies: getDependencies(demoData.raw, {
      codeLanguage: CODE_VARIANTS.TS,
      muiCommitRef:
        process.env.PULL_REQUEST && options.previewPackage ? process.env.COMMIT_REF : undefined,
    }),
    files: {
      'demo.tsx': demoData.raw,
      'index.tsx': `
import * as React from 'react';
import ReactDOM from 'react-dom';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './demo';

ReactDOM.render(
  ,
  document.querySelector("#root")
);
    `.trim(),
      'tsconfig.json': `{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}
      `,
    },
    main: 'index.tsx',
    scripts: {
      start: 'react-scripts start',
    },
  };
}

function getLanguageConfig(demoData, options) {
  switch (demoData.codeVariant) {
    case CODE_VARIANTS.TS:
      return tsDemo(demoData, options);
    case CODE_VARIANTS.JS:
      return jsDemo(demoData, options);
    default:
      throw new Error(`Unsupported codeVariant: ${demoData.codeVariant}`);
  }
}

export default function getDemoConfig(demoData, options = {}) {
  const { indexPath = 'public/index.html', previewPackage = true } = options;
  const baseConfig = {
    title: demoData.title,
    description: demoData.githubLocation,
    files: {
      [indexPath]: `
<!DOCTYPE html>

    <title>${demoData.title}</title>

    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
    />

    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/icon?family=Material+Icons"
    />

`.trim(),
    },
  };
  const languageConfig = getLanguageConfig(demoData, {
    previewPackage,
  });

  return {
    ...baseConfig,
    ...languageConfig,
    files: {
      ...baseConfig.files,
      ...languageConfig.files,
    },
  };
}
<commit_msg>[docs] Update demo config for React 18 (#32130)<commit_after>import { CODE_VARIANTS } from 'docs/src/modules/constants';
import { getDependencies } from 'docs/src/modules/utils/helpers';

function jsDemo(demoData, options) {
  return {
    dependencies: getDependencies(demoData.raw, {
      codeLanguage: CODE_VARIANTS.JS,
      muiCommitRef:
        process.env.PULL_REQUEST && options.previewPackage ? process.env.COMMIT_REF : undefined,
    }),
    files: {
      'demo.js': demoData.raw,
      'index.js': `
import * as React from 'react';
import ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './demo';

ReactDOM.createRoot(document.querySelector("#root")).render(

);
    `.trim(),
    },
  };
}

function tsDemo(demoData, options) {
  return {
    dependencies: getDependencies(demoData.raw, {
      codeLanguage: CODE_VARIANTS.TS,
      muiCommitRef:
        process.env.PULL_REQUEST && options.previewPackage ? process.env.COMMIT_REF : undefined,
    }),
    files: {
      'demo.tsx': demoData.raw,
      'index.tsx': `
import * as React from 'react';
import ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './demo';

ReactDOM.createRoot(document.querySelector("#root")).render(

);
    `.trim(),
      'tsconfig.json': `{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}
      `,
    },
    main: 'index.tsx',
    scripts: {
      start: 'react-scripts start',
    },
  };
}

function getLanguageConfig(demoData, options) {
  switch (demoData.codeVariant) {
    case CODE_VARIANTS.TS:
      return tsDemo(demoData, options);
    case CODE_VARIANTS.JS:
      return jsDemo(demoData, options);
    default:
      throw new Error(`Unsupported codeVariant: ${demoData.codeVariant}`);
  }
}

export default function getDemoConfig(demoData, options = {}) {
  const { indexPath = 'public/index.html', previewPackage = true } = options;
  const baseConfig = {
    title: demoData.title,
    description: demoData.githubLocation,
    files: {
      [indexPath]: `
<!DOCTYPE html>

    <title>${demoData.title}</title>

    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
    />

    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/icon?family=Material+Icons"
    />

`.trim(),
    },
  };
  const languageConfig = getLanguageConfig(demoData, {
    previewPackage,
  });

  return {
    ...baseConfig,
    ...languageConfig,
    files: {
      ...baseConfig.files,
      ...languageConfig.files,
    },
  };
}
<|endoftext|>


<commit_before>var jasmine = require("./jasmine");
var spec = false; // TODO

// Add some matcher for mock functions
jasmine.getEnv().beforeEach(function() {
  this.addMatchers({
    toBeCalled: function() {
      if (this.actual.mock === undefined) {
        throw Error('toBeCalled() should be used on a mock function');
      }
      return this.actual.mock.calls.length !== 0;
    },

    lastCalledWith: function() {
      if (this.actual.mock === undefined) {
        throw Error('toBeCalled() should be used on a mock function');
      }
      var calls = this.actual.mock.calls;
      var args = Array.prototype.slice.call(arguments);
      return this.env.equals_(calls[calls.length - 1], args);
    },

    toBeCalledWith: function() {
      if (this.actual.mock === undefined) {
        throw Error('toBeCalled() should be used on a mock function');
      }
      var args = Array.prototype.slice.call(arguments);
      return this.actual.mock.calls.some(function(call) {
        return this.env.equals_(call, args);
      }.bind(this));
    }
  });
});

var _it = jasmine.Env.prototype.it;
var _xit = jasmine.Env.prototype.xit;
jasmine.Env.prototype.it = function(desc, func) {
  // If spec is provided, only run matching specs
  if (!spec || desc.match(new RegExp(spec, 'i'))) {
    return _it.call(this, desc, func);
  } else {
    return this.xit(desc, func);
  }
};
jasmine.Env.prototype.xit = function(desc, func) {
  if (typeof func == 'function') {
    var matches = func.toString().match(/.*\W?expect\(/g);
    if (matches) {
      this.reporter.subReporters_[0].skipCount += matches.length;
      this.reporter.subReporters_[0].totalCount += matches.length;
    }
  }
  return _xit.call(this, desc, func);
}

// Mainline Jasmine sets __Jasmine_been_here_before__ on each object to detect
// cycles, but that doesn't work on frozen objects so we use a WeakMap instead.
// We can only do this if if WeakMap is available, but if WeakMap is
// unavailable, then objects probably can't be frozen anyway.

if (typeof WeakMap !== "undefined") {
  var _comparedObjects = new WeakMap;

  jasmine.Env.prototype.compareObjects_ =
  function(a, b, mismatchKeys, mismatchValues) {
    if (_comparedObjects.get(a) === b && _comparedObjects.get(b) === a) {
      return true;
    }
    var areArrays = jasmine.isArray_(a) && jasmine.isArray_(b);

    _comparedObjects.set(a, b);
    _comparedObjects.set(b, a);

    var hasKey = function(obj, keyName) {
      return obj != null && obj[keyName] !== jasmine.undefined;
    };

    for (var property in b) {
      if (areArrays && typeof b[property] == 'function') {
        continue;
      }
      if (!hasKey(a, property) && hasKey(b, property)) {
        mismatchKeys.push(
          "expected has key '" + property + "', but missing from actual."
        );
      }
    }
    for (property in a) {
      if (areArrays && typeof a[property] == 'function') {
        continue;
      }
      if (!hasKey(b, property) && hasKey(a, property)) {
        mismatchKeys.push(
          "expected missing key '" + property + "', but present in actual."
        );
      }
    }
    for (property in b) {
      // The only different implementation from the original jasmine
      if (areArrays &&
          (typeof a[property] == 'function' ||
           typeof b[property] == 'function')) {
        continue;
      }
      if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues))
      {
        mismatchValues.push(
          "'" + property + "' was '" + (b[property] ?
            jasmine.util.htmlEscape(b[property].toString()) :
            b[property]) +
          "' in expected, but was '" + (a[property] ?
            jasmine.util.htmlEscape(a[property].toString()) :
            a[property]) + "' in actual."
        );
      }
    }

    if (areArrays &&
        a.length != b.length) {
      mismatchValues.push("arrays were not the same length");
    }

    _comparedObjects["delete"](a);
    _comparedObjects["delete"](b);
    return (mismatchKeys.length == 0 && mismatchValues.length == 0);
  };
}
<commit_msg>browser support for jasmine-support<commit_after>if (typeof jasmine == 'undefined') jasmine = require("./jasmine");
var spec = false; // TODO

// Add some matcher for mock functions
jasmine.getEnv().beforeEach(function() {
  this.addMatchers({
    toBeCalled: function() {
      if (this.actual.mock === undefined) {
        throw Error('toBeCalled() should be used on a mock function');
      }
      return this.actual.mock.calls.length !== 0;
    },

    lastCalledWith: function() {
      if (this.actual.mock === undefined) {
        throw Error('toBeCalled() should be used on a mock function');
      }
      var calls = this.actual.mock.calls;
      var args = Array.prototype.slice.call(arguments);
      return this.env.equals_(calls[calls.length - 1], args);
    },

    toBeCalledWith: function() {
      if (this.actual.mock === undefined) {
        throw Error('toBeCalled() should be used on a mock function');
      }
      var args = Array.prototype.slice.call(arguments);
      return this.actual.mock.calls.some(function(call) {
        return this.env.equals_(call, args);
      }.bind(this));
    }
  });
});

var _it = jasmine.Env.prototype.it;
var _xit = jasmine.Env.prototype.xit;
jasmine.Env.prototype.it = function(desc, func) {
  // If spec is provided, only run matching specs
  if (!spec || desc.match(new RegExp(spec, 'i'))) {
    return _it.call(this, desc, func);
  } else {
    return this.xit(desc, func);
  }
};
jasmine.Env.prototype.xit = function(desc, func) {
  if (typeof func == 'function') {
    var matches = func.toString().match(/.*\W?expect\(/g);
    if (matches) {
      this.reporter.subReporters_[0].skipCount += matches.length;
      this.reporter.subReporters_[0].totalCount += matches.length;
    }
  }
  return _xit.call(this, desc, func);
}

// Mainline Jasmine sets __Jasmine_been_here_before__ on each object to detect
// cycles, but that doesn't work on frozen objects so we use a WeakMap instead.
// We can only do this if if WeakMap is available, but if WeakMap is
// unavailable, then objects probably can't be frozen anyway.

if (typeof WeakMap !== "undefined") {
  var _comparedObjects = new WeakMap;

  jasmine.Env.prototype.compareObjects_ =
  function(a, b, mismatchKeys, mismatchValues) {
    if (_comparedObjects.get(a) === b && _comparedObjects.get(b) === a) {
      return true;
    }
    var areArrays = jasmine.isArray_(a) && jasmine.isArray_(b);

    _comparedObjects.set(a, b);
    _comparedObjects.set(b, a);

    var hasKey = function(obj, keyName) {
      return obj != null && obj[keyName] !== jasmine.undefined;
    };

    for (var property in b) {
      if (areArrays && typeof b[property] == 'function') {
        continue;
      }
      if (!hasKey(a, property) && hasKey(b, property)) {
        mismatchKeys.push(
          "expected has key '" + property + "', but missing from actual."
        );
      }
    }
    for (property in a) {
      if (areArrays && typeof a[property] == 'function') {
        continue;
      }
      if (!hasKey(b, property) && hasKey(a, property)) {
        mismatchKeys.push(
          "expected missing key '" + property + "', but present in actual."
        );
      }
    }
    for (property in b) {
      // The only different implementation from the original jasmine
      if (areArrays &&
          (typeof a[property] == 'function' ||
           typeof b[property] == 'function')) {
        continue;
      }
      if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues))
      {
        mismatchValues.push(
          "'" + property + "' was '" + (b[property] ?
            jasmine.util.htmlEscape(b[property].toString()) :
            b[property]) +
          "' in expected, but was '" + (a[property] ?
            jasmine.util.htmlEscape(a[property].toString()) :
            a[property]) + "' in actual."
        );
      }
    }

    if (areArrays &&
        a.length != b.length) {
      mismatchValues.push("arrays were not the same length");
    }

    _comparedObjects["delete"](a);
    _comparedObjects["delete"](b);
    return (mismatchKeys.length == 0 && mismatchValues.length == 0);
  };
}
<|endoftext|>


<commit_before>/**
 * @author Koszti Lajos [Ajnasz] http://ajnasz.hu ajnasz@ajnasz.hu
 * @licence General Public Licence v2
 */
HP = function() {
  this.M = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  this.get.M = this.set.M = this.M;
};
HP.prototype = {
  M: null, // Manager
  get: {
    trolls: function() {
      return this.M.getCharPref('extensions.hupper.trolls');
    },
    /**
    * @return {Boolean}
    */
    filtertrolls: function() {
      return this.M.getBoolPref('extensions.hupper.filtertrolls');
    },
    trollcolor: function() {
      return this.M.getCharPref('extensions.hupper.trollcolor');
    },
    /**
    * @return hide, hilight
    */
    trollfiltermethod: function() {
      // hide, hilight
      return this.M.getCharPref('extensions.hupper.trollfiltermethod');
    },
    /**
    * @return {String}
    */
    huppers: function() {
      return this.M.getCharPref('extensions.hupper.huppers');
    },
    filterhuppers: function() {
      return this.M.getBoolPref('extensions.hupper.filterhuppers');
    },
    huppercolor: function() {
      return this.M.getCharPref('extensions.hupper.huppercolor');
    },
    replacenewcommenttext: function() {
      return this.M.getBoolPref('extensions.hupper.replacenewcommenttext');
    },
    newcommenttext: function() {
      return this.M.getCharPref('extensions.hupper.newcommenttext');
    },
    extracommentlinks: function() {
      return this.M.getBoolPref('extensions.hupper.extracommentlinks');
    },
    hilightforumlinesonhover: function() {
      return this.M.getBoolPref('extensions.hupper.hilightforumlinesonhover');
    },
    insertpermalink: function() {
      return this.M.getBoolPref('extensions.hupper.insertpermalink');
    },
    insertnewtexttonode: function() {
      return this.M.getBoolPref('extensions.hupper.insertnewtexttonode');
    },
    fadeparentcomment: function() {
      return this.M.getBoolPref('extensions.hupper.fadeparentcomment');
    },
    showqnavbox: function() {
      return this.M.getBoolPref('extensions.hupper.showqnavbox');
    },
    hidetrollanswers: function() {
      return this.M.getBoolPref('extensions.hupper.hidetrollanswers');
    },
    hideads: function() {
      return this.M.getBoolPref('extensions.hupper.hideads');
    },
    highlightusers: function() {
      return this.M.getCharPref('extensions.hupper.highlightusers');
    }
  },
  set: {
    M: this.M,
    trolls: function(value) {
      this.M.setCharPref('extensions.hupper.trolls', value);
    },
    /**
    * @return {Boolean}
    */
    filtertrolls: function(value) {
      this.M.setBoolPref('extensions.hupper.filtertrolls', value);
    },
    /**
    * @return hide, hilight
    */
    trollfiltermethod: function(value) {
      // hide, hilight
      this.M.setCharPref('extensions.hupper.trollfiltermethod', value);
    },
    trollcolor: function(value) {
      this.M.setCharPref('extensions.hupper.trollcolor', value);
    },
    /**
    * @return {String}
    */
    huppers: function(value) {
      this.M.setCharPref('extensions.hupper.huppers', value);
    },
    filterhuppers: function(value) {
      this.M.setBoolPref('extensions.hupper.filterhuppers', value);
    },
    huppercolor: function(value) {
      this.M.setCharPref('extensions.hupper.huppercolor', value);
    },
    replacenewcommenttext: function(value) {
      this.M.setBoolPref('extensions.hupper.replacenewcommenttext', value);
    },
    newcommenttext: function(value) {
      this.M.setCharPref('extensions.hupper.newcommenttext', value);
    },
    extracommentlinks: function(value) {
      this.M.setBoolPref('extensions.hupper.extracommentlinks', value);
    },
    hilightforumlinesonhover: function(value) {
      this.M.setBoolPref('extensions.hupper.hilightforumlinesonhover', value);
    },
    insertpermalink: function(value) {
      this.M.setBoolPref('extensions.hupper.insertpermalink', value);
    },
    insertnewtexttonode: function(value) {
      this.M.setBoolPref('extensions.hupper.insertnewtexttonode', value);
    },
    fadeparentcomment: function(value) {
      this.M.setBoolPref('extensions.hupper.fadeparentcomment', value);
    },
    showqnavbox: function(value) {
      this.M.setBoolPref('extensions.hupper.showqnavbox', value);
    },
    hidetrollanswers: function(value) {
      this.M.setBoolPref('extensions.hupper.hidetrollanswers', value);
    },
    hideads: function(value) {
      this.M.setBoolPref('extensions.hupper.hideads', value);
    },
    highlightusers: function(value) {
      this.M.setCharPref('extensions.hupper.highlightusers', value);
    },
  }
};
setPrefWinVals = function() {
  document.getElementById('enable-trollfilter').checked = hp.get.filtertrolls();
  document.getElementById('trolls').value = hp.get.trolls();
  document.getElementById('troll-color').value = hp.get.trollcolor();
  document.getElementById('trollfilter-method').value = hp.get.trollfiltermethod();
  document.getElementById('enable-hupperfilter').checked = hp.get.filterhuppers();
  document.getElementById('huppers').value = hp.get.huppers();
  document.getElementById('hupper-color').value = hp.get.huppercolor();
  document.getElementById('enable-new-comment-changer').checked = hp.get.replacenewcommenttext();
  document.getElementById('new-comment-text').value = hp.get.newcommenttext();
  document.getElementById('enable-extra-comment-links').checked = hp.get.extracommentlinks();
  document.getElementById('hilight-forum-lines-onhover').checked = hp.get.hilightforumlinesonhover();
  document.getElementById('insert-permalink').checked = hp.get.insertpermalink();
  document.getElementById('insert-new-text-to-node').checked = hp.get.insertnewtexttonode();
  document.getElementById('fade-parent-comment').checked = hp.get.fadeparentcomment();
  document.getElementById('show-quick-nav-box').checked = hp.get.showqnavbox();
  document.getElementById('hide-troll-answers').checked = hp.get.hidetrollanswers();
  document.getElementById('hupper-highlightusers').value = hp.get.highlightusers();
};
savePreferences = function() {
  if(!checkHLUsers()) {return false;}
  hp.set.filtertrolls(document.getElementById('enable-trollfilter').checked);
  hp.set.trolls(document.getElementById('trolls').value);
  hp.set.trollcolor(document.getElementById('troll-color').value);
  hp.set.trollfiltermethod(document.getElementById('trollfilter-method').value);
  hp.set.filterhuppers(document.getElementById('enable-hupperfilter').checked);
  hp.set.huppers(document.getElementById('huppers').value);
  hp.set.huppercolor(document.getElementById('hupper-color').value);
  hp.set.replacenewcommenttext(document.getElementById('enable-new-comment-changer').checked);
  hp.set.newcommenttext(document.getElementById('new-comment-text').value);
  hp.set.extracommentlinks(document.getElementById('enable-extra-comment-links').checked);
  hp.set.hilightforumlinesonhover(document.getElementById('hilight-forum-lines-onhover').checked);
  hp.set.insertpermalink(document.getElementById('insert-permalink').checked);
  hp.set.insertnewtexttonode(document.getElementById('insert-new-text-to-node').checked);
  hp.set.fadeparentcomment(document.getElementById('fade-parent-comment').checked);
  hp.set.showqnavbox(document.getElementById('show-quick-nav-box').checked);
  hp.set.hidetrollanswers(document.getElementById('hide-troll-answers').checked);
  hp.set.highlightusers(document.getElementById('hupper-highlightusers').value);
  return true;
};
var disableFields = function() {
  document.getElementById('trollfilter-method').addEventListener('command', onChangeFilterMethod, false);
};
var onChangeFilterMethod = function() {
  if(document.getElementById('trollfilter-method').value == 'hide') {
    document.getElementById('hide-troll-answers').disabled = false;
  } else {
    document.getElementById('hide-troll-answers').disabled = true;
  }
};
var checkHLUsers = function() {
  var hlUsers = document.getElementById('hupper-highlightusers').value.split(',');
  var trolls = document.getElementById('troll-color').value.split(',');
  var huppers = document.getElementById('huppers').value.split(',');
  var hlUsersObj = {};
  for(var i = 0, hlUsers.length, hlUser; i < hl; i++) {
    hlUser = hlUsers[i].split(':');
    hlUsersObj[hlUser[0]] = hlUsers[1];
  }
  var used = new Array();
  for(i = 0, hl = huppers.length; i < hl; i++) {
    if(hlUsersObj[huppers[i]]) {
      used.push(huppers[i]);
    }
  }
  for(i = 0, trolls.length;; i < tl i++) {
    if(hlUsersObj[huppers[i]]) {
      used.push(huppers[i]);
    }
  }
  if(used.length > 0) {
    return confirm(used.join(',') + ' already highlighted as hupper or troll')
  }
  return true;
};
var StartHupperPrefernces = function() {
  HUP = {};
  HUP.L = new HLog();
  hp = new HP();
  disableFields();
  setPrefWinVals();
  onChangeFilterMethod();
};
<commit_msg>[svn]  - remove HP, moved to hp.js  - fix some for loop  - add login save functions<commit_after>/**
 * @author Koszti Lajos [Ajnasz] http://ajnasz.hu ajnasz@ajnasz.hu
 * @licence General Public Licence v2
 */
setPrefWinVals = function() {
  document.getElementById('enable-trollfilter').checked = hp.get.filtertrolls();
  document.getElementById('trolls').value = hp.get.trolls();
  document.getElementById('troll-color').value = hp.get.trollcolor();
  document.getElementById('trollfilter-method').value = hp.get.trollfiltermethod();
  document.getElementById('enable-hupperfilter').checked = hp.get.filterhuppers();
  document.getElementById('huppers').value = hp.get.huppers();
  document.getElementById('hupper-color').value = hp.get.huppercolor();
  document.getElementById('enable-new-comment-changer').checked = hp.get.replacenewcommenttext();
  document.getElementById('new-comment-text').value = hp.get.newcommenttext();
  document.getElementById('enable-extra-comment-links').checked = hp.get.extracommentlinks();
  document.getElementById('hilight-forum-lines-onhover').checked = hp.get.hilightforumlinesonhover();
  document.getElementById('insert-permalink').checked = hp.get.insertpermalink();
  document.getElementById('insert-new-text-to-node').checked = hp.get.insertnewtexttonode();
  document.getElementById('fade-parent-comment').checked = hp.get.fadeparentcomment();
  document.getElementById('show-quick-nav-box').checked = hp.get.showqnavbox();
  document.getElementById('hide-troll-answers').checked = hp.get.hidetrollanswers();
  document.getElementById('hupper-highlightusers').value = hp.get.highlightusers();
  document.getElementById('hupper-password').value = new _passwordManager().getPassword();
  document.getElementById('hupper-username').value = hp.get.username();
};
savePreferences = function() {
  if(!checkHLUsers()) {return false;}
  hp.set.filtertrolls(document.getElementById('enable-trollfilter').checked);
  hp.set.trolls(document.getElementById('trolls').value);
  hp.set.trollcolor(document.getElementById('troll-color').value);
  hp.set.trollfiltermethod(document.getElementById('trollfilter-method').value);
  hp.set.filterhuppers(document.getElementById('enable-hupperfilter').checked);
  hp.set.huppers(document.getElementById('huppers').value);
  hp.set.huppercolor(document.getElementById('hupper-color').value);
  hp.set.replacenewcommenttext(document.getElementById('enable-new-comment-changer').checked);
  hp.set.newcommenttext(document.getElementById('new-comment-text').value);
  hp.set.extracommentlinks(document.getElementById('enable-extra-comment-links').checked);
  hp.set.hilightforumlinesonhover(document.getElementById('hilight-forum-lines-onhover').checked);
  hp.set.insertpermalink(document.getElementById('insert-permalink').checked);
  hp.set.insertnewtexttonode(document.getElementById('insert-new-text-to-node').checked);
  hp.set.fadeparentcomment(document.getElementById('fade-parent-comment').checked);
  hp.set.showqnavbox(document.getElementById('show-quick-nav-box').checked);
  hp.set.hidetrollanswers(document.getElementById('hide-troll-answers').checked);
  hp.set.highlightusers(document.getElementById('hupper-highlightusers').value);
  hp.set.username(document.getElementById('hupper-username').value);
  new _passwordManager().addPassword(document.getElementById('hupper-password').value);
  return true;
};
var disableFields = function() {
  document.getElementById('trollfilter-method').addEventListener('command', onChangeFilterMethod, false);
};
var onChangeFilterMethod = function() {
  if(document.getElementById('trollfilter-method').value == 'hide') {
    document.getElementById('hide-troll-answers').disabled = false;
  } else {
    document.getElementById('hide-troll-answers').disabled = true;
  }
};
var checkHLUsers = function() {
  var hlUsers = document.getElementById('hupper-highlightusers').value.split(',');
  var trolls = document.getElementById('troll-color').value.split(',');
  var huppers = document.getElementById('huppers').value.split(',');
  var hlUsersObj = {};
  for(var i = 0, hl = hlUsers.length, hlUser; i < hl; i++) {
    hlUser = hlUsers[i].split(':');
    hlUsersObj[hlUser[0]] = hlUsers[1];
  }
  var used = new Array();
  for(var i = 0, hl = huppers.length; i < hl; i++) {
    if(hlUsersObj[huppers[i]]) {
      used.push(huppers[i]);
    }
  }
  for(var i = 0,tl= trolls.length; i < tl; i++) {
    if(hlUsersObj[huppers[i]]) {
      used.push(huppers[i]);
    }
  }
  if(used.length > 0) {
    return confirm(used.join(',') + ' already highlighted as hupper or troll')
  }
  return true;
};
var StartHupperPrefernces = function() {
  HUP = {};
  HUP.L = new HLog();
  hp = new HP();
  disableFields();
  setPrefWinVals();
  onChangeFilterMethod();
};
<|endoftext|>


<commit_before>/* global angular */

(function (angular) {
    'use strict';

    angular.module('eole.games.awale').controller('AwaleController', function ($scope, $routeParams, eoleApi, eoleWs, $timeout, partyManager, eoleSession, $translate, gridManager, animHighlight, Seeds) {
        var ANIMATION_DELAY = 250;
        var partyId = $routeParams.partyId;
        var seedsCoords = new Seeds({x: 19, y: 19});
        var playerPosition = null;
        $scope.currentPlayer = null;
        $scope.reverseBoard = false;
        $scope.winner = null;
        $scope.screenPlayer0 = 0;
        $scope.screenPlayer1 = 1;
        $scope.displayJoinButton = false;
        $scope.party = {};
        $scope.seedsCoords = seedsCoords.toStyle();
        $scope.bottomText = '';
        $scope.grid = gridManager.createInitGrid();
        $scope.flashed = animHighlight.initFlashGrid();
        $scope.lastMove = null;
        var animationThreads = [];
        initLastMove();

        $scope.join = function () {
            eoleSession.oauthTokenPromise.then(function (token) {
                eoleApi.joinParty(token, 'awale', partyId);
            });
        };

        $scope.move = function (move) {
            var lastGrid = gridManager.cloneGrid($scope.grid);

            eoleSession.oauthTokenPromise.then(function (token) {
                eoleApi.callGame('awale', 'post', 'play', token, {
                    move: move,
                    party_id: partyId
                }).then(function (r) {
                    $scope.currentPlayer = r.currentPlayer;
                }).catch(function () {
                    stopAnimation();
                    $scope.grid = lastGrid;
                    $scope.currentPlayer = 1 - $scope.currentPlayer;
                    updateSeedsCoords();
                    initLastMove();
                });
            });

            initLastMove();
            animate(playerPosition, move);
            $scope.currentPlayer = 1 - $scope.currentPlayer;
        };

        eoleApi.callGame('awale', 'get', 'find-by-id/' + partyId).then(function (awaleParty) {
            $scope.party = awaleParty.party;
            $scope.grid = awaleParty.grid;
            $scope.currentPlayer = awaleParty.current_player;
            $scope.winner = awaleParty.winner;
            updateBoardVariables();
            updateSeedsCoords();
            updateWinner();
        });

        eoleWs.socketPromise.then(function (socket) {
            socket.subscribe('eole/games/awale/parties/' + partyId, function (topic, event) {
                switch (event.type) {
                    case 'join':
                        $scope.party = event.party;
                        updateBoardVariables();
                        break;

                    case 'played':
                        if (playerPosition !== event.move.player) {
                            initLastMove();
                            animate(event.move.player, event.move.move);
                            $scope.currentPlayer = event.current_player;
                        }
                        break;

                    case 'party_end':
                        $scope.party.state = 2;
                        $scope.winner = event.winner;
                        updateWinner();
                        break;
                }

                $scope.$apply();
            });
        });

        function animate(player, move) {
            var animationSteps = [];

            var _player = player;
            var _move = move;
            var simulationGrid = gridManager.cloneGrid($scope.grid);
            var hand = gridManager.getSeedsNumber(simulationGrid, player, move);

            animationSteps.push([player, move, -gridManager.getSeedsNumber(simulationGrid, player, move)]);
            gridManager.clearSeedsNumber(simulationGrid, player, move);

            while (hand > 0) {
                if (0 === _player) {
                    _move--;

                    if (_move < 0) {
                        _move = 0;
                        _player = 1;
                    }
                } else {
                    _move++;

                    if (_move > 5) {
                        _move = 5;
                        _player = 0;
                    }
                }

                if (_move === move && _player === player) {
                    continue;
                }

                hand--;
                gridManager.addSeeds(simulationGrid, _player, _move, 1);
                animationSteps.push([_player, _move, 1]);
            }

            if (!gridManager.willStarveOpponent(simulationGrid, player, _player, _move)) {
                if (_player === player) {
                    return;
                }

                while (
                    (-1 !== [0, 1, 2, 3, 4, 5].indexOf(_move)) &&
                    (gridManager.has2Or3Seeds(simulationGrid, _player, _move))
                ) {
                    animationSteps.push([_player, _move, 'store']);
                    _move += _player ? -1 : 1;
                }
            }

            angular.forEach(animationSteps, function (step, i) {
                $scope.lastMove[animationSteps[0][0]][animationSteps[0][1]].push('start');

                var thread = $timeout(function () {
                    if ('store' === step[2]) {
                        gridManager.storeSeeds($scope.grid, step[0], step[1]);
                        $scope.lastMove[step[0]][step[1]].push('eat');
                        animHighlight.flashAttic($scope.flashed, 1 - step[0]);
                    } else {
                        gridManager.addSeeds($scope.grid, step[0], step[1], step[2]);
                    }

                    $scope.lastMove[step[0]][step[1]].push('feed');
                    animHighlight.flashBox($scope.flashed, step[0], step[1]);

                    updateSeedsCoords();
                }, i * ANIMATION_DELAY);

                animationThreads.push(thread);
            });
        }

        function stopAnimation() {
            while (animationThreads.length > 0) {
                $timeout.cancel(animationThreads.pop());
            }
        }

        function updateBoardVariables() {
            $scope.displayJoinButton = ($scope.party.state === 0) && !partyManager.inParty($scope.party);
            playerPosition = partyManager.getPlayerPosition($scope.party);
            $scope.reverseBoard = 0 === playerPosition;
            if ($scope.reverseBoard) {
                $scope.screenPlayer0 = 1;
                $scope.screenPlayer1 = 0;
            }
        }

        function updateSeedsCoords() {
            seedsCoords.setGrid($scope.grid);
            $scope.seedsCoords = seedsCoords.toStyle();
        }

        function updateWinner() {
            if (-1 !== [0, 1].indexOf($scope.winner)) {
                $translate('{username}.won', $scope.party.slots[$scope.winner].player).then(function (message) {
                    $scope.bottomText = message;
                });
            } else if (-1 === $scope.winner) {
                $translate('party.drawn').then(function (message) {
                    $scope.bottomText = message;
                });
            } else {
                $scope.bottomText = '';
            }
        }

        function initLastMove() {
            $scope.lastMove = [
                [[], [], [], [], [], []],
                [[], [], [], [], [], []]
            ];
        }

        $scope.isMyTurn = function () {
            return (null !== playerPosition) && ($scope.currentPlayer === playerPosition);
        };

        $scope.canMove = function () {
            return $scope.isPartyActive() && $scope.isMyTurn();
        };

        $scope.canMoveContainer = function (seedNumber) {
            return $scope.canMove() && seedNumber;
        };

        $scope.isPartyActive = function () {
            if (!$scope.party) {
                return false;
            }

            return 1 === $scope.party.state;
        };
    });
})(angular);
<commit_msg>awele: listen websocket for party start push event<commit_after>/* global angular */

(function (angular) {
    'use strict';

    angular.module('eole.games.awale').controller('AwaleController', function ($scope, $routeParams, eoleApi, eoleWs, $timeout, partyManager, eoleSession, $translate, gridManager, animHighlight, Seeds) {
        var ANIMATION_DELAY = 250;
        var partyId = $routeParams.partyId;
        var seedsCoords = new Seeds({x: 19, y: 19});
        var playerPosition = null;
        $scope.currentPlayer = null;
        $scope.reverseBoard = false;
        $scope.winner = null;
        $scope.screenPlayer0 = 0;
        $scope.screenPlayer1 = 1;
        $scope.displayJoinButton = false;
        $scope.party = {};
        $scope.seedsCoords = seedsCoords.toStyle();
        $scope.bottomText = '';
        $scope.grid = gridManager.createInitGrid();
        $scope.flashed = animHighlight.initFlashGrid();
        $scope.lastMove = null;
        var animationThreads = [];
        initLastMove();

        $scope.join = function () {
            eoleSession.oauthTokenPromise.then(function (token) {
                eoleApi.joinParty(token, 'awale', partyId);
            });
        };

        $scope.move = function (move) {
            var lastGrid = gridManager.cloneGrid($scope.grid);

            eoleSession.oauthTokenPromise.then(function (token) {
                eoleApi.callGame('awale', 'post', 'play', token, {
                    move: move,
                    party_id: partyId
                }).then(function (r) {
                    $scope.currentPlayer = r.currentPlayer;
                }).catch(function () {
                    stopAnimation();
                    $scope.grid = lastGrid;
                    $scope.currentPlayer = 1 - $scope.currentPlayer;
                    updateSeedsCoords();
                    initLastMove();
                });
            });

            initLastMove();
            animate(playerPosition, move);
            $scope.currentPlayer = 1 - $scope.currentPlayer;
        };

        eoleApi.callGame('awale', 'get', 'find-by-id/' + partyId).then(function (awaleParty) {
            $scope.party = awaleParty.party;
            $scope.grid = awaleParty.grid;
            $scope.currentPlayer = awaleParty.current_player;
            $scope.winner = awaleParty.winner;
            updateBoardVariables();
            updateSeedsCoords();
            updateWinner();
        });

        eoleWs.socketPromise.then(function (socket) {
            socket.subscribe('eole/games/awale/parties/' + partyId, function (topic, event) {
                switch (event.type) {
                    case 'join':
                        $scope.party = event.party;
                        updateBoardVariables();
                        break;

                    case 'party_start':
                        $scope.party.state = 1;
                        updateBoardVariables();
                        break;

                    case 'played':
                        if (playerPosition !== event.move.player) {
                            initLastMove();
                            animate(event.move.player, event.move.move);
                            $scope.currentPlayer = event.current_player;
                        }
                        break;

                    case 'party_end':
                        $scope.party.state = 2;
                        $scope.winner = event.winner;
                        updateWinner();
                        break;
                }

                $scope.$apply();
            });
        });

        function animate(player, move) {
            var animationSteps = [];

            var _player = player;
            var _move = move;
            var simulationGrid = gridManager.cloneGrid($scope.grid);
            var hand = gridManager.getSeedsNumber(simulationGrid, player, move);

            animationSteps.push([player, move, -gridManager.getSeedsNumber(simulationGrid, player, move)]);
            gridManager.clearSeedsNumber(simulationGrid, player, move);

            while (hand > 0) {
                if (0 === _player) {
                    _move--;

                    if (_move < 0) {
                        _move = 0;
                        _player = 1;
                    }
                } else {
                    _move++;

                    if (_move > 5) {
                        _move = 5;
                        _player = 0;
                    }
                }

                if (_move === move && _player === player) {
                    continue;
                }

                hand--;
                gridManager.addSeeds(simulationGrid, _player, _move, 1);
                animationSteps.push([_player, _move, 1]);
            }

            if (!gridManager.willStarveOpponent(simulationGrid, player, _player, _move)) {
                if (_player === player) {
                    return;
                }

                while (
                    (-1 !== [0, 1, 2, 3, 4, 5].indexOf(_move)) &&
                    (gridManager.has2Or3Seeds(simulationGrid, _player, _move))
                ) {
                    animationSteps.push([_player, _move, 'store']);
                    _move += _player ? -1 : 1;
                }
            }

            angular.forEach(animationSteps, function (step, i) {
                $scope.lastMove[animationSteps[0][0]][animationSteps[0][1]].push('start');

                var thread = $timeout(function () {
                    if ('store' === step[2]) {
                        gridManager.storeSeeds($scope.grid, step[0], step[1]);
                        $scope.lastMove[step[0]][step[1]].push('eat');
                        animHighlight.flashAttic($scope.flashed, 1 - step[0]);
                    } else {
                        gridManager.addSeeds($scope.grid, step[0], step[1], step[2]);
                    }

                    $scope.lastMove[step[0]][step[1]].push('feed');
                    animHighlight.flashBox($scope.flashed, step[0], step[1]);

                    updateSeedsCoords();
                }, i * ANIMATION_DELAY);

                animationThreads.push(thread);
            });
        }

        function stopAnimation() {
            while (animationThreads.length > 0) {
                $timeout.cancel(animationThreads.pop());
            }
        }

        function updateBoardVariables() {
            $scope.displayJoinButton = ($scope.party.state === 0) && !partyManager.inParty($scope.party);
            playerPosition = partyManager.getPlayerPosition($scope.party);
            $scope.reverseBoard = 0 === playerPosition;
            if ($scope.reverseBoard) {
                $scope.screenPlayer0 = 1;
                $scope.screenPlayer1 = 0;
            }
        }

        function updateSeedsCoords() {
            seedsCoords.setGrid($scope.grid);
            $scope.seedsCoords = seedsCoords.toStyle();
        }

        function updateWinner() {
            if (-1 !== [0, 1].indexOf($scope.winner)) {
                $translate('{username}.won', $scope.party.slots[$scope.winner].player).then(function (message) {
                    $scope.bottomText = message;
                });
            } else if (-1 === $scope.winner) {
                $translate('party.drawn').then(function (message) {
                    $scope.bottomText = message;
                });
            } else {
                $scope.bottomText = '';
            }
        }

        function initLastMove() {
            $scope.lastMove = [
                [[], [], [], [], [], []],
                [[], [], [], [], [], []]
            ];
        }

        $scope.isMyTurn = function () {
            return (null !== playerPosition) && ($scope.currentPlayer === playerPosition);
        };

        $scope.canMove = function () {
            return $scope.isPartyActive() && $scope.isMyTurn();
        };

        $scope.canMoveContainer = function (seedNumber) {
            return $scope.canMove() && seedNumber;
        };

        $scope.isPartyActive = function () {
            if (!$scope.party) {
                return false;
            }

            return 1 === $scope.party.state;
        };
    });
})(angular);
<|endoftext|>


<commit_before>/**
 * XadillaX created at 2016-04-01 13:52:27 With ♥
 *
 * Copyright (c) 2016 Souche.com, all rights
 * reserved.
 */
"use strict";

const Akyuu = require("../../../../");
const Joi = Akyuu.Joi;

let routers = module.exports = [];

const jiandan = (req, resp) => {
    let page = req.params.page;
    req.app.service.get("jiandan").getOOXX(page, function(err, result) {
        if(err) {
            return resp.error(err);
        }

        resp.succ(result);
    });
};

routers.push({
    router: "/config",
    processors: [(req, resp) => {
        console.log(Akyuu.config.func);
        resp.succ(Akyuu.config);
    }]
});

routers.push({
    router: "/jiandan",
    processors: [ jiandan ]
});

routers.push({
    router: "/jiandan/:page",
    processors: [ jiandan ],
    params: {
        page: Joi.number().integer()
    }
});

routers.push({
    body: {},
    desc: "Test router.",
    error: {},
    method: "GET",
    params: {
        0: Joi.string().min(0).max(5).default("akyuu")
    },
    query: {
        app: Joi.string().default("akyuu").min(1).max(5)
    },
    router: /^\/(.*)$/,

    processors: [(req, resp) => {
        resp.succ({
            app: req.query.app,
            welcome: `Hello ${req.params[0]}!`,
            modelData: Akyuu.get().model.get("test").getData()
        });
    }]
});
<commit_msg>add a error test route in demo<commit_after>/**
 * XadillaX created at 2016-04-01 13:52:27 With ♥
 *
 * Copyright (c) 2016 Souche.com, all rights
 * reserved.
 */
"use strict";

const Akyuu = require("../../../../");
const Joi = Akyuu.Joi;

let routers = module.exports = [];

const jiandan = (req, resp) => {
    let page = req.params.page;
    req.app.service.get("jiandan").getOOXX(page, function(err, result) {
        if(err) {
            return resp.error(err);
        }

        resp.succ(result);
    });
};

routers.push({
    router: "/config",
    processors: [(req, resp) => {
        console.log(Akyuu.config.func);
        resp.succ(Akyuu.config);
    }]
});

routers.push({
    router: "/jiandan",
    processors: [ jiandan ]
});

routers.push({
    router: "/jiandan/:page",
    processors: [ jiandan ],
    params: {
        page: Joi.number().integer()
    }
});

routers.push({
    router: "/error/:err",
    processors: [(req, resp) => {
        const Err = req.app.Errors[req.params.err.camelize(true)];
        if(undefined === Err) {
            return resp.error(new Error("Unknown error."));
        }

        resp.error(new Err("这是一个样例。"));
    }],
    params: {
        err: Joi.string()
    }
});

routers.push({
    body: {},
    desc: "Test router.",
    error: {},
    method: "GET",
    params: {
        0: Joi.string().min(0).max(5).default("akyuu")
    },
    query: {
        app: Joi.string().default("akyuu").min(1).max(5)
    },
    router: /^\/(.*)$/,

    processors: [(req, resp) => {
        resp.succ({
            app: req.query.app,
            welcome: `Hello ${req.params[0]}!`,
            modelData: Akyuu.get().model.get("test").getData()
        });
    }]
});
<|endoftext|>