<commit_before>'use strict';
var ObjectId = require('mongodb').ObjectID;

var parseAuthorization = function(authorization) {
  if (!authorization){
    var err = Error('missing authorization header');
    err.statusCode = 401;
    throw err;
  }

  var token = authorization.replace(/Token token=\"(.+)\"/g, '$1');
  return token;
};

var getUserByToken = function*(db, token) {
  var session = yield db.sessions.findOne({token: token});
  var user = yield db.users.findOne({_id: ObjectId(String(session.userId))});
  return user;
};

var sortCFFLinesByDate = function (a, b) {
  const dateStringA = a.invoice ? a.invoice.date : a.payments[0].date;
  const dateStringB = b.invoice ? b.invoice.date : b.payments[0].date;
  const dateA = new Date(dateStringA);
  const dateB = new Date(dateStringB);

  return dateB.getTime() - dateA.getTime();
};

var getPaymentsFromDocumentLines = function (docLines) {
  if (docLines.length === 0) {
    return [];
  }

  var lines = docLines.map(function(docLine) {
    return docLine.line;
  });

  var payments = lines.map(function(line, index) {
    var info = Object.keys(line).reduce(function(acc, key) {
        if (key !== 'payments') {

          acc[key === 'id' ? 'lineId' : key] = line[key];
        }
        return acc;
      },
      {}
    );
    return line.payments.map(function(payment) {
      payment.info = info;
      return payment;
    });
  });

  return [].concat.apply([], payments);
};

var getManualPaymentsFromDocumentLines = function (manualDocLines) {

  var _manualDocLines = manualDocLines.map(function(m) {
    m.line.id = m.id;
    return m;
  });

  var manualPayments = getPaymentsFromDocumentLines(_manualDocLines);

  return manualPayments.map(function(p) {
    p.manual = true;
    p.id = p.info.lineId;
    return p;
  });

};

var getArrayFromObject = function(obj) {
  return Object.keys(obj).reduce(function(acc, key) {
      acc.push(obj[key]);
      return acc;
    },
    []
  );
};

var getTodayFormatted = function() {
  var today = new Date();
  return [today.getFullYear(), ('0' + (today.getMonth() + 1)).slice(-2), ('0' + today.getDate()).slice(-2)].join('-');
};

var getCffFromDocumentLines = function(docLines) {
  var lines = docLines.map(function(docLine) {return docLine.line});
  return {
    sourceId: lines[0].sourceId,
    sourceDescription: lines[0].sourceDescription,
    lines: lines.sort(sortCFFLinesByDate),
  };
};

module.exports = {
  parseAuthorization: parseAuthorization,
  getUserByToken: getUserByToken,
  sortCFFLinesByDate: sortCFFLinesByDate,
  getPaymentsFromDocumentLines: getPaymentsFromDocumentLines,
  getManualPaymentsFromDocumentLines: getManualPaymentsFromDocumentLines,
  getArrayFromObject: getArrayFromObject,
  getTodayFormatted: getTodayFormatted,
  getCffFromDocumentLines: getCffFromDocumentLines,
  captchaError: 'captcha',
  passwordError: 'password',
  loginError: 'login',
  unknownError: 'unknown',
  maxAttempts: 2
};<commit_msg>API: returning correct manual payments IDs (lineId + paymentId)<commit_after>'use strict';
var ObjectId = require('mongodb').ObjectID;

var parseAuthorization = function(authorization) {
  if (!authorization){
    var err = Error('missing authorization header');
    err.statusCode = 401;
    throw err;
  }

  var token = authorization.replace(/Token token=\"(.+)\"/g, '$1');
  return token;
};

var getUserByToken = function*(db, token) {
  var session = yield db.sessions.findOne({token: token});
  var user = yield db.users.findOne({_id: ObjectId(String(session.userId))});
  return user;
};

var sortCFFLinesByDate = function (a, b) {
  const dateStringA = a.invoice ? a.invoice.date : a.payments[0].date;
  const dateStringB = b.invoice ? b.invoice.date : b.payments[0].date;
  const dateA = new Date(dateStringA);
  const dateB = new Date(dateStringB);

  return dateB.getTime() - dateA.getTime();
};

var getPaymentsFromDocumentLines = function (docLines) {
  if (docLines.length === 0) {
    return [];
  }

  var lines = docLines.map(function(docLine) {
    return docLine.line;
  });

  var payments = lines.map(function(line, index) {
    var info = Object.keys(line).reduce(function(acc, key) {
        if (key !== 'payments') {

          acc[key === 'id' ? 'lineId' : key] = line[key];
        }
        return acc;
      },
      {}
    );
    return line.payments.map(function(payment) {
      payment.info = info;
      return payment;
    });
  });

  return [].concat.apply([], payments);
};

var getManualPaymentsFromDocumentLines = function (manualDocLines) {

  var _manualDocLines = manualDocLines.map(function(m) {
    m.line.id = m.id;
    return m;
  });

  var manualPayments = getPaymentsFromDocumentLines(_manualDocLines);

  return manualPayments.map(function(p) {
    p.manual = true;
    p.id = p.info.lineId + (p.id || '');
    return p;
  });

};

var getArrayFromObject = function(obj) {
  return Object.keys(obj).reduce(function(acc, key) {
      acc.push(obj[key]);
      return acc;
    },
    []
  );
};

var getTodayFormatted = function() {
  var today = new Date();
  return [today.getFullYear(), ('0' + (today.getMonth() + 1)).slice(-2), ('0' + today.getDate()).slice(-2)].join('-');
};

var getCffFromDocumentLines = function(docLines) {
  var lines = docLines.map(function(docLine) {return docLine.line});
  return {
    sourceId: lines[0].sourceId,
    sourceDescription: lines[0].sourceDescription,
    lines: lines.sort(sortCFFLinesByDate),
  };
};

module.exports = {
  parseAuthorization: parseAuthorization,
  getUserByToken: getUserByToken,
  sortCFFLinesByDate: sortCFFLinesByDate,
  getPaymentsFromDocumentLines: getPaymentsFromDocumentLines,
  getManualPaymentsFromDocumentLines: getManualPaymentsFromDocumentLines,
  getArrayFromObject: getArrayFromObject,
  getTodayFormatted: getTodayFormatted,
  getCffFromDocumentLines: getCffFromDocumentLines,
  captchaError: 'captcha',
  passwordError: 'password',
  loginError: 'login',
  unknownError: 'unknown',
  maxAttempts: 2
};<|endoftext|>


<commit_before>var r = require('express').Router(),
	ObjectId = require('mongodb').ObjectId,
	db = require('../libs/db-connector.js')

r.get('/all', function (req, res) {
	db().collection('profiles').find({hidden: {$ne: true}, year: req.query.year || new Date()).getFullYear()}).toArray(function (err, profiles) {
		if (!err && profiles) {
			res.json(profiles)
		}
		else if (!!err) {
			res.status(500).json('')
		}
	})
})

r.get('/all-from-institution', function (req, res) {
	if (req.query.id && req.query.id.length === 24) {
		var _id = ObjectId(req.query.id)
		db().collection('profiles').find({institution: _id, year: req.query.year || new Date()).getFullYear()}).toArray(function (err, profiles) {
			if (!err && profiles.length > 0) {
				res.json(profiles)
			}
			else if (!!err) {
				console.log(err)
				res.status(500).json('')
			}
			else {
				res.status(404).json('No institution profile found')
			}
		})
	}
	else {
		res.status(412).json('Missing parameter')
	}
})

r.get('/single', function (req, res) {
	if (req.query.id && req.query.id.length === 24) {
		var _id = ObjectId(req.query.id)
		db().collection('profiles').find({_id: _id, year: req.query.year || new Date()).getFullYear()}).toArray(function (err, profile) {
			if (!err && profile[0]) {
				res.json(profile[0])
			}
			else if (!!err) {
				console.log(err)
				res.status(500).json('Contains malformed data; please removed any copy-pasted images and re insert them with the editor')
			}
			else {
				res.status(404).json('Profile not found')
			}
		})
	}
	else {
		res.status(412).json('Missing parameter')
	}
})

r.get('/meta', function (req, res) {
	db().collection('meta_profiles').find({}).sort({required: -1, _id:1}).toArray(function (err, metaProfiles) {
		res.json(metaProfiles)
	})
})

r.post('/save', function (req, res) {

	if (!!req.body && !!req.body.data && !!req.body.data.institution) {
		var data = req.body.data
		delete data._id
		req.body.data.institution = ObjectId(req.body.data.institution)
		db().collection('profiles').update({'year': (new Date()).getFullYear(), institution: req.body.data.institution}, {$set: data}, {upsert: true, new: true, doc:true}, function (err, doc) {
			db().collection('profiles').update({'year': (new Date()).getFullYear() - 1, institution: req.body.data.institution}, {$set: {hidden: true}})
			if (err) {
				console.log(err)
				res.status(500).json('Contains malformed data; please removed any copy-pasted images and re insert them with the editor')
			}
			else res.status(200).json('OK')
		})
	}
	else {
		res.status(412).json('Missing parameter')
	}
})

module.exports = r
<commit_msg>trying to sort year issue<commit_after>var r = require('express').Router(),
	ObjectId = require('mongodb').ObjectId,
	db = require('../libs/db-connector.js')

r.get('/all', function (req, res) {
	db().collection('profiles').find({hidden: {$ne: true}, year: req.query.year || (new Date()).getFullYear()  }).toArray(function (err, profiles) {
		if (!err && profiles) {
			res.json(profiles)
		}
		else if (!!err) {
			res.status(500).json('')
		}
	})
})

