<commit_before>'use strict';

var util = require('util');
var Tab = require('../client/tab').Tab;
var Amount = ripple.Amount;

function ColdWalletTab() {
  Tab.call(this);
}

util.inherits(ColdWalletTab, Tab);

ColdWalletTab.prototype.tabName = 'coldwallet';
ColdWalletTab.prototype.mainMenu = 'coldwallet';

ColdWalletTab.prototype.generateHtml = function () {
  return require('../../templates/tabs/tx.jade')();
};

ColdWalletTab.prototype.extraRoutes = [
  {name: '/coldwallet/:address'}
];

ColdWalletTab.prototype.angular = function (module) {
  module.controller('ColdWalletCtrl', ['$rootScope', '$routeParams', '$location', '$route', 'rpId', 'rpNetwork',
  function ($scope, $routeParams, $location, $route, id, network) {
    $scope.sequenceNumber = 1;
    $scope.accountError = false;

    // Parse the transaction returned by ripple-lib
    // Return a human-readable message for the UI.
    // We only consider transactions that originate from this account.
    /*function formatTxnMessage(txn, address) {
      var outcome = txn.outcome.result === 'tesSUCCESS' ?
      'successful' : 'failed';

      var txnMessage = 'The most recent transaction was a ' + outcome +
      ' ' + txn.type;

      $scope.sequenceNumber = txn.type === 'orderCancellation' ?
      Number(txn.specification.orderSequence) + 1 : Number(txn.sequence) + 1;

      if (txn.type === 'payment') {
        txnMessage += ' to ' + txn.specification.destination.address + '. ' +
        ' You paid: ';
        var payments =  _.map(txn.outcome.balanceChanges[address],
          function(amount) {
            // Remove leading minus sign from amount
            // Truncate to 6 chars
            return amount.value.slice(1, 6) + ' ' + amount.currency;
          }).join(', ');
        txnMessage += payments + '. ';
      } else if (txn.type === 'order') {
        txnMessage += '. This was a ' + txn.specification.direction +
        ' order for ' + txn.specification.quantity.amount.value +
        ' of ' + txn.specification.quantity.amount.currency +
        ' at a price of ' + txn.specification.quantity.amount
        .value + ' ' + txn.specification.quantity.amount.currency + '. ';
      } else if (txn.type === 'trustline') {
        txnMessage += ' to ' + txn.specification.counterparty +
        ' with a limit of ' + txn.specification.limit + ' ' +
        txn.specification.currency + '.';
      } else if (txn.type === 'orderCancellation') {
        txnMessage += '. The order sequence was ' +
        txn.specification.orderSequence + '. ';
      } else if (txn.type === 'settings') {
        txnMessage += ' transaction.';
      }
      txnMessage += ' The fee was ' + txn.outcome.fee + ' XRP. ' +
      'The ID and sequence number of the transaction are ' + txn.id +
      ' and  ' + txn.sequence + '.';
      return txnMessage;
    }*/

    var address = $routeParams.address;
    $scope.address = address;

    // If we are online, fetch account info
    var watcher = $scope.$watch('connected', function() {
      if (!$scope.connected) return;

      $scope.networkFee = network.remote.createTransaction()._computeFee() / 1000000;

      var account = network.remote.account(address);
      var server = network.remote._getServer();

      account.entry(function(err, entry) {
        $scope.accountLoaded = true;

        if (err && err.remote && err.remote.error === 'actNotFound') {
          $scope.$apply(function() {
            $scope.accountError = 'Account ' + address + ' has not been found';
          });

          return;
        }

        var defaultRipple = !!(entry.account_data.Flags & ripple.Remote.flags.account_root.DefaultRipple);
        var requireAuth = !!(entry.account_data.Flags & ripple.Remote.flags.account_root.RequireAuth);
        var globalFreeze = !!(entry.account_data.Flags & ripple.Remote.flags.account_root.GlobalFreeze);

        // There are three flags the user is concerned with
        var accountInfo = [];
        accountInfo.push({
          setting: 'Require authorization',
          enabled: requireAuth,
          description: 'Prevent issuances from being held without authorization'
        });
        accountInfo.push({
          setting: 'Default Ripple',
          enabled: defaultRipple,
          description: 'Allow balances in trust lines to Ripple by default'
        });
        accountInfo.push({
          setting: 'Global Freeze',
          enabled: globalFreeze,
          description: 'Freeze all issuances'
        });

        $scope.$apply(function() {
          $scope.accountInfo = accountInfo;
        });

        network.remote.requestAccountInfo({account: address})
          .on('success', function(info) {
            $scope.$apply(function() {
              $scope.regularKeyEnabled = info.account_data.RegularKey ? 'Yes' : 'No';
              $scope.xrpBalance = info.account_data.Balance / 1000000;

              // To calcute the XRP reserve and available balance
              var ownerCount  = info.account_data.OwnerCount || 0;
              $scope.reserve = server._reserve(ownerCount);
              var bal = Amount.from_json(info.account_data.Balance);
              $scope.max_spend = bal.subtract($scope.reserve);
            });
          }).request();

        // Fetch account trustlines and determine if any should have a warning
        network.remote.requestAccountLines({account: address})
          .on('success', function(lines) {
            $scope.$apply(function() {
              $scope.lines = lines.lines;
              // Display any trustlines where the flag does not match the
              // corresponding flag on the account root
              $scope.warningLines = _.reduce(lines.lines, function(result, line) {
                var warning1 = '';
                var warning2 = '';
                if (!!line.no_ripple === defaultRipple) {
                  warning1 += 'Rippling flag on line differs from flag on account root.';
                }
                if (!!line.authorized !== requireAuth) { // TODO line.authorized ?
                  warning2 += 'Trust line must be authorized.';
                }
                line.warning1 = warning1;
                line.warning2 =warning2;
                // Convert to boolean so undefined displays as false
                line.no_ripple = !!line.no_ripple;
                line.authorized = !!line.authorized;
                if (warning1 || warning2) {
                  result.push(line);
                }
                return result;
              }, []);
            });
          }).request();

        // If we have a sequence number from the network, display to user
        $scope.sequenceNumber = entry.account_data.Sequence;

        watcher();
      });

      // Fetch the most recent transaction for this account (if exists)
      /*network.remote.requestAccountTransactions({
        account: address,
        ledger_index_min: -1,
        descending: true,
        limit: 1,
        binary: false
      })
      .on('transactions', function(response) {
        if (response.transactions && response.transactions.length) {
          $scope.$apply(function() {
            console.log('tx', response.transactions[0]);
            $scope.txnTime = response.transactions[0].tx.date;
            $scope.lastTxn = formatTxnMessage(response.transactions[0], address);
          });
        }
      })
      .on('error', function(e){
        console.log('error fetching transactions: ', JSON.stringify(e));
        $scope.$apply(function() {
          $scope.transactionError = true;
          $scope.transactionErrorMessage = 'No transaction history available';
        });
      }).request();*/
    });

    $scope.refresh = function() {
      $route.reload();
    };
  }]);
};

module.exports = ColdWalletTab;
<commit_msg>[TASK] Coldwallet: Message change (DC-220)<commit_after>'use strict';

var util = require('util');
var Tab = require('../client/tab').Tab;
var Amount = ripple.Amount;

function ColdWalletTab() {
  Tab.call(this);
}

util.inherits(ColdWalletTab, Tab);

ColdWalletTab.prototype.tabName = 'coldwallet';
ColdWalletTab.prototype.mainMenu = 'coldwallet';

ColdWalletTab.prototype.generateHtml = function () {
  return require('../../templates/tabs/tx.jade')();
};

ColdWalletTab.prototype.extraRoutes = [
  {name: '/coldwallet/:address'}
];

