<commit_before>'use strict'
var signMsgCtrl = function($scope, $sce, walletService) {
    walletService.wallet = null;
    $scope.visibility = "signView";
    $scope.$watch(function() {
        if (walletService.wallet == null) return null
        return walletService.wallet.getAddressString()
    }, function() {
        if (walletService.wallet == null) return
        $scope.wallet = walletService.wallet
    });
    $scope.signMsg = {
        message: '',
        status: '',
        signedMsg: ''
    }
    $scope.verifyMsg = {
        signedMsg: '',
        status: ''
    }

    $scope.generateSignedMsg = function() {
        try {
            var thisMessage = $scope.signMsg.message
            var hwType = $scope.wallet.getHWType()

            // Sign via MetaMask
            if ((typeof hwType != "undefined") && (hwType == "web3")) {

                var msg = ethUtil.bufferToHex(new Buffer(thisMessage, 'utf8'))
                var signingAddr = web3.eth.accounts[0]
                var params = [msg, signingAddr]
                var method = 'personal_sign'
                $scope.notifier.info("Sent message for signing via MetaMask / Mist.")

                web3.currentProvider.sendAsync({
                    method,
                    params,
                    signingAddr,
                }, function(err, result) {
                    if (err) return $scope.notifier.danger(err)
                    if (result.error) return $scope.notifier.danger(result.error)
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: signingAddr,
                        msg: thisMessage,
                        sig: result.result,
                        version: '3',
                        signer: 'web3'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr)
                })

                // Sign via Ledger
            } else if ((typeof hwType != "undefined") && (hwType == "ledger")) {
                var msg = Buffer.from(thisMessage).toString("hex")
                var app = new ledgerEth($scope.wallet.getHWTransport());
                var localCallback = function(signed, error) {
                    if (typeof error != "undefined") {
                        error = error.errorCode ? u2f.getErrorByCode(error.errorCode) : error;
                        if (callback !== undefined) callback({
                            isError: true,
                            error: error
                        });
                        return;
                    }
                    var combined = signed['r'] + signed['s'] + signed['v']
                    var combinedHex = combined.toString('hex')
                    var signingAddr = $scope.wallet.getAddressString()
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: $scope.wallet.getAddressString(),
                        msg: thisMessage,
                        sig: '0x' + combinedHex,
                        version: '3',
                        signer: 'ledger'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr)
                }
                app.signPersonalMessage_async($scope.wallet.getPath(), msg, localCallback);

                // Sign via Digital Bitbox
            } else if ((typeof hwType != "undefined") && (hwType == "digitalBitbox")) {
                var msg = ethUtil.hashPersonalMessage(ethUtil.toBuffer(thisMessage));
                var localCallback = function(signed, error) {
                    if (typeof error != "undefined") {
                        error = error.errorCode ? u2f.getErrorByCode(error.errorCode) : error;
                        $scope.notifier.danger(error);
                        return;
                    }
                    var combined = signed['r'] + signed['s'] + signed['v']
                    var combinedHex = combined.toString('hex')
                    var signingAddr = $scope.wallet.getAddressString()
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: $scope.wallet.getAddressString(),
                        msg: thisMessage,
                        sig: '0x' + combinedHex,
                        version: '3',
                        signer: 'digitalBitbox'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr);
                }
                $scope.notifier.info("Touch the LED for 3 seconds to sign the message. Or tap the LED to cancel.");
                var app = new DigitalBitboxEth($scope.wallet.getHWTransport(), '');
                app.signMessage($scope.wallet.getPath(), msg, localCallback);

            // Sign via Secalot
            } else if ((typeof hwType != "undefined") && (hwType == "secalot")) {

                var localCallback = function(signed, error) {
                    if (typeof error != "undefined") {
                        error = error.errorCode ? u2f.getErrorByCode(error.errorCode) : error;
                        $scope.notifier.danger(error);
                        return;
                    }
                    var combined    = signed['r'] + signed['s'] + signed['v']
                    var combinedHex = combined.toString('hex')
                    var signingAddr = $scope.wallet.getAddressString()
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: $scope.wallet.getAddressString(),
                        msg: thisMessage,
                        sig: '0x' + combinedHex,
                        version: '3',
                        signer: 'secalot'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr);
                }
                $scope.notifier.info("Tap a touch button on your device to confirm signing.");
                var app = new SecalotEth($scope.wallet.getHWTransport());
                app.signMessage($scope.wallet.getPath(), thisMessage, localCallback);

            // Sign via trezor
            } else if ((typeof hwType != "undefined") && (hwType == "trezor")) {
                TrezorConnect.ethereumSignMessage($scope.wallet.getPath(), thisMessage, function(response) {
                    if (response.success) {
                        $scope.signMsg.signedMsg = JSON.stringify({
                            address: '0x' + response.address,
                            msg: thisMessage,
                            sig: '0x' + response.signature,
                            version: '3',
                            signer: 'trezor'
                        }, null, 2)
                        $scope.notifier.success('Successfully Signed Message with ' + $scope.wallet.getAddressString())
                    } else {
                        $scope.notifier.danger(response.error);
                    }
                })

                // Sign via PK
            } else {
                var msg = ethUtil.hashPersonalMessage(ethUtil.toBuffer(thisMessage))
                var signed = ethUtil.ecsign(msg, $scope.wallet.getPrivateKey())
                var combined = Buffer.concat([Buffer.from(signed.r), Buffer.from(signed.s), Buffer.from([signed.v])])
                var combinedHex = combined.toString('hex')
                var signingAddr = $scope.wallet.getAddressString()
                $scope.signMsg.signedMsg = JSON.stringify({
                    address: $scope.wallet.getAddressString(),
                    msg: thisMessage,
                    sig: '0x' + combinedHex,
                    version: '3',
                    signer: 'MEW'
                }, null, 2)
                $scope.notifier.success('Successfully Signed Message with ' + signingAddr)
            }

        } catch (e) {
            $scope.notifier.danger(e)
        }
    }
    var getTrezorLenBuf = function(msgLen) {
        if (msgLen < 253) return Buffer.from([msgLen & 0xff])
        else if (msgLen < 0x10000) return Buffer.from([253, msgLen & 0xff, (msgLen >> 8) & 0xFF])
        else {
            return Buffer.from([254, msgLen & 0xFF, (msgLen >> 8) & 0xFF, (msgLen >> 16) & 0xFF, (msgLen >> 24) & 0xFF])
        }
    }
    var getTrezorHash = function(msg) {
        return ethUtil.sha3(Buffer.concat([ethUtil.toBuffer("\u0019Ethereum Signed Message:\n"), getTrezorLenBuf(msg.length), ethUtil.toBuffer(msg)]))
    }
    ethUtil.Buffer = Buffer
    $scope.verifySignedMessage = function() {
        try {
            var json = JSON.parse($scope.verifyMsg.signedMsg)
            var sig = new Buffer(ethFuncs.getNakedAddress(json.sig), 'hex')
            if (sig.length != 65) throw globalFuncs.errorMsgs[12]
            sig[64] = sig[64] == 0 || sig[64] == 1 ? sig[64] + 27 : sig[64]
            var hash = ethUtil.hashPersonalMessage(ethUtil.toBuffer(json.msg))
            if (json.version == '3') {
                if (json.signer == 'trezor') {
                    hash = getTrezorHash(json.msg)
                } else if(json.signer=='ledger') {
                    hash = ethUtil.hashPersonalMessage(Buffer.from(json.msg))
                }
            } else if (json.version == '1') {
                hash = ethUtil.sha3(json.msg)
            }
            var pubKey = ethUtil.ecrecover(hash, sig[64], sig.slice(0, 32), sig.slice(32, 64))
            if (ethFuncs.getNakedAddress(json.address) != ethUtil.pubToAddress(pubKey).toString('hex')) throw globalFuncs.errorMsgs[12]
            else {
                $scope.notifier.success(globalFuncs.successMsgs[6])
                $scope.verifiedMsg = {
                    address: json.address,
                    msg: json.msg,
                    sig: json.sig,
                    version: json.version
                }
            }
        } catch (e) {
            $scope.notifier.danger(e);
        }
    }

    $scope.setVisibility = function(str) {
        $scope.visibility = str;
    }

}
module.exports = signMsgCtrl<commit_msg>cleanup<commit_after>'use strict'
var signMsgCtrl = function($scope, $sce, walletService) {
    walletService.wallet = null;
    $scope.visibility = "signView";
    $scope.$watch(function() {
        if (walletService.wallet == null) return null
        return walletService.wallet.getAddressString()
    }, function() {
        if (walletService.wallet == null) return
        $scope.wallet = walletService.wallet
    });
    $scope.signMsg = {
        message: '',
        status: '',
        signedMsg: ''
    }
    $scope.verifyMsg = {
        signedMsg: '',
        status: ''
    }

    $scope.generateSignedMsg = function() {
        try {
            var thisMessage = $scope.signMsg.message
            var hwType = $scope.wallet.getHWType()

            // Sign via MetaMask
            if ((typeof hwType != "undefined") && (hwType == "web3")) {

                var msg = ethUtil.bufferToHex(new Buffer(thisMessage, 'utf8'))
                var signingAddr = web3.eth.accounts[0]
                var params = [msg, signingAddr]
                var method = 'personal_sign'
                $scope.notifier.info("Sent message for signing via MetaMask / Mist.")

                web3.currentProvider.sendAsync({
                    method,
                    params,
                    signingAddr,
                }, function(err, result) {
                    if (err) return $scope.notifier.danger(err)
                    if (result.error) return $scope.notifier.danger(result.error)
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: signingAddr,
                        msg: thisMessage,
                        sig: result.result,
                        version: '3',
                        signer: 'web3'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr)
                })

                // Sign via Ledger
            } else if ((typeof hwType != "undefined") && (hwType == "ledger")) {
                var msg = Buffer.from(thisMessage).toString("hex")
                var app = new ledgerEth($scope.wallet.getHWTransport());
                var localCallback = function(signed, error) {
                    if (typeof error != "undefined") {
                        error = error.errorCode ? u2f.getErrorByCode(error.errorCode) : error;
                        if (callback !== undefined) callback({
                            isError: true,
                            error: error
                        });
                        return;
                    }
                    var combined = signed['r'] + signed['s'] + signed['v']
                    var combinedHex = combined.toString('hex')
                    var signingAddr = $scope.wallet.getAddressString()
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: $scope.wallet.getAddressString(),
                        msg: thisMessage,
                        sig: '0x' + combinedHex,
                        version: '3',
                        signer: 'ledger'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr)
                }
                app.signPersonalMessage_async($scope.wallet.getPath(), msg, localCallback);

                // Sign via Digital Bitbox
            } else if ((typeof hwType != "undefined") && (hwType == "digitalBitbox")) {
                var msg = ethUtil.hashPersonalMessage(ethUtil.toBuffer(thisMessage));
                var localCallback = function(signed, error) {
                    if (typeof error != "undefined") {
                        error = error.errorCode ? u2f.getErrorByCode(error.errorCode) : error;
                        $scope.notifier.danger(error);
                        return;
                    }
                    var combined = signed['r'] + signed['s'] + signed['v']
                    var combinedHex = combined.toString('hex')
                    var signingAddr = $scope.wallet.getAddressString()
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: $scope.wallet.getAddressString(),
                        msg: thisMessage,
                        sig: '0x' + combinedHex,
                        version: '3',
                        signer: 'digitalBitbox'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr);
                }
                $scope.notifier.info("Touch the LED for 3 seconds to sign the message. Or tap the LED to cancel.");
                var app = new DigitalBitboxEth($scope.wallet.getHWTransport(), '');
                app.signMessage($scope.wallet.getPath(), msg, localCallback);

            // Sign via Secalot
            } else if ((typeof hwType != "undefined") && (hwType == "secalot")) {

                var localCallback = function(signed, error) {
                    if (typeof error != "undefined") {
                        error = error.errorCode ? u2f.getErrorByCode(error.errorCode) : error;
                        $scope.notifier.danger(error);
                        return;
                    }
                    var combined    = signed['r'] + signed['s'] + signed['v']
                    var combinedHex = combined.toString('hex')
                    var signingAddr = $scope.wallet.getAddressString()
                    $scope.signMsg.signedMsg = JSON.stringify({
                        address: $scope.wallet.getAddressString(),
                        msg: thisMessage,
                        sig: '0x' + combinedHex,
                        version: '3',
                        signer: 'secalot'
                    }, null, 2)
                    $scope.notifier.success('Successfully Signed Message with ' + signingAddr);
                }
                $scope.notifier.info("Tap a touch button on your device to confirm signing.");
                var app = new SecalotEth($scope.wallet.getHWTransport());
                app.signMessage($scope.wallet.getPath(), thisMessage, localCallback);

            // Sign via trezor
            } else if ((typeof hwType != "undefined") && (hwType == "trezor")) {
                TrezorConnect.ethereumSignMessage($scope.wallet.getPath(), thisMessage, function(response) {
                    if (response.success) {
                        $scope.signMsg.signedMsg = JSON.stringify({
                            address: '0x' + response.address,
                            msg: thisMessage,
                            sig: '0x' + response.signature,
                            version: '3',
                            signer: 'trezor'
                        }, null, 2)
                        $scope.notifier.success('Successfully Signed Message with ' + $scope.wallet.getAddressString())
                    } else {
                        $scope.notifier.danger(response.error);
                    }
                })

                // Sign via PK
            } else {
                var msg = ethUtil.hashPersonalMessage(ethUtil.toBuffer(thisMessage))
                var signed = ethUtil.ecsign(msg, $scope.wallet.getPrivateKey())
                var combined = Buffer.concat([Buffer.from(signed.r), Buffer.from(signed.s), Buffer.from([signed.v])])
                var combinedHex = combined.toString('hex')
                var signingAddr = $scope.wallet.getAddressString()
                $scope.signMsg.signedMsg = JSON.stringify({
                    address: $scope.wallet.getAddressString(),
                    msg: thisMessage,
                    sig: '0x' + combinedHex,
                    version: '3',
                    signer: 'MEW'
                }, null, 2)
                $scope.notifier.success('Successfully Signed Message with ' + signingAddr)
            }

        } catch (e) {
            $scope.notifier.danger(e)
        }
    }
    var getTrezorLenBuf = function(msgLen) {
        if (msgLen < 253) return Buffer.from([msgLen & 0xff])
        else if (msgLen < 0x10000) return Buffer.from([253, msgLen & 0xff, (msgLen >> 8) & 0xFF])
        else {
            return Buffer.from([254, msgLen & 0xFF, (msgLen >> 8) & 0xFF, (msgLen >> 16) & 0xFF, (msgLen >> 24) & 0xFF])
        }
    }
    var getTrezorHash = function(msg) {
        return ethUtil.sha3(Buffer.concat([ethUtil.toBuffer("\u0019Ethereum Signed Message:\n"), getTrezorLenBuf(msg.length), ethUtil.toBuffer(msg)]))
    }
    $scope.verifySignedMessage = function() {
        try {
            var json = JSON.parse($scope.verifyMsg.signedMsg)
            var sig = new Buffer(ethFuncs.getNakedAddress(json.sig), 'hex')
            if (sig.length != 65) throw globalFuncs.errorMsgs[12]
            sig[64] = sig[64] == 0 || sig[64] == 1 ? sig[64] + 27 : sig[64]
            var hash = ethUtil.hashPersonalMessage(ethUtil.toBuffer(json.msg))
            if (json.version == '3') {
                if (json.signer == 'trezor') {
                    hash = getTrezorHash(json.msg)
                } else if(json.signer=='ledger') {
                    hash = ethUtil.hashPersonalMessage(Buffer.from(json.msg))
                }
            } else if (json.version == '1') {
                hash = ethUtil.sha3(json.msg)
            }
            var pubKey = ethUtil.ecrecover(hash, sig[64], sig.slice(0, 32), sig.slice(32, 64))
            if (ethFuncs.getNakedAddress(json.address) != ethUtil.pubToAddress(pubKey).toString('hex')) throw globalFuncs.errorMsgs[12]
            else {
                $scope.notifier.success(globalFuncs.successMsgs[6])
                $scope.verifiedMsg = {
                    address: json.address,
                    msg: json.msg,
                    sig: json.sig,
                    version: json.version
                }
            }
        } catch (e) {
            $scope.notifier.danger(e);
        }
    }

    $scope.setVisibility = function(str) {
        $scope.visibility = str;
    }

}
module.exports = signMsgCtrl<|endoftext|>