r.get('/all-from-institution', function (req, res) {
	if (req.query.id && req.query.id.length === 24) {
		var _id = ObjectId(req.query.id)
		db().collection('profiles').find({institution: _id, year: req.query.year || (new Date()).getFullYear()}).toArray(function (err, profiles) {
			if (!err && profiles.length > 0) {
				res.json(profiles)
			}
			else if (!!err) {
				console.log(err)
				res.status(500).json('')
			}
			else {
				res.status(404).json('No institution profile found')
			}
		})
	}
	else {
		res.status(412).json('Missing parameter')
	}
})

r.get('/single', function (req, res) {
	if (req.query.id && req.query.id.length === 24) {
		var _id = ObjectId(req.query.id)
		db().collection('profiles').find({_id: _id, year: req.query.year || (new Date()).getFullYear()}).toArray(function (err, profile) {
			if (!err && profile[0]) {
				res.json(profile[0])
			}
			else if (!!err) {
				console.log(err)
				res.status(500).json('Contains malformed data; please removed any copy-pasted images and re insert them with the editor')
			}
			else {
				res.status(404).json('Profile not found')
			}
		})
	}
	else {
		res.status(412).json('Missing parameter')
	}
})

r.get('/meta', function (req, res) {
	db().collection('meta_profiles').find({}).sort({required: -1, _id:1}).toArray(function (err, metaProfiles) {
		res.json(metaProfiles)
	})
})

r.post('/save', function (req, res) {

	if (!!req.body && !!req.body.data && !!req.body.data.institution) {
		var data = req.body.data
		delete data._id
		req.body.data.institution = ObjectId(req.body.data.institution)
		db().collection('profiles').update({'year': (new Date()).getFullYear(), institution: req.body.data.institution}, {$set: data}, {upsert: true, new: true, doc:true}, function (err, doc) {
			db().collection('profiles').update({'year': (new Date()).getFullYear() - 1, institution: req.body.data.institution}, {$set: {hidden: true}})
			if (err) {
				console.log(err)
				res.status(500).json('Contains malformed data; please removed any copy-pasted images and re insert them with the editor')
			}
			else res.status(200).json('OK')
		})
	}
	else {
		res.status(412).json('Missing parameter')
	}
})

module.exports = r
<|endoftext|>


<commit_before>'use strict';

import { ActionConst } from 'react-native-router-flux';
import { words } from '../words';

const initialState = {
  activeSentence: [{word: '', type: 'pronoun'},
                   {word: '', type: 'aux verb'},
                   {word: '', type: 'main verb'}],
  activeURI: '',
  editIndex: 0,
  inputWord: '',
  modalType: null,
  wordPicker: null,
  itemOrder: [0,1,2],
  sentenceScrollEnabled: true,
};

export default function sentences(state = initialState, action) {
  switch (action.type) {
    case 'ADD_WORD':
      return {
        ...state,
        activeSentence: state.activeSentence.concat([{word: action.word, type: action.wordType}]),
        itemOrder: state.itemOrder.concat([state.activeSentence.length])
      }
    case 'DELETE_WORD':
      state.itemOrder.splice(state.itemOrder.indexOf(action.wordIndex),1);
      var updatedSentence = [
        ...state.activeSentence.slice(0, action.wordIndex),
        {word: 'NULL', type: 'NULL'},
        ...state.activeSentence.slice(action.wordIndex + 1)
      ];
      return {
        ...state,
        activeSentence: updatedSentence
      }
    case 'CLEAR_SENTENCE':
      return {
        ...state,
        activeSentence: initialState.activeSentence
      }
    case 'CLICK_WORD':
      if (words[action.wordType]['custom']) {
        return {
          ...state,
          modalType: action.wordType,
          editIndex: action.wordIndex
        }
      }
      else {
        return {
          ...state,
          wordPicker: action.wordType,
          editIndex: action.wordIndex
        }
      }
    case 'EDIT_WORD':
      var wordType = state.activeSentence[action.wordIndex].type;
      var updatedSentence = [
        ...state.activeSentence.slice(0, action.wordIndex),
        {word: action.word, type: wordType},
        ...state.activeSentence.slice(action.wordIndex + 1)
      ];
      return {
        ...state,
        wordPicker: null,
        modalType: null,
        activeSentence: updatedSentence
      }
    case 'GO_BACK':
      return {
        ...state,
        wordPicker: null,
        modalType: null,
        activeSentence: state.activeSentence
      }
    case 'CLEAR_WORDPICKER':
      return {
        ...state,
        wordPicker: null
      }
    case 'INPUT_WORD':
      return {
        ...state,
        inputWord: action.word
      }
    case 'SENTENCE_DRAG_IN_PROGRESS':
      return {
        ...state,
        sentenceScrollEnabled: false
      }
    case 'REORDER_SENTENCE':
      var newItemOrder = action.itemOrder.map(function(item) {
          return ( parseInt(item.key) )
      });

      return {
        ...state,
        itemOrder: newItemOrder,
        sentenceScrollEnabled: true
      }
    case 'SELECT_PHOTO':
      return {
        ...state,
        activeURI: action.uri
      }
    case 'SET_MODAL':
      return {
        ...state,
        modalType: action.modalType
      }
    default:
      return state
  }
}<commit_msg>fix bug that crashes app when deleting words/clearing sentence<commit_after>'use strict';

import { ActionConst } from 'react-native-router-flux';
import { words } from '../words';

const initialState = {
  activeSentence: [{word: '', type: 'pronoun'},
                   {word: '', type: 'aux verb'},
                   {word: '', type: 'main verb'}],
  activeURI: '',
  editIndex: 0,
  inputWord: '',
  modalType: null,
  wordPicker: null,
  itemOrder: [0,1,2],
  sentenceScrollEnabled: true,
};

export default function sentences(state = initialState, action) {
  switch (action.type) {
    case 'ADD_WORD':
      return {
        ...state,
        activeSentence: state.activeSentence.concat([{word: action.word, type: action.wordType}]),
        itemOrder: state.itemOrder.concat([state.activeSentence.length])
      }
    case 'DELETE_WORD':
      var deleteIndex = state.itemOrder.indexOf(action.wordIndex)
      var newItemOrder = [
        ...state.itemOrder.slice(0, deleteIndex),
        ...state.itemOrder.slice(deleteIndex + 1)
      ];
      var updatedSentence = [
        ...state.activeSentence.slice(0, action.wordIndex),
        {word: 'NULL', type: 'NULL'},
        ...state.activeSentence.slice(action.wordIndex + 1)
      ];
      return {
        ...state,
        activeSentence: updatedSentence,
        itemOrder: newItemOrder
      }
    case 'CLEAR_SENTENCE':
      return {
        ...state,
        activeSentence: initialState.activeSentence,
        itemOrder: initialState.itemOrder
      }
    case 'CLICK_WORD':
      if (words[action.wordType]['custom']) {
        return {
          ...state,
          modalType: action.wordType,
          editIndex: action.wordIndex
        }
      }
      else {
        return {
          ...state,
          wordPicker: action.wordType,
          editIndex: action.wordIndex
        }
      }
    case 'EDIT_WORD':
      var wordType = state.activeSentence[action.wordIndex].type;
      var updatedSentence = [
        ...state.activeSentence.slice(0, action.wordIndex),
        {word: action.word, type: wordType},
        ...state.activeSentence.slice(action.wordIndex + 1)
      ];
      return {
        ...state,
        wordPicker: null,
        modalType: null,
        activeSentence: updatedSentence
      }
    case 'GO_BACK':
      return {
        ...state,
        wordPicker: null,
        modalType: null,
        activeSentence: state.activeSentence
      }
    case 'CLEAR_WORDPICKER':
      return {
        ...state,
        wordPicker: null
      }
    case 'INPUT_WORD':
      return {
        ...state,
        inputWord: action.word
      }
    case 'SENTENCE_DRAG_IN_PROGRESS':
      return {
        ...state,
        sentenceScrollEnabled: false
      }
    case 'REORDER_SENTENCE':
      var newItemOrder = action.itemOrder.map(function(item) {
          return ( parseInt(item.key) )
      });

      return {
        ...state,
        itemOrder: newItemOrder,
        sentenceScrollEnabled: true
      }
    case 'SELECT_PHOTO':
      return {
        ...state,
        activeURI: action.uri
      }
    case 'SET_MODAL':
      return {
        ...state,
        modalType: action.modalType
      }
    default:
      return state
  }
}<|endoftext|>


<commit_before>import { show, hide, delegate } from '@utils';

function updateContactElementsVisibility() {
  const contactSelect = document.querySelector('#contact-form #type');
  if (contactSelect) {
    const type = contactSelect.value;
    const visibleElements = `[data-contact-type-only="${type}"]`;
    const hiddenElements = `[data-contact-type-only]:not([data-contact-type-only="${type}"])`;

    document.querySelectorAll(visibleElements).forEach(show);
    document.querySelectorAll(hiddenElements).forEach(hide);
  }
}

addEventListener('ds:page:update', updateContactElementsVisibility);
delegate('change', '#contact-form #type', updateContactElementsVisibility);
<commit_msg>expand buttons for contact page<commit_after>/*
*   This content is inspired by w3c aria example
*   https://www.w3.org/TR/wai-aria-practices-1.1/examples/disclosure/disclosure-faq.html
*/

var ButtonExpand = function (domNode) {

  this.domNode = domNode;

  this.keyCode = Object.freeze({
    'RETURN': 13
  });
};