ColdWalletTab.prototype.angular = function (module) {
  module.controller('ColdWalletCtrl', ['$rootScope', '$routeParams', '$location', '$route', 'rpId', 'rpNetwork',
  function ($scope, $routeParams, $location, $route, id, network) {
    $scope.sequenceNumber = 1;
    $scope.accountError = false;

    // Parse the transaction returned by ripple-lib
    // Return a human-readable message for the UI.
    // We only consider transactions that originate from this account.
    /*function formatTxnMessage(txn, address) {
      var outcome = txn.outcome.result === 'tesSUCCESS' ?
      'successful' : 'failed';

      var txnMessage = 'The most recent transaction was a ' + outcome +
      ' ' + txn.type;

      $scope.sequenceNumber = txn.type === 'orderCancellation' ?
      Number(txn.specification.orderSequence) + 1 : Number(txn.sequence) + 1;

      if (txn.type === 'payment') {
        txnMessage += ' to ' + txn.specification.destination.address + '. ' +
        ' You paid: ';
        var payments =  _.map(txn.outcome.balanceChanges[address],
          function(amount) {
            // Remove leading minus sign from amount
            // Truncate to 6 chars
            return amount.value.slice(1, 6) + ' ' + amount.currency;
          }).join(', ');
        txnMessage += payments + '. ';
      } else if (txn.type === 'order') {
        txnMessage += '. This was a ' + txn.specification.direction +
        ' order for ' + txn.specification.quantity.amount.value +
        ' of ' + txn.specification.quantity.amount.currency +
        ' at a price of ' + txn.specification.quantity.amount
        .value + ' ' + txn.specification.quantity.amount.currency + '. ';
      } else if (txn.type === 'trustline') {
        txnMessage += ' to ' + txn.specification.counterparty +
        ' with a limit of ' + txn.specification.limit + ' ' +
        txn.specification.currency + '.';
      } else if (txn.type === 'orderCancellation') {
        txnMessage += '. The order sequence was ' +
        txn.specification.orderSequence + '. ';
      } else if (txn.type === 'settings') {
        txnMessage += ' transaction.';
      }
      txnMessage += ' The fee was ' + txn.outcome.fee + ' XRP. ' +
      'The ID and sequence number of the transaction are ' + txn.id +
      ' and  ' + txn.sequence + '.';
      return txnMessage;
    }*/

    var address = $routeParams.address;
    $scope.address = address;

    // If we are online, fetch account info
    var watcher = $scope.$watch('connected', function() {
      if (!$scope.connected) return;

      $scope.networkFee = network.remote.createTransaction()._computeFee() / 1000000;

      var account = network.remote.account(address);
      var server = network.remote._getServer();

      account.entry(function(err, entry) {
        $scope.accountLoaded = true;

        if (err && err.remote && err.remote.error === 'actNotFound') {
          $scope.$apply(function() {
            $scope.accountError = 'Account ' + address + ' has not been funded';
          });

          return;
        }

        var defaultRipple = !!(entry.account_data.Flags & ripple.Remote.flags.account_root.DefaultRipple);
        var requireAuth = !!(entry.account_data.Flags & ripple.Remote.flags.account_root.RequireAuth);
        var globalFreeze = !!(entry.account_data.Flags & ripple.Remote.flags.account_root.GlobalFreeze);

        // There are three flags the user is concerned with
        var accountInfo = [];
        accountInfo.push({
          setting: 'Require authorization',
          enabled: requireAuth,
          description: 'Prevent issuances from being held without authorization'
        });
        accountInfo.push({
          setting: 'Default Ripple',
          enabled: defaultRipple,
          description: 'Allow balances in trust lines to Ripple by default'
        });
        accountInfo.push({
          setting: 'Global Freeze',
          enabled: globalFreeze,
          description: 'Freeze all issuances'
        });

        $scope.$apply(function() {
          $scope.accountInfo = accountInfo;
        });

        network.remote.requestAccountInfo({account: address})
          .on('success', function(info) {
            $scope.$apply(function() {
              $scope.regularKeyEnabled = info.account_data.RegularKey ? 'Yes' : 'No';
              $scope.xrpBalance = info.account_data.Balance / 1000000;

              // To calcute the XRP reserve and available balance
              var ownerCount  = info.account_data.OwnerCount || 0;
              $scope.reserve = server._reserve(ownerCount);
              var bal = Amount.from_json(info.account_data.Balance);
              $scope.max_spend = bal.subtract($scope.reserve);
            });
          }).request();

        // Fetch account trustlines and determine if any should have a warning
        network.remote.requestAccountLines({account: address})
          .on('success', function(lines) {
            $scope.$apply(function() {
              $scope.lines = lines.lines;
              // Display any trustlines where the flag does not match the
              // corresponding flag on the account root
              $scope.warningLines = _.reduce(lines.lines, function(result, line) {
                var warning1 = '';
                var warning2 = '';
                if (!!line.no_ripple === defaultRipple) {
                  warning1 += 'Rippling flag on line differs from flag on account root.';
                }
                if (!!line.authorized !== requireAuth) { // TODO line.authorized ?
                  warning2 += 'Trust line must be authorized.';
                }
                line.warning1 = warning1;
                line.warning2 =warning2;
                // Convert to boolean so undefined displays as false
                line.no_ripple = !!line.no_ripple;
                line.authorized = !!line.authorized;
                if (warning1 || warning2) {
                  result.push(line);
                }
                return result;
              }, []);
            });
          }).request();

        // If we have a sequence number from the network, display to user
        $scope.sequenceNumber = entry.account_data.Sequence;

        watcher();
      });

      // Fetch the most recent transaction for this account (if exists)
      /*network.remote.requestAccountTransactions({
        account: address,
        ledger_index_min: -1,
        descending: true,
        limit: 1,
        binary: false
      })
      .on('transactions', function(response) {
        if (response.transactions && response.transactions.length) {
          $scope.$apply(function() {
            console.log('tx', response.transactions[0]);
            $scope.txnTime = response.transactions[0].tx.date;
            $scope.lastTxn = formatTxnMessage(response.transactions[0], address);
          });
        }
      })
      .on('error', function(e){
        console.log('error fetching transactions: ', JSON.stringify(e));
        $scope.$apply(function() {
          $scope.transactionError = true;
          $scope.transactionErrorMessage = 'No transaction history available';
        });
      }).request();*/
    });

    $scope.refresh = function() {
      $route.reload();
    };
  }]);
};

module.exports = ColdWalletTab;
<|endoftext|>


<commit_before>DEFINE_CLASS("Ymacs_Tokenizer", DlEventProxy, function(D, P){

        D.DEFAULT_ARGS = [ "onChange" ];

        D.DEFAULT_ARGS = {
                buffer : [ "buffer"  , null ],
                line   : [ "line"    , 0 ],
                col    : [ "col"     , 0 ]
        };

        D.CONSTRUCT = function() {
                this.syntax = [];
                this.parens = [];
                this.code = this.buffer.code;
                this.quickUpdate = this.quickUpdate.clearingTimeout(50, this);
        };

        P.WHITE_SPACE = " \xa0\t\n\r".split("").toHash(true);
        P.IDENTIFIER_CHARS = "$_0123456789".split("").toHash(true);
        P.IDENTIFIER_START = "$_".split("").toHash(true);
        P.LINE_COMMENT = "//";
        P.MULTILINE_COMMENT_START = "/*";
        P.MULTILINE_COMMENT_END = "*/";
        P.STRING = "\"";
        P.STRING2 = "'";
        P.OPERATORS = "-+=/!%^&|*<>".split("").toHash(true);
        P.KEYWORDS = {};
        P.KEYWORDS_TYPE = {};
        P.KEYWORDS_CONST = {};
        P.BUILTIN = {};
        P.OPEN_PAREN = "{[(".split("").toHash(true);
        P.CLOSE_PAREN = ")]}".split("").toHash(true);
        P.MATCH_PAREN = { "{" : "}", "[" : "]", "(" : ")" };

        P.skipWhitespace = function() {
                while (!this.eof() && this.peek() in this.WHITE_SPACE)
                        this.next();
        };

        P.position = function() {
                return this.buffer._rowColToPosition(this.line, this.col);
        };

        P.get = function() {
                var line = this.code[this.line], ch = line && (this.col == line.length ? "\n" : line.charAt(this.col));
                this.next();
                return ch;
        };

        P.next = function() {
                if (this.col < this.code[this.line].length) {
                        ++this.col;
                } else {
                        ++this.line;
                        this.col = 0;
                }
        };

        P.eol = function() {
                return this.col == this.code[this.line].length;
        };

        P.eof = function() {
                return this.line >= this.code.length || (
                        this.line == this.code.length - 1 && this.col == this.code[this.line].length
                );
        };

        P.peek = function() {
                var line = this.code[this.line];
                return line && (this.col == line.length ? "\n" : line.charAt(this.col));
        };

        P.back = function() {
                if (this.col > 0) {
                        --this.col;
                } else {
                        --this.line;
                        this.col = 0;
                }
        };

        P.forward = function(n) {
                if (n == null) n = 1;
                while (!this.eof() && n-- > 0)
                        this.next();
        };

        P.lookingAt = function(what) {
                if (what instanceof RegExp) {
                        what.lastIndex = this.col;
                        var m = what.exec(this.code[this.line]);
                        return m && m.index == this.col && what.lastIndex;
                } else if (typeof what == "object") {
                        for (i in what)
                                if (this.lookingAt(i))
                                        return i;
                } else {
                        return this.code[this.line].substr(this.col, what.length) == what && this.col + what.length;
                }
        };

        P.isIdentifierChar = function(ch) {
                if (ch == null)
                        ch = this.peek();
                return ch && (ch.toUpperCase() != ch.toLowerCase() || ch in this.IDENTIFIER_CHARS);
        };

        P.isIdentifierStart = function(ch) {
                if (ch == null)
                        ch = this.peek();
                return ch && (ch.toUpperCase() != ch.toLowerCase() || ch in this.IDENTIFIER_START);
        };

        P.isOperatorChar = function() {
                return this.peek() in this.OPERATORS;
        };

        P.consumeString = function(end, esc) {
                var escape = false, ch;
                if (arguments.length == 1)
                        esc = "\\";
                while (!this.eof()) {
                        ch = this.get();
                        if (ch === end && !escape) {
                                this.back();
                                break;
                        }
                        escape = (ch === esc && !escape);
                }
        };

        P.consumeLineComment = function() {
                while (!this.eof() && !this.eol())
                        this.next();
        };

        P.consumeMultilineComment = function(end) {
                while (!(this.eof() || this.lookingAt(end)))
                        this.next();
        };

        P.consumeNumber = function() {
                var hasdot = false, hase = false, hex = false, ch, code;
                while (!this.eof()) {
                        ch = this.peek();
                        code = ch.charCodeAt(0);
                        if ((code < 48 || code > 57) && !(hex && ((code >= 65 && code <= 70) ||
                                                                  (code >= 97 && code <= 102)))) {
                                if (ch == ".") {
                                        if (hasdot) break;
                                        hasdot = true;
                                } else if (ch == "x") {
                                        if (hex) break;
                                        hex = true;
                                } else if (ch == "e") {
                                        if (hase) break;
                                        hase = true;
                                } else break;
                        }
                        this.next();
                }
        };

        P.consumeOperator = function() {
                while (!this.eof()) {
                        var ch = this.peek();
                        if (ch in this.OPERATORS)
                                this.next();
                        else
                                break;
                }
        };

        P.consumeIdentifier = function() {
                var id = "";
                while (!this.eof()) {
                        if (this.isIdentifierChar()) {
                                id += this.get();
                        } else
                                break;
                }
                return id;
        };

        P.readToken = function() {
                this.skipWhitespace();
                var type, info = { begin: [ this.line, this.col ] };
                if (this.lookingAt(this.LINE_COMMENT)) {
                        type = "line-comment";
                        this.consumeLineComment();
                        this.next(); // skip newline

                } else if (this.lookingAt(this.MULTILINE_COMMENT_START)) {
                        type = "multiline-comment";
                        this.consumeMultilineComment(this.MULTILINE_COMMENT_END);
                        this.forward(this.MULTILINE_COMMENT_END.length);

                } else if (this.lookingAt(this.STRING)) {
                        this.next(); // skip start quote
                        type = "string";
                        this.consumeString(this.STRING);
                        this.next(); // skip end quote

                } else if (this.lookingAt(this.STRING2)) {
                        this.next(); // skip start quote
                        type = "string";
                        this.consumeString(this.STRING2);
                        this.next(); // skip end quote

                } else if (this.isIdentifierStart()) {
                        var id = this.consumeIdentifier();
                        if (id in this.KEYWORDS)
                                type = "keyword";
                        else if (id in this.KEYWORDS_TYPE)
                                type = "type";
                        else if (id in this.KEYWORDS_CONST)
                                type = "constant";
                        else if (id in this.BUILTIN)
                                type = "builtin";

                } else if (this.isOperatorChar()) {
                        this.consumeOperator();
                        type = "operator";

                } else if (this.peek() in this.OPEN_PAREN) {
                        info.paren = this.get();
                        type = "open-paren";
                        this.parens.push(info);

                } else if (this.peek() in this.CLOSE_PAREN) {
                        var last = this.parens.pop();
                        info.paren = this.get();
                        if (last) {
                                info.match = last;
                                last.match = info;
                                if (this.MATCH_PAREN[last.paren] === info.paren)
                                        info.ok = last.ok = true;
                        }
                        type = "close-paren";

                } else if (this.lookingAt(/[0-9]|\.[0-9]/g)) {
                        this.consumeNumber();
                        type = "number";
                }

                if (type) {
                        info.type = type;
                        info.end = [ this.line, this.col ];
                        return info;
                }
        };

        P.add_syntax = function(info) {
                var line = info.begin[0], col = info.begin[1],
                    s = this.syntax[line] || (this.syntax[line] = {}),
                    old = s[col], removed = false;
                s[col] = info;
                return !old || old.type != info.type || old.end[1] != info.end[1] || old.end[0] != info.end[0];
        };

        P.tokenize = function() {
                this.line = 0;
                this.col = 0;
                var changes = {};
                while (!this.eof()) {
                        var info = this.readToken();
                        if (info) {
                                var i = info.begin[0], last = info.end[0];
                                if (i == last && this.add_syntax(info)) {
                                        changes[i] = true;
                                } else {
                                        var tmp = Object.makeCopy(info);
                                        while (i < last) {
                                                tmp.end = [ i, this.code[i].length ];
                                                if (this.add_syntax(tmp))
                                                        changes[i] = true;
                                                tmp = Object.makeCopy(tmp);
                                                i++;
                                                tmp.begin = [ i, 0 ];
                                        }
                                        tmp.end = info.end;
                                        if (this.add_syntax(tmp))
                                                changes[i] = true;
                                }
                        } else {
                                this.next(); // skip characters we didn't match
                        }
                }
                return changes;
        };

        P.highlightLine = function(line) {
                var syntax = this.syntax[line], text = this.code[line];
                if (!syntax)
                        return text.htmlEscape();
                var hl = "", last = 0;
                Array.hashKeys(syntax).mergeSort(function(a, b){
                        return parseInt(a) - parseInt(b);
                }).foreach(function(i){
                        var s = syntax[i];
                        if (i > last)
                                hl += text.substring(last, i);
                        hl += "" + text.substring(i, s.end[1]).htmlEscape() + "";
                        last = s.end[1];
                });
                if (last < text.length)
                        hl += text.substr(last);
                return hl;
        };

        P.reset = function() {
                this.syntax = [];
                this.parens = [];
                this.code = this.buffer.code;
                return this.tokenize();
        };

        P.quickUpdate = function(row) {
                var changed = Array.hashKeys(this.reset());
                changed.foreach(function(row){
                        this.buffer.callHooks("onLineChange", row);
                }, this);
        };

        P.quickInsertLine = function(row) {
                this.syntax.splice(row, 0, null);
        };

        P.quickDeleteLine = function(row) {
                this.syntax.splice(row, 1);
        };

});