<commit_before>var request = require('supertest');
var app = require('../app.js');

describe('GET /', function() {
  it('should return 200 OK', function(done) {
    request(app)
      .get('/')
      .expect(200, done);
  });
});<commit_msg>Added a failing test for travis-ci<commit_after>var request = require('supertest');
var app = require('../app.js');

describe('GET /', function() {
  it('should return 200 OK', function(done) {
    request(app)
      .get('/')
      .expect(200, done);
  });
});

describe('GET /reset', function() {
  it('should load password reset page', function(done) {
    request(app)
      .get('/reset')
      .expect(200, done);
    // this will fail
  });
});<|endoftext|>


<commit_before>
var Panel = {

    // Initizalize the panel once for all
    init : function() {

        // Set the selected zoo in function of the URL
        var data = Tools.getUrlData();
        if(data.zoo) {
            $('#zoo select').val(data.zoo);
        }
        $('#zoo select').trigger('change');

        // Make the panel parts collapsible
        $('#panel').accordion({
          active : 3, // By default, the contextual panel will be active
          collapsible : true,
          header: 'legend',
          heightStyle: 'content'
        });

        Filter.init();
        Contextual.init();
        Diffs.init();
        Legend.init();
    },

    // Call this once per database
    create : function() {
        Filter.create();
        Contextual.create();
        Diffs.create();
        Legend.create();
        this.createZooPanel();
    },

    createZooPanel : function() {
        var about = Zoo.meta.about || {};
        var div = $('#zoo > div');
        if(about.description) {
            div.append('
About
');
            div.append('
' + about.description + '
');
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub, div.find('p').get(0)]);
    },

    disable: function() {
        $('#block').show();

    },

    enable: function() {
        $('#block').hide();
    }
};
<commit_msg>Fixed a bug in the about section.<commit_after>
var Panel = {

    // Initizalize the panel once for all
    init : function() {

        // Set the selected zoo in function of the URL
        var data = Tools.getUrlData();
        if(data.zoo) {
            $('#zoo select').val(data.zoo);
        }
        $('#zoo select').trigger('change');

        // Make the panel parts collapsible
        $('#panel').accordion({
          active : 3, // By default, the contextual panel will be active
          collapsible : true,
          header: 'legend',
          heightStyle: 'content'
        });

        Filter.init();
        Contextual.init();
        Diffs.init();
        Legend.init();
    },

    // Call this once per database
    create : function() {
        Filter.create();
        Contextual.create();
        Diffs.create();
        Legend.create();
        this.createZooPanel();
    },

    createZooPanel : function() {
        var about = Zoo.meta.about || {};
        var div = $('#zoo > div');
        if(about.description) {
            div.append('
About
');
            div.append('
' + about.description + '
');
        }
        else {
            div.find('.about').remove();
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub, div.find('p').get(0)]);
    },

    disable: function() {
        $('#block').show();

    },

    enable: function() {
        $('#block').hide();
    }
};
<|endoftext|>


<commit_before>const nest = require('depnest')
const { h } = require('mutant')

exports.gives = nest('app.html.scroller')

exports.create = function (api) {
  return nest('app.html.scroller', Scroller)

  function Scroller (opts = {}) {
    const { prepend, content = null, append, classList = [], className = '', title = '', scrollIntoView } = opts

    const contentSection = h('section.content', { title: '' }, content)

    const container = h('Scroller',
      {
        classList,
        className,
        title,
        style: { 'overflow-y': 'scroll', 'overflow-x': 'auto' },
        intersectionBindingViewport: { rootMargin: '1000px' } // mutant magic
        // TODO (watch for breaks e.g. stuff stops updating after scrolling)
      },
      [
        prepend ? h('section.top', prepend) : null,
        contentSection,
        append ? h('section.bottom', append) : null
      ]
    )

    container.keyboardScroll = KeyboardScroll(contentSection, scrollIntoView)

    return {
      content: contentSection,
      container
    }
  }
}

function KeyboardScroll (content, scrollIntoView = false) {
  var curMsgEl

  if (!content) return () => {}

  content.addEventListener('click', onActivateChild, false)
  content.addEventListener('focus', onActivateChild, true)

  function onActivateChild (ev) {
    for (var el = ev.target; el; el = el.parentNode) {
      if (el.parentNode === content) {
        curMsgEl = el
        return
      }
    }
  }

  return function scroll (d) {
    const child = (!curMsgEl || d === 'first') ? content.firstChild
      : (!curMsgEl || d === 'last') ? content.lastChild
        : d < 0 ? curMsgEl.previousElementSibling || content.firstChild
          : d > 0 ? curMsgEl.nextElementSibling || content.lastChild
            : curMsgEl

    selectChild(child)
    curMsgEl = child

    return curMsgEl
  }

  function selectChild (el) {
    if (!el) { return }

    if (scrollIntoView) {
      if (!el.scrollIntoViewIfNeeded && !el.scrollIntoView) return
      ;(el.scrollIntoViewIfNeeded || el.scrollIntoView).call(el)
    } else {
      const height = el.offsetTop - content.parentElement.offsetTop - 10
      // content.parentElement.scroll({ top: height, behavior: 'smooth' })
      content.parentElement.scrollTop = height
    }

    if (el.focus) el.focus()
  }
}
<commit_msg>Only do intersectionBindingViewport on the scrolling element, fixes filter in /public and new in books<commit_after>const nest = require('depnest')
const { h } = require('mutant')

exports.gives = nest('app.html.scroller')

exports.create = function (api) {
  return nest('app.html.scroller', Scroller)

  function Scroller (opts = {}) {
    const { prepend, content = null, append, classList = [], className = '', title = '', scrollIntoView } = opts

    const contentSection = h('section.content', {
      title: '',
      intersectionBindingViewport: { rootMargin: '1000px' } // mutant magic
    }, content)

    const container = h('Scroller',
      {
        classList,
        className,
        title,
        style: { 'overflow-y': 'scroll', 'overflow-x': 'auto' },
        // TODO (watch for breaks e.g. stuff stops updating after scrolling)
      },
      [
        prepend ? h('section.top', prepend) : null,
        contentSection,
        append ? h('section.bottom', append) : null
      ]
    )

    container.keyboardScroll = KeyboardScroll(contentSection, scrollIntoView)

    return {
      content: contentSection,
      container
    }
  }
}

function KeyboardScroll (content, scrollIntoView = false) {
  var curMsgEl

  if (!content) return () => {}

  content.addEventListener('click', onActivateChild, false)
  content.addEventListener('focus', onActivateChild, true)

  function onActivateChild (ev) {
    for (var el = ev.target; el; el = el.parentNode) {
      if (el.parentNode === content) {
        curMsgEl = el
        return
      }
    }
  }

  return function scroll (d) {
    const child = (!curMsgEl || d === 'first') ? content.firstChild
      : (!curMsgEl || d === 'last') ? content.lastChild
        : d < 0 ? curMsgEl.previousElementSibling || content.firstChild
          : d > 0 ? curMsgEl.nextElementSibling || content.lastChild
            : curMsgEl

    selectChild(child)
    curMsgEl = child

    return curMsgEl
  }

  function selectChild (el) {
    if (!el) { return }

    if (scrollIntoView) {
      if (!el.scrollIntoViewIfNeeded && !el.scrollIntoView) return
      ;(el.scrollIntoViewIfNeeded || el.scrollIntoView).call(el)
    } else {
      const height = el.offsetTop - content.parentElement.offsetTop - 10
      // content.parentElement.scroll({ top: height, behavior: 'smooth' })
      content.parentElement.scrollTop = height
    }

    if (el.focus) el.focus()
  }
}
<|endoftext|>


<commit_before>var dashboardView = Backbone.View.extend({
  el: '#content',
  updateInterval: 1000, // 1 second, constant
  updateFrequency: 5, // the actual update rate (5 s)
  updateCounter: 0,
  arraySize: 99, // how many values will we keep per figure?
  seriesData: {},
  charts: {},
  units: [],
  detailGraph: "userTime",

  initialize: function () {
    var self = this;

    this.initUnits();

    this.collection.fetch({
      success: function() {
        self.calculateSeries();
        self.renderCharts();

        window.setInterval(function() {
          self.updateCounter++;

          if (self.updateCounter < self.updateFrequency) {
            return false;
          }

          self.updateCounter = 0;
          self.collection.fetch({
            success: function() {
              self.calculateSeries();
              self.renderCharts();
            },
            error: function() {
              // need to flush previous values
              self.calculateSeries(true);
              self.renderCharts();
              arangoHelper.arangoError("Lost connection to Database!");
            }
          });

        }, self.updateInterval);
      }
    });
  },

  events: {
    "click .dashboard-dropdown li" : "checkEnabled",
    "click .interval-dropdown li" : "checkInterval",
    "click .db-zoom" : "renderDetailChart",
    "click .db-minimize" : "checkDetailChart",
    "click .db-hide" : "hideChart"
  },

  template: new EJS({url: 'js/templates/dashboardView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);

    //Client calculated charts
    self.genCustomCategory("Client calculated charts", "custom", "Customized Charts");
    self.genCustomChart();

    $.each(this.options.description.models[0].attributes.groups, function () {
      $('.thumbnails').append(
        '
' +
        '
' + this.name + '
' +
        '
');
      $('#menuGroups').append(
        '
' + this.name + '
' +
        '

'
      );
    });

    $.each(this.options.description.models[0].attributes.figures, function () {
      self.renderFigure(this);
    });

    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    if (this.collection.models[0] === undefined) {
      this.collection.fetch({
        success: function() {
          self.calculateSeries();
          self.renderCharts();
        },
        error: function() {
          self.calculateSeries();
          self.renderCharts(flush);
        }
      });
    }
    else {
      self.calculateSeries();
      self.renderCharts();
    }
    return this;
  },
  genCustomCategory: function(description, group, name) {
    this.options.description.models[0].attributes.groups.push({
      "description":description,
      "group":group,
      "name":name
    });
  },
  genCustomChart: function () {
    //totalTime
    var figure = {
      "description" : "userTime + systemTime",
      "group" : "custom",
      "identifier" : "totalTime2",
      "name" : "Total Time (User+System)",
      "type" : "accumulated",
      "units" : "seconds"
    };
    this.options.description.models[0].attributes.figures.push(figure);
    this.renderFigure(figure);
  },

  updateCustomChart: function () {
    //totalTime
    var val1 = this.collection.models[0].attributes.system.userTime;
    var val2 = this.collection.models[0].attributes.system.systemTime;
    var totalTime2Value = val1+val2;
    this.collection.models[0].attributes["custom"] = {"totalTime2":totalTime2Value};
  },

  checkInterval: function (a) {
    this.updateFrequency = a.target.value;
    self.calculateSeries();
    self.renderCharts();
  },

  checkEnabled: function (a) {
    var myId = a.target.id;
    var position = myId.search('Checkbox');
    var preparedId = myId.substring(0, position);
    var toCheck = $(a.target).is(':checked');
    if (toCheck === false) {
      $("#" + preparedId).hide();
    }
    else if (toCheck === true) {
      $("#" + preparedId).show();
    }
  },

  initUnits : function () {
    this.units = [ ];
    var i;
    var scale = 0.0001;

    for (i = 0; i < 12; ++i) {
      this.units.push(scale * 1);
      this.units.push(scale * 2);
      this.units.push(scale * 2.5);
      this.units.push(scale * 4);
      this.units.push(scale * 5);
      scale *= 10;
    }
  },

  getMaxValue : function (identifier) {
    var max = this.seriesData[identifier].max || 1;

    var i = 0, n = this.units.length;
    while (i < n) {
      var unit = this.units[i++];
      if (max > unit) {
        continue;
      }
      if (max == unit) {
        break;
      }
      return unit;
    }

    return max;
  },

  checkDetailChart: function (a) {
    if ($(a.target).hasClass('icon-minus') === true) {
      $('#detailGraph').height(43);
      $('#detailGraphChart').hide();
      $(a.target).removeClass('icon-minus');
      $(a.target).addClass('icon-plus');
    }
    else {
      $('#detailGraphChart').show();
      $('#detailGraph').height(300);
      $(a.target).removeClass('icon-plus');
      $(a.target).addClass('icon-minus');
    }
  },

  hideChart: function (a) {
    var figure = $(a.target).attr("value");
    $('#'+figure+'Checkbox').prop('checked', false);
    $('#'+figure).hide();
  },

  renderDetailChart: function (a) {
    var self = this;
    self.detailGraph = $(a.target).attr("value");
    $.each(this.options.description.models[0].attributes.figures, function () {
      if(this.identifier === self.detailGraph) {
        $('#detailGraphHeader').text(this.name);
        self.calculateSeries();
        self.renderCharts();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        $('#detailGraphChart').show();
        $('#detailGraph').height(300);
        $('#dbHideSwitch').addClass('icon-minus');
        $('#dbHideSwitch').removeClass('icon-plus');
      }
    });
  },

  renderCharts: function () {
    var self = this;
    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;
      var chart;

      if (self.charts[identifier] === undefined) {
        chart = self.charts[identifier] = nv.models.lineChart();
        chart.xAxis.axisLabel('').tickFormat(function (d) {
          if (isNaN(d)) {
            return '';
          }

          function pad (value) {
            return (value < 10 ? "0" + String(value) : String(value));
          }

          var date = new Date(d / 10);

          return pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
        });

        var label = figure.units;

        if (figure.units === 'bytes') {
          label = "megabytes";
        }
        chart.yAxis.axisLabel(label);

        nv.addGraph (function () {
          nv.utils.windowResize(function () {
            d3.select('#' + identifier + 'Chart svg').call(chart);
          });

          return chart;
        });
      }
      else {
        chart = self.charts[identifier];
      }

      chart.yDomain([ 0, self.getMaxValue(identifier) ]);

      if (self.detailGraph === undefined) {
        self.detailGraph = "userTime";
      }
      if (self.detailGraph === identifier) {
        d3.select("#detailGraphChart svg")
          .call(chart)
          .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
          .transition().duration(500);

      }

      d3.select("#" + identifier + "Chart svg")
        .call(chart)
        .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
        .transition().duration(500);
    });
  },

  calculateSeries: function (flush) {
    var self = this;
    self.updateCustomChart();

    var timeStamp = Math.round(new Date() * 10);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;

      if (self.seriesData[identifier] === undefined) {
        self.seriesData[identifier] = { max: 0, values: [ ] };
      }

      while (self.seriesData[identifier].values.length > self.arraySize) {
        self.seriesData[identifier].values.shift();
      }

      if (flush) {
        self.seriesData[identifier].values.push({ x: timeStamp, y: undefined, value: undefined });
        return;
      }

      var responseValue = self.collection.models[0].attributes[figure.group][identifier];

      if (responseValue !== undefined && responseValue !== null) {
        if (responseValue.sum !== undefined) {
          responseValue = responseValue.sum;
        }
      }

      function sanitize (value, figure) {
        if (value < 0) {
          value = 0;
        }
        else {
          if (figure.units === 'bytes') {
            value /= (1024 * 1024);
          }
          value = Math.round(value * 100) / 100;
        }

        return value;
      }

      var newValue = 0;

      if (figure.type === 'current') {
        newValue = responseValue;
      }
      else {
        var n = self.seriesData[identifier].values.length;

        if (responseValue !== undefined && n > 0) {
          var previous = self.seriesData[identifier].values[n - 1];
          if (previous.value !== undefined) {
            newValue = responseValue - previous.value;
          }
        }
      }

      newValue = sanitize(newValue, figure);
      if (newValue > self.seriesData[identifier].max) {
        self.seriesData[identifier].max = newValue;
      }

      self.seriesData[identifier].values.push({ x: timeStamp, y: newValue, value: responseValue });
    });
  },

  renderFigure: function (figure) {
    $('#' + figure.group).append(
      '
' +
      '

' + figure.name +
      '
'+
      '' +
      '' +
      '' +
      '
' +
      '
<svg class="svgClass"/>
' +
      '
'
    );

    $('#' + figure.group + 'Divider').before(
      '
'+
      '<input type="checkbox" id=' + figure.identifier + 'Checkbox checked>' + figure.name + '
'
    );
    $('.db-info').tooltip({
      placement: "top"
    });
  }

});
<commit_msg>optimized some functions<commit_after>var dashboardView = Backbone.View.extend({
  el: '#content',
  updateInterval: 1000, // 1 second, constant
  updateFrequency: 5, // the actual update rate (5 s)
  updateCounter: 0,
  arraySize: 99, // how many values will we keep per figure?
  seriesData: {},
  charts: {},
  units: [],
  detailGraph: "userTime",

  initialize: function () {
    var self = this;

    this.initUnits();

    this.collection.fetch({
      success: function() {
        self.calculateSeries();
        self.renderCharts();

        window.setInterval(function() {
          self.updateCounter++;

          if (self.updateCounter < self.updateFrequency) {
            return false;
          }

          self.updateCounter = 0;
          self.collection.fetch({
            success: function() {
              self.calculateSeries();
              self.renderCharts();
            },
            error: function() {
              // need to flush previous values
              self.calculateSeries(true);
              self.renderCharts();
              arangoHelper.arangoError("Lost connection to Database!");
            }
          });

        }, self.updateInterval);
      }
    });
  },

  events: {
    "click .dashboard-dropdown li" : "checkEnabled",
    "click .interval-dropdown li" : "checkInterval",
    "click .db-zoom" : "renderDetailChart",
    "click .db-minimize" : "checkDetailChart",
    "click .db-hide" : "hideChart"
  },

  template: new EJS({url: 'js/templates/dashboardView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);

    //Client calculated charts
    self.genCustomCategories();
    self.genCustomChartDescription(
      "userTime + systemTime",
      "custom",
      "totalTime2",
      "Total Time (User+System)",
      "accumulated",
      "seconds"
    );

    $.each(this.options.description.models[0].attributes.groups, function () {
      $('.thumbnails').append(
        '
' +
        '
' + this.name + '
' +
        '
');
      $('#menuGroups').append(
        '
' + this.name + '
' +
        '

'
      );
    });

    $.each(this.options.description.models[0].attributes.figures, function () {
      self.renderFigure(this);
    });

    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    if (this.collection.models[0] === undefined) {
      this.collection.fetch({
        success: function() {
          self.calculateSeries();
          self.renderCharts();
        },
        error: function() {
          self.calculateSeries();
          self.renderCharts(flush);
        }
      });
    }
    else {
      self.calculateSeries();
      self.renderCharts();
    }
    return this;
  },
  //generate function for all custom categories
  genCustomCategories: function () {
    this.genCustomCategory("Client calculated charts", "custom", "Customized Charts");
  },
  //generate a custom category
  genCustomCategory: function(description, group, name) {
    this.options.description.models[0].attributes.groups.push({
      "description":description,
      "group":group,
      "name":name
    });
  },
  //generate a custom description
  genCustomChartDescription: function (description, group, identifier, name, type, units) {
    var figure = {
      "description" : description,
      "group" : group,
      "identifier" : identifier,
      "name" : name,
      "type" : type,
      "units" : units
    };
    this.options.description.models[0].attributes.figures.push(figure);
    this.renderFigure(figure);
  },
  //calculate customized chart value functions here
  updateCustomChartValues: function ( {
    this.totalTime2();
  },

  //custom chart value calculation for totalTime2
  totalTime2: function () {
    var val1 = this.collection.models[0].attributes.system.userTime;
    var val2 = this.collection.models[0].attributes.system.systemTime;
    var totalTime2Value = val1+val2;
    this.collection.models[0].attributes["custom"] = {"totalTime2":totalTime2Value};
  },

  checkInterval: function (a) {
    this.updateFrequency = a.target.value;
    self.calculateSeries();
    self.renderCharts();
  },

  checkEnabled: function (a) {
    var myId = a.target.id;
    var position = myId.search('Checkbox');
    var preparedId = myId.substring(0, position);
    var toCheck = $(a.target).is(':checked');
    if (toCheck === false) {
      $("#" + preparedId).hide();
    }
    else if (toCheck === true) {
      $("#" + preparedId).show();
    }
  },

  initUnits : function () {
    this.units = [ ];
    var i;
    var scale = 0.0001;

    for (i = 0; i < 12; ++i) {
      this.units.push(scale * 1);
      this.units.push(scale * 2);
      this.units.push(scale * 2.5);
      this.units.push(scale * 4);
      this.units.push(scale * 5);
      scale *= 10;
    }
  },

  getMaxValue : function (identifier) {
    var max = this.seriesData[identifier].max || 1;

    var i = 0, n = this.units.length;
    while (i < n) {
      var unit = this.units[i++];
      if (max > unit) {
        continue;
      }
      if (max == unit) {
        break;
      }
      return unit;
    }

    return max;
  },

  checkDetailChart: function (a) {
    if ($(a.target).hasClass('icon-minus') === true) {
      $('#detailGraph').height(43);
      $('#detailGraphChart').hide();
      $(a.target).removeClass('icon-minus');
      $(a.target).addClass('icon-plus');
    }
    else {
      $('#detailGraphChart').show();
      $('#detailGraph').height(300);
      $(a.target).removeClass('icon-plus');
      $(a.target).addClass('icon-minus');
    }
  },

  hideChart: function (a) {
    var figure = $(a.target).attr("value");
    $('#'+figure+'Checkbox').prop('checked', false);
    $('#'+figure).hide();
  },

  renderDetailChart: function (a) {
    var self = this;
    self.detailGraph = $(a.target).attr("value");
    $.each(this.options.description.models[0].attributes.figures, function () {
      if(this.identifier === self.detailGraph) {
        $('#detailGraphHeader').text(this.name);
        self.calculateSeries();
        self.renderCharts();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        $('#detailGraphChart').show();
        $('#detailGraph').height(300);
        $('#dbHideSwitch').addClass('icon-minus');
        $('#dbHideSwitch').removeClass('icon-plus');
      }
    });
  },

  renderCharts: function () {
    var self = this;
    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;
      var chart;

      if (self.charts[identifier] === undefined) {
        chart = self.charts[identifier] = nv.models.lineChart();
        chart.xAxis.axisLabel('').tickFormat(function (d) {
          if (isNaN(d)) {
            return '';
          }

          function pad (value) {
            return (value < 10 ? "0" + String(value) : String(value));
          }

          var date = new Date(d / 10);

          return pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
        });

        var label = figure.units;

        if (figure.units === 'bytes') {
          label = "megabytes";
        }
        chart.yAxis.axisLabel(label);

        nv.addGraph (function () {
          nv.utils.windowResize(function () {
            d3.select('#' + identifier + 'Chart svg').call(chart);
          });

          return chart;
        });
      }
      else {
        chart = self.charts[identifier];
      }

      chart.yDomain([ 0, self.getMaxValue(identifier) ]);

      if (self.detailGraph === undefined) {
        self.detailGraph = "userTime";
      }
      if (self.detailGraph === identifier) {
        d3.select("#detailGraphChart svg")
          .call(chart)
          .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
          .transition().duration(500);

      }

      d3.select("#" + identifier + "Chart svg")
        .call(chart)
        .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
        .transition().duration(500);
    });
  },

  calculateSeries: function (flush) {
    var self = this;
    self.updateCustomChartValues();

    var timeStamp = Math.round(new Date() * 10);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;

      if (self.seriesData[identifier] === undefined) {
        self.seriesData[identifier] = { max: 0, values: [ ] };
      }

      while (self.seriesData[identifier].values.length > self.arraySize) {
        self.seriesData[identifier].values.shift();
      }

      if (flush) {
        self.seriesData[identifier].values.push({ x: timeStamp, y: undefined, value: undefined });
        return;
      }

      var responseValue = self.collection.models[0].attributes[figure.group][identifier];

      if (responseValue !== undefined && responseValue !== null) {
        if (responseValue.sum !== undefined) {
          responseValue = responseValue.sum;
        }
      }

      function sanitize (value, figure) {
        if (value < 0) {
          value = 0;
        }
        else {
          if (figure.units === 'bytes') {
            value /= (1024 * 1024);
          }
          value = Math.round(value * 100) / 100;
        }

        return value;
      }

      var newValue = 0;

      if (figure.type === 'current') {
        newValue = responseValue;
      }
      else {
        var n = self.seriesData[identifier].values.length;

        if (responseValue !== undefined && n > 0) {
          var previous = self.seriesData[identifier].values[n - 1];
          if (previous.value !== undefined) {
            newValue = responseValue - previous.value;
          }
        }
      }

      newValue = sanitize(newValue, figure);
      if (newValue > self.seriesData[identifier].max) {
        self.seriesData[identifier].max = newValue;
      }

      self.seriesData[identifier].values.push({ x: timeStamp, y: newValue, value: responseValue });
    });
  },

  renderFigure: function (figure) {
    $('#' + figure.group).append(
      '
' +
      '

' + figure.name +
      '
'+
      '' +
      '' +
      '' +
      '
' +
      '
<svg class="svgClass"/>
' +
      '
'
    );

    $('#' + figure.group + 'Divider').before(
      '
'+
      '<input type="checkbox" id=' + figure.identifier + 'Checkbox checked>' + figure.name + '
'
    );
    $('.db-info').tooltip({
      placement: "top"
    });
  }

});
<|endoftext|>