ButtonExpand.prototype.init = function () {

  this.allButtons = [];
  this.controlledNode = false;

  var id = this.domNode.getAttribute('aria-controls');

  if (id) {
    this.controlledNode = document.getElementById(id);
  }

  this.domNode.setAttribute('aria-expanded', 'false');
  this.hideContent();

  this.domNode.addEventListener('keydown',    this.handleKeydown.bind(this));
  this.domNode.addEventListener('click',      this.handleClick.bind(this));
  this.domNode.addEventListener('focus',      this.handleFocus.bind(this));
  this.domNode.addEventListener('blur',       this.handleBlur.bind(this));

};

ButtonExpand.prototype.showContent = function () {

  this.domNode.setAttribute('aria-expanded', 'true');
  this.domNode.classList.add('primary');
  if (this.controlledNode) {
    this.controlledNode.classList.remove('hidden');

  }

  this.allButtons.forEach((b) => {
    if (b != this) {
      b.hideContent();
    }
  });
};

ButtonExpand.prototype.hideContent = function () {

  this.domNode.setAttribute('aria-expanded', 'false');
  this.domNode.classList.remove('primary');
  if (this.controlledNode) {
    this.controlledNode.classList.add('hidden');
  }

};

ButtonExpand.prototype.toggleExpand = function () {
  console.log("toggleExpanding...");

  if (this.domNode.getAttribute('aria-expanded') === 'true') {
    this.hideContent();
  }
  else {
    this.showContent();
  }

};

ButtonExpand.prototype.setAllButtons = function(buttons) {
  this.allButtons = buttons;
}

/* EVENT HANDLERS */

ButtonExpand.prototype.handleKeydown = function (event) {

  switch (event.keyCode) {

    case this.keyCode.RETURN:

      this.toggleExpand();

      event.stopPropagation();
      event.preventDefault();
      break;

    default:
      break;
  }

};

ButtonExpand.prototype.handleClick = function (event) {
  event.stopPropagation();
  event.preventDefault();
  this.toggleExpand();
};

ButtonExpand.prototype.handleFocus = function (event) {
  this.domNode.classList.add('focus');
};

ButtonExpand.prototype.handleBlur = function (event) {
  this.domNode.classList.remove('focus');
};

/* Initialize Hide/Show Buttons */

window.addEventListener('load', function (event) {

  var buttons =  document.querySelectorAll('button[aria-expanded][aria-controls], button.button-without-hint');
  var expandButtons = [];

  buttons.forEach((button) => {
    var be = new ButtonExpand(button);
    be.init();
    expandButtons.push(be);
  });
  expandButtons.forEach((button) => button.setAllButtons(expandButtons));

}, false);
<|endoftext|>


<commit_before>/*
* Note: This component will be removed ones
* The issue with jsrepl is resolved. The
* terminal conatiner imitated here, this will be changed
* ones the jsrepl issue is resolved
*/
var React = require('react');

// Note this are initiated from the global
// window in index.html
var pythonRepl = empython,
    jqconsole;

var PythonContainer = React.createClass({

  componentDidMount: function() {
    this.loadLanguage(this.props.language);
  },

  resultOutput: function(value) {
    console.log("asasa")
    jqconsole.Write(value + '\n', 'jqconsole-output');
  },

  loadLanguage: function(language) {
    pythonRepl.Initialize();
    // Override default printing
    pythonRepl.Module.print = pythonRepl.Module.printErr = this.resultOutput;
    jqconsole = $('#console').jqconsole('python loaded...\n', '>');
    this.startPrompt();
  },

  startPrompt: function() {
    // Start the prompt with history enabled.
    var self = this;
    jqconsole.Prompt(true, function (input) {
      // Output input with the class jqconsole-output.
      pythonRepl.Run(input);
      // Restart the prompt.
      self.startPrompt();
    });
  },

  clearTerminal: function() {
    jqconsole.Clear();
  },

  render: function() {

    return (

            clear

    )
  }
});

module.exports = PythonContainer;
<commit_msg>display version of python when python loaded<commit_after>/*
* Note: This component will be removed ones
* The issue with jsrepl is resolved. The
* terminal conatiner imitated here, this will be changed
* ones the jsrepl issue is resolved
*/
var React = require('react');

// Note this are initiated from the global
// window in index.html
var pythonRepl = empython,
    jqconsole;

var PythonContainer = React.createClass({

  componentDidMount: function() {
    this.loadLanguage(this.props.language);
  },

  resultOutput: function(value) {
    jqconsole.Write(value + '\n', 'jqconsole-output');
  },

  loadLanguage: function(language) {
    pythonRepl.Initialize();
    // Override default printing
    pythonRepl.Module.print = pythonRepl.Module.printErr = this.resultOutput;

    jqconsole = $('#console').jqconsole('python ', '>');
    pythonRepl.Run('import sys; print sys.version')

    this.startPrompt();
  },

  startPrompt: function() {
    // Start the prompt with history enabled.
    var self = this;
    jqconsole.Prompt(true, function (input) {
      // Output input with the class jqconsole-output.
      pythonRepl.Run(input);
      // Restart the prompt.
      self.startPrompt();
    });
  },

  clearTerminal: function() {
    jqconsole.Clear();
  },

  render: function() {

    return (

            clear

    )
  }
});

module.exports = PythonContainer;
<|endoftext|>


<commit_before>function SoundController(config){
    this.config = config;

    SoundController.prototype.init = function(){
        //this.audioList = [];
        this.config.stage = new createjs.Stage("loaderCanvas");
        createjs.Sound.registerPlugins([createjs.HTMLAudioPlugin, createjs.WebAudioPlugin, createjs.FlashAudioPlugin]);
        createjs.Sound.alternateExtensions = ["wav"];
        loadEvents(this);
        playMusic(this);

    }

    var loadEvents = function(me){

        var ra = function(sound){removeAudioFromList(me,sound.target)};
        EventBus.addEventListener("removeAudioFromList",ra);

        var pa = function(){pauseAllSound(me)};
        EventBus.addEventListener("pauseAllSound", pa);

        var al = function(sound){addAudioToList(me,sound.target)};
        EventBus.addEventListener("addAudioToList", al);

        var cs = function(type){changeSoundVolume(me,type.target)};
        EventBus.addEventListener("changeSoundVolume", cs);

        var sm = function(){setMute(me)};
        EventBus.addEventListener("setMute", sm);

        var pm = function(sound){playSound(me,sound.target)};
        EventBus.addEventListener("playSound", pm);
    }

    var playSound = function(me,fileId){
        var config = {"file": fileId , "loop": false, "type": me.config.gameState.soundType.EFFECTS, "isMain": false,"loader":me.config.loader, "gameState":me.config.gameState};
        var sound = new Sound(config);
        EventBus.dispatch("addAudioToList",sound);

    }
    var addAudioToList = function(me,sound){
        if(sound.mySound != null){
            sound.play();
            me.config.gameState.audioList.push(sound);
        }
    }
    var removeAudioFromList = function(me,sound){
        if(sound.mySound != null){
            sound.pause();
            var index = me.config.gameState.audioList.indexOf(sound);
            me.config.gameState.audioList.splice(index,1);
        }
    }
    /*var pauseAllSound = function(me){
        for(var i= 0; i< me.audioList.length; i++){
            var sound = me.audioList[i];
            sound.pause();
        }
    }*/
    var pauseAllSound = function(me){
        for(var i= 0; i< me.config.gameState.audioList.length; i++){
            var sound = me.config.gameState.audioList[i];
            if(!sound.config.isMain){
                sound.pause();
            }
        }
    }
    var setMute = function(me){
        var audioList = me.config.gameState.audioList;
        for(var i=0; i<audioList.length; i++){
            var main = audioList[i].config.type;
            if(main == me.config.gameState.soundType.MAIN){
                if(audioList[i].mySound.paused){
                    audioList[i].play();
                }
                else{
                    audioList[i].pause();
                }
            }
        }
    }
    var changeSoundVolume = function(me,type){
        for(var i= 0; i< me.config.gameState.audioList.length; i++){
            var sound = me.config.gameState.audioList[i];
            if(sound.config.type == type){
                var vol = me.config.gameState.gs.music/100;
                if(type == me.config.gameState.soundType.EFFECTS){
                    vol = me.config.gameState.gs.soundEffects/100;
                }
                sound.setVolume(vol);
            }

        }
    }

    var playMusic = function(me){
        var fileId = "mainTheme";
        var config = {"file": fileId , "loop": true, "type": me.config.gameState.soundType.MAIN, "isMain": true,"loader":me.config.loader, "gameState":me.config.gameState};
        var mainSound = new Sound(config);
        EventBus.dispatch("addAudioToList",mainSound);
    }

    var persist = function(me){

    }

}
   <commit_msg>Resolved the issue: If you quickly roll over one button then roll over another then the sound effect does not play.<commit_after>function SoundController(config){
    this.config = config;

    SoundController.prototype.init = function(){
        //this.audioList = [];
        this.config.stage = new createjs.Stage("loaderCanvas");
        createjs.Sound.registerPlugins([createjs.HTMLAudioPlugin, createjs.WebAudioPlugin, createjs.FlashAudioPlugin]);
        createjs.Sound.alternateExtensions = ["wav"];
        loadEvents(this);
        playMusic(this);

    }

    var loadEvents = function(me){

        var ra = function(sound){removeAudioFromList(me,sound.target)};
        EventBus.addEventListener("removeAudioFromList",ra);

        var pa = function(){pauseAllSound(me)};
        EventBus.addEventListener("pauseAllSound", pa);

        var cs = function(type){changeSoundVolume(me,type.target)};
        EventBus.addEventListener("changeSoundVolume", cs);

        var sm = function(){setMute(me)};
        EventBus.addEventListener("setMute", sm);

        var pm = function(sound){playSound(me,sound.target)};
        EventBus.addEventListener("playSound", pm);
    }

    var playSound = function(me,fileId){
        var config = {"file": fileId , "loop": false, "type": me.config.gameState.soundType.EFFECTS, "isMain": false,"loader":me.config.loader, "gameState":me.config.gameState};
        var sound = new Sound(config);
        removeSoundEffects(me);
        addAudioToList(me,sound);
    }
    var addAudioToList = function(me,sound){
        if(sound.mySound != null){
            me.config.gameState.audioList.push(sound);
            sound.play();
        }
    }
    var removeAudioFromList = function(me,sound){
        if(sound.mySound != null){
            sound.pause();
            var index = me.config.gameState.audioList.indexOf(sound);
            me.config.gameState.audioList.splice(index,1);
        }
    }
    var removeSoundEffects = function(me){
        for(var i=0; i< me.config.gameState.audioList.length; i++){
            var removeSound = me.config.gameState.audioList[i];
            if(!removeSound.config.isMain){
                removeSound.mySound.pause();
                removeSound.mySound.currentTime = 0;
                removeAudioFromList(me,removeSound);
            }
        }
    }
    var pauseAllSound = function(me){
        for(var i= 0; i< me.config.gameState.audioList.length; i++){
            var sound = me.config.gameState.audioList[i];
            if(!sound.config.isMain){
                sound.pause();
            }
        }
    }
    var setMute = function(me){
        var audioList = me.config.gameState.audioList;
        for(var i=0; i<audioList.length; i++){
            var main = audioList[i].config.type;
            if(main == me.config.gameState.soundType.MAIN){
                if(audioList[i].mySound.paused){
                    audioList[i].play();
                }
                else{
                    audioList[i].pause();
                }
            }
        }
    }
    var changeSoundVolume = function(me,type){
        for(var i= 0; i< me.config.gameState.audioList.length; i++){
            var sound = me.config.gameState.audioList[i];
            if(sound.config.type == type){
                var vol = me.config.gameState.gs.music/100;
                if(type == me.config.gameState.soundType.EFFECTS){
                    vol = me.config.gameState.gs.soundEffects/100;
                }
                sound.setVolume(vol);
            }

        }
    }

    var playMusic = function(me){
        var fileId = "mainTheme";
        var config = {"file": fileId , "loop": true, "type": me.config.gameState.soundType.MAIN, "isMain": true,"loader":me.config.loader, "gameState":me.config.gameState};
        var mainSound = new Sound(config);
        addAudioToList(me,mainSound);
    }

    var persist = function(me){

    }

}
   <|endoftext|>


