<commit_before>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * @namespace The Utils object provides useful utility functions and properties.
 * @toc {Utilities} Utils
 * @featureID blackberry.utils
 */
blackberry.utils = {

	/**
	 * @description Construct a new String by converting the blob using the specified character encoding
	 * @param {Blob} blob The Blob object to be converted.
The acceptable blob size is documented below:

	 *

	 *
 	OS 5.0	OS 6.0	OS 7.0

	 *
BASE64	<= 89,678 bytes

	 *
Other Encodings	<= 524,288 bytes (512KB)	<= 2,097,152 bytes (2MB)	<= 524,236 bytes (511KB)

	 *

	 * @param {String} [encoding = ISO-8859-1] The name of a supported character encoding.BlackBerry supports the following character encodings: ISO-8859-1, UTF-8, UTF-16BE, US-ASCII. Besides these encodings, Web API also supports BASE64 encoding. Support of other encodings depends on the configuration of the BlackBerry Smartphone.
	 * @returns {String} The String result from converting the Blob
     * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
     * <script type="text/javascript">
	 *
	 *  var fileName = "local:///data/fooFile.txt";
	 *
     *  function handleOpenedFile(fullPath, blobData) // callback function that is passed when using the blackberry.io.file.readFile API
     *  {
     *    xmlString = blackberry.utils.blobToString(blobData);
     *  }
	 *
     *  try{
	 *      if (blackberry.io.file.exists(fileName)) {
	 *		    blackberry.io.file.readFile(fileName, handleOpenedFile);
	 *      }
	 *  }
	 *  catch (ex) {
	 *      alert("exist: " + ex.toString(0));
	 *  }
     *
     * </script>
     */
	blobToString : function(blob,encoding){},

	/**
	 * @description Convert a document into a Blob. Supported in 5.0.0 only.
	 * @param {Document} doc The document to be converted.
	 * @returns {Blob} The Blob result from converting the Document
	 * @deprecated This API is deprecated, please use {@link blackberry.utils.stringToBlob} instead.

	 * For example:
	 *
var foo = blackberry.utils.stringToBlob( document.toString() );

	 * @BB50
	 */
	documentToBlob : function(doc){},

	/**
	 * @description Convert a string object into a Blob using the specified character encoding.
	 * @param {String} str The string to be converted.
The acceptable string length is documented below:

	 *

	 *
 	OS 5.0	OS 6.0	OS 7.0

	 *
BASE64	<= 65,535

	 *
Other Encodings	<= 524,288	<= 2,097,152	<= 524,236

	 *

	 * @param {String} [encoding = ISO-8859-1] The name of a supported character encoding.BlackBerry supports the following character encodings: ISO-8859-1, UTF-8, UTF-16BE, US-ASCII. Besides these encodings, Web API also supports BASE64 encoding. Support of other encodings depends on the configuration of the BlackBerry Smartphone.
	 * @returns {Blob} The Blob result from converting the String
	 * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
	 * <script type="text/javascript">
	 *
	 * var myString = "This is some sort of string that I would like to encode";
	 *
	 * blackberry.utils.stringToBlob (myString, "UTF-8");
	 *
	 * </script>
	 */
	stringToBlob : function(str,encoding){},

	/**
	 * @description This method will generate a unique number.
	 * @returns {Number} A unique number from JavaScript's Math.random() function.
     * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
	 * <script type="text/javascript">
	 *
	 * var myID = blackberry.utils.generateUniqueId();
	 *
	 * </script>
	 */
	generateUniqueId: function(){},

	/**
	 * @description Parses a URL string and returns an URL object.
	 * @param {String} url The URL string to be parsed.
	 * @returns {blackberry.utils.URL} A {@link blackberry.utils.URL} object is returned if the parsing is successful.
     * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
	 * <script type="text/javascript">
	 * var myURL = "https://bdsc.webapps.blackberry.com/html5/";
	 *
	 * var URLObj = blackberry.utils.URL(myURL);
	 *
	 * </script>
	 */
	parseURL: function(url){},

	/**
	 * @class A URL Utility object contains information about a URL string.
	 * @toc {Utilities} URL
	 * @featureID blackberry.utils
	 * @description Construct a URL object.
	 */
	URL : {

		/**
		 * @description Obtain the value of a parameter by key.
		 * @param {String} key The key of the parameter to be retrieved.
		 * @returns {String} An undefined object is returned if the key does not exist in the URL query.
		 * @BB50+
		 * @PB10+
         * @RIPPLE
		 */
		prototype.getURLParameter:function(key){},

		/**
		 * @description Obtain the value of a parameter by index. The values are stored in the order they appear in the URL string.
		 * @param {Number} index The index of the parameter to be retrieved.
		 * @returns {String} An undefined object is returned if the index is invalid.
         * @BB50+
		 * @PB10+
         * @RIPPLE
		 */
		prototype.getURLParameterByIndex:function(index){},

		/**
		 * @readOnly
		 * @type String
		 * @BB50+
		 * @PB10+
         * @RIPPLE
		 * @description Host address in the URL string.
		 */
		prototype.host:null,
		/**
		 * @readOnly
		 * @type Number
		 * @BB50+
		 * @PB10+
         * @RIPPLE
		 * @description Port number in the URL string.
		 */
		prototype.port:null
	}
};
<commit_msg>adding file.write example with stringToBlob example.<commit_after>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
 * @namespace The Utils object provides useful utility functions and properties.
 * @toc {Utilities} Utils
 * @featureID blackberry.utils
 */
blackberry.utils = {

	/**
	 * @description Construct a new String by converting the blob using the specified character encoding
	 * @param {Blob} blob The Blob object to be converted.
The acceptable blob size is documented below:

	 *

	 *
 	OS 5.0	OS 6.0	OS 7.0

	 *
BASE64	<= 89,678 bytes

	 *
Other Encodings	<= 524,288 bytes (512KB)	<= 2,097,152 bytes (2MB)	<= 524,236 bytes (511KB)

	 *

	 * @param {String} [encoding = ISO-8859-1] The name of a supported character encoding.BlackBerry supports the following character encodings: ISO-8859-1, UTF-8, UTF-16BE, US-ASCII. Besides these encodings, Web API also supports BASE64 encoding. Support of other encodings depends on the configuration of the BlackBerry Smartphone.
	 * @returns {String} The String result from converting the Blob
     * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
     * <script type="text/javascript">
	 *
	 *  var fileName = "local:///data/fooFile.txt";
	 *
     *  function handleOpenedFile(fullPath, blobData) // callback function that is passed when using the blackberry.io.file.readFile API
     *  {
     *    xmlString = blackberry.utils.blobToString(blobData);
     *  }
	 *
     *  try{
	 *      if (blackberry.io.file.exists(fileName)) {
	 *		    blackberry.io.file.readFile(fileName, handleOpenedFile);
	 *      }
	 *  }
	 *  catch (ex) {
	 *      alert("exist: " + ex.toString(0));
	 *  }
     *
     * </script>
     */
	blobToString : function(blob,encoding){},

	/**
	 * @description Convert a document into a Blob. Supported in 5.0.0 only.
	 * @param {Document} doc The document to be converted.
	 * @returns {Blob} The Blob result from converting the Document
	 * @deprecated This API is deprecated, please use {@link blackberry.utils.stringToBlob} instead.

	 * For example:
	 *
var foo = blackberry.utils.stringToBlob( document.toString() );

	 * @BB50
	 */
	documentToBlob : function(doc){},

	/**
	 * @description Convert a string object into a Blob using the specified character encoding.
	 * @param {String} str The string to be converted.
The acceptable string length is documented below:

	 *

	 *
 	OS 5.0	OS 6.0	OS 7.0

	 *
BASE64	<= 65,535

	 *
Other Encodings	<= 524,288	<= 2,097,152	<= 524,236

	 *

	 * @param {String} [encoding = ISO-8859-1] The name of a supported character encoding.BlackBerry supports the following character encodings: ISO-8859-1, UTF-8, UTF-16BE, US-ASCII. Besides these encodings, Web API also supports BASE64 encoding. Support of other encodings depends on the configuration of the BlackBerry Smartphone.
	 * @returns {Blob} The Blob result from converting the String
	 * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
	 * <script type="text/javascript">
	 *
	 * var filePath = "file:///store/home/user/myFile.txt";
	 * var myBlob = blackberry.utils.stringToBlob ("This is some sort of string that I would like to encode", "UTF-8");
	 *
	 * blackberry.io.file.saveFile(filePath, myBlob);
	 *
	 * </script>
	 */
	stringToBlob : function(str,encoding){},

	/**
	 * @description This method will generate a unique number.
	 * @returns {Number} A unique number from JavaScript's Math.random() function.
     * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
	 * <script type="text/javascript">
	 *
	 * var myID = blackberry.utils.generateUniqueId();
	 *
	 * </script>
	 */
	generateUniqueId: function(){},

	/**
	 * @description Parses a URL string and returns an URL object.
	 * @param {String} url The URL string to be parsed.
	 * @returns {blackberry.utils.URL} A {@link blackberry.utils.URL} object is returned if the parsing is successful.
     * @BB50+
	 * @PB10+
     * @RIPPLE
	 * @example
	 * <script type="text/javascript">
	 * var myURL = "https://bdsc.webapps.blackberry.com/html5/";
	 *
	 * var URLObj = blackberry.utils.URL(myURL);
	 *
	 * </script>
	 */
	parseURL: function(url){},

	/**
	 * @class A URL Utility object contains information about a URL string.
	 * @toc {Utilities} URL
	 * @featureID blackberry.utils
	 * @description Construct a URL object.
	 */
	URL : {

		/**
		 * @description Obtain the value of a parameter by key.
		 * @param {String} key The key of the parameter to be retrieved.
		 * @returns {String} An undefined object is returned if the key does not exist in the URL query.
		 * @BB50+
		 * @PB10+
         * @RIPPLE
		 */
		prototype.getURLParameter:function(key){},

		/**
		 * @description Obtain the value of a parameter by index. The values are stored in the order they appear in the URL string.
		 * @param {Number} index The index of the parameter to be retrieved.
		 * @returns {String} An undefined object is returned if the index is invalid.
         * @BB50+
		 * @PB10+
         * @RIPPLE
		 */
		prototype.getURLParameterByIndex:function(index){},

		/**
		 * @readOnly
		 * @type String
		 * @BB50+
		 * @PB10+
         * @RIPPLE
		 * @description Host address in the URL string.
		 */
		prototype.host:null,
		/**
		 * @readOnly
		 * @type Number
		 * @BB50+
		 * @PB10+
         * @RIPPLE
		 * @description Port number in the URL string.
		 */
		prototype.port:null
	}
};
<|endoftext|>