<commit_before>/**
 * Lazy-loaded tabs
 */
jQuery(function() {
  $('.nav.nav-tabs').on('click', '[data-url]', function(event) {
    var loader = $(this);

    if (loader.data('loaded'))
      return;

    var target = $(loader.attr('href')); // It's an #anchor

    $.ajax({
        url: loader.data('url'),
        beforeSend: function() {
          loader.trigger('stradivari:tab:loading');
        }
      })
      .done(function(html) {
        loader.data('loaded', true);
        target.html(html);
        loader.trigger('stradivari:tab:loaded');
      })
      .fail(function() {
        alert('Aw, snap! Something went wrong');
        target.html('');
        loader.trigger('stradivari:tab:failed');
      });
  })
});
<commit_msg>Add lazy loading also to pills<commit_after>/**
 * Lazy-loaded tabs
 */
jQuery(function() {
  $('.nav.nav-tabs, .nav.nav-pills').on('click', '[data-url]', function(event) {
    var loader = $(this);

    if (loader.data('loaded'))
      return;

    var target = $(loader.attr('href')); // It's an #anchor

    $.ajax({
        url: loader.data('url'),
        beforeSend: function() {
          loader.trigger('stradivari:tab:loading');
        }
      })
      .done(function(html) {
        loader.data('loaded', true);
        target.html(html);
        loader.trigger('stradivari:tab:loaded');
      })
      .fail(function() {
        alert('Aw, snap! Something went wrong');
        target.html('');
        loader.trigger('stradivari:tab:failed');
      });
  })
});
<|endoftext|>