/* -----[ JavaScript tokenizer ]----- */

DEFINE_CLASS("Ymacs_Tokenizer_JS", Ymacs_Tokenizer, function(D, P){

        P.KEYWORDS = "abstract break case catch class const \
continue debugger default delete do else \
enum export extends final finally for \
function goto if implements import in \
instanceof interface native new package \
private protected public return static \
super switch synchronized throw \
throws transient try typeof var void let \
yield volatile while with".trim().split(/\s+/).toHash(true);

        P.KEYWORDS_TYPE = "boolean byte char double float int long short void".trim().split(/\s+/).toHash(true);

        P.KEYWORDS_CONST = "false null undefined Infinity NaN true arguments this".trim().split(/\s+/).toHash(true);

        P.BUILTIN = "Array Date Function Infinity Math NaN Number \
Object Packages RegExp String decodeURI decodeURIComponent \
encodeURI encodeURIComponent eval isFinite isNaN parseFloat \
parseInt undefined window document".trim().split(/\s+/).toHash(true);

});
<commit_msg>minor<commit_after>DEFINE_CLASS("Ymacs_Tokenizer", DlEventProxy, function(D, P){

        D.DEFAULT_ARGS = [ "onChange" ];

        D.DEFAULT_ARGS = {
                buffer : [ "buffer"  , null ],
                line   : [ "line"    , 0 ],
                col    : [ "col"     , 0 ]
        };

        D.CONSTRUCT = function() {
                this.syntax = [];
                this.parens = [];
                this.code = this.buffer.code;
                this.quickUpdate = this.quickUpdate.clearingTimeout(50, this);
        };

        P.WHITE_SPACE = " \xa0\t\n\r".split("").toHash(true);
        P.IDENTIFIER_CHARS = "$_0123456789".split("").toHash(true);
        P.IDENTIFIER_START = "$_".split("").toHash(true);
        P.LINE_COMMENT = "//";
        P.MULTILINE_COMMENT_START = "/*";
        P.MULTILINE_COMMENT_END = "*/";
        P.STRING = "\"";
        P.STRING2 = "'";
        P.OPERATORS = "-+=/!%^&|*<>:?".split("").toHash(true);
        P.KEYWORDS = {};
        P.KEYWORDS_TYPE = {};
        P.KEYWORDS_CONST = {};
        P.BUILTIN = {};
        P.OPEN_PAREN = "{[(".split("").toHash(true);
        P.CLOSE_PAREN = ")]}".split("").toHash(true);
        P.MATCH_PAREN = { "{" : "}", "[" : "]", "(" : ")" };

        P.skipWhitespace = function() {
                while (!this.eof() && this.peek() in this.WHITE_SPACE)
                        this.next();
        };

        P.get = function() {
                var line = this.code[this.line], ch = line && (this.col == line.length ? "\n" : line.charAt(this.col));
                this.next();
                return ch;
        };

        P.next = function() {
                if (this.col < this.code[this.line].length) {
                        ++this.col;
                } else {
                        ++this.line;
                        this.col = 0;
                }
        };

        P.eol = function() {
                return this.col == this.code[this.line].length;
        };

        P.eof = function() {
                return this.line >= this.code.length || (
                        this.line == this.code.length - 1 && this.col == this.code[this.line].length
                );
        };

        P.peek = function() {
                var line = this.code[this.line];
                return line && (this.col == line.length ? "\n" : line.charAt(this.col));
        };

        P.back = function() {
                if (this.col > 0) {
                        --this.col;
                } else {
                        --this.line;
                        this.col = 0;
                }
        };

        P.forward = function(n) {
                if (n == null) n = 1;
                while (!this.eof() && n-- > 0)
                        this.next();
        };

        P.lookingAt = function(what) {
                if (what instanceof RegExp) {
                        what.lastIndex = this.col;
                        var m = what.exec(this.code[this.line]);
                        return m && m.index == this.col && what.lastIndex;
                } else if (typeof what == "object") {
                        for (i in what)
                                if (this.lookingAt(i))
                                        return i;
                } else {
                        return this.code[this.line].substr(this.col, what.length) == what && this.col + what.length;
                }
        };

        P.isIdentifierChar = function(ch) {
                if (ch == null)
                        ch = this.peek();
                return ch && (ch.toUpperCase() != ch.toLowerCase() || ch in this.IDENTIFIER_CHARS);
        };

        P.isIdentifierStart = function(ch) {
                if (ch == null)
                        ch = this.peek();
                return ch && (ch.toUpperCase() != ch.toLowerCase() || ch in this.IDENTIFIER_START);
        };

        P.isOperatorChar = function() {
                return this.peek() in this.OPERATORS;
        };

        P.consumeString = function(end, esc) {
                var escape = false, ch;
                if (arguments.length == 1)
                        esc = "\\";
                while (!this.eof()) {
                        ch = this.get();
                        if (ch === end && !escape) {
                                this.back();
                                break;
                        }
                        escape = (ch === esc && !escape);
                }
        };

        P.consumeLineComment = function() {
                while (!this.eof() && !this.eol())
                        this.next();
        };

        P.consumeMultilineComment = function(end) {
                while (!(this.eof() || this.lookingAt(end)))
                        this.next();
        };

        P.consumeNumber = function() {
                var hasdot = false, hase = false, hex = false, ch, code;
                while (!this.eof()) {
                        ch = this.peek();
                        code = ch.charCodeAt(0);
                        if ((code < 48 || code > 57) && !(hex && ((code >= 65 && code <= 70) ||
                                                                  (code >= 97 && code <= 102)))) {
                                if (ch == ".") {
                                        if (hasdot) break;
                                        hasdot = true;
                                } else if (ch == "x") {
                                        if (hex) break;
                                        hex = true;
                                } else if (ch == "e") {
                                        if (hase) break;
                                        hase = true;
                                } else break;
                        }
                        this.next();
                }
        };

        P.consumeOperator = function() {
                while (!this.eof()) {
                        var ch = this.peek();
                        if (ch in this.OPERATORS)
                                this.next();
                        else
                                break;
                }
        };

        P.consumeIdentifier = function() {
                var id = "";
                while (!this.eof()) {
                        if (this.isIdentifierChar()) {
                                id += this.get();
                        } else
                                break;
                }
                return id;
        };

        P.readToken = function() {
                this.skipWhitespace();
                var type, info = { begin: [ this.line, this.col ] };
                if (this.lookingAt(this.LINE_COMMENT)) {
                        type = "line-comment";
                        this.consumeLineComment();
                        this.next(); // skip newline

                } else if (this.lookingAt(this.MULTILINE_COMMENT_START)) {
                        type = "multiline-comment";
                        this.consumeMultilineComment(this.MULTILINE_COMMENT_END);
                        this.forward(this.MULTILINE_COMMENT_END.length);

                } else if (this.lookingAt(this.STRING)) {
                        this.next(); // skip start quote
                        type = "string";
                        this.consumeString(this.STRING);
                        this.next(); // skip end quote

                } else if (this.STRING2 && this.lookingAt(this.STRING2)) {
                        this.next(); // skip start quote
                        type = "string";
                        this.consumeString(this.STRING2);
                        this.next(); // skip end quote

                } else if (this.isIdentifierStart()) {
                        var id = info.name = this.consumeIdentifier();
                        if (id in this.KEYWORDS)
                                type = "keyword";
                        else if (id in this.KEYWORDS_TYPE)
                                type = "type";
                        else if (id in this.KEYWORDS_CONST)
                                type = "constant";
                        else if (id in this.BUILTIN)
                                type = "builtin";

                } else if (this.isOperatorChar()) {
                        this.consumeOperator();
                        type = "operator";

                } else if (this.peek() in this.OPEN_PAREN) {
                        info.paren = this.get();
                        type = "open-paren";
                        this.parens.push(info);

                } else if (this.peek() in this.CLOSE_PAREN) {
                        var last = this.parens.pop();
                        info.paren = this.get();
                        if (last) {
                                info.match = last;
                                last.match = info;
                                if (this.MATCH_PAREN[last.paren] === info.paren)
                                        info.ok = last.ok = true;
                        }
                        type = "close-paren";

                } else if (this.lookingAt(/[0-9]|\.[0-9]/g)) {
                        this.consumeNumber();
                        type = "number";
                }

                if (type) {
                        info.type = type;
                        info.end = [ this.line, this.col ];
                        return info;
                }
        };

        P.add_syntax = function(info) {
                var line = info.begin[0], col = info.begin[1],
                    s = this.syntax[line] || (this.syntax[line] = {}),
                    old = s[col], removed = false;
                s[col] = info;
                return !old || old.type != info.type || old.end[1] != info.end[1] || old.end[0] != info.end[0];
        };

        P.tokenize = function() {
                this.line = 0;
                this.col = 0;
                var changes = {};
                while (!this.eof()) {
                        var info = this.readToken();
                        if (info) {
                                var i = info.begin[0], last = info.end[0];
                                if (i == last && this.add_syntax(info)) {
                                        changes[i] = true;
                                } else {
                                        var tmp = Object.makeCopy(info);
                                        while (i < last) {
                                                tmp.end = [ i, this.code[i].length ];
                                                if (this.add_syntax(tmp))
                                                        changes[i] = true;
                                                tmp = Object.makeCopy(tmp);
                                                i++;
                                                tmp.begin = [ i, 0 ];
                                        }
                                        tmp.end = info.end;
                                        if (this.add_syntax(tmp))
                                                changes[i] = true;
                                }
                        } else {
                                this.next(); // skip characters we didn't match
                        }
                }
                return changes;
        };

        P.highlightLine = function(line) {
                var syntax = this.syntax[line], text = this.code[line];
                if (!syntax)
                        return text.htmlEscape();
                var hl = "", last = 0;
                Array.hashKeys(syntax).mergeSort(function(a, b){
                        return parseInt(a) - parseInt(b);
                }).foreach(function(i){
                        var s = syntax[i];
                        if (i > last)
                                hl += text.substring(last, i);
                        hl += "" + text.substring(i, s.end[1]).htmlEscape() + "";
                        last = s.end[1];
                });
                if (last < text.length)
                        hl += text.substr(last);
                return hl;
        };

        P.reset = function() {
                this.syntax = [];
                this.parens = [];
                this.code = this.buffer.code;
                return this.tokenize();
        };

        P.quickUpdate = function(row) {
                var changed = Array.hashKeys(this.reset());
                changed.foreach(function(row){
                        this.buffer.callHooks("onLineChange", row);
                }, this);
        };

        P.quickInsertLine = function(row) {
                this.syntax.splice(row, 0, null);
        };

        P.quickDeleteLine = function(row) {
                this.syntax.splice(row, 1);
        };

});