<commit_before>
function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.");
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    return move || getInput();
}

function getComputerMove(move) {
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    if ((playerMove === 'rock') && (computerMove === 'paper')) {
    winner = 'computer';
    }
    else if ((playerMove === 'rock') && (computerMove === 'scissors')) {
    winner = 'player';
    }
    else if ((playerMove === 'paper') && (computerMove === 'rock')) {
    winner = 'player';
    }
    else if ((playerMove === 'paper') && (computerMove === 'scissors')) {
    winner = 'computer';
    }
    else if ((playerMove === 'scissors') && (computerMove === 'rock')) {
    winner = 'computer';
    }
    else if ((playerMove === 'scissors') && (computerMove === 'paper')) {
    winner = 'player';
    }
    else if ((playerMove === 'rock') && (computerMove === 'rock')) {
    winner = 'tie';
    }
    else if ((playerMove === 'paper') && (computerMove === 'paper')) {
    winner = 'tie';
    }
    else if ((playerMove === 'scissors') && (computerMove === 'scissors')) {
    winner = 'tie';
    }
    else {
            winner = 'wrong value inputted';
    }
    return winner;
}

function playToFive() {
console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;

    var playerMove;
    var computerMove;
    var winner;

    playerMove = getPlayerMove();
    computerMove = getComputerMove();
    winner = getWinner(playerMove,computerMove);

    console.log('playerMove is ' + playerMove);
    console.log('computerMove is ' + computerMove);
    console.log('winner is ' + winner);

for (i = 1; i <= 5; i += 1) {
    if (winner === 'player') {
        playerWins = playerWins + 1;
    }
    else if (winner === 'computer') {
        computerWins = computerWins +1;
    }
}
return [playerWins, computerWins];
}

playToFive();<commit_msg>finished product hopefully<commit_after>function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    return move || getInput();
}

function getComputerMove(move) {
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;

    if (playerMove === 'rock' && computerMove === 'scissors') {
        winner = 'player';
    } else if (playerMove === 'rock' && computerMove === 'paper') {
        winner = 'computer';
    } else if (playerMove === 'scissors' && computerMove === 'rock') {
        winner = 'computer';
    } else if (playerMove === 'scissors' && computerMove === 'paper') {
        winner = 'player';
    } else if (playerMove === 'paper' && computerMove === 'rock') {
        winner = 'player';
    } else if (playerMove === 'paper' && computerMove === 'scissors') {
        winner = 'computer';
    } else {
        winner = 'tie';
    }

    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;

    while ((playerWins < 5) && (computerWins < 5)) {

        var playermove = getPlayerMove();
        var computermove = getComputerMove();
        var winner = getWinner(playermove,computermove);

        if (winner === 'player') {
            playerWins +=1;
            console.log( 'Player wins this round with ' + playermove + ' The computer lost this round with ' + computermove);
            console.log ('The score is currently ' + playerWins + ' to ' + computerWins)
        } else if ( winner === 'computer') {
            computerWins +=1;
            console.log ( 'Sorry! the computer won this round with ' + computermove + ' Player chose ' + playermove );
            console.log ('The score is currently '  + playerWins + ' to ' + computerWins)
      } else {
          console.log ('This round is a tie!');
          console.log (' The score is ' + playerWins + ' to ' + computerWins)
      }
    }
    return [playerWins, computerWins];
}
playToFive();<|endoftext|>


<commit_before>const sleep = require('system-sleep');
const Logging = require('disnode-logger');

class OwnerPlugin {
    constructor() {
        this.ownerName = "Insert Name"; //Insert Name so that users that do [p]owner will know who the owner of the bot is
        this.owner = "Insert ID"; //Insert ID so that only you can run these commands
    }

    default (command) {
        var self = this;
        self.disnode.bot.SendEmbed(command.msg.channel, {
            color: 3447003,
            author: {},
            fields: [{
                name: "Owner",
                inline: false,
                value: this.ownerName + "\n" + this.owner,
            }],
            footer: {}
        });
    }
    commandRestart(command) {
        var self = this;
        if (command.msg.userID == this.owner) {
            self.disnode.bot.SendMessage(command.msg.channel, "I am restarting");
            self.disnode.Restart();
        } else {
            self.disnode.bot.SendEmbed(command.msg.channel, {
                color: 15158332,
                author: {},
                fields: [{
                    name: "Stop",
                    inline: false,
                    value: "**You're not my Owner**",
                }],
                footer: {}
            });
            Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd)
        };
    }
    commandShutdown(command) {
        var self = this;
        if (command.msg.userID == this.owner) {
            self.disnode.bot.SendMessage(command.msg.channel, "I am shutting down");
            self.disnode.bot.Disconnect();
            sleep(1000);
            process.exit();
        } else {
            self.disnode.bot.SendEmbed(command.msg.channel, {
                color: 15158332,
                author: {},
                fields: [{
                    name: "Stop",
                    inline: false,
                    value: "**You're not my Owner**",
                }],
                footer: {}
            });
            Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd)
        };
    }
    commandStatus(command) {
        var self = this;
        var status = command.params.join(" ");
        if (command.msg.userID == this.owner) {
            self.disnode.bot.SetStatus(status);
            self.disnode.bot.SendMessage(command.msg.channel, "Status Set To - **Playing " + status + "**");
        } else {
            self.disnode.bot.SendEmbed(command.msg.channel, {
                color: 15158332,
                author: {},
                fields: [{
                    name: "Stop",
                    inline: false,
                    value: "**You're not my Owner**",
                }],
                footer: {}
            });
            Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd)
        };
    }
    commandUsername(command) {
        var self = this;
        if (command.msg.userID == this.owner) {
            self.disnode.bot.SetUsername(command.params[0]);
            self.disnode.bot.SendMessage(command.msg.channel, "Username set to - **" + command.params[0] + "**");
        } else {
            self.disnode.bot.SendEmbed(command.msg.channel, {
                color: 15158332,
                author: {},
                fields: [{
                    name: "Stop",
                    inline: false,
                    value: "**You're not my Owner**",
                }],
                footer: {}
            });
            Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd)
        };
    }
    commandServers(command) {
        var self = this;
        if (command.msg.userID == this.owner) {
            var serverids = Object.keys(self.disnode.bot.client.servers);
            var servers = '';
            for (var i = 0; i < serverids.length; i++) {
                var amount = i + 1;
                if (servers == '') {
                    servers += amount + ". " + self.disnode.bot.client.servers[serverids[i]].name + "\n";
                } else if (i == serverids.length) {
                    serers += amount + ". " + self.disnode.bot.client.servers[serverids[i]].name;
                } else {
                    servers += amount + ". " + self.disnode.bot.client.servers[serverids[i]].name + "\n";
                }
            }
            var results = "```\n" + servers + "```\n**Servers:** " + serverids.length + "\n**Users:** " + Object.keys(self.disnode.bot.client.users).length;
            self.disnode.bot.SendCompactEmbed(command.msg.channel, "Servers List", results);
        } else {
            self.disnode.bot.SendEmbed(command.msg.channel, {
                color: 15158332,
                author: {},
                fields: [{
                    name: "Stop",
                    inline: false,
                    value: "**You're not my Owner**",
                }],
                footer: {}
            });
            Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd)
        };
    }
    commandEval(command) {
    var self = this;
    try {
        var codes = command.msg.message.split("eval ")[1];
        var results = eval("(() => { " + codes + " })();");
        if (results === "[object Object]") {
          results = JSON.stringify(results, null, 4);
        }
        if (typeof results !== 'string')
            results = require('util').inspect(results);
        self.disnode.bot.SendMessage(command.msg.channel, "```js\n" + results + "```")
    } catch (errors) {
        self.disnode.bot.SendMessage(command.msg.channel, "```js\n" + errors + "```")
    }
}

}
module.exports = OwnerPlugin
// Made by Hazed SPaCE✘#2574 & God of _.#6075
<commit_msg>updated eval and non owner messages<commit_after>const sleep = require('system-sleep');
const Logging = require('disnode-logger');

class OwnerPlugin {
    constructor() {
        this.ownerName = "Insert Name"; //Insert Name so that users that do [p]owner will know who the owner of the bot is
        this.owner = "Insert ID"; //Insert ID so that only you can run these commands
    }