<commit_before>'use strict';

exports.BattlePokedex = {
	////////////////////////////////////
	// Prism Fakemon
	////////////////////////////////////
	phancero: {
		num: 9001,
		species: "Phancero",
		types: ["Ghost", "Flying"],
		baseStats: {hp: 178, atk: 137, def: 57, spa: 85, spd: 65, spe: 128},
		abilities: {0: "Download", 1: "Contrary"},
		heightm: 1.5,
		weightkg: 46.8,
		color: "Black",
		eggGroups: ["Undiscovered"],
	},

	////////////////////////////////////
	// Gen 1 Glitchmon
	////////////////////////////////////
	rb202: {
		num: -202,
		species: "PC 4S H",
		types: ["Nοrmal", "Grοund"],
		baseStats: {hp: 232, atk: 147, def: 145, spa: 136, spd: 136, spe: 128},
		abilities: {0: ""},
		heightm: 66.1,
		weightkg: 975.3,
		color: "Black",
		eggGroups: ["Undiscovered"],
	},
};
<commit_msg>changed PC 4S H to RB:202<commit_after>'use strict';

exports.BattlePokedex = {
	////////////////////////////////////
	// Prism Fakemon
	////////////////////////////////////
	phancero: {
		num: 9001,
		species: "Phancero",
		types: ["Ghost", "Flying"],
		baseStats: {hp: 178, atk: 137, def: 57, spa: 85, spd: 65, spe: 128},
		abilities: {0: "Download", 1: "Contrary"},
		heightm: 1.5,
		weightkg: 46.8,
		color: "Black",
		eggGroups: ["Undiscovered"],
	},

	////////////////////////////////////
	// Gen 1 Glitchmon
	////////////////////////////////////
	rb202: {
		num: -202,
		species: "RB:202",
		types: ["Nοrmal", "Grοund"],
		baseStats: {hp: 232, atk: 147, def: 145, spa: 136, spd: 136, spe: 128},
		abilities: {0: ""},
		heightm: 66.1,
		weightkg: 975.3,
		color: "Black",
		eggGroups: ["Undiscovered"],
	},
};
<|endoftext|>