<commit_before>!function t(e,n,i){function r(u,o){if(!n[u]){if(!e[u]){var l="function"==typeof require&&require;if(!o&&l)return l(u,!0);if(a)return a(u,!0);var h=new Error("Cannot find module '"+u+"'");throw h.code="MODULE_NOT_FOUND",h}var s=n[u]={exports:{}};e[u][0].call(s.exports,function(t){var n=e[u][1][t];return r(n?n:t)},s,s.exports,t,e,n,i)}return n[u].exports}for(var a="function"==typeof require&&require,u=0;u<i.length;u++)r(i[u]);return r}({1:[function(t,e,n){"use strict";var i=t("./list");window.list=new i.List},{"./list":2}],2:[function(t,e,n){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}}(),a=t("./node"),u=function(){function t(){i(this,t),this.head=null,this.tail=null,this._length=0}return r(t,[{key:"push",value:function(t){var e=new a.Node(t,null);this.head?(this.tail.next=e,this.tail=e):(this.head=e,this.tail=this.head),this._length++}},{key:"pop",value:function(t,e){for(var e,n=this.head;n;){if(n.value==t)return e?e.next=n.next:this.head=n.next,n;e=n,n=n.next}}},{key:"shift",value:function(){var t=this.head;return this.head=this.head.next?this.head.next:null,this.tail=this.head,this._length--,t}},{key:"print",value:function(){var t=this.head,e="";if(!t)return console.log("empty list");for(;t;)e+="|"+t.value+"| => ",t=t.next;return e}},{key:"removeDuplicates",value:function(){for(var t=this.head,e=null,n={};t;)n[t.value]?(e?e.next=t.next:this.head=t.next,this._length--):(n[t.value]=!0,e=t),t=t.next}},{key:"clear",value:function(){this.head=null,this.tail=this.head,this._length=0}},{key:"length",get:function(){return this._length}}]),t}();n.List=u},{"./node":3}],3:[function(t,e,n){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var r=function a(t,e){i(this,a),this.value=t,this.next=e};n.Node=r},{}]},{},[1]);<commit_msg>bundled<commit_after>!function t(e,n,i){function r(u,l){if(!n[u]){if(!e[u]){var o="function"==typeof require&&require;if(!l&&o)return o(u,!0);if(a)return a(u,!0);var h=new Error("Cannot find module '"+u+"'");throw h.code="MODULE_NOT_FOUND",h}var s=n[u]={exports:{}};e[u][0].call(s.exports,function(t){var n=e[u][1][t];return r(n?n:t)},s,s.exports,t,e,n,i)}return n[u].exports}for(var a="function"==typeof require&&require,u=0;u<i.length;u++)r(i[u]);return r}({1:[function(t,e,n){"use strict";var i=t("./list");window.list=new i.List},{"./list":2}],2:[function(t,e,n){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}}(),a=t("./node"),u=function(){function t(){i(this,t),this.head=null,this.tail=null,this._length=0}return r(t,[{key:"push",value:function(t){var e=new a.Node(t,null);this.head?(this.tail.next=e,this.tail=e):(this.head=e,this.tail=this.head),this._length++}},{key:"removeNode",value:function(t){for(var e=this.head,n=null;e;){if(e.value==t)return e.next?"":this.tail=n,Object.assign(e,e.next),this._length--,e;n=e,e=e.next}}},{key:"pop",value:function(){for(var t=this.head,e=null;t.next;)e=t,t=t.next;return this.tail=e,this._length--,e.next}},{key:"shift",value:function(){var t=this.head;return this.head=this.head.next?this.head.next:null,this.tail=this.head,this._length--,t}},{key:"print",value:function(){var t=this.head,e="";if(!t)return console.log("empty list");for(;t;)e+="|"+t.value+"| => ",t=t.next;return e}},{key:"removeDuplicates",value:function(){for(var t=this.head,e=null,n={};t;)n[t.value]?(e?e.next=t.next:this.head=t.next,this._length--):(n[t.value]=!0,e=t),t=t.next}},{key:"clear",value:function(){this.head=null,this.tail=this.head,this._length=0}},{key:"length",get:function(){return this._length}}]),t}();n.List=u},{"./node":3}],3:[function(t,e,n){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var r=function a(t,e){i(this,a),this.value=t,this.next=e};n.Node=r},{}]},{},[1]);<|endoftext|>


<commit_before>///import core
///commands 撤销和重做
///commandsName  Undo,Redo
///commandsTitle  撤销,重做
/**
 * @description 回退
 * @author zhanyi
 */