    default (command) {
    var self = this;
    self.disnode.bot.SendEmbed(command.msg.channel, {
        color: 3447003,
        author: {},
        fields: [{
            name: "Owner",
            inline: false,
            value: this.ownerName + "\n" + this.owner,
        }],
        footer: {}
    });
}
commandRestart(command) {
    var self = this;
    if (command.msg.userID == this.owner) {
        self.disnode.bot.SendEmbed(command.msg.channel, {
            color: 0x12ff0a,
            author: {},
            fields: [{
                name: "Restarting",
                inline: false,
                value: ":repeat:"
            }],
            footer: {}
        });
        self.disnode.Restart();
    } else self.disnode.bot.SendEmbed(command.msg.channel, {
        color: 0xd600c4,
        author: {},
        fields: [{
            name: "Stop",
            inline: false,
            value: "**You're not my Owner**",
        }],
        footer: {}
    });
    Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd);
}
commandShutdown(command) {
    var self = this;
    if (command.msg.userID == this.owner) {
        self.disnode.bot.SendEmbed(command.msg.channel, {
            color: 0x12ff0a,
            author: {},
            fields: [{
                name: "Shutting down",
                inline: false,
                value: ":wave:"
            }],
            footer: {}
        });
        self.disnode.bot.Disconnect();
        sleep(1000);
        process.exit();
    } else self.disnode.bot.SendEmbed(command.msg.channel, {
        color: 15158332,
        author: {},
        fields: [{
            name: "Stop",
            inline: false,
            value: "**You're not my Owner**",
        }],
        footer: {}
    });
    Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd);
}
commandStatus(command) {
    var self = this;
    var status = command.params.join(" ");
    if (command.msg.userID == this.owner) {
        self.disnode.bot.SetStatus(status);
        self.disnode.bot.SendEmbed(command.msg.channel, {
            color: 0x12ff0a,
            author: {},
            fields: [{
                name: "New Status",
                inline: false,
                value: "Playing **" + status + "**"
            }],
            footer: {}
        });
    } else self.disnode.bot.SendEmbed(command.msg.channel, {
        color: 15158332,
        author: {},
        fields: [{
            name: "Stop",
            inline: false,
            value: "**You're not my Owner**",
        }],
        footer: {}
    });
    Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd);
}
commandUsername(command) {
    console.log(command.params);
    var self = this;
    if (command.msg.userID == this.owner) {
        self.disnode.bot.SetUsername(command.params[0]);
        self.disnode.bot.SendEmbed(command.msg.channel, {
            color: 0x12ff0a,
            author: {},
            fields: [{
                name: "Username",
                inline: false,
                value: "New username **" + command.params[0] + "**"
            }],
            footer: {}
        });
        Logging.Warning("Owner", "Username", "Changed");
    } else self.disnode.bot.SendEmbed(command.msg.channel, {
        color: 15158332,
        author: {},
        fields: [{
            name: "Stop",
            inline: false,
            value: "**You're not my Owner**",
        }],
        footer: {}
    });
    Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd);
}
commandServers(command) {
    var self = this;
    if (command.msg.userID == this.owner) {
        var serverids = Object.keys(self.disnode.bot.client.servers);
        var servers = '';
        for (var i = 0; i < serverids.length; i++) {
            var amount = i + 1;
            if (servers == '') {
                servers += amount + ". " + self.disnode.bot.client.servers[serverids[i]].name + "\n";
            } else if (i == serverids.length) {
                serers += amount + ". " + self.disnode.bot.client.servers[serverids[i]].name;
            } else {
                servers += amount + ". " + self.disnode.bot.client.servers[serverids[i]].name + "\n";
            }
        }
        var results = "```\n" + servers + "```\n**Servers:** " + serverids.length + "\n**Users:** " + Object.keys(self.disnode.bot.client.users).length;
        self.disnode.bot.SendEmbed(command.msg.channel, {
            color: 1752220,
            author: {},
            fields: [{
                name: "Server List",
                inline: false,
                value: "" + results,
            }],
            footer: {}
        });
    } else self.disnode.bot.SendEmbed(command.msg.channel, {
        color: 15158332,
        author: {},
        fields: [{
            name: "Stop",
            inline: false,
            value: "**You're not my Owner**",
        }],
        footer: {}
    });
    Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd);
}
commandEval(command) {
    var self = this;
    if (command.msg.userID == this.owner) {
        try {
            var codes = command.msg.message.split("eval ")[1];
            var results = eval("(() => { " + codes + " })();");
            if (results === "[object Object]") {
                results = JSON.stringify(results, null, 4);
            }
            if (typeof results !== 'string')
                results = require('util').inspect(results);
            self.disnode.bot.SendMessage(command.msg.channel, "```" + results + "```")
        } catch (errors) {
            self.disnode.bot.SendMessage(command.msg.channel, errors)
        }
    } else self.disnode.bot.SendEmbed(command.msg.channel, {
        color: 15158332,
        author: {},
        fields: [{
            name: "Stop",
            inline: false,
            value: "**You're not my Owner**",
        }],
        footer: {}
    });
    Logging.Warning(command.msg.user, command.msg.userID, "Tried using " + self.disnode.botConfig.prefix + "" + command.command.cmd);
}

}
module.exports = OwnerPlugin
// Made by Hazed SPaCE✘#2574 & God of _.#6075
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
/* Your Expression */
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
/* Your Expression */
}

function getWinner(playerMove,computerMove) {
	var playerMove;
	while (playerMove === “rock”) {
	if (computerMove === “rock”) {
		winner = “tie”;
	} else if (computerMove === “paper”) {
		winner = “computer”;
	} else if (computerMove === “scissors”) {
		winner = “player”;
		}
	}
	while (playerMove === “paper”) {
	if (computerMove === “rock”) {
		winner = “player”;
	} else if (computerMove === “paper”) {
		winner = “tie”;
	} else if (computerMove === “scissors”) {
		winner = “computer”;
		}
	}
	while (playerMove === “scissors”) {
	if (computerMove === “rock”) {
		winner = “computer”;
	} else if (computerMove === “paper”) {
		winner = “player”;
	} else if (computerMove === “scissors”) {
		winner = “tie”;
		}
	}

}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>updated getWinner, added playToFive<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
/* Your Expression */
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
/* Your Expression */
}

function getWinner(playerMove,computerMove) {
	// either have var playerMove and var computerMove and take these out
	// of parentheses (parameters) or keep in paren and take out var.
	while (playerMove === “rock”) {
	if (computerMove === “rock”) {
		return “tie”;
	// Not sure this makes sense—maybe return “tie” instead/ winner not def
	} else if (computerMove === “paper”) {
		return “computer”;
	} else if (computerMove === “scissors”) {
		return “player”;
		}
	}
	while (playerMove === “paper”) {
	if (computerMove === “rock”) {
		return “player”;
	} else if (computerMove === “paper”) {
		return “tie”;
	} else if (computerMove === “scissors”) {
		return “computer”;
		}
	}
	while (playerMove === “scissors”) {
	if (computerMove === “rock”) {
		return “computer”;
	} else if (computerMove === “paper”) {
		return “player”;
	} else if (computerMove === “scissors”) {
		return “tie”;
		}
	}

}

function playToFive() {
  console.log('Let\'s play Rock Paper Scissors');
  var playerWins = 0;
  var computerWins = 0;
  while (playerWins < 5 && computerWins < 5) {
    if (winnerIsPlayer()){
	   playerWins += 1;
    }
    if (winnerIsComputer()){
	computerWins += 1;
    }
 	console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
   console.log('The score is currently ' + playerWins + ' to ' + computerWins);
  return [playerWins, computerWins];
  }
}

function winnerIsPlayer() {
	return playerWinsRock() || playerWinsPaper() || playerWinsScissors();
	}

function winnerIsComputer() {
	return computerWinsRock() || computerWinsPaper()|| computerWinsScissors();
	}

function playerWinsRock() {
	return (playerMove === ‘rock’) && (computerMove === ‘scissors’);
	}

function playerWinsPaper() {
	return (playerMove === ‘paper’) && (computerMove === ‘rock’);
	}

function playerWinsScissors() {
	return (playerMove === ‘scissors’) && (computerMove === ‘paper’);
	}

function computerWinsRock() {
	return (computerMove === ‘rock’) && (playerMove === ‘scissors’);
	}

function computerWinsPaper() {
	return (computerMove === ‘paper’) && (playerMove === ‘rock’);
	}

function computerWinsScissors() {
	return (computerMove === ‘scissors’) && (playerMove === ‘paper’);
	}

/* I think this version of playToFive could operate independently of the getWinner function above, but it makes logical sense to me, whereas I don’t think my attempt at incorporating getWinner function (below) would work. */

/*
// here is a version of playToFive that accounts for getWinner function
function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    while (playerWins < 5 && computerWins < 5) {
    //not sure while is allowed within a function.
    if (winnerIsPlayer()){
	playerWins += 1;
    }
    if (winnerIsComputer()){
	computerWins += 1;
    }
   console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
   console.log('The score is currently ' + playerWins + ' to ' + computerWins + ‘\n’);
	return [playerWins, computerWins];
  }
}

function winnerIsPlayer() {
	return ‘player’;
	// if getWinner = “player” (not sure of syntax)
	}

function winnerIsComputer() {
	return ‘computer’;
	// if getWinner = “computer” (not sure of syntax)
}
*/

<|endoftext|>


<commit_before>var Analytics                        = require('lib/analytics'),
    Features                         = require('lib/features'),
    Hours                            = require('shared/models/hours'),
    fetchLocation                    = require('shared/lib/fetch_location'),
    calculateDistance            = require('shared/lib/distance').calculateDistance;

function calculateDistanceCallback (walkingData, facility){
  var self = this;
    if (!walkingData) { return; }
    var distanceSpan = self.$("#distance_" + facility.objectId),
        durationSpan = self.$("#duration_" + facility.objectId);
    facility.distanceText = walkingData.distance.text;
    facility.durationText = walkingData.duration.text;
    $(distanceSpan).text( facility.distanceText );
    $(durationSpan).text( facility.durationText );
}

var DetailView = Backbone.View.extend({
  template: require('templates/detail'),

  events: {
    'render.done':             'setMap',
    'click .inset-directions': 'launchDirections',

    'click .inset-gmap':       'launchDirections',
    'click .inset-call':       'trackCalling',
    'click .inset-website':    'trackClickingWebsite'
  },

  navButtons: [
    { 'class': 'left', id: 'backNav-button', text: 'Back' }
  ],

  render: function() {
    var facility = this.model,
        $mapdiv  =  this.$('#detail-gmap');

    if ( !facility.distanceData && this.options.currentLocation ) {
      calculateDistance(facility, this.options.currentLocation, calculateDistanceCallback );
    }
    this.$el.html(this.template({
      facility:    facility,
      isMobile:    Features.isMobile()
    }));

    _.defer(
      function(view) { view.setMap();
    },
      this
    );

    return this;
  },

  trackCalling:         function(event) { Analytics.trackDetailsAction('call'); },
  trackClickingWebsite: function(event) { Analytics.trackDetailsAction('website'); },

  launchDirections: function() {
    Analytics.trackDetailsAction('directions');
    var isAndroid22 = Features.isAndroid22(),
        isMobile = Features.isMobile(),
        dAddr = encodeURIComponent(
          this.model.address + '@' +
          this.model.location.latitude + ',' +
          this.model.location.longitude
        ),
        directionsUrl = '';

    if ( isMobile && !isAndroid22 ) {
      directionsUrl = 'comgooglemaps://?daddr=' + dAddr;
      document.location = directionsUrl;
    } else {
      fetchLocation().done(function(loc) {
        var sAddr = '@' + loc.lat + ',' + loc.lon;
        directionsUrl = 'https://maps.google.com?daddr=' + dAddr + '&saddr=' + sAddr;

      }).fail(function() {
        directionsUrl = 'https://maps.google.com?daddr=' + dAddr;
      });
      _.defer( function() {
        isAndroid22 ? (document.location = directionsUrl) : window.open(directionsUrl, '_blank');
      });
    }

    return false;
  },

  setMap: function(){
    var location, mapOptions, map;

    if ( !this.$('#detail-gmap') ) return;

    location = new google.maps.LatLng(
      this.model.location.latitude,
      this.model.location.longitude
    );

    mapOptions = {
      center:            location,
      zoom:              15,
      mapTypeId:         google.maps.MapTypeId.ROADMAP,
      mapTypeControl:    false,
      scrollwheel:       false,
      navigationControl: false,
      draggable:         false,
      streetViewControl: false,
      zoomControl:       false
    };

    map = new google.maps.Map(
      this.$('#detail-gmap')[0],
      mapOptions
    );

    fetchLocation().done(function(current) {
      var directionsService = new google.maps.DirectionsService(),
          directionsDisplay = new google.maps.DirectionsRenderer(),
          request;

      request = {
        origin:      new google.maps.LatLng(current.lat, current.lon),
        destination: location,
        travelMode:  google.maps.DirectionsTravelMode.WALKING
      };

      directionsDisplay.setMap(map);

      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });

    }).fail(function() {
      new google.maps.Marker({
        map:       map,
        position:  location,
        draggable: false
      });
    });
  }
});