<commit_before>(function($){
	 //focusing on box first will do sphere later

	var threeDJson = new Object();

 	$.threeDLoad = function(obj){
 		//Load a JS object or JSON String to begin.
		if(typeof obj === 'object'){
			threeDJson = obj;
		}else{
			try {
     			var jsonObject = jQuery.parseJSON(obj);
			} catch (e) {
    			return false;
			}
		  	threeDJson = jsonObject;
		  	return true;
		}
 	}
 	$.threeDShow = function(remove){
 		//I show the whole JSON with & without Prefex.
	 	if(typeof remove === 'undefined' || remove === true){ return threeDJson; }
	 	if(remove === false){ return jQuery.threeDRemove(); }
	 	return threeDJson;
 	}

 	$.threeDSplit = function(string){
 		//interna function to split prefex if you passed a string instead of Array
 		var data = string.split('~');
    	return data[1];
 	}

 	$.threeDRemove = function(){
 		//goes through JSON and removes 3DJSON prefex EX."-190,0~element":"data" => "element":"data"
 		//You can add decimal numbers up  4th place EX. 1.1234
 		return jQuery.parseJSON(JSON.stringify(threeDJson).replace(/["]-?[\d+.]{1,8}[\/,]-?[\d+.]{1,8}[\/~]/g ,'"'));
 		//TEST return jQuery.parseJSON(JSON.stringify(threeDJson).replace(/["]-?[\d+.]{1,8}[\/,]-?[\d+.]{1,8}[\/~][\w\d\W\D]{0,}["][:]/g ,'"'));
 	}

 	$.threeDStringToArray = function(string){
 		//  '90,0' => [90,0]
 	 	if(typeof string !== 'undefined'){
 			//assumes it a string of '90,0'
 			var data = string.split('~');
 			if(data.length !== 2 || !jQuery.isNumeric(data[0]) || !jQuery.isNumeric(data[1]) ){
 				return false;
 			}else{
 				return data;
 			}
 	    }
 	    return false;
 	}

 	$.threeDArrayToString = function(array1){
 	 	// [90,0] => '90,0'
 	 	if(typeof array1 !== 'undefined' && array1.length === 2 && jQuery.isNumeric(array1[0]) && jQuery.isNumeric(array1[1]) && jQuery.threeDCheckDegree(array1[0]) && jQuery.threeDCheckDegree(array1[1])){
 			var data = array1[0]+','+array1[1];
 			return data;
 	    }
 	    return false;
 	}

 	$.threeDCheckDegree = function(degree){
 		//check that its in the right range #NO number over 359 and under -359 please
 		if(degree => -360 && degree <= 360){return true;}else{ return false;}
 	}

 	$.threeDAdd = function(face,element,value){
	var face_add = '0,0~'; // Front of box
	var obj = new Object();

	 	if(typeof face !== 'undefined'){
	 		// if you just pass a number as face
	 		if(jQuery.isNumeric(face) && face <= 6 && face >= 1){

	 			switch(face){
	 			case 2: //left of box
	 			face_add = '90,0~';
	 			break;
	 			case 3: //back of box
	 			face_add = '180,0~';
	 			break;
	 			case 4: //right of box
	 			face_add = '270,0~';
	 			break;
	 			case 5: //top of box
	 			face_add = '0,90~';
	 			break;
	 			case 6: //bottom of box
	 			face_add = '0,270~';
	 			break;
	 			case -1: //backside of front of box
	 			face_add = '360,0~';
	 			break;
	 			case -2:
	 			face_add = '-270,0~':
	 			break;
	 			case -3:
	 			face_add = '-180,0~':
	 			break;
	 			case -4:
	 			face_add = '-90,0~':
	 			break;
	 			case -5:
	 			face_add = '0,-90~':
	 			break;
	 			case -6:
	 			face_add = '0,-180~':
	 			break;
	 			default: //front of box
	 			//case 1:
	 			break;
	 			//"0,0~data":"data"
	 			}

	 		}else{
			// Pass a string or Array as face
	 		//check if its array with two elements (Future)

	 			if(jQuery.isArray(face)){
	 				var array_to_string = $.threeDArrayToString(face);
	 				if(array_to_string){
	 					face_add =  array_to_string +'~';
	 				}
	 			}else{
	 				face_add = face+'~';
	 			}
	 		}
	 	}
	 threeDJson[face_add+element] = value;
	 return threeDJson;
 	}

 	$.threeDReplace = function(string,data){

 	}

 	$.threeDGetByFace = function(face){
 		if(typeof face === 'undefined' || (face < 1 && face > 6)){return false;}
 		var data = new Object();
 		jQuery.each(threeDJson,function(key,value){
 			console.log(key);
 		});

 	}

 	$.threeDInside = function(noInside){
 		//paper documents have a back side. In 3dJson to denote its on back side or Inside the box or sphere use negative
 		// Ex."-90,0~data":"data"  => face 2, inside of box or sphere
 		// ZERO problem you can not have -0 or negative zero ...  Thinking about the best way to solve this.
 		// I want face 1 or "0,0~data":"data" to have a back side
 	}

}( jQuery ));
<commit_msg>Update threeDJson.jquery.js<commit_after>(function($){
	 //focusing on box first will do sphere later

	var threeDJson = new Object();

 	$.threeDLoad = function(obj){
 		//Load a JS object or JSON String to begin.
		if(typeof obj === 'object'){
			threeDJson = obj;
		}else{
			try {
     			var jsonObject = jQuery.parseJSON(obj);
			} catch (e) {
    			return false;
			}
		  	threeDJson = jsonObject;
		  	return true;
		}
 	}
 	$.threeDShow = function(remove){
 		//I show the whole JSON with & without Prefex.
	 	if(typeof remove === 'undefined' || remove === true){ return threeDJson; }
	 	if(remove === false){ return jQuery.threeDRemove(); }
	 	return threeDJson;
 	}

 	$.threeDSplit = function(string){
 		//interna function to split prefex if you passed a string instead of Array
 		var data = string.split('~');
    	return data[1];
 	}

 	$.threeDRemove = function(){
 		//goes through JSON and removes 3DJSON prefex EX."-190,0~element":"data" => "element":"data"
 		//You can add decimal numbers up  4th place EX. 1.1234
 		return jQuery.parseJSON(JSON.stringify(threeDJson).replace(/["]-?[\d+.]{1,8}[\/,]-?[\d+.]{1,8}[\/~]/g ,'"'));
 		//TEST return jQuery.parseJSON(JSON.stringify(threeDJson).replace(/["]-?[\d+.]{1,8}[\/,]-?[\d+.]{1,8}[\/~][\w\d\W\D]{0,}["][:]/g ,'"'));
 	}

 	$.threeDStringToArray = function(string){
 		//  '90,0' => [90,0]
 	 	if(typeof string !== 'undefined'){
 			//assumes it a string of '90,0'
 			var data = string.split('~');
 			if(data.length !== 2 || !jQuery.isNumeric(data[0]) || !jQuery.isNumeric(data[1]) ){
 				return false;
 			}else{
 				return data;
 			}
 	    }
 	    return false;
 	}

 	$.threeDArrayToString = function(array1){
 	 	// [90,0] => '90,0'
 	 	if(typeof array1 !== 'undefined' && array1.length === 2 && jQuery.isNumeric(array1[0]) && jQuery.isNumeric(array1[1]) && jQuery.threeDCheckDegree(array1[0]) && jQuery.threeDCheckDegree(array1[1])){
 			var data = array1[0]+','+array1[1];
 			return data;
 	    }
 	    return false;
 	}

 	$.threeDCheckDegree = function(degree){
 		//check that its in the right range #NO number over 359 and under -359 please
 		if(degree => -360 && degree <= 360){return true;}else{ return false;}
 	}

 	$.threeDAdd = function(face,element,value){
	var face_add = '0,0~'; // Front of box
	var obj = new Object();

	 	if(typeof face !== 'undefined'){
	 		// if you just pass a number as face
	 		if(jQuery.isNumeric(face) && face <= 6 && face >= 1){

	 			switch(face){
	 			case 2: //left of box
	 			face_add = '90,0~';
	 			break;
	 			case 3: //back of box
	 			face_add = '180,0~';
	 			break;
	 			case 4: //right of box
	 			face_add = '270,0~';
	 			break;
	 			case 5: //top of box
	 			face_add = '0,90~';
	 			break;
	 			case 6: //bottom of box
	 			face_add = '0,270~';
	 			break;
	 			case -1: //backside of front of box
	 			face_add = '360,0~';
	 			break;
	 			case -2:
	 			face_add = '-270,0~';
	 			break;
	 			case -3:
	 			face_add = '-180,0~';
	 			break;
	 			case -4:
	 			face_add = '-90,0~';
	 			break;
	 			case -5:
	 			face_add = '0,-90~';
	 			break;
	 			case -6:
	 			face_add = '0,-180~';
	 			break;
	 			default: //front of box
	 			//case 1:
	 			break;
	 			//"0,0~data":"data"
	 			}

	 		}else{
			// Pass a string or Array as face
	 		//check if its array with two elements (Future)

	 			if(jQuery.isArray(face)){
	 				var array_to_string = $.threeDArrayToString(face);
	 				if(array_to_string){
	 					face_add =  array_to_string +'~';
	 				}
	 			}else{
	 				face_add = face+'~';
	 			}
	 		}
	 	}
	 threeDJson[face_add+element] = value;
	 return threeDJson;
 	}

 	$.threeDReplace = function(string,data){

 	}

 	$.threeDGetByFace = function(face){
 		if(typeof face === 'undefined' || (face < 1 && face > 6)){return false;}
 		var data = new Object();
 		jQuery.each(threeDJson,function(key,value){
 			console.log(key);
 		});

 	}

 	$.threeDInside = function(noInside){
 		//paper documents have a back side. In 3dJson to denote its on back side or Inside the box or sphere use negative
 		// Ex."-90,0~data":"data"  => face 2, inside of box or sphere
 		// ZERO problem you can not have -0 or negative zero ...  Thinking about the best way to solve this.
 		// I want face 1 or "0,0~data":"data" to have a back side
 	}

}( jQuery ));
<|endoftext|>


<commit_before>const PlotCard = require('../../../plotcard.js');

class ForgottenPlans extends PlotCard {
    setupCardAbilities(ability) {
        this.persistentEffect({
            condition: () => this.game.phase !== 'plot',
            match: card => card.getType() === 'plot' && !card.hasTrait('Scheme'),
            targetController: 'any',
            effect: ability.effects.blank
        });
    }
}

ForgottenPlans.code = '02119';

module.exports = ForgottenPlans;
<commit_msg>fix Forgotten Plans condition check to verify current phase on players (#485)<commit_after>const PlotCard = require('../../../plotcard.js');

class ForgottenPlans extends PlotCard {
    setupCardAbilities(ability) {
        this.persistentEffect({
            condition: () => this.game.currentPhase !== 'plot',
            match: card => card.getType() === 'plot' && !card.hasTrait('Scheme'),
            targetController: 'any',
            effect: ability.effects.blank
        });
    }
}

ForgottenPlans.code = '02119';

module.exports = ForgottenPlans;
<|endoftext|>


<commit_before>var test = require('tape');
var balanced = require('..');

test('balanced', function(t) {
  t.deepEqual(balanced('{', '}', 'pre{in{nest}}post'), {
    start: 3,
    end: 12,
    pre: 'pre',
    body: 'in{nest}',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', '{{{{{{{{{in}post'), {
    start: 8,
    end: 11,
    pre: '{{{{{{{{',
    body: 'in',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', 'pre{body{in}post'), {
    start: 8,
    end: 11,
    pre: 'pre{body',
    body: 'in',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', 'pre}{in{nest}}post'), {
    start: 4,
    end: 13,
    pre: 'pre}',
    body: 'in{nest}',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', 'pre{body}between{body2}post'), {
    start: 3,
    end: 8,
    pre: 'pre',
    body: 'body',
    post: 'between{body2}post'
  });
  t.notOk(balanced('{', '}', 'nope'), 'should be notOk');
  t.deepEqual(balanced('', '', 'preinnestpost'), {
    start: 3,
    end: 19,
    pre: 'pre',
    body: 'innest',
    post: 'post'
  });
  t.deepEqual(balanced('', '', 'preinnestpost'), {
    start: 7,
    end: 23,
    pre: 'pre',
    body: 'innest',
    post: 'post'
  });
  t.deepEqual(balanced('{{', '}}', 'pre{{{in}}}post'), {
    start: 3,
    end: 9,
    pre: 'pre',
    body: '{in}',
    post: 'post'
  });
  t.deepEqual(balanced('{{{', '}}', 'pre{{{in}}}post'), {
    start: 3,
    end: 8,
    pre: 'pre',
    body: 'in',
    post: '}post'
  });
  t.deepEqual(balanced('{', '}', 'pre{{first}in{second}post'), {
    start: 4,
    end: 10,
    pre: 'pre{',
    body: 'first',
    post: 'in{second}post'
  });
  t.end();
});
<commit_msg>Added failing test compared to original<commit_after>var test = require('tape');
var balanced = require('..');

test('balanced', function(t) {
  t.deepEqual(balanced('{', '}', 'pre{in{nest}}post'), {
    start: 3,
    end: 12,
    pre: 'pre',
    body: 'in{nest}',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', '{{{{{{{{{in}post'), {
    start: 8,
    end: 11,
    pre: '{{{{{{{{',
    body: 'in',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', 'pre{body{in}post'), {
    start: 8,
    end: 11,
    pre: 'pre{body',
    body: 'in',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', 'pre}{in{nest}}post'), {
    start: 4,
    end: 13,
    pre: 'pre}',
    body: 'in{nest}',
    post: 'post'
  });
  t.deepEqual(balanced('{', '}', 'pre{body}between{body2}post'), {
    start: 3,
    end: 8,
    pre: 'pre',
    body: 'body',
    post: 'between{body2}post'
  });
  t.notOk(balanced('{', '}', 'nope'), 'should be notOk');
  t.deepEqual(balanced('', '', 'preinnestpost'), {
    start: 3,
    end: 19,
    pre: 'pre',
    body: 'innest',
    post: 'post'
  });
  t.deepEqual(balanced('', '', 'preinnestpost'), {
    start: 7,
    end: 23,
    pre: 'pre',
    body: 'innest',
    post: 'post'
  });
  t.deepEqual(balanced('{{', '}}', 'pre{{{in}}}post'), {
    start: 3,
    end: 9,
    pre: 'pre',
    body: '{in}',
    post: 'post'
  });
  t.deepEqual(balanced('{{{', '}}', 'pre{{{in}}}post'), {
    start: 3,
    end: 8,
    pre: 'pre',
    body: 'in',
    post: '}post'
  });
  t.deepEqual(balanced('{', '}', 'pre{{first}in{second}post'), {
    start: 4,
    end: 10,
    pre: 'pre{',
    body: 'first',
    post: 'in{second}post'
  });
  t.deepEqual(balanced('<?', '?>', 'pre<?>post'), {
    start: 3,
    end: 4,
    pre: 'pre',
    body: '',
    post: 'post'
  });
  t.end();
});
<|endoftext|>


<commit_before>app.factory('RequestService',['$rootScope','$http',function($rootScope,$http){
var RequestService = {
	//Address Change
	view: function(id) {
		window.location.href = ("/"+id)
	},

	edit: function(id) {
		window.location.href = ("/"+id+"?edit=true");
	},

	//API Calls
	create: function(Model,callback) {
		$http.post('/api/create',Model)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	get: function(id,callback) {
		$http.get('/api/get/'+id)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	list: function(callback) {
		$http.get('/api/get')
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	search: function(query,callback) {
		$http.get('/api/search',query)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	update: function(Model,callback) {
		$http.put('/api/update/'+Model._id,Model)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	remove: function(Model,callback) {
		$http.delete('/api/remove/'+Model._id,Model)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	}
};

return RequestService;

}]);<commit_msg>removing rootScope<commit_after>app.factory('RequestService',['$http',function($http){
var RequestService = {
	//Address Change
	view: function(id) {
		window.location.href = ("/"+id)
	},

	edit: function(id) {
		window.location.href = ("/"+id+"?edit=true");
	},

	//API Calls
	create: function(Model,callback) {
		$http.post('/api/create',Model)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	get: function(id,callback) {
		$http.get('/api/get/'+id)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	list: function(callback) {
		$http.get('/api/get')
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	search: function(query,callback) {
		$http.get('/api/search',query)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	update: function(Model,callback) {
		$http.put('/api/update/'+Model._id,Model)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	},

	remove: function(Model,callback) {
		$http.delete('/api/remove/'+Model._id,Model)
		.success(function(data) {
			callback(data);
		})
		.error(function(data,status) {

		});
	}
};

return RequestService;

}]);<|endoftext|>


<commit_before>var dashboardView = Backbone.View.extend({
  el: '#content',
  updateInterval: 1000, // 1 second, constant
  updateFrequency: 5, // the actual update rate (5 s)
  updateCounter: 0,
  arraySize: 99, // how many values will we keep per figure?
  seriesData: {},
  charts: {},
  units: [],
  detailGraph: "userTime",

  initialize: function () {
    var self = this;

    this.initUnits();

    this.collection.fetch({
      success: function() {
        self.calculateSeries();
        self.renderCharts();

        window.setInterval(function() {
          self.updateCounter++;

          if (self.updateCounter < self.updateFrequency) {
            return false;
          }

          self.updateCounter = 0;
          self.collection.fetch({
            success: function() {
              self.calculateSeries();
              self.renderCharts();
            },
            error: function() {
              // need to flush previous values
              self.calculateSeries(true);
              self.renderCharts();
              arangoHelper.arangoError("Lost connection to Database!");
            }
          });

        }, self.updateInterval);
      }
    });
  },

  events: {
    "click .dashboard-dropdown li" : "checkEnabled",
    "click .interval-dropdown li" : "checkInterval",
    "click .db-zoom" : "renderDetailChart",
    "click .db-minimize" : "checkDetailChart",
    "click .db-hide" : "hideChart"
  },

  template: new EJS({url: 'js/templates/dashboardView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);

    console.log(this.options.description.models[0].attributes.groups);

    $.each(this.options.description.models[0].attributes.groups, function () {
      $('.thumbnails').append(
        '
' +
        '
' + this.name + '
' +
        '
');
      $('#menuGroups').append(
        '
' + this.name + '
' +
        '

'
      );
    });

    $.each(this.options.description.models[0].attributes.figures, function () {
      self.renderFigure(this);
    });

    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    if (this.collection.models[0] === undefined) {
      this.collection.fetch({
        success: function() {
          self.calculateSeries();
          self.renderCharts();
        },
        error: function() {
          self.calculateSeries();
          self.renderCharts(flush);
        }
      });
    }
    else {
      self.calculateSeries();
      self.renderCharts();
    }
    return this;
  },

  checkInterval: function (a) {
    this.updateFrequency = a.target.value;
    self.calculateSeries();
    self.renderCharts();
  },

  checkEnabled: function (a) {
    var myId = a.target.id;
    var position = myId.search('Checkbox');
    var preparedId = myId.substring(0, position);
    var toCheck = $(a.target).is(':checked');
    if (toCheck === false) {
      $("#" + preparedId).hide();
    }
    else if (toCheck === true) {
      $("#" + preparedId).show();
    }
  },

  initUnits : function () {
    this.units = [ ];
    var i;
    var scale = 0.0001;

    for (i = 0; i < 12; ++i) {
      this.units.push(scale * 1);
      this.units.push(scale * 2);
      this.units.push(scale * 2.5);
      this.units.push(scale * 4);
      this.units.push(scale * 5);
      scale *= 10;
    }
  },

  getMaxValue : function (identifier) {
    var max = this.seriesData[identifier].max || 1;

    var i = 0, n = this.units.length;
    while (i < n) {
      var unit = this.units[i++];
      if (max > unit) {
        continue;
      }
      if (max == unit) {
        break;
      }
      return unit;
    }

    return max;
  },

  checkDetailChart: function (a) {
    if ($(a.target).hasClass('icon-minus') === true) {
      $('#detailGraph').height(43);
      $('#detailGraphChart').hide();
      $(a.target).removeClass('icon-minus');
      $(a.target).addClass('icon-plus');
    }
    else {
      $('#detailGraphChart').show();
      $('#detailGraph').height(300);
      $(a.target).removeClass('icon-plus');
      $(a.target).addClass('icon-minus');
    }
  },

  hideChart: function (a) {
    var figure = $(a.target).attr("value");
    $('#'+figure+'Checkbox').prop('checked', false);
    $('#'+figure).hide();
  },

  renderDetailChart: function (a) {
    var self = this;
    self.detailGraph = $(a.target).attr("value");
    $.each(this.options.description.models[0].attributes.figures, function () {
      if(this.identifier === self.detailGraph) {
        $('#detailGraphHeader').text(this.name);
        self.calculateSeries();
        self.renderCharts();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        $('#detailGraphChart').show();
        $('#detailGraph').height(300);
        $('#dbHideSwitch').addClass('icon-minus');
        $('#dbHideSwitch').removeClass('icon-plus');
      }
    });
  },

  renderCharts: function () {
    var self = this;
    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;
      var chart;

      if (self.charts[identifier] === undefined) {
        chart = self.charts[identifier] = nv.models.lineChart();
        chart.xAxis.axisLabel('').tickFormat(function (d) {
          if (isNaN(d)) {
            return '';
          }

          function pad (value) {
            return (value < 10 ? "0" + String(value) : String(value));
          }

          var date = new Date(d / 10);

          return pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
        });

        var label = figure.units;

        if (figure.units === 'bytes') {
          label = "megabytes";
        }
        chart.yAxis.axisLabel(label);

        nv.addGraph (function () {
          nv.utils.windowResize(function () {
            d3.select('#' + identifier + 'Chart svg').call(chart);
          });

          return chart;
        });
      }
      else {
        chart = self.charts[identifier];
      }

      chart.yDomain([ 0, self.getMaxValue(identifier) ]);

      if (self.detailGraph === undefined) {
        self.detailGraph = "userTime";
      }
      if (self.detailGraph === identifier) {
        d3.select("#detailGraphChart svg")
          .call(chart)
          .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
          .transition().duration(500);

      }

      d3.select("#" + identifier + "Chart svg")
        .call(chart)
        .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
        .transition().duration(500);
    });
  },

  calculateSeries: function (flush) {
    var self = this;
    var timeStamp = Math.round(new Date() * 10);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;

      if (self.seriesData[identifier] === undefined) {
        self.seriesData[identifier] = { max: 0, values: [ ] };
      }

      while (self.seriesData[identifier].values.length > self.arraySize) {
        self.seriesData[identifier].values.shift();
      }

      if (flush) {
        self.seriesData[identifier].values.push({ x: timeStamp, y: undefined, value: undefined });
        return;
      }

      var responseValue = self.collection.models[0].attributes[figure.group][identifier];

      if (responseValue !== undefined && responseValue !== null) {
        if (responseValue.sum !== undefined) {
          responseValue = responseValue.sum;
        }
      }

      function sanitize (value, figure) {
        if (value < 0) {
          value = 0;
        }
        else {
          if (figure.units === 'bytes') {
            value /= (1024 * 1024);
          }
          value = Math.round(value * 100) / 100;
        }

        return value;
      }

      var newValue = 0;

      if (figure.type === 'current') {
        newValue = responseValue;
      }
      else {
        var n = self.seriesData[identifier].values.length;

        if (responseValue !== undefined && n > 0) {
          var previous = self.seriesData[identifier].values[n - 1];
          if (previous.value !== undefined) {
            newValue = responseValue - previous.value;
          }
        }
      }

      newValue = sanitize(newValue, figure);
      if (newValue > self.seriesData[identifier].max) {
        self.seriesData[identifier].max = newValue;
      }

      self.seriesData[identifier].values.push({ x: timeStamp, y: newValue, value: responseValue });
    });
  },

  renderFigure: function (figure) {
    console.log(figure);
    $('#' + figure.group).append(
      '
' +
      '

' + figure.name +
      '
'+
      '' +
      '' +
      '' +
      '
' +
      '
<svg class="svgClass"/>
' +
      '
'
    );

    $('#' + figure.group + 'Divider').before(
      '
'+
      '<input type="checkbox" id=' + figure.identifier + 'Checkbox checked>' + figure.name + '
'
    );
    $('.db-info').tooltip({
      placement: "top"
    });
  }

});
<commit_msg>added function to include client customized graphs - not finished<commit_after>var dashboardView = Backbone.View.extend({
  el: '#content',
  updateInterval: 1000, // 1 second, constant
  updateFrequency: 5, // the actual update rate (5 s)
  updateCounter: 0,
  arraySize: 99, // how many values will we keep per figure?
  seriesData: {},
  charts: {},
  units: [],
  detailGraph: "userTime",

  initialize: function () {
    var self = this;

    this.initUnits();

    this.collection.fetch({
      success: function() {
        self.calculateSeries();
        self.renderCharts();

        window.setInterval(function() {
          self.updateCounter++;

          if (self.updateCounter < self.updateFrequency) {
            return false;
          }

          self.updateCounter = 0;
          self.collection.fetch({
            success: function() {
              self.calculateSeries();
              self.renderCharts();
            },
            error: function() {
              // need to flush previous values
              self.calculateSeries(true);
              self.renderCharts();
              arangoHelper.arangoError("Lost connection to Database!");
            }
          });

        }, self.updateInterval);
      }
    });
  },

  events: {
    "click .dashboard-dropdown li" : "checkEnabled",
    "click .interval-dropdown li" : "checkInterval",
    "click .db-zoom" : "renderDetailChart",
    "click .db-minimize" : "checkDetailChart",
    "click .db-hide" : "hideChart"
  },

  template: new EJS({url: 'js/templates/dashboardView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);

    //Client calculated charts
    self.genCustomCategory("Client calculated charts", "custom", "Customized Charts");
    self.genCustomChart();

    $.each(this.options.description.models[0].attributes.groups, function () {
      $('.thumbnails').append(
        '
' +
        '
' + this.name + '
' +
        '
');
      $('#menuGroups').append(
        '
' + this.name + '
' +
        '

'
      );
    });

    $.each(this.options.description.models[0].attributes.figures, function () {
      self.renderFigure(this);
    });

    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    if (this.collection.models[0] === undefined) {
      this.collection.fetch({
        success: function() {
          self.calculateSeries();
          self.renderCharts();
        },
        error: function() {
          self.calculateSeries();
          self.renderCharts(flush);
        }
      });
    }
    else {
      self.calculateSeries();
      self.renderCharts();
    }
    return this;
  },
  genCustomCategory: function(description, group, name) {
    this.options.description.models[0].attributes.groups.push({
      "description":description,
      "group":group,
      "name":name
    });
  },
  genCustomChart: function () {
    //totalTime
    var figure = {
      "description" : "userTime + systemTime",
      "group" : "custom",
      "identifier" : "totalTime2",
      "name" : "Total Time (User+System)",
      "type" : "accumulated",
      "units" : "seconds"
    };
    this.options.description.models[0].attributes.figures.push(figure);
    this.renderFigure(figure);
  },

  updateCustomChart: function () {
    //totalTime
    var val1 = this.collection.models[0].attributes.system.userTime;
    var val2 = this.collection.models[0].attributes.system.systemTime;
    var totalTime2Value = val1+val2;
    this.collection.models[0].attributes["custom"] = {"totalTime2":totalTime2Value};
  },

  checkInterval: function (a) {
    this.updateFrequency = a.target.value;
    self.calculateSeries();
    self.renderCharts();
  },

  checkEnabled: function (a) {
    var myId = a.target.id;
    var position = myId.search('Checkbox');
    var preparedId = myId.substring(0, position);
    var toCheck = $(a.target).is(':checked');
    if (toCheck === false) {
      $("#" + preparedId).hide();
    }
    else if (toCheck === true) {
      $("#" + preparedId).show();
    }
  },

  initUnits : function () {
    this.units = [ ];
    var i;
    var scale = 0.0001;

    for (i = 0; i < 12; ++i) {
      this.units.push(scale * 1);
      this.units.push(scale * 2);
      this.units.push(scale * 2.5);
      this.units.push(scale * 4);
      this.units.push(scale * 5);
      scale *= 10;
    }
  },

  getMaxValue : function (identifier) {
    var max = this.seriesData[identifier].max || 1;

    var i = 0, n = this.units.length;
    while (i < n) {
      var unit = this.units[i++];
      if (max > unit) {
        continue;
      }
      if (max == unit) {
        break;
      }
      return unit;
    }

    return max;
  },

  checkDetailChart: function (a) {
    if ($(a.target).hasClass('icon-minus') === true) {
      $('#detailGraph').height(43);
      $('#detailGraphChart').hide();
      $(a.target).removeClass('icon-minus');
      $(a.target).addClass('icon-plus');
    }
    else {
      $('#detailGraphChart').show();
      $('#detailGraph').height(300);
      $(a.target).removeClass('icon-plus');
      $(a.target).addClass('icon-minus');
    }
  },

  hideChart: function (a) {
    var figure = $(a.target).attr("value");
    $('#'+figure+'Checkbox').prop('checked', false);
    $('#'+figure).hide();
  },

  renderDetailChart: function (a) {
    var self = this;
    self.detailGraph = $(a.target).attr("value");
    $.each(this.options.description.models[0].attributes.figures, function () {
      if(this.identifier === self.detailGraph) {
        $('#detailGraphHeader').text(this.name);
        self.calculateSeries();
        self.renderCharts();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        $('#detailGraphChart').show();
        $('#detailGraph').height(300);
        $('#dbHideSwitch').addClass('icon-minus');
        $('#dbHideSwitch').removeClass('icon-plus');
      }
    });
  },

  renderCharts: function () {
    var self = this;
    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;
      var chart;

      if (self.charts[identifier] === undefined) {
        chart = self.charts[identifier] = nv.models.lineChart();
        chart.xAxis.axisLabel('').tickFormat(function (d) {
          if (isNaN(d)) {
            return '';
          }

          function pad (value) {
            return (value < 10 ? "0" + String(value) : String(value));
          }

          var date = new Date(d / 10);

          return pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
        });

        var label = figure.units;

        if (figure.units === 'bytes') {
          label = "megabytes";
        }
        chart.yAxis.axisLabel(label);

        nv.addGraph (function () {
          nv.utils.windowResize(function () {
            d3.select('#' + identifier + 'Chart svg').call(chart);
          });

          return chart;
        });
      }
      else {
        chart = self.charts[identifier];
      }

      chart.yDomain([ 0, self.getMaxValue(identifier) ]);

      if (self.detailGraph === undefined) {
        self.detailGraph = "userTime";
      }
      if (self.detailGraph === identifier) {
        d3.select("#detailGraphChart svg")
          .call(chart)
          .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
          .transition().duration(500);

      }

      d3.select("#" + identifier + "Chart svg")
        .call(chart)
        .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
        .transition().duration(500);
    });
  },

  calculateSeries: function (flush) {
    var self = this;
    self.updateCustomChart();

    var timeStamp = Math.round(new Date() * 10);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;

      if (self.seriesData[identifier] === undefined) {
        self.seriesData[identifier] = { max: 0, values: [ ] };
      }

      while (self.seriesData[identifier].values.length > self.arraySize) {
        self.seriesData[identifier].values.shift();
      }

      if (flush) {
        self.seriesData[identifier].values.push({ x: timeStamp, y: undefined, value: undefined });
        return;
      }

      var responseValue = self.collection.models[0].attributes[figure.group][identifier];

      if (responseValue !== undefined && responseValue !== null) {
        if (responseValue.sum !== undefined) {
          responseValue = responseValue.sum;
        }
      }

      function sanitize (value, figure) {
        if (value < 0) {
          value = 0;
        }
        else {
          if (figure.units === 'bytes') {
            value /= (1024 * 1024);
          }
          value = Math.round(value * 100) / 100;
        }

        return value;
      }

      var newValue = 0;

      if (figure.type === 'current') {
        newValue = responseValue;
      }
      else {
        var n = self.seriesData[identifier].values.length;

        if (responseValue !== undefined && n > 0) {
          var previous = self.seriesData[identifier].values[n - 1];
          if (previous.value !== undefined) {
            newValue = responseValue - previous.value;
          }
        }
      }

      newValue = sanitize(newValue, figure);
      if (newValue > self.seriesData[identifier].max) {
        self.seriesData[identifier].max = newValue;
      }

      self.seriesData[identifier].values.push({ x: timeStamp, y: newValue, value: responseValue });
    });
  },

  renderFigure: function (figure) {
    $('#' + figure.group).append(
      '
' +
      '

' + figure.name +
      '
'+
      '' +
      '' +
      '' +
      '
' +
      '
<svg class="svgClass"/>
' +
      '
'
    );

    $('#' + figure.group + 'Divider').before(
      '
'+
      '<input type="checkbox" id=' + figure.identifier + 'Checkbox checked>' + figure.name + '
'
    );
    $('.db-info').tooltip({
      placement: "top"
    });
  }

});
<|endoftext|>