UE.plugins['undo'] = function () {
    var me = this,
        maxUndoCount = me.options.maxUndoCount || 20,
        maxInputCount = me.options.maxInputCount || 20,
        fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的

    function compareAddr(indexA, indexB) {
        if (indexA.length != indexB.length)
            return 0;
        for (var i = 0, l = indexA.length; i < l; i++) {
            if (indexA[i] != indexB[i])
                return 0
        }
        return 1;
    }

    function compareRangeAddress(rngAddrA, rngAddrB) {
        if (rngAddrA.collapsed != rngAddrB.collapsed) {
            return 0;
        }
        if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
            return 0;
        }
        return 1;
    }

    function adjustContent(cont) {
        var specialAttr = /\b(?:href|src|name)="[^"]*?"/gi;
        return cont.replace(specialAttr, '')
            .replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (a, b, c) {
                return b.toLowerCase() + '=' + c.replace(/['"]/g, '').toLowerCase()
            })
            .replace(/(<[\w\-]+)|([\w\-]+>)/gi, function (a, b, c) {
                return (b || c).toLowerCase()
            });
    }

    function UndoManager() {
        this.list = [];
        this.index = 0;
        this.hasUndo = false;
        this.hasRedo = false;
        this.undo = function () {
            if (this.hasUndo) {
                var currentScene = this.getScene(),
                    lastScene = this.list[this.index],
                    lastContent = adjustContent(lastScene.content),
                    currentContent = adjustContent(currentScene.content);

                if (lastContent != currentContent) {
                    this.save();
                }
                if (!this.list[this.index - 1] && this.list.length == 1) {
                    this.reset();
                    return;
                }
                while (this.list[this.index].content == this.list[this.index - 1].content) {
                    this.index--;
                    if (this.index == 0) {
                        return this.restore(0);
                    }
                }
                this.restore(--this.index);
            }
        };
        this.redo = function () {
            if (this.hasRedo) {
                while (this.list[this.index].content == this.list[this.index + 1].content) {
                    this.index++;
                    if (this.index == this.list.length - 1) {
                        return this.restore(this.index);
                    }
                }
                this.restore(++this.index);
            }
        };

        this.restore = function () {
            var scene = this.list[this.index];
            var root = UE.htmlparser(scene.content.replace(fillchar, ''));
            me.filterInputRule(root);
            //trace:873
            //去掉展位符
            me.document.body.innerHTML = root.toHtml();
            me.fireEvent('afterscencerestore');
            //处理undo后空格不展位的问题
            if (browser.ie) {
                utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
                    if(domUtils.isEmptyNode(node)){
                        domUtils.fillNode(me.document, node);
                    }
                })
            }

            try{
                new dom.Range(me.document).moveToAddress(scene.address).select();
            }catch(e){}

            this.update();
            this.clearKey();
            //不能把自己reset了
            me.fireEvent('reset', true);
        };

        this.getScene = function (notSetCursor) {
            var rng = me.selection.getRange(),
                restoreAddress = rng.createAddress(),
                rngAddress = rng.createAddress(false,true);

            me.fireEvent('beforegetscene');
            var root = UE.htmlparser(me.body.innerHTML.replace(fillchar, ''));
            me.filterOutputRule(root);
            var cont = root.toHtml();
            browser.ie && (cont = cont.replace(/> </g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
            me.fireEvent('aftergetscene');
            try{
               !notSetCursor && rng.moveToAddress(restoreAddress).select(true);
            }catch(e){}
            return {
                address:rngAddress,
                content:cont
            }
        };
        this.save = function (notCompareRange,notSetCursor) {
            var currentScene = this.getScene(notSetCursor),
                lastScene = this.list[this.index];
            //内容相同位置相同不存
            if (lastScene && lastScene.content == currentScene.content &&
                ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
                ) {
                return;
            }
            this.list = this.list.slice(0, this.index + 1);
            this.list.push(currentScene);
            //如果大于最大数量了，就把最前的剔除
            if (this.list.length > maxUndoCount) {
                this.list.shift();
            }
            this.index = this.list.length - 1;
            this.clearKey();
            //跟新undo/redo状态
            this.update();
        };
        this.update = function () {
            this.hasRedo = !!this.list[this.index + 1];
            this.hasUndo = !!this.list[this.index - 1];
        };
        this.reset = function () {
            this.list = [];
            this.index = 0;
            this.hasUndo = false;
            this.hasRedo = false;
            this.clearKey();
        };
        this.clearKey = function () {
            keycont = 0;
            lastKeyCode = null;
        };
    }

    me.undoManger = new UndoManager();
    function saveScene() {
        this.undoManger.save();
    }

    me.addListener('saveScene', function () {
        me.undoManger.save();
    });

    me.addListener('beforeexeccommand', saveScene);
    me.addListener('afterexeccommand', saveScene);

    me.addListener('reset', function (type, exclude) {
        if (!exclude) {
            me.undoManger.reset();
        }
    });
    me.commands['redo'] = me.commands['undo'] = {
        execCommand:function (cmdName) {
            me.undoManger[cmdName]();
        },
        queryCommandState:function (cmdName) {
            return me.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
        },
        notNeedUndo:1
    };

    var keys = {
            //  /*Backspace*/ 8:1, /*Delete*/ 46:1,
            /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
            37:1, 38:1, 39:1, 40:1,
            13:1 /*enter*/
        },
        keycont = 0,
        lastKeyCode;
    //输入法状态下不计算字符数
    var inputType = false;
    me.addListener('ready', function () {
        domUtils.on(me.body, 'compositionstart', function () {
            inputType = true;
        });
        domUtils.on(me.body, 'compositionend', function () {
            inputType = false;
        })
    });
    //快捷键
    me.addshortcutkey({
        "Undo":"ctrl+90", //undo
        "Redo":"ctrl+89" //redo

    });
    me.addListener('keydown', function (type, evt) {
        var keyCode = evt.keyCode || evt.which;
        if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
            if (inputType)
                return;
            if (me.undoManger.list.length == 0 || ((keyCode == 8 || keyCode == 46) && lastKeyCode != keyCode)) {
                me.fireEvent('contentchange');
                me.undoManger.save(true);
                lastKeyCode = keyCode;
                return;
            }
            //trace:856
            //修正第一次输入后，回退，再输入要到keycont>maxInputCount才能在回退的问题
            if (me.undoManger.list.length == 2 && me.undoManger.index == 0 && keycont == 0) {
                me.undoManger.list.splice(1, 1);
                me.undoManger.update();
            }
            lastKeyCode = keyCode;
            keycont++;
            if (keycont >= maxInputCount || me.undoManger.mousedown) {
                if (me.selection.getRange().collapsed)
                    me.fireEvent('contentchange');
                me.undoManger.save(false,true);
                me.undoManger.mousedown = false;
            }
        }
    });
    me.addListener('keyup', function (type, evt) {
        var keyCode = evt.keyCode || evt.which;
        if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
            if (inputType)
                return;
            if (me.undoManger.list.length == 1  ) {
                me.undoManger.save(true);
            }

        }
    });
    me.addListener('mousedown',function(){
        me.undoManger.mousedown = true;
    })
};
<commit_msg>by zhanyi<commit_after>///import core
///commands 撤销和重做
///commandsName  Undo,Redo
///commandsTitle  撤销,重做
/**
 * @description 回退
 * @author zhanyi
 */

UE.plugins['undo'] = function () {
    var me = this,
        maxUndoCount = me.options.maxUndoCount || 20,
        maxInputCount = me.options.maxInputCount || 20,
        fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的

    function compareAddr(indexA, indexB) {
        if (indexA.length != indexB.length)
            return 0;
        for (var i = 0, l = indexA.length; i < l; i++) {
            if (indexA[i] != indexB[i])
                return 0
        }
        return 1;
    }

    function compareRangeAddress(rngAddrA, rngAddrB) {
        if (rngAddrA.collapsed != rngAddrB.collapsed) {
            return 0;
        }
        if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
            return 0;
        }
        return 1;
    }

    function adjustContent(cont) {
        var specialAttr = /\b(?:href|src|name)="[^"]*?"/gi;
        return cont.replace(specialAttr, '')
            .replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (a, b, c) {
                return b.toLowerCase() + '=' + c.replace(/['"]/g, '').toLowerCase()
            })
            .replace(/(<[\w\-]+)|([\w\-]+>)/gi, function (a, b, c) {
                return (b || c).toLowerCase()
            });
    }

    function UndoManager() {
        this.list = [];
        this.index = 0;
        this.hasUndo = false;
        this.hasRedo = false;
        this.undo = function () {
            if (this.hasUndo) {
                var currentScene = this.getScene(),
                    lastScene = this.list[this.index];
                //有可能引起undo/redo丢场景
//                    lastContent = adjustContent(lastScene.content),
//                    currentContent = adjustContent(currentScene.content);

//                if (lastContent != currentContent) {
//                    this.save();
//                }
                if (!this.list[this.index - 1] && this.list.length == 1) {
                    this.reset();
                    return;
                }
                while (this.list[this.index].content == this.list[this.index - 1].content) {
                    this.index--;
                    if (this.index == 0) {
                        return this.restore(0);
                    }
                }
                this.restore(--this.index);
            }
        };
        this.redo = function () {
            if (this.hasRedo) {
                while (this.list[this.index].content == this.list[this.index + 1].content) {
                    this.index++;
                    if (this.index == this.list.length - 1) {
                        return this.restore(this.index);
                    }
                }
                this.restore(++this.index);
            }
        };

        this.restore = function () {
            var scene = this.list[this.index];
            var root = UE.htmlparser(scene.content.replace(fillchar, ''));
            me.filterInputRule(root);
            //trace:873
            //去掉展位符
            me.document.body.innerHTML = root.toHtml();
            me.fireEvent('afterscencerestore');
            //处理undo后空格不展位的问题
            if (browser.ie) {
                utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
                    if(domUtils.isEmptyNode(node)){
                        domUtils.fillNode(me.document, node);
                    }
                })
            }

            try{
                new dom.Range(me.document).moveToAddress(scene.address).select();
            }catch(e){}

            this.update();
            this.clearKey();
            //不能把自己reset了
            me.fireEvent('reset', true);
        };

        this.getScene = function (notSetCursor) {
            var rng = me.selection.getRange(),
                restoreAddress = rng.createAddress(),
                rngAddress = rng.createAddress(false,true);

            me.fireEvent('beforegetscene');
            var root = UE.htmlparser(me.body.innerHTML.replace(fillchar, ''));
            me.filterOutputRule(root);
            var cont = root.toHtml();
            browser.ie && (cont = cont.replace(/> </g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
            me.fireEvent('aftergetscene');
            try{
               !notSetCursor && rng.moveToAddress(restoreAddress).select(true);
            }catch(e){}
            return {
                address:rngAddress,
                content:cont
            }
        };
        this.save = function (notCompareRange,notSetCursor) {
            var currentScene = this.getScene(notSetCursor),
                lastScene = this.list[this.index];
            //内容相同位置相同不存
            if (lastScene && lastScene.content == currentScene.content &&
                ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
                ) {
                return;
            }
            this.list = this.list.slice(0, this.index + 1);
            this.list.push(currentScene);
            //如果大于最大数量了，就把最前的剔除
            if (this.list.length > maxUndoCount) {
                this.list.shift();
            }
            this.index = this.list.length - 1;
            this.clearKey();
            //跟新undo/redo状态
            this.update();
        };
        this.update = function () {
            this.hasRedo = !!this.list[this.index + 1];
            this.hasUndo = !!this.list[this.index - 1];
        };
        this.reset = function () {
            this.list = [];
            this.index = 0;
            this.hasUndo = false;
            this.hasRedo = false;
            this.clearKey();
        };
        this.clearKey = function () {
            keycont = 0;
            lastKeyCode = null;
        };
    }

    me.undoManger = new UndoManager();
    function saveScene() {
        this.undoManger.save();
    }

    me.addListener('saveScene', function () {
        me.undoManger.save();
    });

    me.addListener('beforeexeccommand', saveScene);
    me.addListener('afterexeccommand', saveScene);

    me.addListener('reset', function (type, exclude) {
        if (!exclude) {
            me.undoManger.reset();
        }
    });
    me.commands['redo'] = me.commands['undo'] = {
        execCommand:function (cmdName) {
            me.undoManger[cmdName]();
        },
        queryCommandState:function (cmdName) {
            return me.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
        },
        notNeedUndo:1
    };

    var keys = {
            //  /*Backspace*/ 8:1, /*Delete*/ 46:1,
            /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
            37:1, 38:1, 39:1, 40:1,
            13:1 /*enter*/
        },
        keycont = 0,
        lastKeyCode;
    //输入法状态下不计算字符数
    var inputType = false;
    me.addListener('ready', function () {
        domUtils.on(me.body, 'compositionstart', function () {
            inputType = true;
        });
        domUtils.on(me.body, 'compositionend', function () {
            inputType = false;
        })
    });
    //快捷键
    me.addshortcutkey({
        "Undo":"ctrl+90", //undo
        "Redo":"ctrl+89" //redo

    });
    me.addListener('keydown', function (type, evt) {
        var keyCode = evt.keyCode || evt.which;
        if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
            if (inputType)
                return;
            if (me.undoManger.list.length == 0 || ((keyCode == 8 || keyCode == 46) && lastKeyCode != keyCode)) {
                me.fireEvent('contentchange');
                me.undoManger.save(true);
                lastKeyCode = keyCode;
                return;
            }
            //trace:856
            //修正第一次输入后，回退，再输入要到keycont>maxInputCount才能在回退的问题
            if (me.undoManger.list.length == 2 && me.undoManger.index == 0 && keycont == 0) {
                me.undoManger.list.splice(1, 1);
                me.undoManger.update();
            }
            lastKeyCode = keyCode;
            keycont++;
            if (keycont >= maxInputCount || me.undoManger.mousedown) {
                if (me.selection.getRange().collapsed)
                    me.fireEvent('contentchange');
                me.undoManger.save(false,true);
                me.undoManger.mousedown = false;
            }
        }
    });
    me.addListener('keyup', function (type, evt) {
        var keyCode = evt.keyCode || evt.which;
        if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
            if (inputType)
                return;
            if (me.undoManger.list.length == 1  ) {
                me.undoManger.save(true);
            }

        }
    });
    me.addListener('mousedown',function(){
        me.undoManger.mousedown = true;
    })
};
<|endoftext|>