module.exports = DetailView;
<commit_msg>track call, website, and directions from detail<commit_after>var Analytics                        = require('lib/analytics'),
    Features                         = require('lib/features'),
    Hours                            = require('shared/models/hours'),
    fetchLocation                    = require('shared/lib/fetch_location'),
    calculateDistance            = require('shared/lib/distance').calculateDistance;

function calculateDistanceCallback (walkingData, facility){
  var self = this;
    if (!walkingData) { return; }
    var distanceSpan = self.$("#distance_" + facility.objectId),
        durationSpan = self.$("#duration_" + facility.objectId);
    facility.distanceText = walkingData.distance.text;
    facility.durationText = walkingData.duration.text;
    $(distanceSpan).text( facility.distanceText );
    $(durationSpan).text( facility.durationText );
}

var DetailView = Backbone.View.extend({
  template: require('templates/detail'),

  events: {
    'render.done':             'setMap',
    'click .inset-directions': 'launchDirections',

    'click .inset-gmap':       'launchDirections',
    'click .inset-call':       'trackCalling',
    'click .inset-website':    'trackClickingWebsite'
  },

  navButtons: [
    { 'class': 'left', id: 'backNav-button', text: 'Back' }
  ],

  render: function() {
    var facility = this.model,
        $mapdiv  =  this.$('#detail-gmap');

    if ( !facility.distanceData && this.options.currentLocation ) {
      calculateDistance(facility, this.options.currentLocation, calculateDistanceCallback );
    }
    this.$el.html(this.template({
      facility:    facility,
      isMobile:    Features.isMobile()
    }));

    _.defer(
      function(view) { view.setMap();
    },
      this
    );

    return this;
  },

  trackCalling: function(event) {
    Analytics.trackDetailsAction('call');
    ga('send', 'event', 'call', this.model.get('name'));
  },

  trackClickingWebsite: function(event) {
    Analytics.trackDetailsAction('website');
    ga('send', 'event', 'website', this.model.get('name'));
  },

  launchDirections: function() {
    Analytics.trackDetailsAction('directions');
    ga('send', 'event', 'directions', this.model.get('name'));
    var isAndroid22 = Features.isAndroid22(),
        isMobile = Features.isMobile(),
        dAddr = encodeURIComponent(
          this.model.address + '@' +
          this.model.location.latitude + ',' +
          this.model.location.longitude
        ),
        directionsUrl = '';

    if ( isMobile && !isAndroid22 ) {
      directionsUrl = 'comgooglemaps://?daddr=' + dAddr;
      document.location = directionsUrl;
    } else {
      fetchLocation().done(function(loc) {
        var sAddr = '@' + loc.lat + ',' + loc.lon;
        directionsUrl = 'https://maps.google.com?daddr=' + dAddr + '&saddr=' + sAddr;

      }).fail(function() {
        directionsUrl = 'https://maps.google.com?daddr=' + dAddr;
      });
      _.defer( function() {
        isAndroid22 ? (document.location = directionsUrl) : window.open(directionsUrl, '_blank');
      });
    }

    return false;
  },

  setMap: function(){
    var location, mapOptions, map;

    if ( !this.$('#detail-gmap') ) return;

    location = new google.maps.LatLng(
      this.model.location.latitude,
      this.model.location.longitude
    );

    mapOptions = {
      center:            location,
      zoom:              15,
      mapTypeId:         google.maps.MapTypeId.ROADMAP,
      mapTypeControl:    false,
      scrollwheel:       false,
      navigationControl: false,
      draggable:         false,
      streetViewControl: false,
      zoomControl:       false
    };

    map = new google.maps.Map(
      this.$('#detail-gmap')[0],
      mapOptions
    );

    fetchLocation().done(function(current) {
      var directionsService = new google.maps.DirectionsService(),
          directionsDisplay = new google.maps.DirectionsRenderer(),
          request;

      request = {
        origin:      new google.maps.LatLng(current.lat, current.lon),
        destination: location,
        travelMode:  google.maps.DirectionsTravelMode.WALKING
      };

      directionsDisplay.setMap(map);

      directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setDirections(response);
        }
      });

    }).fail(function() {
      new google.maps.Marker({
        map:       map,
        position:  location,
        draggable: false
      });
    });
  }
});

module.exports = DetailView;
<|endoftext|>


<commit_before>var path        = require("path");
var querystring = require("querystring");
var underscore  = require("underscore");
var app         = require(path.join(__dirname, "..", "..", "..", "config", "app"));
var redis       = require(path.join(app.root, "config", "redis"));
var RateLimiter = require(path.join(app.root, "app", "lib", "rate_limiter"));
var HttpJson    = require(path.join(app.root, "app", "lib", "http_json"));
var Spotbox     = require(path.join(app.root, "app", "lib", "spotbox"));

var rateLimiter = new RateLimiter(1000.0 / 10); // 10 requests per second

var apiSettings = {
  host: "ws.spotify.com",
  version: 1
};

function request(opts, params, hollaback) {
  var options = {};
  options.host = apiSettings.host;
  options.path = "/" + opts.type + "/" +  apiSettings.version + "/";

  if (opts.searchType) {
    options.path += opts.searchType;
  }

  options.path += ".json";
  options.path += "?" + querystring.stringify(params);

  rateLimiter.queue(function() {
    HttpJson.get(options, hollaback);
  });
};

function cachedRequest(options, params, cacheKey, hollaback) {
  redis.get(cacheKey, function(error, resultString) {
    if (error) {
      hollaback(error);
    } else if (resultString) {
      hollaback(null, JSON.parse(resultString));
    } else {
      request(options, params, function(error, json) {
        if (error) {
          hollaback(error);
        } else {
          hollaback(null, json);
          redis.set(cacheKey, JSON.stringify(json));
        }
      });
    }
  });
};

function standardizeTrack(spTrack) {
  var track            = {album: {}};
  track.type           = "track";
  track.provider       = "spotify";
  track.id             = spTrack.href;
  track.name           = spTrack.name;
  track.track_number   = spTrack["track-number"];
  track.length         = spTrack.length;
  track.album.name     = spTrack.album.name;
  track.album.id       = spTrack.album.href;
  track.album.released = spTrack.album.released;

  track.ids = underscore.reduce(spTrack["external-ids"], function(memo, extId) {
    memo[extId.type] = extId.id;
    return memo;
  }, {spotify: track.id});

  track.artists = underscore.map(spTrack.artists, function(artist) {
    return {name: artist.name, id: artist.href};
  });

  return track;
};

var SpotifyApi = function() {};

SpotifyApi.lookup = function(spotifyUri, hollaback) {
  var key = Spotbox.namespace(spotifyUri);
  var options = { type: "lookup" };
  var params  = { uri: spotifyUri };
  cachedRequest(options, params, key, function(error, metadata) {
    if (error) {
      hollaback(error);
    } else {
      hollaback(null, standardizeTrack(metadata.track));
    }
  });
};

SpotifyApi.search = function(query, hollaback) {
  var key = Spotbox.namespace("search:" + querystring.escape(query));
  var options = {type: "search", searchType: "track"};
  var params = {q: query};
  cachedRequest(options, params, key, function(error, searchResults) {
    if (error) {
      hollaback(error);
    } else {
      var tracks = underscore.map(searchResults.tracks, function(track) {
        return underscore.extend(standardizeTrack(track), {availability: track.album.availability});
      });
      hollaback(null, tracks);
    }
  });
};

module.exports = SpotifyApi;
<commit_msg>Remove type attribute from spotify track<commit_after>var path        = require("path");
var querystring = require("querystring");
var underscore  = require("underscore");
var app         = require(path.join(__dirname, "..", "..", "..", "config", "app"));
var redis       = require(path.join(app.root, "config", "redis"));
var RateLimiter = require(path.join(app.root, "app", "lib", "rate_limiter"));
var HttpJson    = require(path.join(app.root, "app", "lib", "http_json"));
var Spotbox     = require(path.join(app.root, "app", "lib", "spotbox"));

var rateLimiter = new RateLimiter(1000.0 / 10); // 10 requests per second

var apiSettings = {
  host: "ws.spotify.com",
  version: 1
};

function request(opts, params, hollaback) {
  var options = {};
  options.host = apiSettings.host;
  options.path = "/" + opts.type + "/" +  apiSettings.version + "/";

  if (opts.searchType) {
    options.path += opts.searchType;
  }

  options.path += ".json";
  options.path += "?" + querystring.stringify(params);

  rateLimiter.queue(function() {
    HttpJson.get(options, hollaback);
  });
};

function cachedRequest(options, params, cacheKey, hollaback) {
  redis.get(cacheKey, function(error, resultString) {
    if (error) {
      hollaback(error);
    } else if (resultString) {
      hollaback(null, JSON.parse(resultString));
    } else {
      request(options, params, function(error, json) {
        if (error) {
          hollaback(error);
        } else {
          hollaback(null, json);
          redis.set(cacheKey, JSON.stringify(json));
        }
      });
    }
  });
};

function standardizeTrack(spTrack) {
  var track            = {album: {}};
  track.provider       = "spotify";
  track.id             = spTrack.href;
  track.name           = spTrack.name;
  track.track_number   = spTrack["track-number"];
  track.length         = spTrack.length;
  track.album.name     = spTrack.album.name;
  track.album.id       = spTrack.album.href;
  track.album.released = spTrack.album.released;

  track.ids = underscore.reduce(spTrack["external-ids"], function(memo, extId) {
    memo[extId.type] = extId.id;
    return memo;
  }, {spotify: track.id});

  track.artists = underscore.map(spTrack.artists, function(artist) {
    return {name: artist.name, id: artist.href};
  });

  return track;
};

var SpotifyApi = function() {};

SpotifyApi.lookup = function(spotifyUri, hollaback) {
  var key = Spotbox.namespace(spotifyUri);
  var options = { type: "lookup" };
  var params  = { uri: spotifyUri };
  cachedRequest(options, params, key, function(error, metadata) {
    if (error) {
      hollaback(error);
    } else {
      hollaback(null, standardizeTrack(metadata.track));
    }
  });
};

SpotifyApi.search = function(query, hollaback) {
  var key = Spotbox.namespace("search:" + querystring.escape(query));
  var options = {type: "search", searchType: "track"};
  var params = {q: query};
  cachedRequest(options, params, key, function(error, searchResults) {
    if (error) {
      hollaback(error);
    } else {
      var tracks = underscore.map(searchResults.tracks, function(track) {
        return underscore.extend(standardizeTrack(track), {availability: track.album.availability});
      });
      hollaback(null, tracks);
    }
  });
};