/* -----[ JavaScript tokenizer ]----- */

DEFINE_CLASS("Ymacs_Tokenizer_JS", Ymacs_Tokenizer, function(D, P){

        P.KEYWORDS = "abstract break case catch class const \
continue debugger default delete do else \
enum export extends final finally for \
function goto if implements import in \
instanceof interface native new package \
private protected public return static \
super switch synchronized throw \
throws transient try typeof var void let \
yield volatile while with".trim().split(/\s+/).toHash(true);

        P.KEYWORDS_TYPE = "boolean byte char double float int long short void".trim().split(/\s+/).toHash(true);

        P.KEYWORDS_CONST = "false null undefined Infinity NaN true arguments this".trim().split(/\s+/).toHash(true);

        P.BUILTIN = "Array Date Function Infinity Math NaN Number \
Object Packages RegExp String decodeURI decodeURIComponent \
encodeURI encodeURIComponent eval isFinite isNaN parseFloat \
parseInt undefined window document".trim().split(/\s+/).toHash(true);

});
<|endoftext|>


<commit_before>charts.point = function(args) {
    this.args = args;

    this.init = function(args) {
        raw_data_transformation(args);
        process_point(args);
        init(args);
        x_axis(args);
        y_axis(args);
        return this;
    }

    this.markers = function() {
        markers(args);
        if (args.least_squares){
            add_ls(args);
        }
        // if (args.lowess){
        //     add_lowess(args);
        // }
        return this
    }

    this.mainPlot = function() {
        var svg = d3.select(args.target + ' svg');
        var g;

        // plot the points, pretty straight-forward
        g = svg.append('g')
            .classed('points', true);

        var pts = g.selectAll('circle')
            .data(args.data[0])
            .enter().append('svg:circle')
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf);

        if (args.color_accessor!=null){
            pts.attr('fill',   args.scalefns.color);
            pts.attr('stroke', args.scalefns.color);
        } else {
            pts.attr('fill',   '#0000ff');
            pts.attr('stroke', '#0000ff');
        }
        if (args.size_accessor!=null){
            pts.attr('r', args.scalefns.size);
        } else {
            pts.attr('r', 2);
        }
        var rug;
        if (args.x_rug){
            //var data = args.data[0].map(function(d){return d[args.x_accessor]});
            rug=g.selectAll('line.x_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.scalefns.xf)
                .attr('x2', args.scalefns.xf)
                .attr('y1', args.height-args.top+args.buffer)
                .attr('y2', args.height-args.top)
                .attr('opacity', .3);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }
        if (args.y_rug){
            rug=g.selectAll('line.y_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.left+1)
                .attr('x2', args.left+args.buffer)
                .attr('y1', args.scalefns.yf)
                .attr('y2', args.scalefns.yf)
                .attr('stroke', 'black')
                .attr('opacity', .2);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }

        return this;
    }

    this.rollover = function() {
        var svg = d3.select(args.target + ' svg');

        var clips = svg.append('g')
                .attr('id', 'point-clips');

        var paths = svg.append('g')
            .attr('id', 'point-paths');

        //remove rollover text if it already exists
        if($(args.target + ' svg .active_datapoint').length > 0) {
            $(args.target + ' svg .active_datapoint').remove();
        }

        //add rollover text
        svg.append('text')
            .attr('class', 'active_datapoint')
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end');

        clips.selectAll('clipPath')
            .data(args.data[0])
                .enter().append('clipPath')
                    .attr('id', function(d, i) { return 'clip-'+i;})
                    .append('circle')
                        .attr('cx', args.scalefns.xf)
                        .attr('cy', args.scalefns.yf)
                        .attr('r', 20);

        var voronoi = d3.geom.voronoi()
            .x(args.scalefns.xf)
            .y(args.scalefns.yf);

        paths.selectAll('path')
            .data(voronoi(args.data[0]))
            .enter().append('path')
                .attr('d', function(d) {
                    return 'M' + d.join(',') + 'Z';
                })
                .attr('id', function(d,i) {
                    return 'path-' + i;
                })
                .attr('clip-path', function(d,i) {
                    return 'url(#clip-'+i+')';
                })
                .style('fill-opacity', 0)
                .on('mouseover', this.rolloverOn(args))
                .on('mouseout', this.rolloverOff(args));

        return this;
    }

    this.rolloverOn = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d, i){
            svg.selectAll('.points circle')
                .classed('unselected', true);

            var fmt = d3.time.format('%b %e, %Y');

            if (args.format == 'count') {
                var num = function(d_) {
                    var is_float = d_ % 1 != 0;
                    var n = d3.format("0,000");
                    d_ = is_float ? d3.round(d_, args.decimals) : d_;
                    return n(d_);
                }
            }
            else {
                var num = function(d_) {
                    var fmt_string = (args.decimals ? '.' + args.decimals : '' ) + '%';
                    var n = d3.format(fmt_string);
                    return n(d_);
                }
            }

            //highlight active point
            var pts = svg.selectAll('.points circle')
                .filter(function(g,j){return i == j})
                .classed('unselected', false)
                .classed('selected', true);

            if (args.size_accessor){
                pts.attr('r', function(di){return args.scalefns.size(di)+1});
            } else {
                pts.attr('r', 3);
            }

            //update rollover text
            if (args.show_rollover_text) {
                svg.select('.active_datapoint')
                    .text(function() {
                        if(args.time_series) {
                            var dd = new Date(+d['point'][args.x_accessor]);
                            dd.setDate(dd.getDate());

                            return fmt(dd) + '  ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                        else {
                            return args.x_accessor + ': ' + num(d['point'][args.x_accessor])
                                + ', ' + args.y_accessor + ': ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                    });
            }
        }
    }

    this.rolloverOff = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d,i){
            //reset active point
            var pts = svg.selectAll('.points circle')
                .classed('unselected', false)
                .classed('selected', false);

            if (args.size_accessor){
                pts.attr('r', args.scalefns.size);
            } else {
                pts.attr('r', 2);
            }

            //reset active data point text
            svg.select('.active_datapoint')
                .text('');
        }
    }

    this.update = function(args) {
        return this;
    }

    this.init(args);

    return this;
}
<commit_msg>Fix issue #154<commit_after>charts.point = function(args) {
    this.args = args;

    this.init = function(args) {
        raw_data_transformation(args);
        process_point(args);
        init(args);
        x_axis(args);
        y_axis(args);
        return this;
    }

    this.markers = function() {
        markers(args);
        if (args.least_squares){
            add_ls(args);
        }
        // if (args.lowess){
        //     add_lowess(args);
        // }
        return this
    }

    this.mainPlot = function() {
        var svg = d3.select(args.target + ' svg');
        var g;

        // plot the points, pretty straight-forward
        g = svg.append('g')
            .classed('points', true);

        var pts = g.selectAll('circle')
            .data(args.data[0])
            .enter().append('svg:circle')
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf);

        if (args.color_accessor!=null){
            pts.attr('fill',   args.scalefns.color);
            pts.attr('stroke', args.scalefns.color);
        } else {
            pts.attr('fill',   '#0000ff');
            pts.attr('stroke', '#0000ff');
        }
        if (args.size_accessor!=null){
            pts.attr('r', args.scalefns.size);
        } else {
            pts.attr('r', 2);
        }
        var rug;
        if (args.x_rug){
            //var data = args.data[0].map(function(d){return d[args.x_accessor]});
            rug=g.selectAll('line.x_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.scalefns.xf)
                .attr('x2', args.scalefns.xf)
                .attr('y1', args.height-args.top+args.buffer)
                .attr('y2', args.height-args.top)
                .attr('opacity', .3);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }
        if (args.y_rug){
            rug=g.selectAll('line.y_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.left+1)
                .attr('x2', args.left+args.buffer)
                .attr('y1', args.scalefns.yf)
                .attr('y2', args.scalefns.yf)
                .attr('stroke', 'black')
                .attr('opacity', .2);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }

        return this;
    }

    this.rollover = function() {
        var svg = d3.select(args.target + ' svg');

        var clips = svg.append('g')
                .attr('id', 'point-clips');

        var paths = svg.append('g')
            .attr('id', 'point-paths');

        //remove rollover text if it already exists
        if($(args.target + ' svg .active_datapoint').length > 0) {
            $(args.target + ' svg .active_datapoint').remove();
        }

        //add rollover text
        svg.append('text')
            .attr('class', 'active_datapoint')
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end');

        clips.selectAll('clipPath')
            .data(args.data[0])
                .enter().append('clipPath')
                    .attr('id', function(d, i) { return 'clip-'+i;})
                    .append('circle')
                        .attr('cx', args.scalefns.xf)
                        .attr('cy', args.scalefns.yf)
                        .attr('r', 20);

        var voronoi = d3.geom.voronoi()
            .x(args.scalefns.xf)
            .y(args.scalefns.yf)
            .clipExtent([[args.buffer, args.buffer], [args.width - args.buffer, args.height - args.buffer]]);

        paths.selectAll('path')
            .data(voronoi(args.data[0]))
            .enter().append('path')
                .attr('d', function(d) {
                    return 'M' + d.join(',') + 'Z';
                })
                .attr('id', function(d,i) {
                    return 'path-' + i;
                })
                .attr('clip-path', function(d,i) {
                    return 'url(#clip-'+i+')';
                })
                .style('fill-opacity', 0)
                .on('mouseover', this.rolloverOn(args))
                .on('mouseout', this.rolloverOff(args));

        return this;
    }

    this.rolloverOn = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d, i){
            svg.selectAll('.points circle')
                .classed('unselected', true);

            var fmt = d3.time.format('%b %e, %Y');

            if (args.format == 'count') {
                var num = function(d_) {
                    var is_float = d_ % 1 != 0;
                    var n = d3.format("0,000");
                    d_ = is_float ? d3.round(d_, args.decimals) : d_;
                    return n(d_);
                }
            }
            else {
                var num = function(d_) {
                    var fmt_string = (args.decimals ? '.' + args.decimals : '' ) + '%';
                    var n = d3.format(fmt_string);
                    return n(d_);
                }
            }

            //highlight active point
            var pts = svg.selectAll('.points circle')
                .filter(function(g,j){return i == j})
                .classed('unselected', false)
                .classed('selected', true);

            if (args.size_accessor){
                pts.attr('r', function(di){return args.scalefns.size(di)+1});
            } else {
                pts.attr('r', 3);
            }

            //update rollover text
            if (args.show_rollover_text) {
                svg.select('.active_datapoint')
                    .text(function() {
                        if(args.time_series) {
                            var dd = new Date(+d['point'][args.x_accessor]);
                            dd.setDate(dd.getDate());

                            return fmt(dd) + '  ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                        else {
                            return args.x_accessor + ': ' + num(d['point'][args.x_accessor])
                                + ', ' + args.y_accessor + ': ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                    });
            }
        }
    }

    this.rolloverOff = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d,i){
            //reset active point
            var pts = svg.selectAll('.points circle')
                .classed('unselected', false)
                .classed('selected', false);

            if (args.size_accessor){
                pts.attr('r', args.scalefns.size);
            } else {
                pts.attr('r', 2);
            }

            //reset active data point text
            svg.select('.active_datapoint')
                .text('');
        }
    }

    this.update = function(args) {
        return this;
    }

    this.init(args);

    return this;
}
<|endoftext|>