<commit_before>define(
    ['backform'],
    function(Backform) {
	var ModelSelectControl = Backform.SelectControl.extend({
	    initialize: function() {
		Backform.SelectControl.prototype.initialize.apply(this, arguments);
		var self = this;
		var ModelModule = this.field.get('room_model_module');
		var modl = new ModelModule();
		this.field.set('room_model', modl);  // just for debugging
		modl.on('change', function(m) {
		    var new_options = _.map(m.get('choice'), function(e) { return {label: e.label, value: e.id}; });
		    new_options.unshift({label: '--- please select one ---', value: null});
		    self.field.set('options', new_options);
		    self.render();
		});
		modl.fetch();
	    },
	    render: function() {
		return Backform.SelectControl.prototype.render.apply(this, arguments);
	    }
	});
	return ModelSelectControl;
    }
);
<commit_msg>reformat<commit_after>define(
    ['backform'],
    function(Backform) {
	      var ModelSelectControl = Backform.SelectControl.extend({
	          initialize: function() {
		            Backform.SelectControl.prototype.initialize.apply(this, arguments);
		            var self = this;
		            var ModelModule = this.field.get('room_model_module');
		            var modl = new ModelModule();
		            this.field.set('room_model', modl);  // just for debugging
		            modl.on('change', function(m) {
		                var new_options = _.map(m.get('choice'), function(e) {
                        return {label: e.label, value: e.id};
                    });
		                new_options.unshift({label: '--- please select one ---',
                                         value: null});
		                self.field.set('options', new_options);
		                self.render();
		            });
		            modl.fetch();
	          },
	          render: function() {
		            return Backform.SelectControl.prototype.render.apply(this, arguments);
	          }
	      });
	      return ModelSelectControl;
    }
);
<|endoftext|>


<commit_before>const gulp          = require('gulp');
const Metalsmith    = require('metalsmith');
const markdown      = require('metalsmith-markdown');
const permalink     = require('metalsmith-permalinks');
const collections   = require('metalsmith-collections');
const assets        = require('metalsmith-assets');
const layouts       = require('metalsmith-layouts');
const inplace       = require('metalsmith-in-place');
const handlebars    = require('handlebars');
const hbsLayout     = require('handlebars-layouts');
const requiredir    = require('require-dir');

// register Helpers
handlebars.registerHelper(hbsLayout(handlebars));
const helpers = requiredir('../src/_helpers/');
Object.keys(helpers).forEach((k) => handlebars.registerHelper(k, helpers[k]));
const partials = requiredir('../src/_partials/');
Object.keys(partials).forEach((k) => handlebars.registerPartial(k, partials[k]));

gulp.task('site', () => {
  Metalsmith('./src')
    .source('.')
    .destination('../dist/')
    .ignore(['_*', '**/_*'])

    .use(collections({
      articles: {
        pattern: '*/**.md',
        sortBy: 'date',
        reverse: true
      }
    }))
    .use(inplace({
      engine: 'handlebars',
    }))
    .use(markdown({
      smartypants: true,
      gfm: true,
      tables: true
    }))
    .use(permalink({
      linksets: [{
        match: {collection: 'articles' },
        pattern: ':date/:title'
      }]
    }))
    .use(layouts({
      engine: 'handlebars',
      default: 'default.hbs',
      directory: '_layouts/',
      pattern: '**.html',     //TODO: not applying layout to articles... why you no?
    }))
    .use(assets({
      source: '../assets',
      destination: './assets/'
    }))

    .build((e) => {
      if(e) {
        throw e;
      }
    });
});

gulp.task('site:watch', () => {
  gulp.watch(['./src/**/*', '!./src/_**/*', './assets/**/*'], ['site']);
});
<commit_msg>use drafts in site generation<commit_after>const gulp          = require('gulp');
const Metalsmith    = require('metalsmith');
const markdown      = require('metalsmith-markdown');
const drafts        = require('metalsmith-drafts');
const permalink     = require('metalsmith-permalinks');
const collections   = require('metalsmith-collections');
const assets        = require('metalsmith-assets');
const layouts       = require('metalsmith-layouts');
const inplace       = require('metalsmith-in-place');
const handlebars    = require('handlebars');
const hbsLayout     = require('handlebars-layouts');
const requiredir    = require('require-dir');

// register Helpers
handlebars.registerHelper(hbsLayout(handlebars));
const helpers = requiredir('../src/_helpers/');
Object.keys(helpers).forEach((k) => handlebars.registerHelper(k, helpers[k]));
const partials = requiredir('../src/_partials/');
Object.keys(partials).forEach((k) => handlebars.registerPartial(k, partials[k]));

gulp.task('site', () => {
  Metalsmith('./src')
    .source('.')
    .destination('../dist/')
    .ignore(['_*', '**/_*'])

    .use(drafts())
    .use(collections({
      articles: {
        pattern: 'articles/**.md',
        sortBy: 'date',
        reverse: true
      }
    }))
    .use(inplace({
      engine: 'handlebars',
    }))
    .use(markdown({
      smartypants: true,
      gfm: true,
      tables: true
    }))
    .use(permalink({
      linksets: [{
        match: {collection: 'articles' },
        pattern: ':date/:title'
      }]
    }))
    .use((files, metalsmith, done) => {
      console.log(files);
      done();
    })
    .use(layouts({
      engine: 'handlebars',
      default: 'default.hbs',
      directory: '_layouts/',
      pattern: '**/*.html',     //TODO: not applying layout to articles... why you no?
    }))
    .use(assets({
      source: '../assets',
      destination: './assets/'
    }))

    .build((e) => {
      if(e) {
        throw e;
      }
    });
});