module.exports = SpotifyApi;
<|endoftext|>


<commit_before>'use strict';

var srlog = SIREPO.srlog;
var srdbg = SIREPO.srdbg;

SIREPO.appDefaultSimulationValues.simulation.sourceType = 'laserPulse';

SIREPO.app.factory('warpPBAService', function(appState, $rootScope) {
    var self = {};
    self.laserGridDimensions = null;
    self.beamGridDimensions = null;

    function initGridDimensions() {
        if (self.laserGridDimensions) {
            return;
        }
        self.laserGridDimensions = appState.clone(SIREPO.APP_SCHEMA.enum.GridDimensions);
        self.beamGridDimensions = appState.clone(self.laserGridDimensions);
        self.laserGridDimensions.splice(2, 1);
        self.beamGridDimensions.splice(1, 1);
    }

    function isSourceType(sourceType) {
        if (appState.isLoaded()) {
            return appState.applicationState().simulation.sourceType == sourceType;
        }
        return false;
    }

    self.computeModel = function (analysisModel) {
        return 'animation';
    };

    self.isElectronBeam = function() {
        return isSourceType('electronBeam');
    };

    self.isLaserPulse = function() {
        return isSourceType('laserPulse');
    };

    appState.setAppService(self);

    appState.whenModelsLoaded($rootScope, function() {
        initGridDimensions();
        SIREPO.APP_SCHEMA.enum.GridDimensions = self.isLaserPulse()
            ? self.laserGridDimensions
            : self.beamGridDimensions;
    });
    return self;
});

SIREPO.app.controller('WarpPBADynamicsController', function(appState, frameCache, panelState, warpPBAService, persistentSimulation, $scope) {
    var self = this;
    self.panelState = panelState;

    function handleStatus(data) {
        if (data.frameCount) {
            frameCache.setFrameCount(parseInt(data.frameCount));
        }
    }

    self.isElectronBeam = function() {
        return warpPBAService.isElectronBeam();
    };

    self.simState = persistentSimulation.initSimulationState(
        $scope,
        warpPBAService.computeModel(),
        handleStatus
    );

    self.simState.initMessage = function() {
        return 'Initializing Laser Pulse and Plasma';
    };

    /* SIREPO.app.directive('srJobsettingsEditor', function(appState, panelState) {
     *     return {
     *         restrict: 'A',
     *         controller: function($scope) {
     *
     *             function jobRunModeChanged() {
     *                 if (! appState.models.jobSettings) {
     *                     return;
     *                 }
     *                 if (jobState.isReady()) {
     *                     processFields();
     *                     return;
     *                 }
     *                 jobService.checkReady(
     *                     sends request
     *                     function (auth_request) {
     *                         if
     *                         sorry no nersc, popup sbatch directive;
     *                         else processFields();
     *                     }
     *                 }
     * revert jobRunMode if no credentials
     * cancel changes to model
     *
     *             }
     *             function processFields() {
     *                 if (! appState.models.jobSettings) {
     *                     return;
     *                 }
     *                 appState
     *                 do not show jobRunMode sbatch if no sbatch;
     *                 var isSbatch = appState.models.jobSettings.jobRunMode == 'sbatch';
     *                 panelState.showField('jobSettings', 'jobCores', isSbatch);
     *                 panelState.showField('jobSettings', 'jobDbRoot', isSbatch);
     *                 jobState controlls pr
     *                 panelState.showField('jobSettings', 'jobProject', isSbatch);
     *
     *             }
     *
     *             appState.whenModelsLoaded($scope, function() {
     *                 appState.watchModelFields($scope, ['jobSettings.jobRunMode'], jobRunModeChanged);
     *                 processFields();
     *             });
     *         },
     *     };
     * });
     * */
});

SIREPO.app.controller('WarpPBASourceController', function(appState, frameCache, warpPBAService, $scope) {
    var self = this;
    $scope.appState = appState;
    var constants = {
        beamFactor: 0.728583,
        clight: 299792458.0,
        echarge: 1.602176565e-19,
        emass: 9.10938291e-31,
        eps0: 8.85418781762e-12,
    };

    function beamBunchLengthMethodChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamBunchLengthMethod == 'a';
        setVisibility(['electronBeam.rmsLength'], ! isAbsolute, oldValue);
        setReadOnly(['electronBeam.rmsLength'], true);
        setReadOnly(['electronBeam.bunchLength'], ! isAbsolute);
        recalcBeamBunchLength();
    }

    function beamRadiusMethodChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamRadiusMethod == 'a';
        setVisibility(['electronBeam.transverseEmittance'], ! isAbsolute, oldValue);
        setReadOnly(['electronBeam.rmsRadius'], ! isAbsolute);
        recalcRMSRadius();
    }

    function fieldClass(field) {
        return '.model-' + field.replace('.', '-');
    }

    function gridDimensionsChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var fields = {
            visible: ['simulationGrid.rScale', 'simulationGrid.zScale'],
            editable: ['simulationGrid.rLength', 'simulationGrid.zLength'],
        };
        var isAbsolute = appState.models.simulationGrid.gridDimensions == 'a';
        setVisibility(fields.visible, ! isAbsolute, oldValue);
        setReadOnly(fields.editable, ! isAbsolute);
        setReadOnly(['simulationGrid.rMin', 'simulationGrid.rMax', 'simulationGrid.zMin', 'simulationGrid.zMax', 'simulationGrid.rCount', 'simulationGrid.zCount'], true);
        var sourceFields = {
            laserPulse: ['simulationGrid.rCellsPerSpotSize', 'simulationGrid.zCellsPerWavelength'],
            electronBeam: ['simulationGrid.rCellResolution', 'simulationGrid.zCellResolution'],
        };
        setVisibility(sourceFields[self.isLaserPulse() ? 'laserPulse' : 'electronBeam'], true);
        setVisibility(sourceFields[self.isLaserPulse() ? 'electronBeam' : 'laserPulse'], false);
        recalcValues();
    }

    function lambdaLaser() {
        return appState.models.laserPulse.wavelength / 1e6;
    }

    function lambdaPlasma() {
        return 3.34e7 / Math.sqrt(appState.models.electronPlasma.density);
    }

    function pulseDimensionsChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var fields = {
            visible: ['laserPulse.length', 'laserPulse.spotSize'],
            editable: ['laserPulse.waist', 'laserPulse.duration'],
        };
        var isAbsolute = appState.models.laserPulse.pulseDimensions == 'a';
        setVisibility(fields.visible, ! isAbsolute, oldValue);
        setReadOnly(fields.editable, ! isAbsolute);
        recalcValues();
    }

    function recalcBeamBunchLength() {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamBunchLengthMethod == 'a';
        if (isAbsolute) {
            return;
        }

        var rmsMax = lambdaPlasma() / Math.PI;
        var rmsLength = constants.beamFactor * rmsMax;
        var xBunchHw = 3 * rmsLength;
        appState.models.electronBeam.rmsLength = rmsLength * 1e6;
        appState.models.electronBeam.bunchLength = 2 * xBunchHw * 1e6;
    }

    function recalcCellCount() {
        if (! appState.isLoaded()) {
            return;
        }
        var grid = appState.models.simulationGrid;
        if (self.isLaserPulse()) {
            var laserPulse = appState.models.laserPulse;
            var lambda = lambdaLaser();
            grid.zCount = Math.round((grid.zMax - grid.zMin) / 1e6 * grid.zCellsPerWavelength / lambda);
            grid.rCount = Math.round((grid.rMax - grid.rMin) * grid.rCellsPerSpotSize / laserPulse.waist);
        }
        else {
            grid.zCount = Math.round(grid.zScale * grid.zCellResolution);
            grid.rCount = Math.round(grid.rScale * grid.rCellResolution);
        }
    }

    function recalcHistogramBins(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        if (newValue && oldValue) {
            appState.models.particleAnimation.histogramBins = newValue;
            //TODO(pjm): beam reports require a slight increase to match the grid
            appState.models.beamAnimation.histogramBins = newValue + 1;
            appState.models.beamPreviewReport.histogramBins = newValue + 1;
            appState.saveQuietly('particleAnimation');
            appState.saveQuietly('beamAnimation');
        }
    }

    function recalcLength() {
        if (! appState.isLoaded()) {
            return;
        }
        var grid = appState.models.simulationGrid;
        grid.rMax = grid.rLength;
        grid.zMin = - grid.zLength;
    }

    function recalcRMSRadius() {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamRadiusMethod == 'a';
        if (isAbsolute) {
            return;
        }
        var kPe = 2 * Math.PI / lambdaPlasma();
        var twissBetaMatch = Math.sqrt(2) / kPe;
        appState.models.electronBeam.rmsRadius = Math.sqrt(twissBetaMatch * parseFloat(appState.models.electronBeam.transverseEmittance)) * 1e6;
    }

    function recalcValues() {
        if (! appState.isLoaded()) {
            return;
        }
        var grid = appState.models.simulationGrid;
        if (self.isLaserPulse()) {
            var laserPulse = appState.models.laserPulse;
            var wplab = Math.sqrt(
                appState.models.electronPlasma.density
                    * Math.pow(constants.echarge, 2)
                    / (constants.eps0 * constants.emass));
            var kplab = wplab / constants.clight;
            // resonant wth plasma density
            if (laserPulse.pulseDimensions == 'r') {
                laserPulse.waist = (1e6 * laserPulse.spotSize / kplab).toFixed(12);
                laserPulse.duration = (1e12 * laserPulse.length / kplab / constants.clight).toFixed(12);
            }
            grid.rMin = 0;
            grid.zMax = (2.0 * lambdaLaser() * 1e6).toFixed(12);
            // scale to laser pulse
            if (grid.gridDimensions == 's') {
                grid.rLength = (grid.rScale * laserPulse.waist).toFixed(12);
                grid.zLength = (grid.zScale * laserPulse.duration / 1e6 * 4 * constants.clight).toFixed(12);
            }
        }
        else {
            var lambda = lambdaPlasma();
            grid.zMax = 0;
            if (grid.gridDimensions == 'e') {
                grid.rLength = 0.5 * grid.rScale * lambda * 1e6;
                grid.zLength = grid.zScale * lambda * 1e6;
            }
        }
        recalcLength();
        recalcCellCount();
        recalcRMSRadius();
        recalcBeamBunchLength();
    }

    function setReadOnly(fields, isReadOnly) {
        for (var i = 0; i < fields.length; i++) {
            $(fieldClass(fields[i]) + ' input').prop('readonly', isReadOnly);
        }
    }

    function setVisibility(fields, isVisible, oldValue) {
        for (var i = 0; i < fields.length; i++) {
            var el = $(fieldClass(fields[i])).closest('.form-group');
            if (isVisible) {
                if (oldValue) {
                    el.slideDown();
                }
            }
            else {
                if (oldValue) {
                    el.slideUp();
                }
                else {
                    el.hide();
                }
            }
        }
    }

    function updateFieldState() {
        gridDimensionsChanged();
        pulseDimensionsChanged();
        beamRadiusMethodChanged();
        beamBunchLengthMethodChanged();
    }

    self.isLaserPulse = function() {
        return warpPBAService.isLaserPulse();
    };

    self.isElectronBeam = function() {
        return warpPBAService.isElectronBeam();
    };

    $scope.$watch('appState.models.laserPulse.pulseDimensions', pulseDimensionsChanged);
    $scope.$watch('appState.models.laserPulse.length', recalcValues);
    $scope.$watch('appState.models.laserPulse.spotSize', recalcValues);
    $scope.$watch('appState.models.electronPlasma.density', recalcValues);
    $scope.$watch('appState.models.simulationGrid.gridDimensions', gridDimensionsChanged);
    $scope.$watch('appState.models.simulationGrid.rScale', recalcValues);
    $scope.$watch('appState.models.simulationGrid.zScale', recalcValues);
    $scope.$watch('appState.models.simulationGrid.rCellsPerSpotSize', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.zCellsPerWavelength', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.rCellResolution', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.zCellResolution', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.rLength', recalcLength);
    $scope.$watch('appState.models.simulationGrid.zLength', recalcLength);
    $scope.$watch('appState.models.laserPulse.duration', recalcValues);
    $scope.$watch('appState.models.laserPulse.wavelength', recalcValues);
    $scope.$watch('appState.models.simulationGrid.zCount', recalcHistogramBins);

    $scope.$watch('appState.models.electronBeam.beamRadiusMethod', beamRadiusMethodChanged);
    $scope.$watch('appState.models.electronBeam.beamBunchLengthMethod', beamBunchLengthMethodChanged);
    $scope.$watch('appState.models.electronBeam.transverseEmittance', recalcRMSRadius);

    $scope.$on(
        'laserPulse.changed',
        function() {
            appState.saveQuietly('simulationGrid');
        });
    $scope.$on(
        'electronPlasma.changed',
        function() {
            if (appState.models.laserPulse.pulseDimensions == 'r') {
                appState.saveQuietly('laserPulse');
            }
            appState.saveQuietly('simulationGrid');
        });
    appState.whenModelsLoaded($scope, updateFieldState);
});