<commit_before>charts.point = function(args) {
    this.args = args;

    this.init = function(args) {
        raw_data_transformation(args);
        process_point(args);
        init(args);
        x_axis(args);
        y_axis(args);
        return this;
    }

    this.markers = function() {
        markers(args);
        if (args.least_squares){
            add_ls(args);
        }
        // if (args.lowess){
        //     add_lowess(args);
        // }
        return this
    }

    this.mainPlot = function() {
        var svg = d3.select(args.target + ' svg');
        var g;

        // plot the points, pretty straight-forward
        g = svg.append('g')
            .classed('points', true);

        var pts = g.selectAll('circle')
            .data(args.data[0])
            .enter().append('svg:circle')
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf);

        if (args.color_accessor!=null){
            pts.attr('fill',   args.scalefns.color);
            pts.attr('stroke', args.scalefns.color);
        } else {
            pts.attr('fill',   '#0000ff');
            pts.attr('stroke', '#0000ff');
        }
        if (args.size_accessor!=null){
            pts.attr('r', args.scalefns.size);
        } else {
            pts.attr('r', 2);
        }
        var rug;
        if (args.x_rug){
            //var data = args.data[0].map(function(d){return d[args.x_accessor]});
            rug=g.selectAll('line.x_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.scalefns.xf)
                .attr('x2', args.scalefns.xf)
                .attr('y1', args.height-args.top+args.buffer)
                .attr('y2', args.height-args.top)
                .attr('opacity', .3);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }
        if (args.y_rug){
            rug=g.selectAll('line.y_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.left+1)
                .attr('x2', args.left+args.buffer)
                .attr('y1', args.scalefns.yf)
                .attr('y2', args.scalefns.yf)
                .attr('stroke', 'black')
                .attr('opacity', .2);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }

        return this;
    }

    this.rollover = function() {
        var svg = d3.select(args.target + ' svg');

        var clips = svg.append('g')
                .attr('id', 'point-clips');

        var paths = svg.append('g')
            .attr('id', 'point-paths');

        //remove rollover text if it already exists
        if($(args.target + ' svg .active_datapoint').length > 0) {
            $(args.target + ' svg .active_datapoint').remove();
        }

        //add rollover text
        svg.append('text')
            .attr('class', 'active_datapoint')
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end');

        clips.selectAll('clipPath')
            .data(args.data[0])
                .enter().append('clipPath')
                    .attr('id', function(d, i) { return 'clip-'+i;})
                    .append('circle')
                        .attr('cx', args.scalefns.xf)
                        .attr('cy', args.scalefns.yf)
                        .attr('r', 20);

        var voronoi = d3.geom.voronoi()
            .x(args.scalefns.xf)
            .y(args.scalefns.yf)
            .clipExtent([[args.buffer, args.buffer], [args.width - args.buffer, args.height - args.buffer]]);

        paths.selectAll('path')
            .data(voronoi(args.data[0]))
            .enter().append('path')
                .attr('d', function(d) {
                    return 'M' + d.join(',') + 'Z';
                })
                .attr('id', function(d,i) {
                    return 'path-' + i;
                })
                .attr('clip-path', function(d,i) {
                    return 'url(#clip-'+i+')';
                })
                .style('fill-opacity', 0)
                .on('mouseover', this.rolloverOn(args))
                .on('mouseout', this.rolloverOff(args));

        return this;
    }

    this.rolloverOn = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d, i){
            svg.selectAll('.points circle')
                .classed('unselected', true);

            var fmt = d3.time.format('%b %e, %Y');

            if (args.format == 'count') {
                var num = function(d_) {
                    var is_float = d_ % 1 != 0;
                    var n = d3.format("0,000");
                    d_ = is_float ? d3.round(d_, args.decimals) : d_;
                    return n(d_);
                }
            }
            else {
                var num = function(d_) {
                    var fmt_string = (args.decimals ? '.' + args.decimals : '' ) + '%';
                    var n = d3.format(fmt_string);
                    return n(d_);
                }
            }

            //highlight active point
            var pts = svg.selectAll('.points circle')
                .filter(function(g,j){return i == j})
                .classed('unselected', false)
                .classed('selected', true);

            if (args.size_accessor){
                pts.attr('r', function(di){return args.scalefns.size(di)+1});
            } else {
                pts.attr('r', 3);
            }

            //update rollover text
            if (args.show_rollover_text) {
                svg.select('.active_datapoint')
                    .text(function() {
                        if(args.time_series) {
                            var dd = new Date(+d['point'][args.x_accessor]);
                            dd.setDate(dd.getDate());

                            return fmt(dd) + '  ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                        else {
                            return args.x_accessor + ': ' + num(d['point'][args.x_accessor])
                                + ', ' + args.y_accessor + ': ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                    });
            }
        }
    }

    this.rolloverOff = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d,i){
            //reset active point
            var pts = svg.selectAll('.points circle')
                .classed('unselected', false)
                .classed('selected', false);

            if (args.size_accessor){
                pts.attr('r', args.scalefns.size);
            } else {
                pts.attr('r', 2);
            }

            //reset active data point text
            svg.select('.active_datapoint')
                .text('');
        }
    }

    this.update = function(args) {
        return this;
    }

    this.init(args);

    return this;
}
<commit_msg>Fix issue #154<commit_after>charts.point = function(args) {
    this.args = args;

    this.init = function(args) {
        raw_data_transformation(args);
        process_point(args);
        init(args);
        x_axis(args);
        y_axis(args);
        return this;
    }

    this.markers = function() {
        markers(args);
        if (args.least_squares){
            add_ls(args);
        }
        // if (args.lowess){
        //     add_lowess(args);
        // }
        return this
    }

    this.mainPlot = function() {
        var svg = d3.select(args.target + ' svg');
        var g;

        // plot the points, pretty straight-forward
        g = svg.append('g')
            .classed('points', true);

        var pts = g.selectAll('circle')
            .data(args.data[0])
            .enter().append('svg:circle')
                .attr('cx', args.scalefns.xf)
                .attr('cy', args.scalefns.yf);

        if (args.color_accessor!=null){
            pts.attr('fill',   args.scalefns.color);
            pts.attr('stroke', args.scalefns.color);
        } else {
            pts.attr('fill',   '#0000ff');
            pts.attr('stroke', '#0000ff');
        }
        if (args.size_accessor!=null){
            pts.attr('r', args.scalefns.size);
        } else {
            pts.attr('r', 2);
        }
        var rug;
        if (args.x_rug){
            //var data = args.data[0].map(function(d){return d[args.x_accessor]});
            rug=g.selectAll('line.x_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.scalefns.xf)
                .attr('x2', args.scalefns.xf)
                .attr('y1', args.height-args.top+args.buffer)
                .attr('y2', args.height-args.top)
                .attr('opacity', .3);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }
        if (args.y_rug){
            rug=g.selectAll('line.y_rug').data(args.data[0]).enter().append('svg:line')
                .attr('x1', args.left+1)
                .attr('x2', args.left+args.buffer)
                .attr('y1', args.scalefns.yf)
                .attr('y2', args.scalefns.yf)
                .attr('stroke', 'black')
                .attr('opacity', .2);
            if (args.color_accessor){
                rug.attr('stroke', args.scalefns.color);
            } else {
                rug.attr('stroke', 'black');
            }
        }

        return this;
    }

    this.rollover = function() {
        var svg = d3.select(args.target + ' svg');

        var clips = svg.append('g')
                .attr('id', 'point-clips');

        var paths = svg.append('g')
            .attr('id', 'point-paths');

        //remove rollover text if it already exists
        if($(args.target + ' svg .active_datapoint').length > 0) {
            $(args.target + ' svg .active_datapoint').remove();
        }

        //add rollover text
        svg.append('text')
            .attr('class', 'active_datapoint')
            .attr('xml:space', 'preserve')
            .attr('x', args.width - args.right)
            .attr('y', args.top / 2)
            .attr('text-anchor', 'end');

        var voronoi = d3.geom.voronoi()
            .x(args.scalefns.xf)
            .y(args.scalefns.yf)
            .clipExtent([[args.buffer, args.buffer], [args.width - args.buffer, args.height - args.buffer]]);

        paths.selectAll('path')
            .data(voronoi(args.data[0]))
            .enter().append('path')
                .attr('d', function(d) {
                    return 'M' + d.join(',') + 'Z';
                })
                .attr('id', function(d,i) {
                    return 'path-' + i;
                })
                .attr('clip-path', function(d,i) {
                    return 'url(#clip-'+i+')';
                })
                .style('fill-opacity', 0)
                .on('mouseover', this.rolloverOn(args))
                .on('mouseout', this.rolloverOff(args));

        return this;
    }

    this.rolloverOn = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d, i){
            svg.selectAll('.points circle')
                .classed('unselected', true);

            var fmt = d3.time.format('%b %e, %Y');

            if (args.format == 'count') {
                var num = function(d_) {
                    var is_float = d_ % 1 != 0;
                    var n = d3.format("0,000");
                    d_ = is_float ? d3.round(d_, args.decimals) : d_;
                    return n(d_);
                }
            }
            else {
                var num = function(d_) {
                    var fmt_string = (args.decimals ? '.' + args.decimals : '' ) + '%';
                    var n = d3.format(fmt_string);
                    return n(d_);
                }
            }

            //highlight active point
            var pts = svg.selectAll('.points circle')
                .filter(function(g,j){return i == j})
                .classed('unselected', false)
                .classed('selected', true);

            if (args.size_accessor){
                pts.attr('r', function(di){return args.scalefns.size(di)+1});
            } else {
                pts.attr('r', 3);
            }

            //update rollover text
            if (args.show_rollover_text) {
                svg.select('.active_datapoint')
                    .text(function() {
                        if(args.time_series) {
                            var dd = new Date(+d['point'][args.x_accessor]);
                            dd.setDate(dd.getDate());

                            return fmt(dd) + '  ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                        else {
                            return args.x_accessor + ': ' + num(d['point'][args.x_accessor])
                                + ', ' + args.y_accessor + ': ' + args.yax_units
                                + num(d['point'][args.y_accessor]);
                        }
                    });
            }
        }
    }

    this.rolloverOff = function(args) {
        var svg = d3.select(args.target + ' svg');

        return function(d,i){
            //reset active point
            var pts = svg.selectAll('.points circle')
                .classed('unselected', false)
                .classed('selected', false);

            if (args.size_accessor){
                pts.attr('r', args.scalefns.size);
            } else {
                pts.attr('r', 2);
            }

            //reset active data point text
            svg.select('.active_datapoint')
                .text('');
        }
    }

    this.update = function(args) {
        return this;
    }

    this.init(args);

    return this;
}
<|endoftext|>