gulp.task('site:watch', () => {
  gulp.watch(['./src/**/*', '!./src/_**/*', './assets/**/*'], ['site']);
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import $ from 'jquery'
import wikiSidebar from 'wikiSidebar'

// for each command, there are three possibilities:
//
//   .data('remoteEditor') is set:
//     feature flag is on and succeeded, just use the remote editor call
//
//   .data('rich_text') is set:
//     feature flag is off, use the legacy editorBox/wikiSidebar interface
//
//   neither is set:
//     probably feature flag is on but failed, or maybe just a poorly set up
//     spec (or worst case, poorly set up actual usage... booo). the action
//     will do the best it can (see send for example), but often will be a
//     no-op
//
export function send ($target, methodName, ...args) {
  const remoteEditor = $target.data('remoteEditor')
  if (remoteEditor) {
    if (methodName === 'get_code' && remoteEditor.isHidden()) {
      return $target.val()
    }
    if (methodName === 'create_link') {
      // correct for link insertion api difference between editor_box and
      // canvas-rce
      methodName = 'insertLink'
      args[0].href = args[0].url
      args[0].class = args[0].classes
      const dataAttributes = args[0].dataAttributes
      args[0]['data-preview-alt'] = dataAttributes && dataAttributes['preview-alt']
    }
    return remoteEditor.call(methodName, ...args)
  } else if ($target.data('rich_text')) {
    return $target.editorBox(methodName, ...args)
  } else {
    // we're not set up, so tell the caller that `exists?` is false,
    // `get_code` is the textarea value, and ignore anything else.
    if (methodName === 'exists?') {
      return false
    } else if (methodName === 'get_code') {
      return $target.val()
    } else {
      console.warn(`called send('${methodName}') on an RCE instance that hasn't fully loaded, ignored`)
    }
  }
}

export function focus ($target) {
  const remoteEditor = $target.data('remoteEditor')
  if (remoteEditor) {
    remoteEditor.focus()
  } else if ($target.data('rich_text')) {
    wikiSidebar.attachToEditor($target)
  } else {
    console.warn("called focus() on an RCE instance that hasn't fully loaded, ignored")
  }
}

export function destroy ($target) {
  const remoteEditor = $target.data('remoteEditor')
  if (remoteEditor) {
    // detach the remote editor reference after destroying it
    remoteEditor.destroy()
    $target.data('remoteEditor', null)
  } else if ($target.data('rich_text')) {
    $target.editorBox && $target.editorBox('destroy')
  } else {
    console.warn("called destroy() on an RCE instance that hasn't fully loaded, ignored")
  }
}
<commit_msg>check for nil on RceCommandShim in case of double delete. don't except<commit_after>/*
 * Copyright (C) 2016 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import $ from 'jquery'
import wikiSidebar from 'wikiSidebar'

// for each command, there are three possibilities:
//
//   .data('remoteEditor') is set:
//     feature flag is on and succeeded, just use the remote editor call
//
//   .data('rich_text') is set:
//     feature flag is off, use the legacy editorBox/wikiSidebar interface
//
//   neither is set:
//     probably feature flag is on but failed, or maybe just a poorly set up
//     spec (or worst case, poorly set up actual usage... booo). the action
//     will do the best it can (see send for example), but often will be a
//     no-op
//
export function send ($target, methodName, ...args) {
  const remoteEditor = $target.data('remoteEditor')
  if (remoteEditor) {
    if (methodName === 'get_code' && remoteEditor.isHidden()) {
      return $target.val()
    }
    if (methodName === 'create_link') {
      // correct for link insertion api difference between editor_box and
      // canvas-rce
      methodName = 'insertLink'
      args[0].href = args[0].url
      args[0].class = args[0].classes
      const dataAttributes = args[0].dataAttributes
      args[0]['data-preview-alt'] = dataAttributes && dataAttributes['preview-alt']
    }
    return remoteEditor.call(methodName, ...args)
  } else if ($target.data('rich_text')) {
    return $target.editorBox && $target.editorBox(methodName, ...args)
  } else {
    // we're not set up, so tell the caller that `exists?` is false,
    // `get_code` is the textarea value, and ignore anything else.
    if (methodName === 'exists?') {
      return false
    } else if (methodName === 'get_code') {
      return $target.val()
    } else {
      console.warn(`called send('${methodName}') on an RCE instance that hasn't fully loaded, ignored`)
    }
  }
}

export function focus ($target) {
  const remoteEditor = $target.data('remoteEditor')
  if (remoteEditor) {
    remoteEditor.focus()
  } else if ($target.data('rich_text')) {
    wikiSidebar.attachToEditor($target)
  } else {
    console.warn("called focus() on an RCE instance that hasn't fully loaded, ignored")
  }
}

export function destroy ($target) {
  const remoteEditor = $target.data('remoteEditor')
  if (remoteEditor) {
    // detach the remote editor reference after destroying it
    remoteEditor.destroy()
    $target.data('remoteEditor', null)
  } else if ($target.data('rich_text')) {
    $target.editorBox && $target.editorBox('destroy')
  } else {
    console.warn("called destroy() on an RCE instance that hasn't fully loaded, ignored")
  }
}
<|endoftext|>


<commit_before>var assert = require("assert");

var bitset = function(value,bit) {
  return !!(value & (1 << bit));
};

var bitsSet = function(value) {
  var bits = numberOfBits(value);
  var ret = [];
  for (var i=0;i<bits;++i) {
    bits.push(bitset(value,i) ? 1 : 0);
  }
  return ret;
};

var numberOfBits = function(value) {
  if (value === 0) {
    return value;
  }

  var log2 = Math.log(value) / Math.LN2;
  return (Math.pow(2,log2) >= value) ? log2 : log2 + 1;
};

describe('Diversion', function() {
  it('has a bit that is set', function() {
    assert(bitset(1,0));
    assert(bitset(256,8));
  });

  it('number of bits within a value', function() {
    assert.equal(8, numberOfBits(256));
    assert.equal(0, numberOfBits(0));
  });

  it('has bits that are not set', function() {
    assert(!bitset(257,7));
  });

  it('returns the binary representation', function() {
    assert.deepEqual([], bitsSet(0));
    assert.deepEqual([0,1], bitsSet(2));
  });

  it('bit shift operations', function() {
    assert.equal(1, 1 << 0);
    assert.equal(2, 1 << 1);
    assert.equal(4, 1 << 2);
  });
});<commit_msg>fix bug where push called on wrong value<commit_after>var assert = require("assert");

var bitset = function(value,bit) {
  return !!(value & (1 << bit));
};

var bitsSet = function(value) {
  var bits = numberOfBits(value);
  var ret = [];
  for (var i=0;i<bits;++i) {
    ret.push(bitset(value,i) ? 1 : 0);
  }
  return ret;
};

var numberOfBits = function(value) {
  if (value === 0) {
    return value;
  }

  var log2 = Math.log(value) / Math.LN2;
  return (Math.pow(2,log2) >= value) ? log2 : log2 + 1;
};

describe('Diversion', function() {
  it('has a bit that is set', function() {
    assert(bitset(1,0));
    assert(bitset(256,8));
  });

  it('number of bits within a value', function() {
    assert.equal(8, numberOfBits(256));
    assert.equal(0, numberOfBits(0));
  });

  it('has bits that are not set', function() {
    assert(!bitset(257,7));
  });

  it('returns the binary representation', function() {
    assert.deepEqual([], bitsSet(0));
    assert.deepEqual([0,1], bitsSet(2));
  });

  it('bit shift operations', function() {
    assert.equal(1, 1 << 0);
    assert.equal(2, 1 << 1);
    assert.equal(4, 1 << 2);
  });
});<|endoftext|>


<commit_before>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var updateModel = process.require("updates/updateModel.js");
var updateService = process.require("updates/updateService.js");
var guildModel = process.require("guilds/guildModel.js");
var killModel = process.require("kills/killModel.js");
var rankModel = process.require("ranks/rankModel.js");

/**
 * ProgressUpdateProcess constructor
 * @constructor
 */
function ProgressUpdateProcess() {
}

/**
 * Update Guild progress
 */
ProgressUpdateProcess.prototype.updateGuildProgress = function () {
    var logger = applicationStorage.logger;
    var config = applicationStorage.config;
    var self = this;
    async.waterfall([
            function (callback) {
                //Get next guild to update
                updateService.getNextUpdate('wp_pu', function (error, guildProgress) {
                    if (guildProgress == null) {
                        //Guild update is empty
                        logger.info("No guild progress to update ... waiting 3 sec");
                        setTimeout(function () {
                            callback(true);
                        }, 3000);
                    } else {
                        logger.info("Update guild process %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                        callback(error, guildProgress);
                    }
                });
            },
            function (guildProgress, callback) {
                async.eachSeries(config.progress.raids, function (raid, callback) {
                    async.waterfall([
                            function (callback) {
                                killModel.computeProgress(guildProgress.region, guildProgress.realm, guildProgress.name, raid.tier, function (error, result) {
                                    callback(error, result);
                                });
                            },
                            function (result, callback) {
                                var progress = {};
                                var bestNormalKillTimestamp = 0;
                                var bestHeroicKillTimestamp = 0;
                                var bestMythicKillTimestamp = 0;

                                async.forEachSeries(result, function (obj, callback) {

                                    logger.verbose("Kills found for %s-%s R:(%s) I:(%s)", obj._id.boss, obj._id.difficulty, obj.value.timestamps.join(','),obj.value.irrelevantTimestamps.join(','))

                                    if (!progress[obj._id.difficulty]) {
                                        progress[obj._id.difficulty] = {};
                                    }
                                    progress[obj._id.difficulty][obj._id.boss] = obj.value;

                                    if (!progress[obj._id.difficulty + "Count"]) {
                                        progress[obj._id.difficulty + "Count"] = 0;
                                    }

                                    if (obj.value.timestamps.length > 0) {
                                        progress[obj._id.difficulty + "Count"]++;
                                        if (obj._id.difficulty == "normal") {
                                            if (obj.value.timestamps[0][0] > bestNormalKillTimestamp) {
                                                bestNormalKillTimestamp = obj.value.timestamps[0][0];
                                            }
                                        } else if (obj._id.difficulty == "heroic") {
                                            if (obj.value.timestamps[0][0] > bestHeroicKillTimestamp) {
                                                bestHeroicKillTimestamp = obj.value.timestamps[0][0];
                                            }
                                        } else {
                                            if (obj.value.timestamps[0][0] > bestMythicKillTimestamp) {
                                                bestMythicKillTimestamp = obj.value.timestamps[0][0];
                                            }
                                        }
                                    }

                                    callback();
                                }, function () {
                                    var obj = {};
                                    if (bestMythicKillTimestamp != 0) {
                                        progress.bestKillTimestamp = bestMythicKillTimestamp;
                                    } else if (bestHeroicKillTimestamp != 0) {
                                        progress.bestKillTimestamp = bestHeroicKillTimestamp;
                                    } else if (bestNormalKillTimestamp != 0) {
                                        progress.bestKillTimestamp = bestNormalKillTimestamp;
                                    }

                                    progress.updated = new Date().getTime();
                                    obj["tier_" + raid.tier] = progress;

                                    guildModel.upsert(guildProgress.region, guildProgress.realm, guildProgress.name, {progress: obj}, function (error) {
                                        logger.verbose("Update Progress for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                        callback(error, progress);
                                    });

                                });
                            }, function (progress, callback) {
                                if (progress.bestKillTimestamp) {
                                    logger.verbose("Update Score for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);

                                    var preScore = 0;
                                    if (progress.normalCount && progress.normalCount > 0) {
                                        preScore = progress.normalCount;
                                    }
                                    if (progress.heroicCount && progress.heroicCount > 0) {
                                        preScore = progress.heroicCount * 100;
                                    }
                                    if (progress.mythicCount && progress.mythicCount > 0) {
                                        preScore = progress.mythicCount * 10000;
                                    }
                                    //Calculate the score for redis bestTimestamp - 2Years * score
                                    var score = parseInt(progress.bestKillTimestamp / 1000, 10) - (3600 * 24 * 365 * 2 * preScore);
                                    async.parallel([
                                        function (callback) {
                                            rankModel.upsert(raid.tier, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                callback(error);
                                            });
                                        },
                                        function (callback) {
                                            rankModel.upsert(raid.tier + "_" + guildProgress.region, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                callback(error);
                                            });
                                        }
                                    ], function (error) {
                                        callback(error);
                                    });
                                } else {
                                    callback();
                                }
                            }
                        ],
                        function (error) {
                            callback(error);
                        }
                    )
                }, function (error) {
                    callback(error);
                });
            }
        ],
        function (error) {
            if (error && error !== true) {
                logger.error(error.message);
            }
            //Wait 200 before next update
            setTimeout(function () {
                self.updateGuildProgress();

            }, 200);

        }
    )
    ;
}
;

/**
 * Start ProgressUpdateProcess
 * @param callback
 */
ProgressUpdateProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting ProgressUpdateProcess");
    this.updateGuildProgress();
    callback();

};

module.exports = ProgressUpdateProcess;<commit_msg>No delay in Progress Update ...<commit_after>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var updateModel = process.require("updates/updateModel.js");
var updateService = process.require("updates/updateService.js");
var guildModel = process.require("guilds/guildModel.js");
var killModel = process.require("kills/killModel.js");
var rankModel = process.require("ranks/rankModel.js");

/**
 * ProgressUpdateProcess constructor
 * @constructor
 */
function ProgressUpdateProcess() {
}

/**
 * Update Guild progress
 */
ProgressUpdateProcess.prototype.updateGuildProgress = function () {
    var logger = applicationStorage.logger;
    var config = applicationStorage.config;
    var self = this;
    async.waterfall([
            function (callback) {
                //Get next guild to update
                updateService.getNextUpdate('wp_pu', function (error, guildProgress) {
                    if (guildProgress == null) {
                        //Guild update is empty
                        logger.info("No guild progress to update ... waiting 3 sec");
                        setTimeout(function () {
                            callback(true);
                        }, 3000);
                    } else {
                        logger.info("Update guild process %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                        callback(error, guildProgress);
                    }
                });
            },
            function (guildProgress, callback) {
                async.eachSeries(config.progress.raids, function (raid, callback) {
                    async.waterfall([
                            function (callback) {
                                killModel.computeProgress(guildProgress.region, guildProgress.realm, guildProgress.name, raid.tier, function (error, result) {
                                    callback(error, result);
                                });
                            },
                            function (result, callback) {
                                var progress = {};
                                var bestNormalKillTimestamp = 0;
                                var bestHeroicKillTimestamp = 0;
                                var bestMythicKillTimestamp = 0;

                                async.forEachSeries(result, function (obj, callback) {

                                    logger.verbose("Kills found for %s-%s R:(%s) I:(%s)", obj._id.boss, obj._id.difficulty, obj.value.timestamps.join(','),obj.value.irrelevantTimestamps.join(','))

                                    if (!progress[obj._id.difficulty]) {
                                        progress[obj._id.difficulty] = {};
                                    }
                                    progress[obj._id.difficulty][obj._id.boss] = obj.value;

                                    if (!progress[obj._id.difficulty + "Count"]) {
                                        progress[obj._id.difficulty + "Count"] = 0;
                                    }

                                    if (obj.value.timestamps.length > 0) {
                                        progress[obj._id.difficulty + "Count"]++;
                                        if (obj._id.difficulty == "normal") {
                                            if (obj.value.timestamps[0][0] > bestNormalKillTimestamp) {
                                                bestNormalKillTimestamp = obj.value.timestamps[0][0];
                                            }
                                        } else if (obj._id.difficulty == "heroic") {
                                            if (obj.value.timestamps[0][0] > bestHeroicKillTimestamp) {
                                                bestHeroicKillTimestamp = obj.value.timestamps[0][0];
                                            }
                                        } else {
                                            if (obj.value.timestamps[0][0] > bestMythicKillTimestamp) {
                                                bestMythicKillTimestamp = obj.value.timestamps[0][0];
                                            }
                                        }
                                    }

                                    callback();
                                }, function () {
                                    var obj = {};
                                    if (bestMythicKillTimestamp != 0) {
                                        progress.bestKillTimestamp = bestMythicKillTimestamp;
                                    } else if (bestHeroicKillTimestamp != 0) {
                                        progress.bestKillTimestamp = bestHeroicKillTimestamp;
                                    } else if (bestNormalKillTimestamp != 0) {
                                        progress.bestKillTimestamp = bestNormalKillTimestamp;
                                    }

                                    progress.updated = new Date().getTime();
                                    obj["tier_" + raid.tier] = progress;

                                    guildModel.upsert(guildProgress.region, guildProgress.realm, guildProgress.name, {progress: obj}, function (error) {
                                        logger.verbose("Update Progress for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);
                                        callback(error, progress);
                                    });

                                });
                            }, function (progress, callback) {
                                if (progress.bestKillTimestamp) {
                                    logger.verbose("Update Score for guild %s-%s-%s", guildProgress.region, guildProgress.realm, guildProgress.name);

                                    var preScore = 0;
                                    if (progress.normalCount && progress.normalCount > 0) {
                                        preScore = progress.normalCount;
                                    }
                                    if (progress.heroicCount && progress.heroicCount > 0) {
                                        preScore = progress.heroicCount * 100;
                                    }
                                    if (progress.mythicCount && progress.mythicCount > 0) {
                                        preScore = progress.mythicCount * 10000;
                                    }
                                    //Calculate the score for redis bestTimestamp - 2Years * score
                                    var score = parseInt(progress.bestKillTimestamp / 1000, 10) - (3600 * 24 * 365 * 2 * preScore);
                                    async.parallel([
                                        function (callback) {
                                            rankModel.upsert(raid.tier, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                callback(error);
                                            });
                                        },
                                        function (callback) {
                                            rankModel.upsert(raid.tier + "_" + guildProgress.region, guildProgress.region, guildProgress.realm, guildProgress.name, score, function (error) {
                                                callback(error);
                                            });
                                        }
                                    ], function (error) {
                                        callback(error);
                                    });
                                } else {
                                    callback();
                                }
                            }
                        ],
                        function (error) {
                            callback(error);
                        }
                    )
                }, function (error) {
                    callback(error);
                });
            }
        ],
        function (error) {
            if (error && error !== true) {
                logger.error(error.message);
            }
            self.updateGuildProgress();

        }
    )
    ;
}
;

/**
 * Start ProgressUpdateProcess
 * @param callback
 */
ProgressUpdateProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting ProgressUpdateProcess");
    this.updateGuildProgress();
    callback();

};

module.exports = ProgressUpdateProcess;<|endoftext|>


<commit_before>'use strict';

angular.module('BaubleApp')
    .controller('GenusViewCtrl', function ($scope, $location, globals, Genus) {
        $scope.genus = globals.selected;
        Genus.details(globals.selected)
            .success(function(data, status, headers, config) {
                $scope.genus = result.data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

        $scope.$on('genus-edit', function(){
            $scope.$apply(function() {
                $location.path('/edit/genus');
            });
        });

        $scope.$on('genus-addtaxon', function(){
            $scope.$apply(function() {
                $location.path('/new/taxon').search({'genus': $scope.genus.ref});
            });
        });

        $scope.counts = {};

        Genus.count($scope.genus, "/taxa")
            .success(function(data, status, headers, config) {
                $scope.counts.taxa = data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

        Genus.count($scope.genus, "/taxa/accessions")
            .success(function(data, status, headers, config) {
                $scope.counts.accessions = data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

        Genus.count($scope.genus, "/taxa/accessions/plants")
            .success(function(data, status, headers, config) {
                $scope.counts.plants = data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

    });
<commit_msg>- another genus view fix<commit_after>'use strict';

angular.module('BaubleApp')
    .controller('GenusViewCtrl', function ($scope, $location, globals, Genus) {
        $scope.genus = globals.selected;
        Genus.details(globals.selected)
            .success(function(data, status, headers, config) {
                $scope.genus = data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

        $scope.$on('genus-edit', function(){
            $scope.$apply(function() {
                $location.path('/edit/genus');
            });
        });

        $scope.$on('genus-addtaxon', function(){
            $scope.$apply(function() {
                $location.path('/new/taxon').search({'genus': $scope.genus.ref});
            });
        });

        $scope.counts = {};

        Genus.count($scope.genus, "/taxa")
            .success(function(data, status, headers, config) {
                $scope.counts.taxa = data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

        Genus.count($scope.genus, "/taxa/accessions")
            .success(function(data, status, headers, config) {
                $scope.counts.accessions = data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

        Genus.count($scope.genus, "/taxa/accessions/plants")
            .success(function(data, status, headers, config) {
                $scope.counts.plants = data;
            })
            .error(function(data, status, headers, config) {
                // do something
            });

    });
<|endoftext|>