SIREPO.app.directive('appFooter', function() {
    return {
        restrict: 'A',
        scope: {
            nav: '=appFooter',
        },
        template: [
            '

',
            '

',
        ].join(''),
    };
});

SIREPO.app.directive('appHeader', function() {
    return {
        restrict: 'A',
        scope: {
            nav: '=appHeader',
        },
        template: [
            '

',
            '

',
            '
',
              '<app-header-right-sim-loaded>',
                '
',
                  '
 Source
',
                  '
 Dynamics
',
                '
',
              '</app-header-right-sim-loaded>',
              '<app-settings>',
                //  '
App-specific setting item
',
              '</app-settings>',
              '<app-header-right-sim-list>',
                '
',
                  '
 Import
',
                '
',
              '</app-header-right-sim-list>',
            '
',
        ].join(''),
    };
});
<commit_msg>cruft<commit_after>'use strict';

var srlog = SIREPO.srlog;
var srdbg = SIREPO.srdbg;

SIREPO.appDefaultSimulationValues.simulation.sourceType = 'laserPulse';

SIREPO.app.factory('warpPBAService', function(appState, $rootScope) {
    var self = {};
    self.laserGridDimensions = null;
    self.beamGridDimensions = null;

    function initGridDimensions() {
        if (self.laserGridDimensions) {
            return;
        }
        self.laserGridDimensions = appState.clone(SIREPO.APP_SCHEMA.enum.GridDimensions);
        self.beamGridDimensions = appState.clone(self.laserGridDimensions);
        self.laserGridDimensions.splice(2, 1);
        self.beamGridDimensions.splice(1, 1);
    }

    function isSourceType(sourceType) {
        if (appState.isLoaded()) {
            return appState.applicationState().simulation.sourceType == sourceType;
        }
        return false;
    }

    self.computeModel = function (analysisModel) {
        return 'animation';
    };

    self.isElectronBeam = function() {
        return isSourceType('electronBeam');
    };

    self.isLaserPulse = function() {
        return isSourceType('laserPulse');
    };

    appState.setAppService(self);

    appState.whenModelsLoaded($rootScope, function() {
        initGridDimensions();
        SIREPO.APP_SCHEMA.enum.GridDimensions = self.isLaserPulse()
            ? self.laserGridDimensions
            : self.beamGridDimensions;
    });
    return self;
});

SIREPO.app.controller('WarpPBADynamicsController', function(appState, frameCache, panelState, warpPBAService, persistentSimulation, $scope) {
    var self = this;
    self.panelState = panelState;

    function handleStatus(data) {
        if (data.frameCount) {
            frameCache.setFrameCount(parseInt(data.frameCount));
        }
    }

    self.isElectronBeam = function() {
        return warpPBAService.isElectronBeam();
    };

    self.simState = persistentSimulation.initSimulationState(
        $scope,
        warpPBAService.computeModel(),
        handleStatus
    );

    self.simState.initMessage = function() {
        return 'Initializing Laser Pulse and Plasma';
    };
});

SIREPO.app.controller('WarpPBASourceController', function(appState, frameCache, warpPBAService, $scope) {
    var self = this;
    $scope.appState = appState;
    var constants = {
        beamFactor: 0.728583,
        clight: 299792458.0,
        echarge: 1.602176565e-19,
        emass: 9.10938291e-31,
        eps0: 8.85418781762e-12,
    };

    function beamBunchLengthMethodChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamBunchLengthMethod == 'a';
        setVisibility(['electronBeam.rmsLength'], ! isAbsolute, oldValue);
        setReadOnly(['electronBeam.rmsLength'], true);
        setReadOnly(['electronBeam.bunchLength'], ! isAbsolute);
        recalcBeamBunchLength();
    }

    function beamRadiusMethodChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamRadiusMethod == 'a';
        setVisibility(['electronBeam.transverseEmittance'], ! isAbsolute, oldValue);
        setReadOnly(['electronBeam.rmsRadius'], ! isAbsolute);
        recalcRMSRadius();
    }

    function fieldClass(field) {
        return '.model-' + field.replace('.', '-');
    }

    function gridDimensionsChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var fields = {
            visible: ['simulationGrid.rScale', 'simulationGrid.zScale'],
            editable: ['simulationGrid.rLength', 'simulationGrid.zLength'],
        };
        var isAbsolute = appState.models.simulationGrid.gridDimensions == 'a';
        setVisibility(fields.visible, ! isAbsolute, oldValue);
        setReadOnly(fields.editable, ! isAbsolute);
        setReadOnly(['simulationGrid.rMin', 'simulationGrid.rMax', 'simulationGrid.zMin', 'simulationGrid.zMax', 'simulationGrid.rCount', 'simulationGrid.zCount'], true);
        var sourceFields = {
            laserPulse: ['simulationGrid.rCellsPerSpotSize', 'simulationGrid.zCellsPerWavelength'],
            electronBeam: ['simulationGrid.rCellResolution', 'simulationGrid.zCellResolution'],
        };
        setVisibility(sourceFields[self.isLaserPulse() ? 'laserPulse' : 'electronBeam'], true);
        setVisibility(sourceFields[self.isLaserPulse() ? 'electronBeam' : 'laserPulse'], false);
        recalcValues();
    }

    function lambdaLaser() {
        return appState.models.laserPulse.wavelength / 1e6;
    }

    function lambdaPlasma() {
        return 3.34e7 / Math.sqrt(appState.models.electronPlasma.density);
    }

    function pulseDimensionsChanged(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        var fields = {
            visible: ['laserPulse.length', 'laserPulse.spotSize'],
            editable: ['laserPulse.waist', 'laserPulse.duration'],
        };
        var isAbsolute = appState.models.laserPulse.pulseDimensions == 'a';
        setVisibility(fields.visible, ! isAbsolute, oldValue);
        setReadOnly(fields.editable, ! isAbsolute);
        recalcValues();
    }

    function recalcBeamBunchLength() {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamBunchLengthMethod == 'a';
        if (isAbsolute) {
            return;
        }

        var rmsMax = lambdaPlasma() / Math.PI;
        var rmsLength = constants.beamFactor * rmsMax;
        var xBunchHw = 3 * rmsLength;
        appState.models.electronBeam.rmsLength = rmsLength * 1e6;
        appState.models.electronBeam.bunchLength = 2 * xBunchHw * 1e6;
    }

    function recalcCellCount() {
        if (! appState.isLoaded()) {
            return;
        }
        var grid = appState.models.simulationGrid;
        if (self.isLaserPulse()) {
            var laserPulse = appState.models.laserPulse;
            var lambda = lambdaLaser();
            grid.zCount = Math.round((grid.zMax - grid.zMin) / 1e6 * grid.zCellsPerWavelength / lambda);
            grid.rCount = Math.round((grid.rMax - grid.rMin) * grid.rCellsPerSpotSize / laserPulse.waist);
        }
        else {
            grid.zCount = Math.round(grid.zScale * grid.zCellResolution);
            grid.rCount = Math.round(grid.rScale * grid.rCellResolution);
        }
    }

    function recalcHistogramBins(newValue, oldValue) {
        if (! appState.isLoaded()) {
            return;
        }
        if (newValue && oldValue) {
            appState.models.particleAnimation.histogramBins = newValue;
            //TODO(pjm): beam reports require a slight increase to match the grid
            appState.models.beamAnimation.histogramBins = newValue + 1;
            appState.models.beamPreviewReport.histogramBins = newValue + 1;
            appState.saveQuietly('particleAnimation');
            appState.saveQuietly('beamAnimation');
        }
    }

    function recalcLength() {
        if (! appState.isLoaded()) {
            return;
        }
        var grid = appState.models.simulationGrid;
        grid.rMax = grid.rLength;
        grid.zMin = - grid.zLength;
    }

    function recalcRMSRadius() {
        if (! appState.isLoaded()) {
            return;
        }
        var isAbsolute = appState.models.electronBeam.beamRadiusMethod == 'a';
        if (isAbsolute) {
            return;
        }
        var kPe = 2 * Math.PI / lambdaPlasma();
        var twissBetaMatch = Math.sqrt(2) / kPe;
        appState.models.electronBeam.rmsRadius = Math.sqrt(twissBetaMatch * parseFloat(appState.models.electronBeam.transverseEmittance)) * 1e6;
    }

    function recalcValues() {
        if (! appState.isLoaded()) {
            return;
        }
        var grid = appState.models.simulationGrid;
        if (self.isLaserPulse()) {
            var laserPulse = appState.models.laserPulse;
            var wplab = Math.sqrt(
                appState.models.electronPlasma.density
                    * Math.pow(constants.echarge, 2)
                    / (constants.eps0 * constants.emass));
            var kplab = wplab / constants.clight;
            // resonant wth plasma density
            if (laserPulse.pulseDimensions == 'r') {
                laserPulse.waist = (1e6 * laserPulse.spotSize / kplab).toFixed(12);
                laserPulse.duration = (1e12 * laserPulse.length / kplab / constants.clight).toFixed(12);
            }
            grid.rMin = 0;
            grid.zMax = (2.0 * lambdaLaser() * 1e6).toFixed(12);
            // scale to laser pulse
            if (grid.gridDimensions == 's') {
                grid.rLength = (grid.rScale * laserPulse.waist).toFixed(12);
                grid.zLength = (grid.zScale * laserPulse.duration / 1e6 * 4 * constants.clight).toFixed(12);
            }
        }
        else {
            var lambda = lambdaPlasma();
            grid.zMax = 0;
            if (grid.gridDimensions == 'e') {
                grid.rLength = 0.5 * grid.rScale * lambda * 1e6;
                grid.zLength = grid.zScale * lambda * 1e6;
            }
        }
        recalcLength();
        recalcCellCount();
        recalcRMSRadius();
        recalcBeamBunchLength();
    }

    function setReadOnly(fields, isReadOnly) {
        for (var i = 0; i < fields.length; i++) {
            $(fieldClass(fields[i]) + ' input').prop('readonly', isReadOnly);
        }
    }

    function setVisibility(fields, isVisible, oldValue) {
        for (var i = 0; i < fields.length; i++) {
            var el = $(fieldClass(fields[i])).closest('.form-group');
            if (isVisible) {
                if (oldValue) {
                    el.slideDown();
                }
            }
            else {
                if (oldValue) {
                    el.slideUp();
                }
                else {
                    el.hide();
                }
            }
        }
    }

    function updateFieldState() {
        gridDimensionsChanged();
        pulseDimensionsChanged();
        beamRadiusMethodChanged();
        beamBunchLengthMethodChanged();
    }

    self.isLaserPulse = function() {
        return warpPBAService.isLaserPulse();
    };

    self.isElectronBeam = function() {
        return warpPBAService.isElectronBeam();
    };

    $scope.$watch('appState.models.laserPulse.pulseDimensions', pulseDimensionsChanged);
    $scope.$watch('appState.models.laserPulse.length', recalcValues);
    $scope.$watch('appState.models.laserPulse.spotSize', recalcValues);
    $scope.$watch('appState.models.electronPlasma.density', recalcValues);
    $scope.$watch('appState.models.simulationGrid.gridDimensions', gridDimensionsChanged);
    $scope.$watch('appState.models.simulationGrid.rScale', recalcValues);
    $scope.$watch('appState.models.simulationGrid.zScale', recalcValues);
    $scope.$watch('appState.models.simulationGrid.rCellsPerSpotSize', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.zCellsPerWavelength', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.rCellResolution', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.zCellResolution', recalcCellCount);
    $scope.$watch('appState.models.simulationGrid.rLength', recalcLength);
    $scope.$watch('appState.models.simulationGrid.zLength', recalcLength);
    $scope.$watch('appState.models.laserPulse.duration', recalcValues);
    $scope.$watch('appState.models.laserPulse.wavelength', recalcValues);
    $scope.$watch('appState.models.simulationGrid.zCount', recalcHistogramBins);

    $scope.$watch('appState.models.electronBeam.beamRadiusMethod', beamRadiusMethodChanged);
    $scope.$watch('appState.models.electronBeam.beamBunchLengthMethod', beamBunchLengthMethodChanged);
    $scope.$watch('appState.models.electronBeam.transverseEmittance', recalcRMSRadius);

    $scope.$on(
        'laserPulse.changed',
        function() {
            appState.saveQuietly('simulationGrid');
        });
    $scope.$on(
        'electronPlasma.changed',
        function() {
            if (appState.models.laserPulse.pulseDimensions == 'r') {
                appState.saveQuietly('laserPulse');
            }
            appState.saveQuietly('simulationGrid');
        });
    appState.whenModelsLoaded($scope, updateFieldState);
});