<commit_before>'use strict'
const clearKeys = require('vigour-observable').prototype.clearKeys

// will become a million times cleaner
exports.properties = {
  insertBefore (val) {
    console.log('is this ever used???')
    this.__order = this.parent[val].__order - 0.5
  },
  index: true,
  __order: true
}

exports.define = {
  addNewProperty  (key, val, stamp) {
    if (val.val !== null) {
      this[key] = val
      this.clearKeys(val)
      if (this._Constructor) {
        this.createContextGetter(key)
      }
      if (val.isElement && !val.__order) {
        val.__order = val.uid()
      }
    }
  },
  keysInternal (keys, field, check) {
    if (!keys && keys !== false) {
      keys = this[field] = []
      let prevorder
      let easyorder
      let ordered
      let target
      // ---
      for (let key in this) {
        if (key[0] !== '_' && ((target = this[key]), target !== null) && check(this, key, field)) {
          if (!ordered) {
            if (target.order) {
              ordered = true
            } else if (!easyorder) {
              let order = target.__order
              if (order > prevorder) {
                easyorder = true
              }
              prevorder = order
            }
          }
          // check if keys need to be sorted by uid
          // if this is true => we need to sort the shit
          keys.push(key)
        }
      }
      if (ordered) {
        // @todo: .sort is very slow fix this using a custom qsort
        keys.sort(this.sort.bind(this))
      } else if (easyorder) {
        keys.sort((a, b) => this[a].__order - this[b].__order)
      } if (!keys[0]) {
        keys = this[field] = false
      }
      if (keys && field === '_keys') {
        cacheIndex(this, keys)
      }
    }
    return keys
  },
  clearKeys (target) {
    this._staticElements = void 0
    this._staticProps = void 0
    clearKeys.apply(this, arguments)
  },
  sort (a, b) {
    let ai = this[a].order || 0
    let bi = this[b].order || 0
    ai = ai.compute && ai.compute() || ai || 0
    bi = bi.compute && bi.compute() || bi || 0
    return ai === bi ? this[a].__order - this[b].__order : ai < bi ? -1 : 1
  }
}

function cacheIndex (target, keys) {
  // do this in sort (one loop)
  for (let i = 0, len = keys.length; i < len; i++) {
    target[keys[i]].index = i
  }
}
<commit_msg>start of keys refactor<commit_after>'use strict'
const clearKeys = require('vigour-observable').prototype.clearKeys

// will become a million times cleaner
exports.properties = {
  insertBefore (val) {
    console.log('is this ever used???')
    this.__order = this.parent[val].__order - 0.5
  },
  index: true,
  __order: true
}

//clearkeys is gone ofcourse

exports.define = {
  addNewProperty  (key, val, stamp) {
    if (val.val !== null) {
      this[key] = val
      this.clearKeys(val)
      if (this._Constructor) {
        this.createContextGetter(key)
      }
      if (val.isElement && !val.__order) {
        val.__order = val.uid()
      }
    }
  },
  keysInternal (keys, field, check) {
    if (!keys && keys !== false) {
      keys = this[field] = []
      let prevorder
      let easyorder
      let ordered
      let target
      // ---
      for (let key in this) {
        if (key[0] !== '_' && ((target = this[key]), target !== null) && check(this, key, field)) {
          if (!ordered) {
            if (target.order) {
              ordered = true
            } else if (!easyorder) {
              let order = target.__order
              if (order > prevorder) {
                easyorder = true
              }
              prevorder = order
            }
          }
          // check if keys need to be sorted by uid
          // if this is true => we need to sort the shit
          keys.push(key)
        }
      }
      if (ordered) {
        // @todo: .sort is very slow fix this using a custom qsort
        keys.sort(this.sort.bind(this))
      } else if (easyorder) {
        keys.sort((a, b) => this[a].__order - this[b].__order)
      } if (!keys[0]) {
        keys = this[field] = false
      }
      if (keys && field === '_keys') {
        cacheIndex(this, keys)
      }
    }
    return keys
  },
  clearKeys (target) {
    this._staticElements = void 0
    this._staticProps = void 0
    clearKeys.apply(this, arguments)
  },
  sort (a, b) {
    let ai = this[a].order || 0
    let bi = this[b].order || 0
    ai = ai.compute && ai.compute() || ai || 0
    bi = bi.compute && bi.compute() || bi || 0
    return ai === bi ? this[a].__order - this[b].__order : ai < bi ? -1 : 1
  }
}

function cacheIndex (target, keys) {
  // do this in sort (one loop)
  for (let i = 0, len = keys.length; i < len; i++) {
    target[keys[i]].index = i
  }
}
<|endoftext|>


