<commit_before>/** Handle the creation of HTML links to documented symbols.
	@constructor
*/
function Link() {
	this.alias = "";
	this.src = "";
	this.file = "";
	this.text = "";
	this.innerName = "";
	this.classLink = false;
	this.targetName = "";

	this.target = function(targetName) {
		if (defined(targetName)) this.targetName = targetName;
		return this;
	}
	this.inner = function(inner) {
		if (defined(inner)) this.innerName = inner;
		return this;
	}
	this.withText = function(text) {
		if (defined(text)) this.text = text;
		return this;
	}
	this.toSrc = function(filename) {
		if (defined(filename)) this.src = filename;
		return this;
	}
	this.toSymbol = function(alias) {
		// 'Class[]' to 'Array of Class objects'
		if(/\[\]$/.test(alias)) {
			alias = alias.replace(/\[\]$/, '');
			this.prefix = 'Array of ';
			this.text = alias;
			this.suffix = ' objects';
		}
		if (defined(alias)) this.alias = new String(alias);
		return this;
	}
	this.toClass = function(alias) {
		this.classLink = true;
		return this.toSymbol(alias);
	}
	this.toFile = function(file) {
		if (defined(file)) this.file = file;
		return this;
	}

	this.toString = function() {
		var linkString;
		var thisLink = this;

		if (this.alias) {
			linkString = this.alias.replace(/(^|[^a-z$0-9_#.:^-])([|a-z$0-9_#.:^-]+)(\([^)]+\))*($|[^a-z$0-9_#.:^-])/i,
				function(match, prematch, symbolName, parameters, postmatch) {
					var symbolNames = symbolName.split("|");
					var links = [];
					for (var i = 0, l = symbolNames.length; i < l; i++) {
						thisLink.alias = symbolNames[i];
						links.push(thisLink._makeSymbolLink(symbolNames[i], parameters));
					}
					return prematch+links.join("|")+postmatch;
				}
			);
		}
		else if (this.src) {
			linkString = thisLink._makeSrcLink(this.src);
		}
		else if (this.file) {
			linkString = thisLink._makeFileLink(this.file);
		}

		return linkString;
	}
}

/** prefixed for hashes */
Link.hashPrefix = "";

/** Appended to the front of relative link paths. */
Link.base = "";

Link.symbolNameToLinkName = function(symbol) {
	var linker = "",
		ns = "";

	if (symbol.isStatic) linker = "-";
	else if (symbol.isInner) linker = "-";

	if (symbol.isEvent && !/^event:/.test(symbol.name)) {
		ns = "event:";
	}
	return Link.hashPrefix+linker+ns+symbol.name;
}

Link.getSymbol= function(alias) {
    var symbol= Link.symbolSet.getSymbol(alias);

    if (symbol)
        return symbol;

    if ('#'!==alias.charAt(0) || !Link.currentSymbol)
        return null;

    //  resolve relative name
    var container= Link.currentSymbol;

    while (container)
    {
        symbol= Link.symbolSet.getSymbol(container.alias + alias);
        if (symbol)
            return symbol;

        //  No superclass
        if (!container.augments.length)
            return null;

        container= Link.symbolSet.getSymbol(container.augments[0].desc);
    }

    return null;
}

/** Create a link to another symbol. */
Link.prototype._makeSymbolLink = function(alias, parameters) {
	var linkBase = Link.base+publish.conf.symbolsDir;
	var linkTo = Link.getSymbol(alias);
	var linkPath;
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";
	// Expand (parameter,parameter) to (parameter, parameter)
	if (parameters) {
		parameters = parameters.replace(/\,([^\s])/, ', $1')
	}

	// if there is no symbol by that name just return the name unaltered
	if (!linkTo) {
	    return this.text || alias + (parameters || '');
	} else {
		// it's a symbol in another file
		if (!linkTo.is("CONSTRUCTOR") && !linkTo.isNamespace) { // it's a method or property
			linkPath= (Link.filemap) ? Link.filemap[linkTo.memberOf] :
				      escape(linkTo.memberOf) || "global";
				linkPath += publish.conf.ext + "#" + Link.symbolNameToLinkName(linkTo).toLowerCase();
			if (parameters) {
				linkPath += '-' + parameters.replace(/[()]+/g, '').split(', ').join('-').toLowerCase();
			}
		} else {
			linkPath = (Link.filemap)? Link.filemap[linkTo.alias] : escape(linkTo.alias);
			linkPath += publish.conf.ext;// + (this.classLink? "":"#" + Link.hashPrefix + "constructor");
		}
		linkPath = linkBase + linkPath
	}

	var linkText= (this.text || alias) + (parameters || '');

	var link = {
		linkPath: linkPath,
		linkText: linkText.replace(/^#/, ''),
		linkInner: (this.innerName? "#" + this.innerName : "")
	};

	if (typeof JSDOC.PluginManager != "undefined") {
		JSDOC.PluginManager.run("onSymbolLink", link);
	}
	if (/^[A-Z].+\#/.test(link.linkText)) {
		link.linkText = link.linkText.charAt(0).toLowerCase() + link.linkText.slice(1);
		link.linkText = link.linkText.replace(/#/g, '.');
	}
	var onClick = '';
	// If linking to a member of the same class, we also need to toggle it:
	if (alias.charAt(0) == '#') {
		var linkName = link.linkPath.replace(/^[^#]+#/, '');
		onClick = " onclick=\"return toggleMember('" + linkName + "', true);\"";
	}
	var html = "<tt>"+link.linkText+"</tt>";
	if (this.prefix || this.suffix)
		html = (this.prefix || '') + html + (this.suffix || '');
	return html;
}

/** Create a link to a source file. */
Link.prototype._makeSrcLink = function(srcFilePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	// transform filepath into a filename
	var srcFile = srcFilePath.replace(/\.\.?[\\\/]/g, "").replace(/[:\\\/]/g, "_");
	var outFilePath = Link.base + publish.conf.srcDir + srcFile + publish.conf.ext;

	if (!this.text) this.text = FilePath.fileName(srcFilePath);
	return ""+this.text+"";
}

/** Create a link to a source file. */
Link.prototype._makeFileLink = function(filePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	var outFilePath =  Link.base + filePath;

	if (!this.text) this.text = filePath;
	return ""+this.text+"";
}<commit_msg>JSDocs: Separate different options with ' / ' rather than '|'.<commit_after>/** Handle the creation of HTML links to documented symbols.
	@constructor
*/
function Link() {
	this.alias = "";
	this.src = "";
	this.file = "";
	this.text = "";
	this.innerName = "";
	this.classLink = false;
	this.targetName = "";

	this.target = function(targetName) {
		if (defined(targetName)) this.targetName = targetName;
		return this;
	}
	this.inner = function(inner) {
		if (defined(inner)) this.innerName = inner;
		return this;
	}
	this.withText = function(text) {
		if (defined(text)) this.text = text;
		return this;
	}
	this.toSrc = function(filename) {
		if (defined(filename)) this.src = filename;
		return this;
	}
	this.toSymbol = function(alias) {
		// 'Class[]' to 'Array of Class objects'
		if(/\[\]$/.test(alias)) {
			alias = alias.replace(/\[\]$/, '');
			this.prefix = 'Array of ';
			this.text = alias;
			this.suffix = ' objects';
		}
		if (defined(alias)) this.alias = new String(alias);
		return this;
	}
	this.toClass = function(alias) {
		this.classLink = true;
		return this.toSymbol(alias);
	}
	this.toFile = function(file) {
		if (defined(file)) this.file = file;
		return this;
	}

	this.toString = function() {
		var linkString;
		var thisLink = this;

		if (this.alias) {
			linkString = this.alias.replace(/(^|[^a-z$0-9_#.:^-])([|a-z$0-9_#.:^-]+)(\([^)]+\))*($|[^a-z$0-9_#.:^-])/i,
				function(match, prematch, symbolName, parameters, postmatch) {
					var symbolNames = symbolName.split("|");
					var links = [];
					for (var i = 0, l = symbolNames.length; i < l; i++) {
						thisLink.alias = symbolNames[i];
						links.push(thisLink._makeSymbolLink(symbolNames[i], parameters));
					}
					return prematch+links.join(" / ")+postmatch;
				}
			);
		}
		else if (this.src) {
			linkString = thisLink._makeSrcLink(this.src);
		}
		else if (this.file) {
			linkString = thisLink._makeFileLink(this.file);
		}

		return linkString;
	}
}

/** prefixed for hashes */
Link.hashPrefix = "";

/** Appended to the front of relative link paths. */
Link.base = "";

Link.symbolNameToLinkName = function(symbol) {
	var linker = "",
		ns = "";

	if (symbol.isStatic) linker = "-";
	else if (symbol.isInner) linker = "-";

	if (symbol.isEvent && !/^event:/.test(symbol.name)) {
		ns = "event:";
	}
	return Link.hashPrefix+linker+ns+symbol.name;
}

Link.getSymbol= function(alias) {
    var symbol= Link.symbolSet.getSymbol(alias);

    if (symbol)
        return symbol;

    if ('#'!==alias.charAt(0) || !Link.currentSymbol)
        return null;

    //  resolve relative name
    var container= Link.currentSymbol;

    while (container)
    {
        symbol= Link.symbolSet.getSymbol(container.alias + alias);
        if (symbol)
            return symbol;

        //  No superclass
        if (!container.augments.length)
            return null;

        container= Link.symbolSet.getSymbol(container.augments[0].desc);
    }

    return null;
}

/** Create a link to another symbol. */
Link.prototype._makeSymbolLink = function(alias, parameters) {
	var linkBase = Link.base+publish.conf.symbolsDir;
	var linkTo = Link.getSymbol(alias);
	var linkPath;
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";
	// Expand (parameter,parameter) to (parameter, parameter)
	if (parameters) {
		parameters = parameters.replace(/\,([^\s])/, ', $1')
	}

	// if there is no symbol by that name just return the name unaltered
	if (!linkTo) {
	    return this.text || alias + (parameters || '');
	} else {
		// it's a symbol in another file
		if (!linkTo.is("CONSTRUCTOR") && !linkTo.isNamespace) { // it's a method or property
			linkPath= (Link.filemap) ? Link.filemap[linkTo.memberOf] :
				      escape(linkTo.memberOf) || "global";
				linkPath += publish.conf.ext + "#" + Link.symbolNameToLinkName(linkTo).toLowerCase();
			if (parameters) {
				linkPath += '-' + parameters.replace(/[()]+/g, '').split(', ').join('-').toLowerCase();
			}
		} else {
			linkPath = (Link.filemap)? Link.filemap[linkTo.alias] : escape(linkTo.alias);
			linkPath += publish.conf.ext;// + (this.classLink? "":"#" + Link.hashPrefix + "constructor");
		}
		linkPath = linkBase + linkPath
	}

	var linkText= (this.text || alias) + (parameters || '');

	var link = {
		linkPath: linkPath,
		linkText: linkText.replace(/^#/, ''),
		linkInner: (this.innerName? "#" + this.innerName : "")
	};

	if (typeof JSDOC.PluginManager != "undefined") {
		JSDOC.PluginManager.run("onSymbolLink", link);
	}
	if (/^[A-Z].+\#/.test(link.linkText)) {
		link.linkText = link.linkText.charAt(0).toLowerCase() + link.linkText.slice(1);
		link.linkText = link.linkText.replace(/#/g, '.');
	}
	var onClick = '';
	// If linking to a member of the same class, we also need to toggle it:
	if (alias.charAt(0) == '#') {
		var linkName = link.linkPath.replace(/^[^#]+#/, '');
		onClick = " onclick=\"return toggleMember('" + linkName + "', true);\"";
	}
	var html = "<tt>"+link.linkText+"</tt>";
	if (this.prefix || this.suffix)
		html = (this.prefix || '') + html + (this.suffix || '');
	return html;
}

/** Create a link to a source file. */
Link.prototype._makeSrcLink = function(srcFilePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	// transform filepath into a filename
	var srcFile = srcFilePath.replace(/\.\.?[\\\/]/g, "").replace(/[:\\\/]/g, "_");
	var outFilePath = Link.base + publish.conf.srcDir + srcFile + publish.conf.ext;

	if (!this.text) this.text = FilePath.fileName(srcFilePath);
	return ""+this.text+"";
}

/** Create a link to a source file. */
Link.prototype._makeFileLink = function(filePath) {
	var target = (this.targetName)? " target=\""+this.targetName+"\"" : "";

	var outFilePath =  Link.base + filePath;

	if (!this.text) this.text = filePath;
	return ""+this.text+"";
}<|endoftext|>


<commit_before>angular.module('genesis.video', ['pubnub.angular.service'])

.controller('VideoController', function($scope, $window, $location, Keys, Video, Auction) {
  $scope.here_now = Video.here_now;

  // use ID on URL as channel
  var id = $location.path().split("/")[2]; //domain.com/auctions/15

  // state of video buttons
  $scope.on = false;
  $scope.audience = 0;

  $scope.username = JSON.parse($window.localStorage.getItem('com.genesis')).username;

  $scope.toggle = function() {
    $scope.on = Video.toggle($scope.on);
  };

  // set owner property on $scope
  $scope.getAuction = function() {
    Auction.getAuction(id)
      .then(function (data) {
        $scope.owner = data.owner === $scope.username ? true: false;
        //show auction DNE error
        if (!data)  {
          $scope.DNE();
        }
      })
  };

  // set ownership on $scope
  $scope.getAuction();

  // need access to keys
  Keys.then(function(pub_sub) {

    // PubNub Video Functionality
    $scope.stream = function() {
        Video.stream(pub_sub, id, function(occupancy) {
          $scope.audience = occupancy;
        });
    };

    $scope.watch = function() {
        Video.watch(pub_sub, id);
    };

    $scope.end = function() {
        Video.end(pub_sub, id);
    };

  });

});
<commit_msg>(refactor) here_now declared with other $scope vars<commit_after>angular.module('genesis.video', ['pubnub.angular.service'])

.controller('VideoController', function($scope, $window, $location, Keys, Video, Auction) {

  // use ID on URL as channel
  var id = $location.path().split("/")[2]; //domain.com/auctions/15

  // state of video buttons
  $scope.on = false;
  $scope.here_now = Video.here_now;

  $scope.username = JSON.parse($window.localStorage.getItem('com.genesis')).username;

  $scope.toggle = function() {
    $scope.on = Video.toggle($scope.on);
  };

  // set owner property on $scope
  $scope.getAuction = function() {
    Auction.getAuction(id)
      .then(function (data) {
        $scope.owner = data.owner === $scope.username ? true: false;
        //show auction DNE error
        if (!data)  {
          $scope.DNE();
        }
      })
  };

  // set ownership on $scope
  $scope.getAuction();

  // need access to keys
  Keys.then(function(pub_sub) {

    // PubNub Video Functionality
    $scope.stream = function() {
        Video.stream(pub_sub, id, function(occupancy) {
          $scope.audience = occupancy;
        });
    };

    $scope.watch = function() {
        Video.watch(pub_sub, id);
    };

    $scope.end = function() {
        Video.end(pub_sub, id);
    };

  });

});
<|endoftext|>


<commit_before>/* global on:false */

import { AbilityChecks } from './AbilityChecks';
const abilityChecks = new AbilityChecks();
import { Actions } from './Actions';
const actions = new Actions();
import { Attacks } from './Attacks';
const attacks = new Attacks();
import { Spells } from './Spells';
const spells = new Spells();
import { getSetItems, getIntValue, getFloatValue, getAbilityMod, addArithmeticOperator, showSign, firstThree } from './utilities';

export class Abilities {
  updateModifier(ability) {
    const collectionArray = [ability, `${ability}_bonus`, `${ability}_mod`, `${ability}_mod_with_sign`, `${ability}_check_mod`, `${ability}_check_mod_formula`, `${ability}_check_bonus`, 'global_ability_bonus', 'strength_mod', 'dexterity_mod', 'jack_of_all_trades_toggle', 'jack_of_all_trades', 'remarkable_athlete_toggle', 'remarkable_athlete', 'global_check_bonus'];
    if (ability === 'strength' || ability === 'dexterity') {
      collectionArray.push('finesse_mod');
    }
    if (ability === 'strength') {
      collectionArray.push('weight_multiplier');
      collectionArray.push('carrying_capacity');
      collectionArray.push('max_push_drag_lift');
      collectionArray.push('encumbered');
      collectionArray.push('heavily_encumbered');
    }

    getSetItems('abilities.updateModifier', {
      collectionArray,
      callback: (v, finalSetAttrs) => {
        const abilityScore = getIntValue(v[ability]);
        const abilityBonus = getIntValue(v[`${ability}_bonus`]);
        const globalAbilityBonus = v.global_ability_bonus;
        let abilityScoreCalc = abilityScore + abilityBonus;

        if (!isNaN(globalAbilityBonus)) {
          abilityScoreCalc += getIntValue(globalAbilityBonus);
        }

        const abilityCheckBonus = getIntValue(v[`${ability}_check_bonus`]);
        const abilityMod = getAbilityMod(abilityScoreCalc);

        let abilityCheck = abilityMod;
        let abilityCheckFormula = '';

        if (abilityMod !== 0) {
          abilityCheckFormula = `${abilityMod}[${firstThree(ability)} mod with bonus]`;
        }
        if ((ability === 'strength' || ability === 'dexterity' || ability === 'constitution') && v.remarkable_athlete_toggle === '@{remarkable_athlete}') {
          const remarkableAthlete = getIntValue(v.remarkable_athlete);
          abilityCheck += remarkableAthlete;
          abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, remarkableAthlete)}[remarkable athlete]`;
        } else if (v.jack_of_all_trades_toggle === '@{jack_of_all_trades}') {
          const jackOfAllTrades = getIntValue(v.jack_of_all_trades);
          abilityCheck += jackOfAllTrades;
          abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, jackOfAllTrades)}[jack of all trades]`;
        }
        if (abilityCheckBonus) {
          abilityCheck += abilityCheckBonus;
          abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, abilityCheckBonus)}[${ability} check bonus]`;
        }
        if (v.global_check_bonus) {
          if (!isNaN(v.global_check_bonus)) {
            abilityCheck += getIntValue(v.global_check_bonus);
          }
          if (abilityCheckFormula) {
            abilityCheckFormula += ' + ';
          }
          abilityCheckFormula += '(@{global_check_bonus})[global check bonus]';
        }

        finalSetAttrs[`${ability}_calculated`] = abilityScoreCalc;
        finalSetAttrs[`${ability}_mod`] = abilityMod;
        finalSetAttrs[`${ability}_mod_with_sign`] = showSign(abilityMod);
        finalSetAttrs[`${ability}_check_mod`] = abilityCheck;
        finalSetAttrs[`${ability}_check_mod_with_sign`] = showSign(abilityCheck);
        finalSetAttrs[`${ability}_check_mod_formula`] = abilityCheckFormula;

        if (ability === 'strength') {
          finalSetAttrs.finesse_mod = Math.max(abilityMod, getIntValue(v.dexterity_mod));
          const weightMultiplier = getFloatValue(v.weight_multiplier, 1);
          finalSetAttrs.carrying_capacity = abilityScoreCalc * 15 * weightMultiplier;
          finalSetAttrs.max_push_drag_lift = abilityScoreCalc * 30 * weightMultiplier;
          finalSetAttrs.encumbered = abilityScoreCalc * 5 * weightMultiplier;
          finalSetAttrs.heavily_encumbered = abilityScoreCalc * 10 * weightMultiplier;
        } else if (ability === 'dexterity') {
          finalSetAttrs.finesse_mod = Math.max(abilityMod, getIntValue(v.strength_mod));
        }
      },
    });
  }
  updateModifiers() {
    this.updateModifier('strength');
    this.updateModifier('dexterity');
    this.updateModifier('constitution');
    this.updateModifier('intelligence');
    this.updateModifier('wisdom');
    this.updateModifier('charisma');
  }
  setup() {
    on('change:jack_of_all_trades_toggle change:jack_of_all_trades change:global_ability_bonus change:global_check_bonus', () => {
      this.updateModifiers();
    });
    on('change:strength change:strength_bonus change:strength_check_mod change:strength_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete change:weight_multiplier', () => {
      this.updateModifier('strength');
    });
    on('change:dexterity change:dexterity_bonus change:dexterity_check_mod change:dexterity_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => {
      this.updateModifier('dexterity');
    });
    on('change:constitution change:constitution_bonus change:constitution_check_mod change:constitution_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => {
      this.updateModifier('constitution');
    });
    on('change:intelligence change:intelligence_bonus change:intelligence_check_mod change:intelligence_check_bonus', () => {
      this.updateModifier('intelligence');
    });
    on('change:wisdom change:wisdom_bonus change:wisdom_check_mod change:wisdom_check_bonus', () => {
      this.updateModifier('wisdom');
    });
    on('change:charisma change:charisma_bonus change:charisma_check_mod change:charisma_check_bonus', () => {
      this.updateModifier('charisma');
    });
    on('change:strength_mod change:dexterity_mod change:constitution_mod change:intelligence_mod change:wisdom_mod change:charisma_mod', () => {
      abilityChecks.updateSkill();
      attacks.update();
      spells.update();
      actions.updateAll();
    });
  }
}
<commit_msg>move carrying capacity to equipment script<commit_after>/* global on:false */

import { AbilityChecks } from './AbilityChecks';
const abilityChecks = new AbilityChecks();
import { Actions } from './Actions';
const actions = new Actions();
import { Attacks } from './Attacks';
const attacks = new Attacks();
import { Spells } from './Spells';
const spells = new Spells();
import { getSetItems, getIntValue, getFloatValue, getAbilityMod, addArithmeticOperator, showSign, firstThree } from './utilities';

export class Abilities {
  updateModifier(ability) {
    const collectionArray = [ability, `${ability}_bonus`, `${ability}_mod`, `${ability}_mod_with_sign`, `${ability}_check_mod`, `${ability}_check_mod_formula`, `${ability}_check_bonus`, 'global_ability_bonus', 'strength_mod', 'dexterity_mod', 'jack_of_all_trades_toggle', 'jack_of_all_trades', 'remarkable_athlete_toggle', 'remarkable_athlete', 'global_check_bonus'];
    if (ability === 'strength' || ability === 'dexterity') {
      collectionArray.push('finesse_mod');
    }

    getSetItems('abilities.updateModifier', {
      collectionArray,
      callback: (v, finalSetAttrs) => {
        const abilityScore = getIntValue(v[ability]);
        const abilityBonus = getIntValue(v[`${ability}_bonus`]);
        const globalAbilityBonus = v.global_ability_bonus;
        let abilityScoreCalc = abilityScore + abilityBonus;

        if (!isNaN(globalAbilityBonus)) {
          abilityScoreCalc += getIntValue(globalAbilityBonus);
        }

        const abilityCheckBonus = getIntValue(v[`${ability}_check_bonus`]);
        const abilityMod = getAbilityMod(abilityScoreCalc);

        let abilityCheck = abilityMod;
        let abilityCheckFormula = '';

        if (abilityMod !== 0) {
          abilityCheckFormula = `${abilityMod}[${firstThree(ability)} mod with bonus]`;
        }
        if ((ability === 'strength' || ability === 'dexterity' || ability === 'constitution') && v.remarkable_athlete_toggle === '@{remarkable_athlete}') {
          const remarkableAthlete = getIntValue(v.remarkable_athlete);
          abilityCheck += remarkableAthlete;
          abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, remarkableAthlete)}[remarkable athlete]`;
        } else if (v.jack_of_all_trades_toggle === '@{jack_of_all_trades}') {
          const jackOfAllTrades = getIntValue(v.jack_of_all_trades);
          abilityCheck += jackOfAllTrades;
          abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, jackOfAllTrades)}[jack of all trades]`;
        }
        if (abilityCheckBonus) {
          abilityCheck += abilityCheckBonus;
          abilityCheckFormula += `${addArithmeticOperator(abilityCheckFormula, abilityCheckBonus)}[${ability} check bonus]`;
        }
        if (v.global_check_bonus) {
          if (!isNaN(v.global_check_bonus)) {
            abilityCheck += getIntValue(v.global_check_bonus);
          }
          if (abilityCheckFormula) {
            abilityCheckFormula += ' + ';
          }
          abilityCheckFormula += '(@{global_check_bonus})[global check bonus]';
        }

        finalSetAttrs[`${ability}_calculated`] = abilityScoreCalc;
        finalSetAttrs[`${ability}_mod`] = abilityMod;
        finalSetAttrs[`${ability}_mod_with_sign`] = showSign(abilityMod);
        finalSetAttrs[`${ability}_check_mod`] = abilityCheck;
        finalSetAttrs[`${ability}_check_mod_with_sign`] = showSign(abilityCheck);
        finalSetAttrs[`${ability}_check_mod_formula`] = abilityCheckFormula;

        if (ability === 'strength') {
          finalSetAttrs.finesse_mod = Math.max(abilityMod, getIntValue(v.dexterity_mod));
        } else if (ability === 'dexterity') {
          finalSetAttrs.finesse_mod = Math.max(abilityMod, getIntValue(v.strength_mod));
        }
      },
    });
  }
  updateModifiers() {
    this.updateModifier('strength');
    this.updateModifier('dexterity');
    this.updateModifier('constitution');
    this.updateModifier('intelligence');
    this.updateModifier('wisdom');
    this.updateModifier('charisma');
  }
  setup() {
    on('change:jack_of_all_trades_toggle change:jack_of_all_trades change:global_ability_bonus change:global_check_bonus', () => {
      this.updateModifiers();
    });
    on('change:strength change:strength_bonus change:strength_check_mod change:strength_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => {
      this.updateModifier('strength');
    });
    on('change:dexterity change:dexterity_bonus change:dexterity_check_mod change:dexterity_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => {
      this.updateModifier('dexterity');
    });
    on('change:constitution change:constitution_bonus change:constitution_check_mod change:constitution_check_bonus change:remarkable_athlete_toggle change:remarkable_athlete', () => {
      this.updateModifier('constitution');
    });
    on('change:intelligence change:intelligence_bonus change:intelligence_check_mod change:intelligence_check_bonus', () => {
      this.updateModifier('intelligence');
    });
    on('change:wisdom change:wisdom_bonus change:wisdom_check_mod change:wisdom_check_bonus', () => {
      this.updateModifier('wisdom');
    });
    on('change:charisma change:charisma_bonus change:charisma_check_mod change:charisma_check_bonus', () => {
      this.updateModifier('charisma');
    });
    on('change:strength_mod change:dexterity_mod change:constitution_mod change:intelligence_mod change:wisdom_mod change:charisma_mod', () => {
      abilityChecks.updateSkill();
      attacks.update();
      spells.update();
      actions.updateAll();
    });
  }
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var browserify = require('browserify');
var babelify = require('babelify');

if (!fs.existsSync('./es5')) {
  fs.mkdirSync('./es5');
}

browserify({'debug': true})
  .transform(babelify)
  .require('./index.js', {'entry': true})
  .bundle()
  .on('error', function (err) { console.log('Error : ' + err.message); })
  .pipe(fs.createWriteStream('es5/index.js'));
<commit_msg>Remove browserify task/file.<commit_after><|endoftext|>


<commit_before>var pf = require('performanceFramework');
var qm = require('./queueMonitor.js');
var client = require('./client.js');
var server = require('./server.js');

var scenario2 = pf.describe('Second scenario', 'In this scenario we will test Rush behaviour with a server wit no lag'
    , 'wijmo', ['Xaxis', 'Yaxis'], [], './log'); //monitor on localhost
scenario2.test('test2', function (log, point) {
    'use strict';
    var i = 0;
    var monitorInterval = setInterval(function () {
        qm.monitorQueue('wrL:hpri', function (i, value) {
            point(i, value);
            console.log(value);
        }.bind(null, i));
        i++;
    }, 1000);

    var server1 = server.createServer(0, 1000, function () {
        var completed = 0;
        function doReq(i){
            client.client('localhost', 3001, "http://localhost:5001");
            i++;
            if(i < 300){
                setTimeout(function(){
                    doReq(i);
                },10);
            }

        }
        doReq(0);
    });

    function freeAll(){
        clearInterval(monitorInterval);
        scenario1.done();
        server.closeServer(server1);
    }

    setTimeout(freeAll, 60000);

});
<commit_msg>bug fixed<commit_after>var pf = require('performanceFramework');
var qm = require('./queueMonitor.js');
var client = require('./client.js');
var server = require('./server.js');

var scenario2 = pf.describe('Second scenario', 'In this scenario we will test Rush behaviour with a server wit no lag'
    , 'wijmo', ['Xaxis', 'Yaxis'], [], './log'); //monitor on localhost
scenario2.test('test2', function (log, point) {
    'use strict';
    var i = 0;
    var monitorInterval = setInterval(function () {
        qm.monitorQueue('wrL:hpri', function (i, value) {
            point(i, value);
            console.log(value);
        }.bind(null, i));
        i++;
    }, 1000);

    var server1 = server.createServer(0, 10000000, function () {
        var completed = 0;
        function doReq(i){
            client.client('localhost', 3001, "http://localhost:5001");
            i++;
            if(i < 300){
                setTimeout(function(){
                    doReq(i);
                },10);
            }

        }
        doReq(0);
    });

    function freeAll(){
        clearInterval(monitorInterval);
        scenario2.done();
        server.closeServer(server1);
    }

    setTimeout(freeAll, 120000);

});
<|endoftext|>


<commit_before>/*!
 * msgpack-response
 * Copyright(c) 2017 Mobiltron Inc
 * MIT Licensed
 */

/**
 * Module dependencies.
 */
const _ = require('lodash');
const onHeaders = require('on-headers')
const msgpackLite = require('msgpack-lite');

/**
 * Module variables.
 * @private
 */
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/;

/**
 * Transform response data using msgpack.
 *
 * @return {Function} middleware
 * @public
 */
function mgsPackResponse () {

  return function _mgsPackResponse(req, res, next) {
    var ended = false;
    var length;
    var listeners = [];
    var stream;
    var _end = res.end;
    var _on = res.on;
    var _write = res.write;

    // flush
    res.flush = function flush () {
      if (stream) {
        stream.flush()
      }
    };

    // proxy
    res.write = function write(chunk, encoding) {
      if (ended) {
        return false
      }

      if (!this._header) {
        this._implicitHeader()
      }

      console.log(chunk);

      return stream
        ? stream.write(new Buffer(chunk, encoding))
        : _write.call(this, chunk, encoding)
    };

    //end
    res.end = function end (chunk, encoding) {
      if (ended) {
        return false;
      }

      if (!this._header) {
        // estimate the length
        if (!this.getHeader('Content-Length')) {
          length = chunkLength(chunk, encoding)
        }

        this._implicitHeader()
      }

      if (!stream) {
        return _end.call(this, chunk, encoding)
      }

      // mark ended
      ended = true;

      return chunk
        ? stream.end(new Buffer(chunk, encoding))
        : stream.end()
    };

    res.on = function on(type, listener) {
      if (!listeners || type !== 'drain') {
        return _on.call(this, type, listener)
      }

      if (stream) {
        return stream.on(type, listener)
      }

      // buffer listeners for future stream
      listeners.push([type, listener]);

      return this;
    };

    function noMsgPacking() {
      addListeners(res, _on, listeners);
      listeners = null;
    }

    onHeaders(res, function onResponseHeaders () {
      if (!shouldMsgPack(req, res)) {
        noMsgPacking();
        return;
      }

      // already msg packed
      if (res.get('Content-Type') === 'application/json') {
        noMsgPacking();
        return;
      }

      // head
      if (req.method === 'HEAD') {
        noMsgPacking();
        return;
      }

      stream = msgpackLite.createEncodeStream();
      console.log(req.body);

      addListeners(stream, stream.on, listeners);

      res.setHeader('Content-Type', 'application/x-msgpack');
      res.removeHeader('Content-Length');

      stream.on('data', function onStreamData (chunk) {
        if (_write.call(res, chunk) === false) {
          stream.pause()
        }
      });

      stream.on('end', function onStreamEnd () {
         _end.call(res)
      });

      _on.call(res, 'drain', function onResponseDrain () {
        stream.resume();
      });
    });

    next();
  }
}

function chunkLength (chunk, encoding) {
  if (!chunk) {
    return 0
  }

  return !Buffer.isBuffer(chunk)
    ? Buffer.byteLength(chunk, encoding)
    : chunk.length
}

/**
 * Default filter function.
 * @private
 */
function shouldMsgPack(req, res) {
  var acceptType = req.get('accept');
  var type = res.get('Content-Type');

  return _.isNil(acceptType) === false && acceptType === 'application/x-msgpack' && _.isNil(type) === false && type.match(/application\/json/)[0] === 'application/json';
}

/**
 * Add bufferred listeners to stream
 * @private
 */
function addListeners (stream, on, listeners) {
  for (var i = 0; i < listeners.length; i++) {
    on.apply(stream, listeners[i])
  }
}

/**
 * Module exports.
 * @public
 */
module.exports = mgsPackResponse;
<commit_msg>override json() also<commit_after>/*!
 * msgpack-response
 * Copyright(c) 2017 Mobiltron Inc
 * MIT Licensed
 */

/**
 * Module dependencies.
 */
const _ = require('lodash');
const onHeaders = require('on-headers')
const msgpackLite = require('msgpack-lite');

/**
 * Module variables.
 * @private
 */
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/;

/**
 * Transform response data using msgpack.
 *
 * @return {Function} middleware
 * @public
 */
function mgsPackResponse () {

  return function _mgsPackResponse(req, res, next) {
    var ended = false;
    var length;
    var listeners = [];
    var stream;
    var _end = res.end;
    var _on = res.on;
    var _write = res.write;

    // flush
    res.flush = function flush () {
      if (stream) {
        stream.flush()
      }
    };

    res.json = function(chunk) {
      console.log(chunk);
      stream.write(chunk, 'utf-8');
    };

    // proxy
    res.write = function write(chunk, encoding) {
      if (ended) {
        return false
      }

      if (!this._header) {
        this._implicitHeader()
      }

      console.log(chunk);

      return stream
        ? stream.write(new Buffer(chunk, encoding))
        : _write.call(this, chunk, encoding)
    };

    //end
    res.end = function end (chunk, encoding) {
      if (ended) {
        return false;
      }

      if (!this._header) {
        // estimate the length
        if (!this.getHeader('Content-Length')) {
          length = chunkLength(chunk, encoding)
        }

        this._implicitHeader()
      }

      if (!stream) {
        return _end.call(this, chunk, encoding)
      }

      // mark ended
      ended = true;

      return chunk
        ? stream.end(new Buffer(chunk, encoding))
        : stream.end()
    };

    res.on = function on(type, listener) {
      if (!listeners || type !== 'drain') {
        return _on.call(this, type, listener)
      }

      if (stream) {
        return stream.on(type, listener)
      }

      // buffer listeners for future stream
      listeners.push([type, listener]);

      return this;
    };

    function noMsgPacking() {
      addListeners(res, _on, listeners);
      listeners = null;
    }

    onHeaders(res, function onResponseHeaders () {
      if (!shouldMsgPack(req, res)) {
        noMsgPacking();
        return;
      }

      // already msg packed
      if (res.get('Content-Type') === 'application/json') {
        noMsgPacking();
        return;
      }

      // head
      if (req.method === 'HEAD') {
        noMsgPacking();
        return;
      }

      stream = msgpackLite.createEncodeStream();
      console.log(req.body);

      addListeners(stream, stream.on, listeners);

      res.setHeader('Content-Type', 'application/x-msgpack');
      res.removeHeader('Content-Length');

      stream.on('data', function onStreamData (chunk) {
        if (_write.call(res, chunk) === false) {
          stream.pause()
        }
      });

      stream.on('end', function onStreamEnd () {
         _end.call(res)
      });

      _on.call(res, 'drain', function onResponseDrain () {
        stream.resume();
      });
    });

    next();
  }
}

function chunkLength (chunk, encoding) {
  if (!chunk) {
    return 0
  }

  return !Buffer.isBuffer(chunk)
    ? Buffer.byteLength(chunk, encoding)
    : chunk.length
}

/**
 * Default filter function.
 * @private
 */
function shouldMsgPack(req, res) {
  var acceptType = req.get('accept');
  var type = res.get('Content-Type');

  return _.isNil(acceptType) === false && acceptType === 'application/x-msgpack' && _.isNil(type) === false && type.match(/application\/json/)[0] === 'application/json';
}

/**
 * Add bufferred listeners to stream
 * @private
 */
function addListeners (stream, on, listeners) {
  for (var i = 0; i < listeners.length; i++) {
    on.apply(stream, listeners[i])
  }
}

/**
 * Module exports.
 * @public
 */
module.exports = mgsPackResponse;
<|endoftext|>


<commit_before>MMMDash.WS = function (env) {
    var dev_url = "http://www.dev-romimate.com:8000/lm", prod_url = "";

    var that = {};
    var _RE_WS = {};
    _RE_WS.getConfig = function () {
        return (env.toUpperCase() == 'DEV' ? dev_url : prod_url);
    }
    that.RE_WS = _RE_WS;
    return that;
};
module.exports = MMMDash.WS;
<commit_msg>Fixed Regression service call issue for WS<commit_after>MMMDash.WS = function (env) {
    var dev_url = "http://www.dev-romimate.com:8000/lm", prod_url = "http://www.romimate.com:8000/lm";

    var that = {};
    var _RE_WS = {};
    _RE_WS.getConfig = function () {
        return (env.toUpperCase() == 'DEV' ? dev_url : prod_url);
    }
    that.RE_WS = _RE_WS;
    return that;
};
module.exports = MMMDash.WS;
<|endoftext|>


<commit_before>$(document).ajaxError(function (e, r, ajaxOptions, thrownError) {
    if ($.trim(r.responseText).length > 0) {
        if (ON_PRODUCTION) {
            alert(r.responseText);
        } else {
            $('body').html(r.responseText);
        }
    }
});

Date.prototype.getWeek = function (dowOffset) {
	/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
	dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
	var newYear = new Date(this.getFullYear(),0,1);
	var day = newYear.getDay() - dowOffset; //the day of week the year begins on
	day = (day >= 0 ? day : day + 7);
	var daynum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
	var weeknum;
	//if the year starts before the middle of a week
	if(day < 4) {
		weeknum = Math.floor((daynum+day-1)/7) + 1;
		if(weeknum > 52) {
			nYear = new Date(this.getFullYear() + 1,0,1);
			nday = nYear.getDay() - dowOffset;
			nday = nday >= 0 ? nday : nday + 7;
			/*if the next year starts before the middle of
			the week, it is week #1 of that year*/
			weeknum = nday < 4 ? 1 : 53;
		}
	} else {
		weeknum = Math.floor((daynum+day-1)/7);
	}
	return weeknum;
};

function toggle(feed, parameters) {
	var event = parameters['event'];
	var playlist = parameters['playlist'];

	if (playlist.find('ul').length) {
		playlist.find('ul').toggle();
	} else {
		$('
').appendTo($(playlist));
		if (feed) {
			$.each(feed, function(i, item) {
                var videoId = item['media$group']['yt$videoid']['$t'];
                var title = item['title']['$t'];
                createResultsItem(title, videoId).appendTo(playlist.find('ul'));
            });
		}
	}
}

function getVidsInPlaylist(playlistId, callback, parameters, start, feed) {
	if (!parameters['playlist'].hasClass('loading')) {
		parameters['playlist'].addClass('loading')
    }
	if (start === undefined) {
		start = 1;
    }
	if (feed === undefined) {
		feed = [];
    }
    var url = 'http://gdata.youtube.com/feeds/api/playlists/' + playlistId + '?start-index='+start+'&max-results=50&v=2&alt=json&callback=?';
    $.getJSON(url, {}, function(data) {
		if (data.feed.entry && data.feed.entry.length > 0) {
			feed = $.merge(feed, data.feed.entry);
			getVidsInPlaylist(playlistId, callback, parameters, start+50, feed);
		} else {
			callback(feed, parameters);
			parameters['playlist'].removeClass('loading');
		}
    });
}

// -webkit-calc is not working
$(window).resize(function() {
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	if (windowWidth < 650) {
		windowWidth = 650;
    }

    // height
	$('#content').height(windowHeight);

	var leftMenuSiblingHeights = 0;
	$('#left-menu').siblings().each(function(index, item) {
        leftMenuSiblingHeights += $(item).height();
    });
	$('#left-menu').height(windowHeight - leftMenuSiblingHeights);

	var resultsContainerSiblingsHeights = 0;
	$('#results-container').siblings(':visible').each(function(index, item) {
        resultsContainerSiblingsHeights += $(item).height();
    });
	$('#results-container').height(windowHeight - resultsContainerSiblingsHeights);

    // width
	$('#content-right').width(windowWidth - $('#content-left').width());
	$('#timeline-container').width($('#content-right').width());
	$('#timeline').width($('#content-right').width() - 102);

	if (Player._isFullscreen) {
		Player.startFullscreen();
	} else {
		var offset = $('#youtube-container').offset();
		$('#youtube').css('left', offset.left);
		$('#youtube').css('top', offset.top);
	}
});

$(window).load(function() {
	$(window).resize();
	$('#loading span').text('Done');
	$('#loading').fadeOut();
    loadUrl();
});

$(document).ready(function() {
    var settings = new Settings();

    $('#info .title').data('type', 'video');
    $('#new-playlist').data('type', 'button');

    changeTheme(settings.theme);

	// Legal & Information
	$('#infomenu-text').click(function() {
        var blocker = $('

').mousedown(function(event) {
            $('#blocker').remove();
            $('#infomenu-popup').hide();
            event.stopPropagation();
        });
        blocker.appendTo('body');
        $('#infomenu-popup').show();
    });

	// CONTROLS
	$('#playpause').click(Player.playPause);
	$('#next').click(Player.next);
	$('#prev').click(Player.prev);

	// FULLSCREEN
	$('#fullscreen').click(function() {
		Player.toggleFullscreen();
	});

	// TIMELINE
	$('#timeline').click(Player.timelineClick);

	// ABOUT
	$('#about-link').click(function() {
		$('#about-box').show();
		$('#about-box').click(function() {
			$('#about-box').hide();
		});
	});

	// FUNNY LOGO
	$('#logo').click(function() {
		Player.play(Player._hiddenPlaylist[new Date().getWeek()]);
	});

    // Initially show Top 100 if not a playlist should be loaded instead.
    if (location.href.indexOf('playlists') === -1) {
        TopList.select();
    }

	//Notification.show('We are experiencing connection issues with YouTube at the moment. Sorry for the inconvenience.');
});

function onYouTubePlayerAPIReady() {
	//
	// Player cannot be loaded before
	// $(window).load()
}
<commit_msg>Fix bug where video URLs did not work<commit_after>$(document).ajaxError(function (e, r, ajaxOptions, thrownError) {
    if ($.trim(r.responseText).length > 0) {
        if (ON_PRODUCTION) {
            alert(r.responseText);
        } else {
            $('body').html(r.responseText);
        }
    }
});

Date.prototype.getWeek = function (dowOffset) {
	/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
	dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
	var newYear = new Date(this.getFullYear(),0,1);
	var day = newYear.getDay() - dowOffset; //the day of week the year begins on
	day = (day >= 0 ? day : day + 7);
	var daynum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
	var weeknum;
	//if the year starts before the middle of a week
	if(day < 4) {
		weeknum = Math.floor((daynum+day-1)/7) + 1;
		if(weeknum > 52) {
			nYear = new Date(this.getFullYear() + 1,0,1);
			nday = nYear.getDay() - dowOffset;
			nday = nday >= 0 ? nday : nday + 7;
			/*if the next year starts before the middle of
			the week, it is week #1 of that year*/
			weeknum = nday < 4 ? 1 : 53;
		}
	} else {
		weeknum = Math.floor((daynum+day-1)/7);
	}
	return weeknum;
};

function toggle(feed, parameters) {
	var event = parameters['event'];
	var playlist = parameters['playlist'];

	if (playlist.find('ul').length) {
		playlist.find('ul').toggle();
	} else {
		$('
').appendTo($(playlist));
		if (feed) {
			$.each(feed, function(i, item) {
                var videoId = item['media$group']['yt$videoid']['$t'];
                var title = item['title']['$t'];
                createResultsItem(title, videoId).appendTo(playlist.find('ul'));
            });
		}
	}
}

function getVidsInPlaylist(playlistId, callback, parameters, start, feed) {
	if (!parameters['playlist'].hasClass('loading')) {
		parameters['playlist'].addClass('loading')
    }
	if (start === undefined) {
		start = 1;
    }
	if (feed === undefined) {
		feed = [];
    }
    var url = 'http://gdata.youtube.com/feeds/api/playlists/' + playlistId + '?start-index='+start+'&max-results=50&v=2&alt=json&callback=?';
    $.getJSON(url, {}, function(data) {
		if (data.feed.entry && data.feed.entry.length > 0) {
			feed = $.merge(feed, data.feed.entry);
			getVidsInPlaylist(playlistId, callback, parameters, start+50, feed);
		} else {
			callback(feed, parameters);
			parameters['playlist'].removeClass('loading');
		}
    });
}

// -webkit-calc is not working
$(window).resize(function() {
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	if (windowWidth < 650) {
		windowWidth = 650;
    }

    // height
	$('#content').height(windowHeight);

	var leftMenuSiblingHeights = 0;
	$('#left-menu').siblings().each(function(index, item) {
        leftMenuSiblingHeights += $(item).height();
    });
	$('#left-menu').height(windowHeight - leftMenuSiblingHeights);

	var resultsContainerSiblingsHeights = 0;
	$('#results-container').siblings(':visible').each(function(index, item) {
        resultsContainerSiblingsHeights += $(item).height();
    });
	$('#results-container').height(windowHeight - resultsContainerSiblingsHeights);

    // width
	$('#content-right').width(windowWidth - $('#content-left').width());
	$('#timeline-container').width($('#content-right').width());
	$('#timeline').width($('#content-right').width() - 102);

	if (Player._isFullscreen) {
		Player.startFullscreen();
	} else {
		var offset = $('#youtube-container').offset();
		$('#youtube').css('left', offset.left);
		$('#youtube').css('top', offset.top);
	}
});

$(window).load(function() {
	$(window).resize();
	$('#loading span').text('Done');
	$('#loading').fadeOut();
    loadUrl();
});

$(document).ready(function() {
    var settings = new Settings();

    $('#info .title').data('type', 'video');
    $('#new-playlist').data('type', 'button');

    changeTheme(settings.theme);

	// Legal & Information
	$('#infomenu-text').click(function() {
        var blocker = $('

').mousedown(function(event) {
            $('#blocker').remove();
            $('#infomenu-popup').hide();
            event.stopPropagation();
        });
        blocker.appendTo('body');
        $('#infomenu-popup').show();
    });

	// CONTROLS
	$('#playpause').click(Player.playPause);
	$('#next').click(Player.next);
	$('#prev').click(Player.prev);

	// FULLSCREEN
	$('#fullscreen').click(function() {
		Player.toggleFullscreen();
	});

	// TIMELINE
	$('#timeline').click(Player.timelineClick);

	// ABOUT
	$('#about-link').click(function() {
		$('#about-box').show();
		$('#about-box').click(function() {
			$('#about-box').hide();
		});
	});

	// FUNNY LOGO
	$('#logo').click(function() {
		Player.play(Player._hiddenPlaylist[new Date().getWeek()]);
	});

    // Initially show Top 100 if not a playlist should be loaded instead.
    if (location.pathname === '/') {
        TopList.select();
    }

	//Notification.show('We are experiencing connection issues with YouTube at the moment. Sorry for the inconvenience.');
});

function onYouTubePlayerAPIReady() {
	//
	// Player cannot be loaded before
	// $(window).load()
}
<|endoftext|>


<commit_before>angular.module('opal.controllers').controller(
    'ExtractCtrl', function($scope, $http, $window, $modal,
                            filters, options, schema){

    $scope.JSON = window.JSON;
    $scope.state =  'normal';
    $scope.filters = filters;
    $scope.columns = schema.columns;
    $scope.column_names = _.map(schema.columns, function(c){
        return c.name.underscoreToCapWords();
    });

	for (var name in options) {
		$scope[name + '_list'] = options[name];
	};

    $scope.model = {
        combine  : "and",
        column   : null,
        field    : null,
        queryType: "Equals",
        query    : null
    };

    $scope.criteria = [_.clone($scope.model)];

    $scope.searchableFields = function(column){
        // TODO - don't hard-code this
        if(column.name == 'microbiology_test'){
            return [
                'Test',
                'Date Ordered',
                'Details',
                'Microscopy',
                'Organism',
                'Sensitive Antibiotics',
                'Resistant Antibiotics'
            ]
        }
        return _.map(
            _.reject(
                column.fields,
                function(c){ return c.type == 'token' ||  c.type ==  'list'; }),
            function(c){ return c.name.underscoreToCapWords(); }
        );
    };

    $scope.isType = function(column, field, type){
        if(!column || !field){
            return false;
        }
        var col = _.find($scope.columns, function(item){return item.name == column.toLowerCase().replace( / /g,  '_')});
        var theField =  _.find(col.fields, function(f){return f.name == field.toLowerCase().replace( / /g,  '_')});
        return theField.type == type;
    };

    $scope.isBoolean = function(column, field){
        return $scope.isType(column, field, "boolean");
    };

    $scope.isText = function(column, field){
        return $scope.isType(column, field, "string") || $scope.isType(column, field, "text");
    }

    $scope.isDate = function(column, field){
        return $scope.isType(column, field, "date");
    };

    $scope.addFilter = function(){
        $scope.criteria.push(_.clone($scope.model));
    };

    $scope.removeFilter = function(index){
        $scope.criteria.splice(index, 1);
    };

    $scope.search = function(){
        $scope.state = 'pending';
        $http.post('/search/extract/', $scope.criteria).success(
            function(results){
                $scope.results = results;
                $scope.state = 'normal';
            }).error(function(){
                $scope.state = 'normal';
                $window.alert('ERROR: Could not process this search. Please report it to the OPAL team')
            });
    };

    $scope.jumpToFilter = function($event, filter){
        $event.preventDefault()
        $scope.criteria = filter.criteria;
    }

    $scope.editFilter = function($event, filter, $index){
        $event.preventDefault();
		modal = $modal.open({
			templateUrl: '/templates/modals/save_filter_modal.html/',
			controller: 'SaveFilterCtrl',
			resolve: {
				params: function() { return $scope.filters[$index]; },
			}
		}).result.then(function(result){
            $scope.filters[$index] = result;
        });
    }

    $scope.save = function(){

		modal = $modal.open({
			templateUrl: '/templates/modals/save_filter_modal.html/',
			controller: 'SaveFilterCtrl',
			resolve: {
				params: function() { return {name: null, criteria: $scope.criteria}; },
			}
		}).result.then(function(result){
            $scope.filters.push(result);
        });
    };

});
<commit_msg>Only pass complete extract criteria to the server.<commit_after>angular.module('opal.controllers').controller(
    'ExtractCtrl', function($scope, $http, $window, $modal,
                            filters, options, schema){

    $scope.JSON = window.JSON;
    $scope.state =  'normal';
    $scope.filters = filters;
    $scope.columns = schema.columns;
    $scope.column_names = _.map(schema.columns, function(c){
        return c.name.underscoreToCapWords();
    });

	for (var name in options) {
		$scope[name + '_list'] = options[name];
	};

    $scope.model = {
        combine  : "and",
        column   : null,
        field    : null,
        queryType: "Equals",
        query    : null
    };

    $scope.criteria = [_.clone($scope.model)];

    $scope.completeCriteria =  function(){
        return _.filter($scope.criteria, function(c){
            if(c.column &&  c.field &&  c.query){
                return true
            }
            return false
        })
    };

    $scope.searchableFields = function(column){
        // TODO - don't hard-code this
        if(column.name == 'microbiology_test'){
            return [
                'Test',
                'Date Ordered',
                'Details',
                'Microscopy',
                'Organism',
                'Sensitive Antibiotics',
                'Resistant Antibiotics'
            ]
        }
        return _.map(
            _.reject(
                column.fields,
                function(c){ return c.type == 'token' ||  c.type ==  'list'; }),
            function(c){ return c.name.underscoreToCapWords(); }
        );
    };

    $scope.isType = function(column, field, type){
        if(!column || !field){
            return false;
        }
        var col = _.find($scope.columns, function(item){return item.name == column.toLowerCase().replace( / /g,  '_')});
        var theField =  _.find(col.fields, function(f){return f.name == field.toLowerCase().replace( / /g,  '_')});
        return theField.type == type;
    };

    $scope.isBoolean = function(column, field){
        return $scope.isType(column, field, "boolean");
    };

    $scope.isText = function(column, field){
        return $scope.isType(column, field, "string") || $scope.isType(column, field, "text");
    }

    $scope.isDate = function(column, field){
        return $scope.isType(column, field, "date");
    };

    $scope.addFilter = function(){
        $scope.criteria.push(_.clone($scope.model));
    };

    $scope.removeFilter = function(index){
        $scope.criteria.splice(index, 1);
    };

    $scope.search = function(){
        $scope.state = 'pending';
        $http.post('/search/extract/', $scope.completeCriteria()).success(
            function(results){
                $scope.results = results;
                $scope.state = 'normal';
            }).error(function(){
                $scope.state = 'normal';
                $window.alert('ERROR: Could not process this search. Please report it to the OPAL team')
            });
    };

    $scope.jumpToFilter = function($event, filter){
        $event.preventDefault()
        $scope.criteria = filter.criteria;
    }

    $scope.editFilter = function($event, filter, $index){
        $event.preventDefault();
		modal = $modal.open({
			templateUrl: '/templates/modals/save_filter_modal.html/',
			controller: 'SaveFilterCtrl',
			resolve: {
				params: function() { return $scope.filters[$index]; },
			}
		}).result.then(function(result){
            $scope.filters[$index] = result;
        });
    }

    $scope.save = function(){

		modal = $modal.open({
			templateUrl: '/templates/modals/save_filter_modal.html/',
			controller: 'SaveFilterCtrl',
			resolve: {
				params: function() { return {name: null, criteria: $scope.criteria}; },
			}
		}).result.then(function(result){
            $scope.filters.push(result);
        });
    };

});
<|endoftext|>


<commit_before>var projec = window.location.hash.replace(/#/g, '');
var project = projec.replace(/\./g, '-').replace(/\//g, '-');
var editor;
var firebase;

function init() {
    save_code();
    projec = window.location.hash.replace(/#/g, '');
    project = projec.replace(/\./g, '-').replace(/\//g, '-');
    $("#editor").html("");
    setup_editor();
    setup_stuff();
}

function save_code() {
    firebase.child("code").child(project).child("text").set(editor.getSession().getValue());
}

function setup_editor() {
    firebase = new Firebase("https://dep10y.firebaseio.com/");
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    var type = firebase.child("projects").child(project).child("type");
    if (type == 'flask'){
        editor.getSession().setMode("ace/mode/python");
    }
    if (type == 'sinatra'){
        editor.getSession().setMode("ace/mode/ruby");
    }
    if (type == 'php'){
        editor.getSession().setMode("ace/mode/php");
    }
    var firepad = Firepad.fromACE(firebase.child("code").child(project), editor, {
        defaultText: ''
    });
    $(window).bind('beforeunload', function() {
        save_code();
    });
}

function setup_stuff() {
    var shreks = projec.split(":");
    firebase.child("code").child(project).update({user: shreks[0], projectid: shreks[1], filepath: shreks[2]});
    var shrek2 = shreks[2].split(".");
    var shrek = shrek2[shrek2.length - 1];
    window.shreks = shreks;
    editor.getSession().setMode("ace/mode/" + {py: "python", html: "html", rb: "ruby"}[shrek]);
    $("#filename").html(shreks[2]);
    firebase.child("projects").child(shreks[0]).child(shreks[1]).child("name").on("value", function(q) {
        $("#projectname").html(q.val());
    });
    firebase.child("projects").child(shreks[0]).child(shreks[1]).child("state").on("value", function(q){
        var staturl = /Running at ([a-z0-9\.]+)/g.exec(q.val());
        if (staturl.length > 1){
            $("#projurl").html(staturl[1]);
        }
    });

    construct_things(shreks[1]);
}
function restore() {
	$("#depBut").html("Deploy");
}
function push_that_button() {
    save_code();
    $("#depBut").html("Deploying...");
    window.setTimeout(restore, 10000);
    firebase.child("code").once("value", function(v) {
        forreal = []
        v.forEach(function(x) {
            console.log(window.shreks);
            console.log(x.val());
            if(x.val().projectid == window.shreks[1]) {
                forreal.push(x.val());
            }
        });
        forreal.forEach(function(x) {
            firebase.child("files").child(window.shreks[1]).push({
                filepath: x.filepath,
                text: x.text
            });
        });
    });
}
<commit_msg>SHREK DA DSHREK<commit_after>var projec = window.location.hash.replace(/#/g, '');
var project = projec.replace(/\./g, '-').replace(/\//g, '-');
var editor;
var firebase;

function init() {
    save_code();
    projec = window.location.hash.replace(/#/g, '');
    project = projec.replace(/\./g, '-').replace(/\//g, '-');
    $("#editor").html("");
    setup_editor();
    setup_stuff();
}

function save_code() {
    firebase.child("code").child(project).child("text").set(editor.getSession().getValue());
}

function setup_editor() {
    firebase = new Firebase("https://dep10y.firebaseio.com/");
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    var type = firebase.child("projects").child(project).child("type");
    if (type == 'flask'){
        editor.getSession().setMode("ace/mode/python");
    }
    if (type == 'sinatra'){
        editor.getSession().setMode("ace/mode/ruby");
    }
    if (type == 'php'){
        editor.getSession().setMode("ace/mode/php");
    }
    console.log("THE FIREPAD IS " + project);
    var firepad = Firepad.fromACE(firebase.child("code").child(project), editor, {
        defaultText: ''
    });
    $(window).bind('beforeunload', function() {
        save_code();
    });
}

function setup_stuff() {
    var shreks = projec.split(":");
    firebase.child("code").child(project).update({user: shreks[0], projectid: shreks[1], filepath: shreks[2]});
    var shrek2 = shreks[2].split(".");
    var shrek = shrek2[shrek2.length - 1];
    window.shreks = shreks;
    editor.getSession().setMode("ace/mode/" + {py: "python", html: "html", rb: "ruby"}[shrek]);
    $("#filename").html(shreks[2]);
    firebase.child("projects").child(shreks[0]).child(shreks[1]).child("name").on("value", function(q) {
        $("#projectname").html(q.val());
    });
    firebase.child("projects").child(shreks[0]).child(shreks[1]).child("state").on("value", function(q){
        var staturl = /Running at ([a-z0-9\.]+)/g.exec(q.val());
        if (staturl.length > 1){
            $("#projurl").html(staturl[1]);
        }
    });

    construct_things(shreks[1]);
}
function restore() {
	$("#depBut").html("Deploy");
}
function push_that_button() {
    save_code();
    $("#depBut").html("Deploying...");
    window.setTimeout(restore, 10000);
    firebase.child("code").once("value", function(v) {
        forreal = []
        v.forEach(function(x) {
            console.log(window.shreks);
            console.log(x.val());
            if(x.val().projectid == window.shreks[1]) {
                forreal.push(x.val());
            }
        });
        forreal.forEach(function(x) {
            firebase.child("files").child(window.shreks[1]).push({
                filepath: x.filepath,
                text: x.text
            });
        });
    });
}
<|endoftext|>


<commit_before>var Utils = require('./../utils')

module.exports = (function() {
  var HasManyDoubleLinked = function(definition, instance) {
    this.__factory = definition
    this.instance = instance
  }

  HasManyDoubleLinked.prototype.injectGetter = function(options) {
    var self = this, _options = options

    var customEventEmitter = new Utils.CustomEventEmitter(function() {
      var where = {}
        , options = _options || {}
        , queryOptions = {}
        , association = self.__factory.target.associations[self.__factory.associationAccessor]

      //fully qualify
      var instancePrimaryKeys = Object.keys(self.instance.daoFactory.primaryKeys)
        , instancePrimaryKey = instancePrimaryKeys.length > 0 ? instancePrimaryKeys[0] : 'id'

      where[self.__factory.connectorDAO.tableName+"."+self.__factory.identifier] = self.instance[instancePrimaryKey]

      var primaryKeys = Object.keys(self.__factory.connectorDAO.primaryKeys)
        , foreignKey  = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
        , foreignPrimary = Object.keys(self.__factory.target.primaryKeys)

      foreignPrimary = foreignPrimary.length === 1 ? foreignPrimary[0] : 'id'

      where[self.__factory.connectorDAO.tableName+"."+foreignKey] = {join: self.__factory.target.tableName+"."+foreignPrimary}

      if (association.customJoinTableModel) {
        queryOptions.hasJoinTableModel = true
        queryOptions.joinTableModel = self.__factory.connectorDAO

        if (!options.attributes) {
          options.attributes = [
            self.__factory.target.QueryInterface.quoteIdentifier(self.__factory.target.tableName)+".*"
          ]
        }

        if (options.joinTableAttributes) {
          options.joinTableAttributes.forEach(function (elem) {
            options.attributes.push(
              self.__factory.target.QueryInterface.quoteIdentifiers(self.__factory.connectorDAO.tableName + '.' + elem) + ' as ' +
              self.__factory.target.QueryInterface.quoteIdentifier(self.__factory.connectorDAO.name + '.' + elem)
            )
          })
        } else {
          Utils._.forOwn(self.__factory.connectorDAO.rawAttributes, function (elem, key) {
              options.attributes.push(
                self.__factory.target.QueryInterface.quoteIdentifiers(self.__factory.connectorDAO.tableName + '.' + key) + ' as ' +
                self.__factory.target.QueryInterface.quoteIdentifier(self.__factory.connectorDAO.name + '.' + key)
              )
          })
        }
      }

      if (options.where) {
        if (Array.isArray(options.where)) {
          smart = Utils.smartWhere([where, options.where], self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          smart = Utils.compileSmartWhere.call(self.__factory.target, smart, self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          if (smart.length > 0) {
            options.where = smart
          }
        } else {
          smart = Utils.smartWhere([where, options.where], self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          smart = Utils.compileSmartWhere.call(self.__factory.target, smart, self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          if (smart.length > 0) {
            options.where = smart
          }
        }
      } else {
        options.where = where;
      }

      self.__factory.target.findAllJoin(self.__factory.connectorDAO.tableName, options, queryOptions)
        .on('success', function(objects) { customEventEmitter.emit('success', objects) })
        .on('error', function(err){ customEventEmitter.emit('error', err) })
        .on('sql', function(sql) { customEventEmitter.emit('sql', sql)})
    })

    return customEventEmitter.run()
  }

  HasManyDoubleLinked.prototype.injectSetter = function(emitterProxy, oldAssociations, newAssociations, defaultAttributes) {
    var self = this
      , chainer             = new Utils.QueryChainer()
      , association         = self.__factory.target.associations[self.__factory.associationAccessor]
      , foreignIdentifier   = association.isSelfAssociation ? association.foreignIdentifier : association.identifier
      , sourceKeys          = Object.keys(self.__factory.source.primaryKeys)
      , targetKeys          = Object.keys(self.__factory.target.primaryKeys)
      , obsoleteAssociations = []
      , changedAssociations = []
      , unassociatedObjects;

    unassociatedObjects = newAssociations.filter(function (obj) {
      return !Utils._.find(oldAssociations, function (old) {
        return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
      })
    })

    oldAssociations.forEach(function (old) {
      var newObj = Utils._.find(newAssociations, function (obj) {
        return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
      })

      if (!newObj) {
        obsoleteAssociations.push(old)
      } else if (association.customJoinTableModel) {
        var changedAssociation = {
          where: {},
          attributes: Utils._.defaults({}, newObj[self.__factory.connectorDAO.name], defaultAttributes)
        }

        changedAssociation.where[self.__factory.identifier] = self.instance[self.__factory.identifier] || self.instance.id
        changedAssociation.where[foreignIdentifier] = newObj[foreignIdentifier] || newObj.id

        changedAssociations.push(changedAssociation)
      }
    })

    if (obsoleteAssociations.length > 0) {
      var foreignIds = obsoleteAssociations.map(function (associatedObject) {
        return ((targetKeys.length === 1) ? associatedObject[targetKeys[0]] : associatedObject.id)
      })

      var where = {}
      where[self.__factory.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id)
      where[foreignIdentifier] = foreignIds

      chainer.add(self.__factory.connectorDAO.destroy(where))
    }

    if (unassociatedObjects.length > 0) {
      var bulk = unassociatedObjects.map(function(unassociatedObject) {
        var attributes = {}
        attributes[self.__factory.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id)
        attributes[foreignIdentifier] = ((targetKeys.length === 1) ? unassociatedObject[targetKeys[0]] : unassociatedObject.id)

        if (association.customJoinTableModel) {
          attributes = Utils._.defaults(attributes, unassociatedObject[association.connectorDAO.name], defaultAttributes)
        }

        if (association.customJoinTableModel) {
          attributes = Utils._.defaults(attributes, unassociatedObject[association.connectorDAO.name], defaultAttributes)
        }

        return attributes
      })

      chainer.add(self.__factory.connectorDAO.bulkCreate(bulk))
    }

    if (changedAssociations.length > 0) {
      changedAssociations.forEach(function (assoc) {
        chainer.add(self.__factory.connectorDAO.update(assoc.attributes, assoc.where))
      })
    }

    chainer
      .run()
      .success(function() { emitterProxy.emit('success', newAssociations) })
      .error(function(err) { emitterProxy.emit('error', err) })
      .on('sql', function(sql) { emitterProxy.emit('sql', sql) })
  }

  HasManyDoubleLinked.prototype.injectAdder = function(emitterProxy, newAssociation, additionalAttributes, exists) {
    var attributes = {}
      , association         = this.__factory.target.associations[this.__factory.associationAccessor]
      , foreignIdentifier   = association.isSelfAssociation ? association.foreignIdentifier : association.identifier;

    var sourceKeys = Object.keys(this.__factory.source.primaryKeys);
    var targetKeys = Object.keys(this.__factory.target.primaryKeys);

    attributes[this.__factory.identifier] = ((sourceKeys.length === 1) ? this.instance[sourceKeys[0]] : this.instance.id)
    attributes[foreignIdentifier] = ((targetKeys.length === 1) ? newAssociation[targetKeys[0]] : newAssociation.id)

    if (exists) { // implies customJoinTableModel === true
      var where = attributes
      attributes = Utils._.defaults({}, newAssociation[association.connectorDAO.name], additionalAttributes)

      association.connectorDAO.update(attributes, where).proxy(emitterProxy)
    } else {
      if (association.customJoinTableModel === true) {
        attributes = Utils._.defaults(attributes, newAssociation[association.connectorDAO.name], additionalAttributes)
      }

      this.__factory.connectorDAO.create(attributes)
        .success(function() { emitterProxy.emit('success', newAssociation) })
        .error(function(err) { emitterProxy.emit('error', err) })
        .on('sql', function(sql) { emitterProxy.emit('sql', sql) })
    }
  }

  return HasManyDoubleLinked
})()
<commit_msg>alias the queryinterface on hasmany double linked for brevity<commit_after>var Utils = require('./../utils')

module.exports = (function() {
  var HasManyDoubleLinked = function(definition, instance) {
    this.__factory = definition
    this.instance = instance

    // Alias the quoting methods for code brevity
    this.QueryInterface = instance.QueryInterface
  }

  HasManyDoubleLinked.prototype.injectGetter = function(options) {
    var self = this, _options = options

    var customEventEmitter = new Utils.CustomEventEmitter(function() {
      var where = {}
        , options = _options || {}
        , queryOptions = {}
        , association = self.__factory.target.associations[self.__factory.associationAccessor]

      //fully qualify
      var instancePrimaryKeys = Object.keys(self.instance.daoFactory.primaryKeys)
        , instancePrimaryKey = instancePrimaryKeys.length > 0 ? instancePrimaryKeys[0] : 'id'

      where[self.__factory.connectorDAO.tableName+"."+self.__factory.identifier] = self.instance[instancePrimaryKey]

      var primaryKeys = Object.keys(self.__factory.connectorDAO.primaryKeys)
        , foreignKey  = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
        , foreignPrimary = Object.keys(self.__factory.target.primaryKeys)

      foreignPrimary = foreignPrimary.length === 1 ? foreignPrimary[0] : 'id'

      where[self.__factory.connectorDAO.tableName+"."+foreignKey] = {join: self.__factory.target.tableName+"."+foreignPrimary}

      if (association.customJoinTableModel) {
        queryOptions.hasJoinTableModel = true
        queryOptions.joinTableModel = self.__factory.connectorDAO

        if (!options.attributes) {
          options.attributes = [
            self.QueryInterface.quoteIdentifier(self.__factory.target.tableName)+".*"
          ]
        }

        if (options.joinTableAttributes) {
          options.joinTableAttributes.forEach(function (elem) {
            options.attributes.push(
              self.QueryInterface.quoteIdentifiers(self.__factory.connectorDAO.tableName + '.' + elem) + ' as ' +
              self.QueryInterface.quoteIdentifier(self.__factory.connectorDAO.name + '.' + elem)
            )
          })
        } else {
          Utils._.forOwn(self.__factory.connectorDAO.rawAttributes, function (elem, key) {
              options.attributes.push(
                self.QueryInterface.quoteIdentifiers(self.__factory.connectorDAO.tableName + '.' + key) + ' as ' +
                self.QueryInterface.quoteIdentifier(self.__factory.connectorDAO.name + '.' + key)
              )
          })
        }
      }

      if (options.where) {
        if (Array.isArray(options.where)) {
          smart = Utils.smartWhere([where, options.where], self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          smart = Utils.compileSmartWhere.call(self.__factory.target, smart, self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          if (smart.length > 0) {
            options.where = smart
          }
        } else {
          smart = Utils.smartWhere([where, options.where], self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          smart = Utils.compileSmartWhere.call(self.__factory.target, smart, self.__factory.target.daoFactoryManager.sequelize.options.dialect)
          if (smart.length > 0) {
            options.where = smart
          }
        }
      } else {
        options.where = where;
      }

      self.__factory.target.findAllJoin(self.__factory.connectorDAO.tableName, options, queryOptions)
        .on('success', function(objects) { customEventEmitter.emit('success', objects) })
        .on('error', function(err){ customEventEmitter.emit('error', err) })
        .on('sql', function(sql) { customEventEmitter.emit('sql', sql)})
    })

    return customEventEmitter.run()
  }

  HasManyDoubleLinked.prototype.injectSetter = function(emitterProxy, oldAssociations, newAssociations, defaultAttributes) {
    var self = this
      , chainer             = new Utils.QueryChainer()
      , association         = self.__factory.target.associations[self.__factory.associationAccessor]
      , foreignIdentifier   = association.isSelfAssociation ? association.foreignIdentifier : association.identifier
      , sourceKeys          = Object.keys(self.__factory.source.primaryKeys)
      , targetKeys          = Object.keys(self.__factory.target.primaryKeys)
      , obsoleteAssociations = []
      , changedAssociations = []
      , unassociatedObjects;

    unassociatedObjects = newAssociations.filter(function (obj) {
      return !Utils._.find(oldAssociations, function (old) {
        return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
      })
    })

    oldAssociations.forEach(function (old) {
      var newObj = Utils._.find(newAssociations, function (obj) {
        return (!!obj[foreignIdentifier] && !!old[foreignIdentifier] ? obj[foreignIdentifier] === old[foreignIdentifier] : obj.id === old.id)
      })

      if (!newObj) {
        obsoleteAssociations.push(old)
      } else if (association.customJoinTableModel) {
        var changedAssociation = {
          where: {},
          attributes: Utils._.defaults({}, newObj[self.__factory.connectorDAO.name], defaultAttributes)
        }

        changedAssociation.where[self.__factory.identifier] = self.instance[self.__factory.identifier] || self.instance.id
        changedAssociation.where[foreignIdentifier] = newObj[foreignIdentifier] || newObj.id

        changedAssociations.push(changedAssociation)
      }
    })

    if (obsoleteAssociations.length > 0) {
      var foreignIds = obsoleteAssociations.map(function (associatedObject) {
        return ((targetKeys.length === 1) ? associatedObject[targetKeys[0]] : associatedObject.id)
      })

      var where = {}
      where[self.__factory.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id)
      where[foreignIdentifier] = foreignIds

      chainer.add(self.__factory.connectorDAO.destroy(where))
    }

    if (unassociatedObjects.length > 0) {
      var bulk = unassociatedObjects.map(function(unassociatedObject) {
        var attributes = {}
        attributes[self.__factory.identifier] = ((sourceKeys.length === 1) ? self.instance[sourceKeys[0]] : self.instance.id)
        attributes[foreignIdentifier] = ((targetKeys.length === 1) ? unassociatedObject[targetKeys[0]] : unassociatedObject.id)

        if (association.customJoinTableModel) {
          attributes = Utils._.defaults(attributes, unassociatedObject[association.connectorDAO.name], defaultAttributes)
        }

        if (association.customJoinTableModel) {
          attributes = Utils._.defaults(attributes, unassociatedObject[association.connectorDAO.name], defaultAttributes)
        }

        return attributes
      })

      chainer.add(self.__factory.connectorDAO.bulkCreate(bulk))
    }

    if (changedAssociations.length > 0) {
      changedAssociations.forEach(function (assoc) {
        chainer.add(self.__factory.connectorDAO.update(assoc.attributes, assoc.where))
      })
    }

    chainer
      .run()
      .success(function() { emitterProxy.emit('success', newAssociations) })
      .error(function(err) { emitterProxy.emit('error', err) })
      .on('sql', function(sql) { emitterProxy.emit('sql', sql) })
  }

  HasManyDoubleLinked.prototype.injectAdder = function(emitterProxy, newAssociation, additionalAttributes, exists) {
    var attributes = {}
      , association         = this.__factory.target.associations[this.__factory.associationAccessor]
      , foreignIdentifier   = association.isSelfAssociation ? association.foreignIdentifier : association.identifier;

    var sourceKeys = Object.keys(this.__factory.source.primaryKeys);
    var targetKeys = Object.keys(this.__factory.target.primaryKeys);

    attributes[this.__factory.identifier] = ((sourceKeys.length === 1) ? this.instance[sourceKeys[0]] : this.instance.id)
    attributes[foreignIdentifier] = ((targetKeys.length === 1) ? newAssociation[targetKeys[0]] : newAssociation.id)

    if (exists) { // implies customJoinTableModel === true
      var where = attributes
      attributes = Utils._.defaults({}, newAssociation[association.connectorDAO.name], additionalAttributes)

      association.connectorDAO.update(attributes, where).proxy(emitterProxy)
    } else {
      if (association.customJoinTableModel === true) {
        attributes = Utils._.defaults(attributes, newAssociation[association.connectorDAO.name], additionalAttributes)
      }

      this.__factory.connectorDAO.create(attributes)
        .success(function() { emitterProxy.emit('success', newAssociation) })
        .error(function(err) { emitterProxy.emit('error', err) })
        .on('sql', function(sql) { emitterProxy.emit('sql', sql) })
    }
  }

  return HasManyDoubleLinked
})()
<|endoftext|>


<commit_before>import R from 'ramda';
import React from 'react';
import { connect } from 'react-redux';
import { formValueSelector, SubmissionError } from 'redux-form';
import PropTypes from 'prop-types';
import {
  Stepper,
  Step,
  StepContent,
  StepLabel,
} from '../customStepper';
import LegalStatus from './legalStatus';
import OrganizationType from './organizationType';
import BasicInformation from './basicInformation';
import RegistrationStep from './registrationStep';
import Declaration, { PLAIN_DECLRATIONS } from './declaration';
import Account from './account';
import AlertDialog from '../common/alertDialog';
import { loadCountries } from '../../reducers/countries';
import { registerUser } from '../../reducers/session';
import { loadPartnerConfig } from '../../reducers/partnerProfileConfig';

const messages = {
  error: 'Registration failed',
  declarationInfo: 'You must answer "yes" to all of the declarations in order to proceed.',
  warning: 'Notice',
  legalInfo: 'You must upload at least one of the following documents: (1) Registration certificate or (2) Governing document or (3) Letter of reference' +
  'from a donor agency, government authority or community association in order to register your organization on UN Partner Portal.',
};

class RegistrationStepper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      stepIndex: 0,
      lastStep: 4,
      declarationAlert: false,
      legalStatusAlert: false,
    };
    this.handleNext = this.handleNext.bind(this);
    this.handleNextQuestions = this.handleNextQuestions.bind(this);
    this.handleNextLegalStatus = this.handleNextLegalStatus.bind(this);
    this.handlePrev = this.handlePrev.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillMount() {
    this.props.loadCountries();
    this.props.loadPartnerConfig();
  }

  handleNext() {
    const { stepIndex } = this.state;
    this.setState({
      stepIndex: stepIndex + 1,
    });
  }

  handleNextQuestions() {
    const answers = this.props.answers;
    if (answers && answers.some(answer => answer === false)) {
      this.setState({ declarationAlert: true });
      return;
    }
    this.handleNext();
  }

  handleNextLegalStatus() {
    const formData = this.props.formData;

    if (!formData.partner_profile.have_governing_document
      && !formData.partner_profile.have_ref_letter
      && !(formData.partner_profile.registered_to_operate_in_country
          && formData.registration_document.have_registration_doc)) {
      this.setState({ legalStatusAlert: true });
      return;
    }

    this.handleNext();
  }

  handlePrev() {
    const { stepIndex } = this.state;
    if (stepIndex > 0) {
      this.setState({ stepIndex: stepIndex - 1 });
    }
  }

  handleSubmit(values) {
    let payload = R.assocPath(['json', 'declaration'],
      Object.keys(PLAIN_DECLRATIONS.questions).map((key, index) =>
        ({ answer: 'Yes', question: PLAIN_DECLRATIONS.questions[key] }),
      ), values);

    payload = R.dissoc('questions', payload);

    return this.props.registerUser(payload.json).catch((error) => {
      const errorMsg = R.path(['response', 'data', 'non_field_errors'], error) || messages.error;
      if (error.response.data.user) {
        this.setState({ stepIndex: 3 });
      }
      throw new SubmissionError({
        json: { ...error.response.data },
        _error: errorMsg,
      });
    });
  }

  render() {
    const { stepIndex } = this.state;
    return (

        <Stepper linear activeStep={stepIndex} orientation="vertical">
          <Step>
            <StepLabel>Select type of organization</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNext} first>
                <OrganizationType />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Enter basic identification information</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNext} handlePrev={this.handlePrev}>
                <BasicInformation />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Legal Status</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNextLegalStatus} handlePrev={this.handlePrev}>
                <LegalStatus />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Partner Declaration</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNextQuestions} handlePrev={this.handlePrev}>
                <Declaration />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Provide e-mail and create password</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNext} handlePrev={this.handlePrev}>
                <Account />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Terms of Use and Privacy Policy</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleSubmit} handlePrev={this.handlePrev} last />
            </StepContent>
          </Step>
        </Stepper>
        <AlertDialog
          trigger={!!this.state.declarationAlert}
          title={messages.warning}
          text={messages.declarationInfo}
          handleDialogClose={() => this.setState({ declarationAlert: false })}
        />
        <AlertDialog
          trigger={!!this.state.legalStatusAlert}
          title={messages.warning}
          text={messages.legalInfo}
          handleDialogClose={() => this.setState({ legalStatusAlert: false })}
        />

    );
  }
}
RegistrationStepper.propTypes = {
  /**
   * answers to all questions in declaration component, show dialog when at least one is false
   */
  answers: PropTypes.arrayOf(PropTypes.bool),
  formData: PropTypes.object,
  loadPartnerConfig: PropTypes.func,
  loadCountries: PropTypes.func,
  registerUser: PropTypes.func,
};

const selector = formValueSelector('registration');
const connectedRegistrationStepper = connect(
  state => ({
    answers: selector(state, 'questions'),
    formData: selector(state, 'json'),
  }),
  dispatch => ({
    loadCountries: () => dispatch(loadCountries()),
    loadPartnerConfig: () => dispatch(loadPartnerConfig()),
    registerUser: values => dispatch(registerUser(values)),
  }),
)(RegistrationStepper);

export default connectedRegistrationStepper;
<commit_msg>#1351 Registration: spelling<commit_after>import R from 'ramda';
import React from 'react';
import { connect } from 'react-redux';
import { formValueSelector, SubmissionError } from 'redux-form';
import PropTypes from 'prop-types';
import {
  Stepper,
  Step,
  StepContent,
  StepLabel,
} from '../customStepper';
import LegalStatus from './legalStatus';
import OrganizationType from './organizationType';
import BasicInformation from './basicInformation';
import RegistrationStep from './registrationStep';
import Declaration, { PLAIN_DECLRATIONS } from './declaration';
import Account from './account';
import AlertDialog from '../common/alertDialog';
import { loadCountries } from '../../reducers/countries';
import { registerUser } from '../../reducers/session';
import { loadPartnerConfig } from '../../reducers/partnerProfileConfig';

const messages = {
  error: 'Registration failed',
  declarationInfo: 'You must answer "yes" to all of the declarations in order to proceed.',
  warning: 'Notice',
  legalInfo: 'You must upload at least one of the following documents: (1) Registration certificate or (2) Governing document or (3) Letter of reference ' +
  'from a donor agency, government authority or community association in order to register your organization on UN Partner Portal.',
};

class RegistrationStepper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      stepIndex: 0,
      lastStep: 4,
      declarationAlert: false,
      legalStatusAlert: false,
    };
    this.handleNext = this.handleNext.bind(this);
    this.handleNextQuestions = this.handleNextQuestions.bind(this);
    this.handleNextLegalStatus = this.handleNextLegalStatus.bind(this);
    this.handlePrev = this.handlePrev.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillMount() {
    this.props.loadCountries();
    this.props.loadPartnerConfig();
  }

  handleNext() {
    const { stepIndex } = this.state;
    this.setState({
      stepIndex: stepIndex + 1,
    });
  }

  handleNextQuestions() {
    const answers = this.props.answers;
    if (answers && answers.some(answer => answer === false)) {
      this.setState({ declarationAlert: true });
      return;
    }
    this.handleNext();
  }

  handleNextLegalStatus() {
    const formData = this.props.formData;

    if (!formData.partner_profile.have_governing_document
      && !formData.partner_profile.have_ref_letter
      && !(formData.partner_profile.registered_to_operate_in_country
          && formData.registration_document.have_registration_doc)) {
      this.setState({ legalStatusAlert: true });
      return;
    }

    this.handleNext();
  }

  handlePrev() {
    const { stepIndex } = this.state;
    if (stepIndex > 0) {
      this.setState({ stepIndex: stepIndex - 1 });
    }
  }

  handleSubmit(values) {
    let payload = R.assocPath(['json', 'declaration'],
      Object.keys(PLAIN_DECLRATIONS.questions).map((key, index) =>
        ({ answer: 'Yes', question: PLAIN_DECLRATIONS.questions[key] }),
      ), values);

    payload = R.dissoc('questions', payload);

    return this.props.registerUser(payload.json).catch((error) => {
      const errorMsg = R.path(['response', 'data', 'non_field_errors'], error) || messages.error;
      if (error.response.data.user) {
        this.setState({ stepIndex: 3 });
      }
      throw new SubmissionError({
        json: { ...error.response.data },
        _error: errorMsg,
      });
    });
  }

  render() {
    const { stepIndex } = this.state;
    return (

        <Stepper linear activeStep={stepIndex} orientation="vertical">
          <Step>
            <StepLabel>Select type of organization</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNext} first>
                <OrganizationType />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Enter basic identification information</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNext} handlePrev={this.handlePrev}>
                <BasicInformation />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Legal Status</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNextLegalStatus} handlePrev={this.handlePrev}>
                <LegalStatus />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Partner Declaration</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNextQuestions} handlePrev={this.handlePrev}>
                <Declaration />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Provide e-mail and create password</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleNext} handlePrev={this.handlePrev}>
                <Account />
              </RegistrationStep>
            </StepContent>
          </Step>
          <Step>
            <StepLabel>Terms of Use and Privacy Policy</StepLabel>
            <StepContent>
              <RegistrationStep onSubmit={this.handleSubmit} handlePrev={this.handlePrev} last />
            </StepContent>
          </Step>
        </Stepper>
        <AlertDialog
          trigger={!!this.state.declarationAlert}
          title={messages.warning}
          text={messages.declarationInfo}
          handleDialogClose={() => this.setState({ declarationAlert: false })}
        />
        <AlertDialog
          trigger={!!this.state.legalStatusAlert}
          title={messages.warning}
          text={messages.legalInfo}
          handleDialogClose={() => this.setState({ legalStatusAlert: false })}
        />

    );
  }
}
RegistrationStepper.propTypes = {
  /**
   * answers to all questions in declaration component, show dialog when at least one is false
   */
  answers: PropTypes.arrayOf(PropTypes.bool),
  formData: PropTypes.object,
  loadPartnerConfig: PropTypes.func,
  loadCountries: PropTypes.func,
  registerUser: PropTypes.func,
};

const selector = formValueSelector('registration');
const connectedRegistrationStepper = connect(
  state => ({
    answers: selector(state, 'questions'),
    formData: selector(state, 'json'),
  }),
  dispatch => ({
    loadCountries: () => dispatch(loadCountries()),
    loadPartnerConfig: () => dispatch(loadPartnerConfig()),
    registerUser: values => dispatch(registerUser(values)),
  }),
)(RegistrationStepper);

export default connectedRegistrationStepper;
<|endoftext|>


<commit_before>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
var pokerAppServices = angular.module('pokerApp.services', []);

pokerAppServices.value('version', '0.1');

pokerAppServices.service('socketService', ['$rootScope',  '$timeout', function($rootScope) {
  var sock = new Sock($rootScope);
  return sock;
}]);

var Sock = function(rootScope) {
  var that = this;

  this.rootScope = rootScope;
  this.rootScope.socketMessage = null;
  this.rootScope.activity = false;
  this.rootScope.sessionId = null;

  this.socket = io.connect(location.protocol + '//' + location.host, {
    'reconnect': true,
    'reconnection delay': 500,
    'max reconnection attempts': 10,
    'try multiple transports': true,
    'transports': ['websocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling']
  });

  this.socket.on('error', function(reason) {
    // console.log('service: on error', reason);
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = ":-(  Error = " + reason;
    });
    // console.log(reason);
  });
  this.socket.on('connect_failed', function(reason) {
    // console.log('service: on connect failed', reason);
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = ":-(  Connect failed ";
    });
    // console.log(reason);
  });
  this.socket.on('disconnect', function() {
    // console.log('service: on disconnect');
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = ":-(  Disconnected";
    });
    // console.log('disconnected');
  });
  this.socket.on('connect', function() {
    var sessionId = this.socket.sessionid;
    // console.log('service: on connect');
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = null;
      // console.log("new session id = " + sessionId);
      if (!$.cookie("sessionId")) {
        $.cookie("sessionId", sessionId);
      }
      that.rootScope.sessionId = $.cookie("sessionId");
      // console.log("session id = " + that.rootScope.sessionId);
    });
  });
};

Sock.prototype.emit = function(msg, data, callback) {
  var that = this;

  // console.log('service: emit ' + msg);
   this.rootScope.activity = true;
   this.socket.emit(msg, data, function(response) {
    that.rootScope.activity = false;
    callback.call(this, response);
   });
}

Sock.prototype.on = function(msg, callback) {
  // console.log('service: on ' + msg);
  this.rootScope.socketMessage = null;
  this.socket.on(msg, callback);
}<commit_msg>Added some extra socket events to listen on - just in case.<commit_after>'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
var pokerAppServices = angular.module('pokerApp.services', []);

pokerAppServices.value('version', '0.1');

pokerAppServices.service('socketService', ['$rootScope',  '$timeout', function($rootScope) {
  var sock = new Sock($rootScope);
  return sock;
}]);

var Sock = function(rootScope) {
  var that = this;

  this.rootScope = rootScope;
  this.rootScope.socketMessage = null;
  this.rootScope.activity = false;
  this.rootScope.sessionId = null;

  this.socket = io.connect(location.protocol + '//' + location.host, {
    'reconnect': true,
    'reconnection delay': 500,
    'max reconnection attempts': 10,
    'try multiple transports': true,
    'transports': ['websocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling']
  });

  this.socket.on('error', function(reason) {
    // console.log('service: on error', reason);
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = ":-(  Error = " + reason;
    });
    // console.log(reason);
  });
  this.socket.on('connect_failed', function(reason) {
    // console.log('service: on connect failed', reason);
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = ":-(  Connect failed ";
    });
    // console.log(reason);
  });
  this.socket.on('disconnect', function() {
    // console.log('service: on disconnect');
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = ":-(  Disconnected";
    });
    // console.log('disconnected');
  });
  this.socket.on('connecting', function() {
    // console.log('service: on connecting');
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = "Connecting...";
    });
    // console.log('disconnected');
  });
  this.socket.on('reconnecting', function() {
    // console.log('service: on reconnecting');
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = "Reconnecting...";
    });
    // console.log('disconnected');
  });
  this.socket.on('connect', function() {
    var sessionId = this.socket.sessionid;
    // console.log('service: on connect');
    that.rootScope.$apply(function() {
      that.rootScope.socketMessage = null;
      // console.log("new session id = " + sessionId);
      if (!$.cookie("sessionId")) {
        $.cookie("sessionId", sessionId);
      }
      that.rootScope.sessionId = $.cookie("sessionId");
      // console.log("session id = " + that.rootScope.sessionId);
    });
  });
};

Sock.prototype.emit = function(msg, data, callback) {
  var that = this;

  // console.log('service: emit ' + msg);
   this.rootScope.activity = true;
   this.socket.emit(msg, data, function(response) {
    that.rootScope.activity = false;
    callback.call(this, response);
   });
}

Sock.prototype.on = function(msg, callback) {
  // console.log('service: on ' + msg);
  this.rootScope.socketMessage = null;
  this.socket.on(msg, callback);
}<|endoftext|>