SIREPO.app.directive('appFooter', function() {
    return {
        restrict: 'A',
        scope: {
            nav: '=appFooter',
        },
        template: [
            '

',
            '

',
        ].join(''),
    };
});

SIREPO.app.directive('appHeader', function() {
    return {
        restrict: 'A',
        scope: {
            nav: '=appHeader',
        },
        template: [
            '

',
            '

',
            '
',
              '<app-header-right-sim-loaded>',
                '
',
                  '
 Source
',
                  '
 Dynamics
',
                '
',
              '</app-header-right-sim-loaded>',
              '<app-settings>',
                //  '
App-specific setting item
',
              '</app-settings>',
              '<app-header-right-sim-list>',
                '
',
                  '
 Import
',
                '
',
              '</app-header-right-sim-list>',
            '
',
        ].join(''),
    };
});
<|endoftext|>


<commit_before>/* globals NexudusAccount */
var Slack = require('../services/Slack')
import randomstring from 'randomstring'
import HasSettings from './mixins/HasSettings'
import { merge, differenceBy } from 'lodash'

const defaultBanner = 'https://d3ngex8q79bk55.cloudfront.net/misc/default_community_banner.jpg'
const defaultAvatar = 'https://d3ngex8q79bk55.cloudfront.net/misc/default_community_avatar.png'
const axolotlId = '13986'

module.exports = bookshelf.Model.extend(merge({
  tableName: 'communities',

  creator: function () {
    return this.belongsTo(User, 'created_by_id')
  },

  inactiveUsers: function () {
    return this.belongsToMany(User, 'communities_users', 'community_id', 'user_id')
      .query({where: {'communities_users.active': false}})
  },

  invitations: function () {
    return this.hasMany(Invitation)
  },

  leader: function () {
    return this.belongsTo(User, 'leader_id')
  },

  tagFollows: function () {
    return this.hasMany(TagFollow)
  },

  memberships: function () {
    return this.hasMany(Membership).query({where: {'communities_users.active': true}})
  },

  moderators: function () {
    return this.belongsToMany(User, 'communities_users', 'community_id', 'user_id')
      .query({where: {role: Membership.MODERATOR_ROLE}})
  },

  network: function () {
    return this.belongsTo(Network)
  },

  users: function () {
    return this.belongsToMany(User).through(Membership)
      .query({where: {'communities_users.active': true, 'users.active': true}}).withPivot('role')
  },

  posts: function () {
    return this.belongsToMany(Post).through(PostMembership)
      .query({where: {'posts.active': true}})
  },

  tags: function () {
    return this.belongsToMany(Tag).through(CommunityTag).withPivot(['user_id', 'description'])
  },

  comments: function () {
    var communityId = this.id
    return Comment.collection().query(q => {
      q.where({
        'communities_posts.community_id': communityId,
        'comments.active': true
      })
      q.join('communities_posts', 'communities_posts.post_id', 'comments.post_id')
    })
  },

  nexudusAccounts: function () {
    this.hasMany(NexudusAccount)
  },

  createStarterPosts: function (transacting) {
    var now = new Date()
    var timeShift = {null: 0, intention: 1, offer: 2, request: 3}
    return Community.find('starter-posts', {withRelated: [
      'posts', 'posts.followers', 'posts.selectedTags'
    ]})
    .tap(c => {
      if (!c) throw new Error('Starter posts community not found')
    })
    .then(c => c.relations.posts.models)
    .then(posts => Promise.map(posts, post => {
      if (post.get('type') === 'welcome') return
      const tag = post.relations.selectedTags.first()
      const tagName = tag ? tag.get('name') : null

      var newPost = post.copy()
      var time = new Date(now - timeShift[tagName] * 1000)
      return newPost.save({created_at: time, updated_at: time}, {transacting})
      .then(() => Promise.all(_.flatten([
        this.posts().attach(newPost, {transacting}),
        tagName && Tag.find(tagName).then(tag =>
          newPost.tags().attach({tag_id: tag.id, selected: true}, {transacting})),
        post.relations.followers.map(u =>
          Follow.create(u.id, newPost.id, null, {transacting}))
      ])))
    }))
  },

  createStarterTags: function (userId, trx) {
    return Tag.starterTags(trx).then(tags =>
      Promise.map(tags.models, tag => new CommunityTag({
        community_id: this.id,
        is_default: true,
        tag_id: tag.id,
        user_id: userId,
        created_at: new Date()
      })
      .save({}, {transacting: trx})))
  },

  updateChecklist: function () {
    return this.load(['posts', 'invitations', 'tags'])
    .then(() => Tag.starterTags())
    .then(starterTags => {
      const { invitations, posts, tags } = this.relations

      this.addSetting({
        checklist: {
          logo: this.get('avatar_url') !== defaultAvatar,
          banner: this.get('banner_url') !== defaultBanner,
          invite: invitations.length > 0,
          topics: differenceBy(tags.models, starterTags.models, 'id').length > 0,
          post: !!posts.find(p => p.get('user_id') !== axolotlId)
        }
      })
      return this.save()
    })
  },

  popularSkills: function (limit = 15) {
    return Tag.query(q => {
      q.select(bookshelf.knex.raw('tags.name, count(*)'))
      q.join('tags_users', 'tags.id', 'tags_users.tag_id')
      q.join('communities_users', 'tags_users.user_id', 'communities_users.user_id')
      q.where('communities_users.community_id', this.id)
      q.where('communities_users.active', true)
      q.groupBy('tags.name')
      q.orderBy('count', 'desc')
      q.limit(limit)
    })
    .fetchAll()
    .then(skills => skills.pluck('name'))
  },

  memberCount: function () {
    return User.query(q => {
      q.select(bookshelf.knex.raw('count(*)'))
      q.join('communities_users', 'users.id', 'communities_users.user_id')
      q.where({'communities_users.community_id': this.id, 'communities_users.active': true})
    })
    .fetch()
    .then(result => result.get('count'))
  },

  postCount: function () {
    return Post.query(q => {
      q.select(bookshelf.knex.raw('count(*)'))
      q.join('communities_posts', 'posts.id', 'communities_posts.post_id')
      q.where({'communities_posts.community_id': this.id, 'active': true})
    })
    .fetch()
    .then(result => result.get('count'))
  }

}, HasSettings), {
  find: function (id_or_slug, opts = {}) {
    if (!id_or_slug) return Promise.resolve(null)

    let where = isNaN(Number(id_or_slug))
      ? (opts.active ? {slug: id_or_slug, active: true} : {slug: id_or_slug})
      : (opts.active ? {id: id_or_slug, active: true} : {id: id_or_slug})
    return this.where(where).fetch(opts)
  },

  findActive: function (id_or_slug, opts = {}) {
    return this.find(id_or_slug, merge({active: true}, opts))
  },

  canInvite: function (userId, communityId) {
    return Community.find(communityId).then(function (community) {
      if (community.get('settings').all_can_invite) return true
      return Membership.hasModeratorRole(userId, communityId)
    })
  },

  copyAssets: function (opts) {
    return Community.find(opts.communityId).then(c => Promise.join(
        AssetManagement.copyAsset(c, 'community', 'avatar_url'),
        AssetManagement.copyAsset(c, 'community', 'banner_url')
    ))
  },

  notifyAboutCreate: function (opts) {
    return Community.find(opts.communityId, {withRelated: ['creator']}).then(c => {
      var creator = c.relations.creator
      var recipient = process.env.ASANA_NEW_COMMUNITIES_EMAIL
      Email.sendRawEmail(recipient, {
        subject: c.get('name'),
        body: format(
          '%s
created by %s
%s
%s',
          Frontend.Route.community(c),
          creator.get('name'),
          creator.get('email'),
          Frontend.Route.profile(creator))
      }, {
        sender: {
          name: 'Hylobot',
          address: 'dev+bot@hylo.com'
        }
      })
    })
  },

  inNetworkWithUser: function (communityId, userId) {
    return Community.find(communityId)
    .then(community => community && community.get('network_id'))
    .then(networkId => networkId && Network.containsUser(networkId, userId))
  },

  notifySlack: function (communityId, post) {
    return Community.find(communityId)
    .then(community => {
      if (!community || !community.get('slack_hook_url')) return
      var slackMessage = Slack.textForNewPost(post, community)
      return Slack.send(slackMessage, community.get('slack_hook_url'))
    })
  },

  getNewAccessCode: function () {
    const test = code => Community.where({beta_access_code: code}).count().then(Number)
    const loop = () => {
      const code = randomstring.generate({length: 20, charset: 'alphanumeric'})
      return test(code).then(count => count ? loop() : code)
    }
    return loop()
  }
})
<commit_msg>modify new community email to be more zapier-friendly<commit_after>/* globals NexudusAccount */
var Slack = require('../services/Slack')
import randomstring from 'randomstring'
import HasSettings from './mixins/HasSettings'
import { merge, differenceBy } from 'lodash'