<commit_before><commit_msg>added test suite for audit log (#5681)<commit_after><|endoftext|>


<commit_before>var request = require('request');
var _ = require('underscore');
require('../public/userdata');

function updateDb(model, entry) {
	model.set('entries.' + entry.id, entry);
}

function processTraktRequest(entry, data) {
	entry.image = data.images.poster;
	entry.synopsis = data.overview;
	entry.genres = data.genres;

	entry.seasons = []; //TODO: Merge seasons
	entry.episodes = [];
	for (var i = 0; i < data.seasons.length; ++i) {
		entry.seasons.push({
			season: data.seasons[i].season,
			image: data.seasons[i].images.poster,
			providers: {
				mal: null,
				trakt: data.tvdb_id
			}
		});

		entry.episodes = entry.episodes.concat(_.map(data.seasons[i].episodes, function (episode) {
			return {
				season: episode.season,
				episode: episode.episode,
				title: episode.title,
				synopsis: episode.overview,
				image: episode.screen
			};
		}));
	}
}

function processTraktMovie(entry, data) {
	entry.image = data.images.poster;
	entry.synopsis = data.overview;
	entry.genres = data.genres;
}

function processMalRequest(entry, data) {
	entry.synopsis = data.synopsis;
	entry.genres = data.genres;
	entry.image = data.image_url;

	/*
	for (var i = 0; i < data.episodes; ++i) {
		entry.episodes[i] = {
			season: entry.seasons.length,
			episode: i + 1,
			title: null,
			synopsis: null,
			image: null
		};
	}*/
}

exports.refreshMetadata = function (model, id) {
	var entries = {};
	if (id) {
		entries[id] = model.get('entries.' + id);
	} else {
		entries = model.get('entries');
	}

	_.forEach(entries, function (entry) {
		if (entry.metadataProvider === 'trakt') {
			request('http://api.trakt.tv/show/summary.json/' + Trakt.apiKey + '/' + entry.metadataId + '/true/', function (err, resp, data) {
				if (err) throw e;
				data = JSON.parse(data);

				processTraktRequest(entry, data);
				updateDb(model, entry);
			});
		} else if (entry.metadataProvider === 'trakt-movie') {
			request('http://api.trakt.tv/show/summary.json/' + Trakt.apiKey + '/' + entry.metadataId + '/true/', function (err, resp, data) {
				if (err) throw e;
				data = JSON.parse(data);

				processTraktMovie(entry, data);
				updateDb(model, entry);
			});
		} else if (entry.metadataProvider === 'mal') {
			request('http://mal-api.com/anime/' + entry.metadataId, function (err, resp, data) {
				if (err) throw e;
				data = JSON.parse(data);

				processMalRequest(entry, data);
				updateDb(model, entry);
			});
		}

		//TODO: process seasons
	});
};<commit_msg>Only refresh the metadata once per day<commit_after>var request = require('request');
var _ = require('underscore');
require('../public/userdata');

function updateDb(model, entry) {
	entry.lastUpdated = Date.now();
	model.set('entries.' + entry.id, entry);
}

function processTraktRequest(entry, data) {
	entry.image = data.images.poster;
	entry.synopsis = data.overview;
	entry.genres = data.genres;

	entry.seasons = []; //TODO: Merge seasons
	entry.episodes = [];
	for (var i = 0; i < data.seasons.length; ++i) {
		entry.seasons.push({
			season: data.seasons[i].season,
			image: data.seasons[i].images.poster,
			providers: {
				mal: null,
				trakt: data.tvdb_id
			}
		});

		entry.episodes = entry.episodes.concat(_.map(data.seasons[i].episodes, function (episode) {
			return {
				season: episode.season,
				episode: episode.episode,
				title: episode.title,
				synopsis: episode.overview,
				image: episode.screen
			};
		}));
	}
}

function processTraktMovie(entry, data) {
	entry.image = data.images.poster;
	entry.synopsis = data.overview;
	entry.genres = data.genres;
}

function processMalRequest(entry, data) {
	entry.synopsis = data.synopsis;
	entry.genres = data.genres;
	entry.image = data.image_url;

	/*
	for (var i = 0; i < data.episodes; ++i) {
		entry.episodes[i] = {
			season: entry.seasons.length,
			episode: i + 1,
			title: null,
			synopsis: null,
			image: null
		};
	}*/
}

exports.refreshMetadata = function (model, id) {
	var entries = {};
	if (id) {
		entries[id] = model.get('entries.' + id);
	} else {
		entries = model.get('entries');
	}

	var maxUpdated = Date.now() - 3600 * 24 * 1000;
	_.forEach(entries, function (entry) {
		if (entry.lastUpdated >= maxUpdated) return;

		if (entry.metadataProvider === 'trakt') {
			request('http://api.trakt.tv/show/summary.json/' + Trakt.apiKey + '/' + entry.metadataId + '/true/', function (err, resp, data) {
				if (err) throw e;
				data = JSON.parse(data);

				processTraktRequest(entry, data);
				updateDb(model, entry);
			});
		} else if (entry.metadataProvider === 'trakt-movie') {
			request('http://api.trakt.tv/show/summary.json/' + Trakt.apiKey + '/' + entry.metadataId + '/true/', function (err, resp, data) {
				if (err) throw e;
				data = JSON.parse(data);

				processTraktMovie(entry, data);
				updateDb(model, entry);
			});
		} else if (entry.metadataProvider === 'mal') {
			request('http://mal-api.com/anime/' + entry.metadataId, function (err, resp, data) {
				if (err) throw e;
				data = JSON.parse(data);

				processMalRequest(entry, data);
				updateDb(model, entry);
			});
		}

		//TODO: process seasons
	});
};<|endoftext|>


<commit_before>/**
 * Jasmine-Bloom - Cleaner reporting with metadata output for your Jasmine specs
 * Copyright (C) 2010, Rudy Lattae
 * License: Simplified BSD
 *
 * Jasmine-Bloom provides a slightly modified Html Reporter that outputs additional
 * meta-data relating to your specs. The aim is to make it easier to modify the
 * presentation of the spec report.
 */

// Top level namespace for the package
jasmine.bloom = (typeof jasmine.bloom === 'undefined') ? {} : jasmine.bloom;

jasmine.bloom.VERSION = '0.4.2dev';

jasmine.bloom.StyledHtmlReporter = function(doc) {
    this.document = doc || document;
    this.suiteDivs = {};
    this.logRunningSpecs = false;
};

jasmine.bloom.StyledHtmlReporter.prototype = new jasmine.TrivialReporter();
jasmine.bloom.StyledHtmlReporter.prototype.constructor = jasmine.aroma.StyledHtmlReporter;

jasmine.bloom.StyledHtmlReporter.prototype.reportRunnerStarting = function(runner) {
  var showPassed, showSkipped;

  this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' },
      this.createDom('div', { className: 'banner' },
        this.createDom('div', { className: 'logo' },
            this.createDom('a', { href: 'http://pivotal.github.com/jasmine/', target: "_blank" }, "Jasmine"),
            this.createDom('span', { className: 'version' }, runner.env.versionString())),
        this.createDom('div', { className: 'options' },
            "Show ",
            showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
            this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
            showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
            this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
            )
          ),

      this.runnerDiv = this.createDom('div', { className: 'runner running' },
          this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
          this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
          this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
      );

  this.document.body.appendChild(this.outerDiv);

  var suites = runner.suites();
  for (var i = 0; i < suites.length; i++) {
    var suite = suites[i];

    var suiteTags = (typeof suite.tags === 'undefined') ? '' : ' ' + suite.tags.join(' ');
    var suiteDiv = this.createDom('div', { className: 'suite' + suiteTags },
        this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
        this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description),
        (typeof suite.details !== 'undefined') ? this.createDomFromDetails(suite.details) : null,
        (typeof suite.expose !== 'undefined' && suite.expose) ? this.createDom('pre', {}, suite.defs): null);
    this.suiteDivs[suite.id] = suiteDiv;
    var parentDiv = this.outerDiv;
    if (suite.parentSuite) {
      parentDiv = this.suiteDivs[suite.parentSuite.id];
    }
    parentDiv.appendChild(suiteDiv);
  }

  this.startedAt = new Date();

  var self = this;
  showPassed.onchange = function(evt) {
    if (evt.target.checked) {
      self.outerDiv.className += ' show-passed';
    } else {
      self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
    }
  };

  showSkipped.onchange = function(evt) {
    if (evt.target.checked) {
      self.outerDiv.className += ' show-skipped';
    } else {
      self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
    }
  };
};

jasmine.bloom.StyledHtmlReporter.prototype.reportSuiteResults = function(suite) {
  var results = suite.results();
  var status = results.passed() ? 'passed' : 'failed';
  if (results.totalCount == 0 && (!status == 'failed' || !suite.isIntermediate)) { // todo: change this to check results.skipped
    status = 'skipped';
  }
  this.suiteDivs[suite.id].className += " " + status;
};

/**
 * Creates the proper dom element for the given details object.
 *
 * If the details.value is a simple string, the element created is a "p".
 * If the details.value is a list, the element created is an unordered list.
 * The details.tags are rendered to the class attribute on the dom element created
 */
jasmine.bloom.StyledHtmlReporter.prototype.createDomFromDetails = function(details) {
    var classAttrs = '';
    if (typeof details.tags !== 'undefined') {
        classAttrs = (details.tags instanceof Array) ? details.tags.join(' ') : details.tags;
    }
    if (details.value instanceof Array) {
        return this.createDomList('ul', { className: classAttrs}, details.value);
    }

    return this.createDom('p', { className: classAttrs}, details.value);
}

/**
 * Creates dom element with the suite defs as content
 */
jasmine.bloom.StyledHtmlReporter.prototype.createDomFromSuiteDefs = function(defs) {
    var classAttrs = '';
    if (typeof defs !== 'undefined') {
        return this.createDom('p', {}, defs);
    }
}

/**
 * Creates a list of 'li' elements given an array
 */
jasmine.bloom.StyledHtmlReporter.prototype.createDomList = function(type, attrs, items) {
    var list;
    if (typeof items !== 'undefined' && items.length > 0) {
        list = this.createDom(type, attrs);
        for (var i = 0; i < items.length; i++) {
            list.appendChild(this.createDom('li', {}, items[i]));
        }
    }
    return list;
};<commit_msg>Upped the version<commit_after>/**
 * Jasmine-Bloom - Cleaner reporting with metadata output for your Jasmine specs
 * Copyright (C) 2010, Rudy Lattae
 * License: Simplified BSD
 *
 * Jasmine-Bloom provides a slightly modified Html Reporter that outputs additional
 * meta-data relating to your specs. The aim is to make it easier to modify the
 * presentation of the spec report.
 */

// Top level namespace for the package
jasmine.bloom = (typeof jasmine.bloom === 'undefined') ? {} : jasmine.bloom;

jasmine.bloom.VERSION = '0.4.3dev';

jasmine.bloom.StyledHtmlReporter = function(doc) {
    this.document = doc || document;
    this.suiteDivs = {};
    this.logRunningSpecs = false;
};