const defaultBanner = 'https://d3ngex8q79bk55.cloudfront.net/misc/default_community_banner.jpg'
const defaultAvatar = 'https://d3ngex8q79bk55.cloudfront.net/misc/default_community_avatar.png'
const axolotlId = '13986'

module.exports = bookshelf.Model.extend(merge({
  tableName: 'communities',

  creator: function () {
    return this.belongsTo(User, 'created_by_id')
  },

  inactiveUsers: function () {
    return this.belongsToMany(User, 'communities_users', 'community_id', 'user_id')
      .query({where: {'communities_users.active': false}})
  },

  invitations: function () {
    return this.hasMany(Invitation)
  },

  leader: function () {
    return this.belongsTo(User, 'leader_id')
  },

  tagFollows: function () {
    return this.hasMany(TagFollow)
  },

  memberships: function () {
    return this.hasMany(Membership).query({where: {'communities_users.active': true}})
  },

  moderators: function () {
    return this.belongsToMany(User, 'communities_users', 'community_id', 'user_id')
      .query({where: {role: Membership.MODERATOR_ROLE}})
  },

  network: function () {
    return this.belongsTo(Network)
  },

  users: function () {
    return this.belongsToMany(User).through(Membership)
      .query({where: {'communities_users.active': true, 'users.active': true}}).withPivot('role')
  },

  posts: function () {
    return this.belongsToMany(Post).through(PostMembership)
      .query({where: {'posts.active': true}})
  },

  tags: function () {
    return this.belongsToMany(Tag).through(CommunityTag).withPivot(['user_id', 'description'])
  },

  comments: function () {
    var communityId = this.id
    return Comment.collection().query(q => {
      q.where({
        'communities_posts.community_id': communityId,
        'comments.active': true
      })
      q.join('communities_posts', 'communities_posts.post_id', 'comments.post_id')
    })
  },

  nexudusAccounts: function () {
    this.hasMany(NexudusAccount)
  },

  createStarterPosts: function (transacting) {
    var now = new Date()
    var timeShift = {null: 0, intention: 1, offer: 2, request: 3}
    return Community.find('starter-posts', {withRelated: [
      'posts', 'posts.followers', 'posts.selectedTags'
    ]})
    .tap(c => {
      if (!c) throw new Error('Starter posts community not found')
    })
    .then(c => c.relations.posts.models)
    .then(posts => Promise.map(posts, post => {
      if (post.get('type') === 'welcome') return
      const tag = post.relations.selectedTags.first()
      const tagName = tag ? tag.get('name') : null

      var newPost = post.copy()
      var time = new Date(now - timeShift[tagName] * 1000)
      return newPost.save({created_at: time, updated_at: time}, {transacting})
      .then(() => Promise.all(_.flatten([
        this.posts().attach(newPost, {transacting}),
        tagName && Tag.find(tagName).then(tag =>
          newPost.tags().attach({tag_id: tag.id, selected: true}, {transacting})),
        post.relations.followers.map(u =>
          Follow.create(u.id, newPost.id, null, {transacting}))
      ])))
    }))
  },

  createStarterTags: function (userId, trx) {
    return Tag.starterTags(trx).then(tags =>
      Promise.map(tags.models, tag => new CommunityTag({
        community_id: this.id,
        is_default: true,
        tag_id: tag.id,
        user_id: userId,
        created_at: new Date()
      })
      .save({}, {transacting: trx})))
  },

  updateChecklist: function () {
    return this.load(['posts', 'invitations', 'tags'])
    .then(() => Tag.starterTags())
    .then(starterTags => {
      const { invitations, posts, tags } = this.relations

      this.addSetting({
        checklist: {
          logo: this.get('avatar_url') !== defaultAvatar,
          banner: this.get('banner_url') !== defaultBanner,
          invite: invitations.length > 0,
          topics: differenceBy(tags.models, starterTags.models, 'id').length > 0,
          post: !!posts.find(p => p.get('user_id') !== axolotlId)
        }
      })
      return this.save()
    })
  },

  popularSkills: function (limit = 15) {
    return Tag.query(q => {
      q.select(bookshelf.knex.raw('tags.name, count(*)'))
      q.join('tags_users', 'tags.id', 'tags_users.tag_id')
      q.join('communities_users', 'tags_users.user_id', 'communities_users.user_id')
      q.where('communities_users.community_id', this.id)
      q.where('communities_users.active', true)
      q.groupBy('tags.name')
      q.orderBy('count', 'desc')
      q.limit(limit)
    })
    .fetchAll()
    .then(skills => skills.pluck('name'))
  },

  memberCount: function () {
    return User.query(q => {
      q.select(bookshelf.knex.raw('count(*)'))
      q.join('communities_users', 'users.id', 'communities_users.user_id')
      q.where({'communities_users.community_id': this.id, 'communities_users.active': true})
    })
    .fetch()
    .then(result => result.get('count'))
  },

  postCount: function () {
    return Post.query(q => {
      q.select(bookshelf.knex.raw('count(*)'))
      q.join('communities_posts', 'posts.id', 'communities_posts.post_id')
      q.where({'communities_posts.community_id': this.id, 'active': true})
    })
    .fetch()
    .then(result => result.get('count'))
  }

}, HasSettings), {
  find: function (id_or_slug, opts = {}) {
    if (!id_or_slug) return Promise.resolve(null)

    let where = isNaN(Number(id_or_slug))
      ? (opts.active ? {slug: id_or_slug, active: true} : {slug: id_or_slug})
      : (opts.active ? {id: id_or_slug, active: true} : {id: id_or_slug})
    return this.where(where).fetch(opts)
  },

  findActive: function (id_or_slug, opts = {}) {
    return this.find(id_or_slug, merge({active: true}, opts))
  },

  canInvite: function (userId, communityId) {
    return Community.find(communityId).then(function (community) {
      if (community.get('settings').all_can_invite) return true
      return Membership.hasModeratorRole(userId, communityId)
    })
  },

  copyAssets: function (opts) {
    return Community.find(opts.communityId).then(c => Promise.join(
        AssetManagement.copyAsset(c, 'community', 'avatar_url'),
        AssetManagement.copyAsset(c, 'community', 'banner_url')
    ))
  },

  notifyAboutCreate: function (opts) {
    return Community.find(opts.communityId, {withRelated: ['creator']})
    .then(c => {
      var creator = c.relations.creator
      var recipient = process.env.ASANA_NEW_COMMUNITIES_EMAIL
      return Email.sendRawEmail(recipient, {
        subject: c.get('name'),
        body: `Community
          ${c.get('name')}
          Email
          ${creator.get('email')}
          First Name
          ${creator.get('name').split(' ')[0]}
          Last Name
          ${creator.get('name').split(' ').slice(1).join(' ')}
          Community URL
          ${Frontend.Route.community(c)}
          Creator URL
          ${Frontend.Route.profile(creator)}
        `.replace(/^\s+/gm, '').replace(/\n/g, '
\n')
      }, {
        sender: {
          name: 'Hylobot',
          address: 'dev+bot@hylo.com'
        }
      })
    })
  },

  inNetworkWithUser: function (communityId, userId) {
    return Community.find(communityId)
    .then(community => community && community.get('network_id'))
    .then(networkId => networkId && Network.containsUser(networkId, userId))
  },

  notifySlack: function (communityId, post) {
    return Community.find(communityId)
    .then(community => {
      if (!community || !community.get('slack_hook_url')) return
      var slackMessage = Slack.textForNewPost(post, community)
      return Slack.send(slackMessage, community.get('slack_hook_url'))
    })
  },

  getNewAccessCode: function () {
    const test = code => Community.where({beta_access_code: code}).count().then(Number)
    const loop = () => {
      const code = randomstring.generate({length: 20, charset: 'alphanumeric'})
      return test(code).then(count => count ? loop() : code)
    }
    return loop()
  }
})
<|endoftext|>