jasmine.bloom.StyledHtmlReporter.prototype = new jasmine.TrivialReporter();
jasmine.bloom.StyledHtmlReporter.prototype.constructor = jasmine.aroma.StyledHtmlReporter;

jasmine.bloom.StyledHtmlReporter.prototype.reportRunnerStarting = function(runner) {
  var showPassed, showSkipped;

  this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' },
      this.createDom('div', { className: 'banner' },
        this.createDom('div', { className: 'logo' },
            this.createDom('a', { href: 'http://pivotal.github.com/jasmine/', target: "_blank" }, "Jasmine"),
            this.createDom('span', { className: 'version' }, runner.env.versionString())),
        this.createDom('div', { className: 'options' },
            "Show ",
            showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
            this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
            showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
            this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
            )
          ),

      this.runnerDiv = this.createDom('div', { className: 'runner running' },
          this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
          this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
          this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
      );

  this.document.body.appendChild(this.outerDiv);

  var suites = runner.suites();
  for (var i = 0; i < suites.length; i++) {
    var suite = suites[i];

    var suiteTags = (typeof suite.tags === 'undefined') ? '' : ' ' + suite.tags.join(' ');
    var suiteDiv = this.createDom('div', { className: 'suite' + suiteTags },
        this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
        this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description),
        (typeof suite.details !== 'undefined') ? this.createDomFromDetails(suite.details) : null,
        (typeof suite.expose !== 'undefined' && suite.expose) ? this.createDom('pre', {}, suite.defs): null);
    this.suiteDivs[suite.id] = suiteDiv;
    var parentDiv = this.outerDiv;
    if (suite.parentSuite) {
      parentDiv = this.suiteDivs[suite.parentSuite.id];
    }
    parentDiv.appendChild(suiteDiv);
  }

  this.startedAt = new Date();

  var self = this;
  showPassed.onchange = function(evt) {
    if (evt.target.checked) {
      self.outerDiv.className += ' show-passed';
    } else {
      self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
    }
  };

  showSkipped.onchange = function(evt) {
    if (evt.target.checked) {
      self.outerDiv.className += ' show-skipped';
    } else {
      self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
    }
  };
};

jasmine.bloom.StyledHtmlReporter.prototype.reportSuiteResults = function(suite) {
  var results = suite.results();
  var status = results.passed() ? 'passed' : 'failed';
  if (results.totalCount == 0 && (!status == 'failed' || !suite.isIntermediate)) { // todo: change this to check results.skipped
    status = 'skipped';
  }
  this.suiteDivs[suite.id].className += " " + status;
};

/**
 * Creates the proper dom element for the given details object.
 *
 * If the details.value is a simple string, the element created is a "p".
 * If the details.value is a list, the element created is an unordered list.
 * The details.tags are rendered to the class attribute on the dom element created
 */
jasmine.bloom.StyledHtmlReporter.prototype.createDomFromDetails = function(details) {
    var classAttrs = '';
    if (typeof details.tags !== 'undefined') {
        classAttrs = (details.tags instanceof Array) ? details.tags.join(' ') : details.tags;
    }
    if (details.value instanceof Array) {
        return this.createDomList('ul', { className: classAttrs}, details.value);
    }

    return this.createDom('p', { className: classAttrs}, details.value);
}

/**
 * Creates dom element with the suite defs as content
 */
jasmine.bloom.StyledHtmlReporter.prototype.createDomFromSuiteDefs = function(defs) {
    var classAttrs = '';
    if (typeof defs !== 'undefined') {
        return this.createDom('p', {}, defs);
    }
}

/**
 * Creates a list of 'li' elements given an array
 */
jasmine.bloom.StyledHtmlReporter.prototype.createDomList = function(type, attrs, items) {
    var list;
    if (typeof items !== 'undefined' && items.length > 0) {
        list = this.createDom(type, attrs);
        for (var i = 0; i < items.length; i++) {
            list.appendChild(this.createDom('li', {}, items[i]));
        }
    }
    return list;
};<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// getWeek and getUTCWeekYear are from:
// van den Broek, Taco. Calculate ISO 8601 week and year in javascript. Procuios. 2009-04-22. URL:http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html. Accessed: 2015-12-07. (Archived by WebCite® at http://www.webcitation.org/6dbdvnbtj)
// Released and used under the MIT license.

// Get ISO 8601 week number for a date.
Date.prototype.getUTCWeek = function () {
	var target  = new Date(this.valueOf());
	var dayNr   = (this.getUTCDay() + 6) % 7;
	target.setDate(target.getUTCDate() - dayNr + 3);
	var firstThursday = target.valueOf();
	target.setUTCMonth(0, 1);
	if (target.getUTCDay() != 4) {
		target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
	}
	return 1 + Math.ceil((firstThursday - target) / 604800000);
}

// Get ISO 8601 year, assuming we're using week numbers.
Date.prototype.getUTCWeekYear = function () {
	var target	= new Date(this.valueOf());
	target.setUTCDate(target.getUTCDate() - ((this.getUTCDay() + 6) % 7) + 3);
	return target.getUTCFullYear();
}

// Get ISO 8610 year and week in form "2016-W01"
Date.prototype.getUTCISOWeekDate = function ()  {
	var week = this.getUTCWeek();
	week = ("0"+week).slice(-2); // Zero pad.
	var year = this.getUTCWeekYear();
	return year+"-W"+week;
}

Date.prototype.getUTCISOYearMonth = function() {
	var year = this.getUTCFullYear();
	var month = this.getUTCMonth()+1;
	month = ("0"+month).slice(-2); // Zero pad.
	return year+"-"+month;
}

Date.prototype.getUTCISOYearMonthDay = function() {
	var yearmonth = this.getUTCISOYearMonth();
	var day = this.getUTCDate();
	day = ("0"+day).slice(-2); // Zero pad.
	return yearmonth+"-"+day;
}

// Identical to "new Date(str)", but accepts ISO 8601 week dates (eg "2015-W04").
// Week dates will return midnight on the Monday morning of that week.
Date.parseMore = function(str) {
	var fields = /^(\d\d\d\d)-W(\d\d)$/.exec(str);
	if((!fields) || fields.length !== 3) { return new Date(Date.parse(str)); }
	var year = Number(fields[1]);
	var week = Number(fields[2]);

	// Based on http://stackoverflow.com/a/19375264/16672
	var d = new Date(Date.UTC(year, 0, 1));
	var week_in_ms = 1000*60*60*24*7;
	d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
	d.setTime(d.getTime() + week_in_ms * (week + (year == d.getUTCFullYear() ? -1 : 0 )));
	d.setUTCDate(d.getUTCDate() - 3);
	return d;
}
<commit_msg>UTC. Always UTC.<commit_after>////////////////////////////////////////////////////////////////////////////////
// getUTCWeek and getUTCWeekYear are from:
// van den Broek, Taco. Calculate ISO 8601 week and year in javascript. Procuios. 2009-04-22. URL:http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html. Accessed: 2015-12-07. (Archived by WebCite® at http://www.webcitation.org/6dbdvnbtj)
// Released and used under the MIT license.

// Get ISO 8601 week number for a date.
Date.prototype.getUTCWeek = function () {
	var target  = new Date(this.valueOf());
	var dayNr   = (this.getUTCDay() + 6) % 7;
	target.setUTCDate(target.getUTCDate() - dayNr + 3);
	var firstThursday = target.valueOf();
	target.setUTCMonth(0, 1);
	if (target.getUTCDay() != 4) {
		target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
	}
	return 1 + Math.ceil((firstThursday - target) / 604800000);
}

// Get ISO 8601 year, assuming we're using week numbers.
Date.prototype.getUTCWeekYear = function () {
	var target	= new Date(this.valueOf());
	target.setUTCDate(target.getUTCDate() - ((this.getUTCDay() + 6) % 7) + 3);
	return target.getUTCFullYear();
}

// Get ISO 8610 year and week in form "2016-W01"
Date.prototype.getUTCISOWeekDate = function ()  {
	var week = this.getUTCWeek();
	week = ("0"+week).slice(-2); // Zero pad.
	var year = this.getUTCWeekYear();
	return year+"-W"+week;
}

Date.prototype.getUTCISOYearMonth = function() {
	var year = this.getUTCFullYear();
	var month = this.getUTCMonth()+1;
	month = ("0"+month).slice(-2); // Zero pad.
	return year+"-"+month;
}

Date.prototype.getUTCISOYearMonthDay = function() {
	var yearmonth = this.getUTCISOYearMonth();
	var day = this.getUTCDate();
	day = ("0"+day).slice(-2); // Zero pad.
	return yearmonth+"-"+day;
}

// Identical to "new Date(str)", but accepts ISO 8601 week dates (eg "2015-W04"). Dates are assumed to always be in UTC.
// Week dates will return midnight on the Monday morning of that week.
Date.parseMore = function(str) {
	var fields = /^(\d\d\d\d)-W(\d\d)$/.exec(str);
	if((!fields) || fields.length !== 3) { return new Date(Date.parse(str)); }
	var year = Number(fields[1]);
	var week = Number(fields[2]);

	// Based on http://stackoverflow.com/a/19375264/16672
	var d = new Date(Date.UTC(year, 0, 1));
	var week_in_ms = 1000*60*60*24*7;
	d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
	d.setTime(d.getTime() + week_in_ms * (week + (year == d.getUTCFullYear() ? -1 : 0 )));
	d.setUTCDate(d.getUTCDate() - 3);
	return d;
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Component from 'hyper/component'
import decorate from 'hyper/decorate'

class HyperLine extends Component {
  static propTypes() {
    return {
      plugins: PropTypes.array.isRequired
    }
  }

  render() {
    const { plugins, ...props } = this.props

    return (

        {plugins.map((Component, index) => (

            <Component />

        ))}

    )
  }
}

export default decorate(HyperLine, 'HyperLine')
<commit_msg>Don't collide with the terminal<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Component from 'hyper/component'
import decorate from 'hyper/decorate'

class HyperLine extends Component {
  static propTypes() {
    return {
      plugins: PropTypes.array.isRequired
    }
  }

  render() {
    const { plugins, ...props } = this.props

    return (

        {plugins.map((Component, index) => (

            <Component />

        ))}

    )
  }
}

export default decorate(HyperLine, 'HyperLine')
<|endoftext|>