<commit_before>// grunt-exec
// ==========
// * GitHub: https://github.com/jharding/grunt-exec
// * Original Copyright (c) 2012 Jake Harding
// * Copyright (c) 2017 grunt-exec
// * Licensed under the MIT license.

// grunt-exe 2.0.0+ simulates the convenience of child_process.exec with the capabilities of child_process.spawn
// this was done primarily to preserve colored output from applications such as npm
// a lot of work was done to simulate the original behavior of both child_process.exec and grunt-exec
// as such there may be unintended consequences so the major revision was bumped
// a breaking change was made to the 'maxBuffer kill process' scenario so it is treated as an error and provides more detail (--verbose)
// stdout and stderr buffering & maxBuffer constraints are removed entirely where possible
// new features: detached (boolean), argv0 (override the executable name passed to the application), shell (boolean or string)
// fd #s greater than 2 not yet supported (ipc piping) which is spawn-specific and very rarely required
// TODO: support stdout and stderr Buffer objects passed in
// TODO: stdin/stdout/stderr string as file name => open the file and read/write from it

module.exports = function(grunt) {
  var cp = require('child_process')
    , f = require('util').format
    , _ = grunt.util._
    , log = grunt.log
    , verbose = grunt.verbose;

  grunt.registerMultiTask('exec', 'Execute shell commands.', function() {

    var callbackErrors = false;

    var defaultOut = log.write;
    var defaultError = log.error;

    var defaultCallback = function(err, stdout, stderr) {
      if (err) {
        callbackErrors = true;
        defaultError('Error executing child process: ' + err.toString());
      }
    };

    var data = this.data
      , execOptions = data.options !== undefined ? data.options : {}
      , stdout = data.stdout !== undefined ? data.stdout : true
      , stderr = data.stderr !== undefined ? data.stderr : true
      , stdin = data.stdin !== undefined ? data.stdin : false
      , stdio = data.stdio
      , callback = _.isFunction(data.callback) ? data.callback : defaultCallback
      , callbackArgs = data.callbackArgs !== undefined ? data.callbackArgs : []
      , sync = data.sync !== undefined ? data.sync : false
      , exitCodes = data.exitCode || data.exitCodes || 0
      , command
      , childProcess
      , args = [].slice.call(arguments, 0)
      , done = this.async();

    // https://github.com/jharding/grunt-exec/pull/30
    exitCodes = _.isArray(exitCodes) ? exitCodes : [exitCodes];

    // allow for command to be specified in either
    // 'command' or 'cmd' property, or as a string.
    command = data.command || data.cmd || (_.isString(data) && data);

    if (!command) {
      defaultError('Missing command property.');
      return done(false);
    }

    if (data.cwd && _.isFunction(data.cwd)) {
      execOptions.cwd = data.cwd.apply(grunt, args);
    } else if (data.cwd) {
      execOptions.cwd = data.cwd;
    }

    // default to current process cwd
    execOptions.cwd = execOptions.cwd || process.cwd();

    // manually supported (spawn vs exec)
    // 200*1024 is default maxBuffer of child_process.exec
    // NOTE: must be < require('buffer').kMaxLength or a RangeError will be triggered
    var maxBuffer = data.maxBuffer || execOptions.maxBuffer || (200*1024);

    // timeout manually supportted (spawn vs exec)
    execOptions.timeout = execOptions.timeout || data.timeout || 0;
    // kill signal manually supportted (spawn vs exec)
    execOptions.killSignal = execOptions.killSignal || data.killSignal || 'SIGTERM';

    // support shell scripts like 'npm.cmd' by default (spawn vs exec)
    var shell = (typeof data.shell === 'undefined') ? execOptions.shell : data.shell;
    execOptions.shell = (typeof shell === 'string') ? shell : (shell === false ? false : true);

    // kept in data.encoding in case it is set to 'buffer' for final callback
    data.encoding = data.encoding || execOptions.encoding || 'utf8';

    stdio = stdio || execOptions.stdio || undefined;
    if (stdio === 'inherit') {
      stdout = 'inherit';
      stderr = 'inherit';
      stdin = 'inherit';
    } else if (stdio === 'pipe') {
      stdout = 'pipe';
      stderr = 'pipe';
      stdin = 'pipe';
    } else if (stdio === 'ignore') {
      stdout = 'ignore';
      stderr = 'ignore';
      stdin = 'ignore';
    }

    if (_.isFunction(command)) {
      command = command.apply(grunt, args);
    }

    if (!_.isString(command)) {
      defaultError('Command property must be a string.');
      return done(false);
    }

    verbose.subhead(command);

    // manually parse args into array (spawn vs exec)
    var splitArgs = function(command) {
      // Regex Explanation                                          Regex
      // ---------------------------------------------------------------------
      // 0-* spaces                                                 \s*
      // followed by either:
      //   [NOT: a space, half quote, or double quote] 1-* times    [^\s'"]+
      //     followed by either:
      //       [half quote or double quote] in the future           (?=['"])
      //       or 1-* spaces                                        \s+
      //       or end of string                                     $
      //   or half quote                                            [']
      //     followed by 0-*:
      //       [NOT: a backslash, or half quote]                    [^\\']
      //       or a backslash followed by any character             \\.
      //     followed by a half quote                               [']
      //   or double quote                                          ["]
      //     followed by 0-*:
      //       [NOT: a backslash, or double quote]                  [^\\"]
      //       or a backslash followed by any character             \\.
      //     followed by a double quote                             ["]
      //   or end of string                                         $
      var pieces = command.match(/\s*([^\s'"]+(?:(?=['"])|\s+|$)|(?:(?:['](?:([^\\']|\\.)*)['])|(?:["](?:([^\\"]|\\.)*)["]))|$)/g);
      var args = [];
      var next = false;

      for (var i = 0; i < pieces.length; i++) {
        var piece = pieces[i];
        if (piece.length > 0) {
          if (next || args.length === 0 || piece.charAt(0) === ' ') {
            args.push(piece.trim());
          } else {
            var last = args.length - 1;
            args[last] = args[last] + piece.trim();
          }
          next = piece.endsWith(' ');
        }
      }

      // NodeJS on Windows does not have this issue
      if (process.platform !== 'win32') {
        for (var i = 0; i < args.length; i++) {
          // NOTE: there may be other characters that require escaping!
          // Find ; or " or ' that is not preceeded by a slash and add a slash
          // Syntax a little odd due to JavaScript having no negative-lookbehind support for Regex
          // so it matches the previous character with a positive lookahead assertion
          // Cannot match both characters since two side-by-side would cause the 2nd to not be a match (such as semi-colon double-quote)
          args[i] = args[i].replace(/(^|[^\\])(?=[";'])/g, function($0,$1) { return $1 + "\\"; });
        }
      }

      console.log(inspect(args, false, null));

      return args;
    };

    var args = splitArgs(command);
    command = args[0];

    if (args.length > 1) {
      args = args.slice(1);
    } else {
      args = [];
    }

    // only save stdout and stderr if a custom callback is used
    var bufferedOutput = callback !== defaultCallback;

    // different stdio behavior (spawn vs exec)
    var stdioOption = function(value, integerValue, inheritValue) {
      return value === integerValue ? integerValue
        : value === 'inherit' ? inheritValue
        : bufferedOutput ? 'pipe' : value === 'pipe' || value === true || value === null || value === undefined ? 'pipe'
        : 'ignore'; /* value === false || value === 'ignore' */
    }

    execOptions.stdio = [
      stdioOption(stdin, 0, process.stdin),
      stdioOption(stdout, 1, process.stdout),
      stdioOption(stderr, 2, process.stderr)
      ];

    var encoding = data.encoding;
    var bufferedStdOut = bufferedOutput && execOptions.stdio[1] === 'pipe';
    var bufferedStdErr = bufferedOutput && execOptions.stdio[2] === 'pipe';
    var stdOutLength = 0;
    var stdErrLength = 0;
    var stdOutBuffers = [];
    var stdErrBuffers = [];

    if (bufferedOutput && !Buffer.isEncoding(encoding)) {
      if (encoding === 'buffer') {
        encoding = 'binary';
      } else {
        grunt.fail.fail('Encoding "' + encoding + '" is not a supported character encoding!');
        done(false);
      }
    }

    if (verbose) {
      stdioDescriptions = execOptions.stdio.slice();
      for (var i = 0; i < stdioDescriptions.length; i++) {
        stdioDescription = stdioDescriptions[i];
        if (stdioDescription === process.stdin) {
          stdioDescriptions[i] = 'process.stdin';
        } else if (stdioDescription === process.stdout) {
          stdioDescriptions[i] = 'process.stdout';
        } else if (stdioDescription === process.stderr) {
          stdioDescriptions[i] = 'process.stderr';
        }
      }

      verbose.writeln('buffer   : ' + (bufferedOutput ?
        (bufferedStdOut ? 'stdout=enabled' : 'stdout=disabled')
        + ';' +
        (bufferedStdErr ? 'stderr=enabled' : 'stderr=disabled')
        + ';' +
        'max size=' + maxBuffer
        : 'disabled'));
      verbose.writeln('timeout  : ' + (execOptions.timeout === 0 ? 'infinite' : '' + execOptions.timeout + 'ms'));
      verbose.writeln('killSig  : ' + execOptions.killSignal);
      verbose.writeln('shell    : ' + execOptions.shell);
      verbose.writeln('command  : ' + command);
      verbose.writeln('args     : [' + args.join(',') + ']');
      verbose.writeln('stdio    : [' + stdioDescriptions.join(',') + ']');
      verbose.writeln('cwd      : ' + execOptions.cwd);
      //verbose.writeln('env path : ' + process.env.PATH);
      verbose.writeln('exitcodes:', exitCodes.join(','));
    }

    if (sync)
    {
      childProcess = cp.spawnSync(command, args, execOptions);
    }
    else {
      childProcess = cp.spawn(command, args, execOptions);
    }

    if (verbose) {
      verbose.writeln('pid     : ' + childProcess.pid);
    }

    var killChild = function (reason) {
      defaultError(reason);
      process.kill(childProcess.pid, execOptions.killSignal);
      //childProcess.kill(execOptions.killSignal);
      done(false); // unlike exec, this will indicate an error - after all, it did kill the process
    };

    if (execOptions.timeout !== 0) {
      var timeoutProcess = function() {
        killChild('Timeout child process');
      };
      setInterval(timeoutProcess, execOptions.timeout);
    }

    var writeStdOutBuffer = function(d) {
      var b = !Buffer.isBuffer(d) ? new Buffer(d.toString(encoding)) : d;
      if (stdOutLength + b.length > maxBuffer) {
        if (verbose) {
          verbose.writeln("EXCEEDING MAX BUFFER: stdOut " + stdOutLength + " buffer " + b.length + " maxBuffer " + maxBuffer);
        }
        killChild("stdout maxBuffer exceeded");
      } else {
        stdOutLength += b.length;
        stdOutBuffers.push(b);
      }

      // default piping behavior
      if (stdout !== false && data.encoding !== 'buffer') {
        defaultOut(d);
      }
    };

    var writeStdErrBuffer = function(d) {
      var b = !Buffer.isBuffer(d) ? new Buffer(d.toString(encoding)) : d;
      if (stdErrLength + b.length > maxBuffer) {
        if (verbose) {
          verbose.writeln("EXCEEDING MAX BUFFER: stdErr " + stdErrLength + " buffer " + b.length + " maxBuffer " + maxBuffer);
        }
        killChild("stderr maxBuffer exceeded");
      } else {
        stdErrLength += b.length;
        stdErrBuffers.push(b);
      }

      // default piping behavior
      if (stderr !== false && data.encoding !== 'buffer') {
        defaultError(d);
      }
    };

    if (execOptions.stdio[1] === 'pipe') {
      var pipeOut = bufferedStdOut ? writeStdOutBuffer : defaultOut;
      // Asynchronous + Synchronous Support
      if (sync) { pipeOut(childProcess.stdout); }
      else { childProcess.stdout.on('data', function (d) { pipeOut(d); }); }
    }

    if (execOptions.stdio[2] === 'pipe') {
      var pipeErr = bufferedStdErr ? writeStdErrBuffer : defaultError;
      // Asynchronous + Synchronous Support
      if (sync) { pipeOut(childProcess.stderr); }
      else { childProcess.stderr.on('data', function (d) { pipeErr(d); }); }
    }

    // Catches failing to execute the command at all (eg spawn ENOENT),
    // since in that case an 'exit' event will not be emitted.
    // Asynchronous + Synchronous Support
    if (sync) {
      if (childProcess.error != null)
      {
        defaultError(f('Failed with: %s', error.message));
        done(false);
      }
    }
    else {
      childProcess.on('error', function (err) {
        defaultError(f('Failed with: %s', err));
        done(false);
      });
    }

    // Exit Function (used for process exit callback / exit function)
    var exitFunc = function (code) {
      if (callbackErrors) {
        defaultError('Node returned an error for this child process');
        return done(false);
      }

      var stdOutBuffer = undefined;
      var stdErrBuffer = undefined;

      if (bufferedStdOut) {
        stdOutBuffer = new Buffer(stdOutLength);
        var offset = 0;
        for (var i = 0; i < stdOutBuffers.length; i++) {
          var buf = stdOutBuffers[i];
          buf.copy(stdOutBuffer, offset);
          offset += buf.length;
        }

        if (data.encoding !== 'buffer') {
          stdOutBuffer = stdOutBuffer.toString(encoding);
        }
      }

      if (bufferedStdErr) {
        stdErrBuffer = new Buffer(stdErrLength);
        var offset = 0;
        for (var i = 0; i < stdErrBuffers.length; i++) {
          var buf = stdErrBuffers[i];
          buf.copy(stdErrBuffer, offset);
          offset += buf.length;
        }

        if (data.encoding !== 'buffer') {
          stdErrBuffer = stdErrBuffer.toString(encoding);
        }
      }

      if (exitCodes.indexOf(code) < 0) {
        defaultError(f('Exited with code: %d.', code));
        if (callback) {
          var err = new Error(f('Process exited with code %d.', code));
          err.code = code;

          callback(err, stdOutBuffer, stdErrBuffer, callbackArgs);
        }
        return done(false);
      }

      verbose.ok(f('Exited with code: %d.', code));

      if (callback) {
        callback(null, stdOutBuffer, stdErrBuffer, callbackArgs);
      }

      done();
    }

    // Asynchronous + Synchronous Support
    if (sync) {
      exitFunc(childProcess.status);
    }
    else {
      childProcess.on('exit', exitFunc);
    }

  });
};
<commit_msg>Fix broken code due to committed debugging statement<commit_after>// grunt-exec
// ==========
// * GitHub: https://github.com/jharding/grunt-exec
// * Original Copyright (c) 2012 Jake Harding
// * Copyright (c) 2017 grunt-exec
// * Licensed under the MIT license.

// grunt-exe 2.0.0+ simulates the convenience of child_process.exec with the capabilities of child_process.spawn
// this was done primarily to preserve colored output from applications such as npm
// a lot of work was done to simulate the original behavior of both child_process.exec and grunt-exec
// as such there may be unintended consequences so the major revision was bumped
// a breaking change was made to the 'maxBuffer kill process' scenario so it is treated as an error and provides more detail (--verbose)
// stdout and stderr buffering & maxBuffer constraints are removed entirely where possible
// new features: detached (boolean), argv0 (override the executable name passed to the application), shell (boolean or string)
// fd #s greater than 2 not yet supported (ipc piping) which is spawn-specific and very rarely required
// TODO: support stdout and stderr Buffer objects passed in
// TODO: stdin/stdout/stderr string as file name => open the file and read/write from it

module.exports = function(grunt) {
  var cp = require('child_process')
    , f = require('util').format
    , _ = grunt.util._
    , log = grunt.log
    , verbose = grunt.verbose;

  grunt.registerMultiTask('exec', 'Execute shell commands.', function() {

    var callbackErrors = false;

    var defaultOut = log.write;
    var defaultError = log.error;

    var defaultCallback = function(err, stdout, stderr) {
      if (err) {
        callbackErrors = true;
        defaultError('Error executing child process: ' + err.toString());
      }
    };

    var data = this.data
      , execOptions = data.options !== undefined ? data.options : {}
      , stdout = data.stdout !== undefined ? data.stdout : true
      , stderr = data.stderr !== undefined ? data.stderr : true
      , stdin = data.stdin !== undefined ? data.stdin : false
      , stdio = data.stdio
      , callback = _.isFunction(data.callback) ? data.callback : defaultCallback
      , callbackArgs = data.callbackArgs !== undefined ? data.callbackArgs : []
      , sync = data.sync !== undefined ? data.sync : false
      , exitCodes = data.exitCode || data.exitCodes || 0
      , command
      , childProcess
      , args = [].slice.call(arguments, 0)
      , done = this.async();

    // https://github.com/jharding/grunt-exec/pull/30
    exitCodes = _.isArray(exitCodes) ? exitCodes : [exitCodes];

    // allow for command to be specified in either
    // 'command' or 'cmd' property, or as a string.
    command = data.command || data.cmd || (_.isString(data) && data);

    if (!command) {
      defaultError('Missing command property.');
      return done(false);
    }

    if (data.cwd && _.isFunction(data.cwd)) {
      execOptions.cwd = data.cwd.apply(grunt, args);
    } else if (data.cwd) {
      execOptions.cwd = data.cwd;
    }

    // default to current process cwd
    execOptions.cwd = execOptions.cwd || process.cwd();

    // manually supported (spawn vs exec)
    // 200*1024 is default maxBuffer of child_process.exec
    // NOTE: must be < require('buffer').kMaxLength or a RangeError will be triggered
    var maxBuffer = data.maxBuffer || execOptions.maxBuffer || (200*1024);

    // timeout manually supportted (spawn vs exec)
    execOptions.timeout = execOptions.timeout || data.timeout || 0;
    // kill signal manually supportted (spawn vs exec)
    execOptions.killSignal = execOptions.killSignal || data.killSignal || 'SIGTERM';

    // support shell scripts like 'npm.cmd' by default (spawn vs exec)
    var shell = (typeof data.shell === 'undefined') ? execOptions.shell : data.shell;
    execOptions.shell = (typeof shell === 'string') ? shell : (shell === false ? false : true);

    // kept in data.encoding in case it is set to 'buffer' for final callback
    data.encoding = data.encoding || execOptions.encoding || 'utf8';

    stdio = stdio || execOptions.stdio || undefined;
    if (stdio === 'inherit') {
      stdout = 'inherit';
      stderr = 'inherit';
      stdin = 'inherit';
    } else if (stdio === 'pipe') {
      stdout = 'pipe';
      stderr = 'pipe';
      stdin = 'pipe';
    } else if (stdio === 'ignore') {
      stdout = 'ignore';
      stderr = 'ignore';
      stdin = 'ignore';
    }

    if (_.isFunction(command)) {
      command = command.apply(grunt, args);
    }

    if (!_.isString(command)) {
      defaultError('Command property must be a string.');
      return done(false);
    }

    verbose.subhead(command);

    // manually parse args into array (spawn vs exec)
    var splitArgs = function(command) {
      // Regex Explanation                                          Regex
      // ---------------------------------------------------------------------
      // 0-* spaces                                                 \s*
      // followed by either:
      //   [NOT: a space, half quote, or double quote] 1-* times    [^\s'"]+
      //     followed by either:
      //       [half quote or double quote] in the future           (?=['"])
      //       or 1-* spaces                                        \s+
      //       or end of string                                     $
      //   or half quote                                            [']
      //     followed by 0-*:
      //       [NOT: a backslash, or half quote]                    [^\\']
      //       or a backslash followed by any character             \\.
      //     followed by a half quote                               [']
      //   or double quote                                          ["]
      //     followed by 0-*:
      //       [NOT: a backslash, or double quote]                  [^\\"]
      //       or a backslash followed by any character             \\.
      //     followed by a double quote                             ["]
      //   or end of string                                         $
      var pieces = command.match(/\s*([^\s'"]+(?:(?=['"])|\s+|$)|(?:(?:['](?:([^\\']|\\.)*)['])|(?:["](?:([^\\"]|\\.)*)["]))|$)/g);
      var args = [];
      var next = false;

      for (var i = 0; i < pieces.length; i++) {
        var piece = pieces[i];
        if (piece.length > 0) {
          if (next || args.length === 0 || piece.charAt(0) === ' ') {
            args.push(piece.trim());
          } else {
            var last = args.length - 1;
            args[last] = args[last] + piece.trim();
          }
          next = piece.endsWith(' ');
        }
      }

      // NodeJS on Windows does not have this issue
      if (process.platform !== 'win32') {
        for (var i = 0; i < args.length; i++) {
          // NOTE: there may be other characters that require escaping!
          // Find ; or " or ' that is not preceeded by a slash and add a slash
          // Syntax a little odd due to JavaScript having no negative-lookbehind support for Regex
          // so it matches the previous character with a positive lookahead assertion
          // Cannot match both characters since two side-by-side would cause the 2nd to not be a match (such as semi-colon double-quote)
          args[i] = args[i].replace(/(^|[^\\])(?=[";'])/g, function($0,$1) { return $1 + "\\"; });
        }
      }

      return args;
    };

    var args = splitArgs(command);
    command = args[0];

    if (args.length > 1) {
      args = args.slice(1);
    } else {
      args = [];
    }

    // only save stdout and stderr if a custom callback is used
    var bufferedOutput = callback !== defaultCallback;

    // different stdio behavior (spawn vs exec)
    var stdioOption = function(value, integerValue, inheritValue) {
      return value === integerValue ? integerValue
        : value === 'inherit' ? inheritValue
        : bufferedOutput ? 'pipe' : value === 'pipe' || value === true || value === null || value === undefined ? 'pipe'
        : 'ignore'; /* value === false || value === 'ignore' */
    }

    execOptions.stdio = [
      stdioOption(stdin, 0, process.stdin),
      stdioOption(stdout, 1, process.stdout),
      stdioOption(stderr, 2, process.stderr)
      ];

    var encoding = data.encoding;
    var bufferedStdOut = bufferedOutput && execOptions.stdio[1] === 'pipe';
    var bufferedStdErr = bufferedOutput && execOptions.stdio[2] === 'pipe';
    var stdOutLength = 0;
    var stdErrLength = 0;
    var stdOutBuffers = [];
    var stdErrBuffers = [];

    if (bufferedOutput && !Buffer.isEncoding(encoding)) {
      if (encoding === 'buffer') {
        encoding = 'binary';
      } else {
        grunt.fail.fail('Encoding "' + encoding + '" is not a supported character encoding!');
        done(false);
      }
    }

    if (verbose) {
      stdioDescriptions = execOptions.stdio.slice();
      for (var i = 0; i < stdioDescriptions.length; i++) {
        stdioDescription = stdioDescriptions[i];
        if (stdioDescription === process.stdin) {
          stdioDescriptions[i] = 'process.stdin';
        } else if (stdioDescription === process.stdout) {
          stdioDescriptions[i] = 'process.stdout';
        } else if (stdioDescription === process.stderr) {
          stdioDescriptions[i] = 'process.stderr';
        }
      }

      verbose.writeln('buffer   : ' + (bufferedOutput ?
        (bufferedStdOut ? 'stdout=enabled' : 'stdout=disabled')
        + ';' +
        (bufferedStdErr ? 'stderr=enabled' : 'stderr=disabled')
        + ';' +
        'max size=' + maxBuffer
        : 'disabled'));
      verbose.writeln('timeout  : ' + (execOptions.timeout === 0 ? 'infinite' : '' + execOptions.timeout + 'ms'));
      verbose.writeln('killSig  : ' + execOptions.killSignal);
      verbose.writeln('shell    : ' + execOptions.shell);
      verbose.writeln('command  : ' + command);
      verbose.writeln('args     : [' + args.join(',') + ']');
      verbose.writeln('stdio    : [' + stdioDescriptions.join(',') + ']');
      verbose.writeln('cwd      : ' + execOptions.cwd);
      //verbose.writeln('env path : ' + process.env.PATH);
      verbose.writeln('exitcodes:', exitCodes.join(','));
    }

    if (sync)
    {
      childProcess = cp.spawnSync(command, args, execOptions);
    }
    else {
      childProcess = cp.spawn(command, args, execOptions);
    }

    if (verbose) {
      verbose.writeln('pid     : ' + childProcess.pid);
    }

    var killChild = function (reason) {
      defaultError(reason);
      process.kill(childProcess.pid, execOptions.killSignal);
      //childProcess.kill(execOptions.killSignal);
      done(false); // unlike exec, this will indicate an error - after all, it did kill the process
    };

    if (execOptions.timeout !== 0) {
      var timeoutProcess = function() {
        killChild('Timeout child process');
      };
      setInterval(timeoutProcess, execOptions.timeout);
    }

    var writeStdOutBuffer = function(d) {
      var b = !Buffer.isBuffer(d) ? new Buffer(d.toString(encoding)) : d;
      if (stdOutLength + b.length > maxBuffer) {
        if (verbose) {
          verbose.writeln("EXCEEDING MAX BUFFER: stdOut " + stdOutLength + " buffer " + b.length + " maxBuffer " + maxBuffer);
        }
        killChild("stdout maxBuffer exceeded");
      } else {
        stdOutLength += b.length;
        stdOutBuffers.push(b);
      }

      // default piping behavior
      if (stdout !== false && data.encoding !== 'buffer') {
        defaultOut(d);
      }
    };

    var writeStdErrBuffer = function(d) {
      var b = !Buffer.isBuffer(d) ? new Buffer(d.toString(encoding)) : d;
      if (stdErrLength + b.length > maxBuffer) {
        if (verbose) {
          verbose.writeln("EXCEEDING MAX BUFFER: stdErr " + stdErrLength + " buffer " + b.length + " maxBuffer " + maxBuffer);
        }
        killChild("stderr maxBuffer exceeded");
      } else {
        stdErrLength += b.length;
        stdErrBuffers.push(b);
      }

      // default piping behavior
      if (stderr !== false && data.encoding !== 'buffer') {
        defaultError(d);
      }
    };

    if (execOptions.stdio[1] === 'pipe') {
      var pipeOut = bufferedStdOut ? writeStdOutBuffer : defaultOut;
      // Asynchronous + Synchronous Support
      if (sync) { pipeOut(childProcess.stdout); }
      else { childProcess.stdout.on('data', function (d) { pipeOut(d); }); }
    }

    if (execOptions.stdio[2] === 'pipe') {
      var pipeErr = bufferedStdErr ? writeStdErrBuffer : defaultError;
      // Asynchronous + Synchronous Support
      if (sync) { pipeOut(childProcess.stderr); }
      else { childProcess.stderr.on('data', function (d) { pipeErr(d); }); }
    }

    // Catches failing to execute the command at all (eg spawn ENOENT),
    // since in that case an 'exit' event will not be emitted.
    // Asynchronous + Synchronous Support
    if (sync) {
      if (childProcess.error != null)
      {
        defaultError(f('Failed with: %s', error.message));
        done(false);
      }
    }
    else {
      childProcess.on('error', function (err) {
        defaultError(f('Failed with: %s', err));
        done(false);
      });
    }

    // Exit Function (used for process exit callback / exit function)
    var exitFunc = function (code) {
      if (callbackErrors) {
        defaultError('Node returned an error for this child process');
        return done(false);
      }

      var stdOutBuffer = undefined;
      var stdErrBuffer = undefined;

      if (bufferedStdOut) {
        stdOutBuffer = new Buffer(stdOutLength);
        var offset = 0;
        for (var i = 0; i < stdOutBuffers.length; i++) {
          var buf = stdOutBuffers[i];
          buf.copy(stdOutBuffer, offset);
          offset += buf.length;
        }

        if (data.encoding !== 'buffer') {
          stdOutBuffer = stdOutBuffer.toString(encoding);
        }
      }

      if (bufferedStdErr) {
        stdErrBuffer = new Buffer(stdErrLength);
        var offset = 0;
        for (var i = 0; i < stdErrBuffers.length; i++) {
          var buf = stdErrBuffers[i];
          buf.copy(stdErrBuffer, offset);
          offset += buf.length;
        }

        if (data.encoding !== 'buffer') {
          stdErrBuffer = stdErrBuffer.toString(encoding);
        }
      }

      if (exitCodes.indexOf(code) < 0) {
        defaultError(f('Exited with code: %d.', code));
        if (callback) {
          var err = new Error(f('Process exited with code %d.', code));
          err.code = code;

          callback(err, stdOutBuffer, stdErrBuffer, callbackArgs);
        }
        return done(false);
      }

      verbose.ok(f('Exited with code: %d.', code));

      if (callback) {
        callback(null, stdOutBuffer, stdErrBuffer, callbackArgs);
      }

      done();
    }

    // Asynchronous + Synchronous Support
    if (sync) {
      exitFunc(childProcess.status);
    }
    else {
      childProcess.on('exit', exitFunc);
    }

  });
};
<|endoftext|>


<commit_before>import React from 'react';

import { TagGroup, TableListView, GenericGroup } from '../components/textual_summary';
import { Quadicon } from '../components/quadicon';
import { Toolbar } from '../components/toolbar';

import AggregateStatusCard from '../components/aggregate_status_card';
import AnsibleCredentialsForm from '../components/ansible-credentials-form';
import AuthKeypairCloudForm from '../components/auth-key-pair-cloud';
import { BreadcrumbsBar } from '../components/breadcrumbs';
import CatalogForm from '../components/catalog-form/catalog-form';
import CloudNetworkForm from '../components/cloud-network-form/cloud-network-form';
import CloudTenantForm from '../components/cloud-tenant-form';
import CloudVolumeForm from '../components/cloud-volume-form';
import ProviderForm from '../components/provider-form';
import CopyCatalogForm from '../components/copy-catalog-form/copy-catalog-form';
import CopyDashboardForm from '../components/copy-dashboard-form/copy-dashboard-form';
import DashboardWidget from '../components/dashboard-charts';
import FlavorForm from '../components/flavor-form';
import FirmwareRegistryForm from '../components/firmware-registry/firmware-registry-form';
import FormButtonsRedux from '../forms/form-buttons-redux';
import GenericGroupWrapper from '../react/generic_group_wrapper';
import GtlView from  '../components/gtl-view';
import { TreeViewRedux } from '../components/tree-view';
import FonticonPicker from '../components/fonticon-picker';
import ImportDatastoreViaGit from '../components/automate-import-export-form/import-datastore-via-git';
import MiqAboutModal from '../components/miq-about-modal';
import MiqToolbar from '../components/miq-toolbar';
import { MainMenu, Navbar } from '../menu';
import NotificationDrawer from '../components/notification-drawer/notification-drawer';
import OptimizationList from '../optimization/optimization_list';
import OpsTenantForm from '../components/ops-tenant-form/ops-tenant-form';
import OrcherstrationTemplateForm from '../components/orchestration-template/orcherstration-template-form';
import PxeImageForm from '../components/pxe-image-type-form';
import PxeCustomizationTemplateForm from '../components/pxe-customization-template-form';
import PxeServersForm from '../components/pxe-servers-form/pxe-server-form';
import PerformanceChartWidget from '../components/performance-charts';
import PodsTrendChart from '../components/provider-dashboard-charts/pod-trend-charts';
import RecentHostGraph from '../components/provider-dashboard-charts/recent-host-chart';
import RecentVmGraph from '../components/provider-dashboard-charts/recent-vm-chart'
import RegionForm from '../components/region-form';
import RemoveCatalogItemModal from '../components/remove-catalog-item-modal';
import RemoveGenericItemModal from '../components/remove-generic-item-modal';
import ReportChartWidget from '../components/create-report-chart-form';
import ReportDataTable from '../components/report-data-table';
import RetirementForm from '../components/retirement-form';
import ServiceDialogFromForm from '../components/service-dialog-from-form/service-dialog-from';
import EditServiceForm from '../components/edit-service-form';
import SetOwnershipForm from '../components/set-ownership-form';
import ServersDataChart from '../components/provider-dashboard-charts/servers-pie-chart';
import TableListViewWrapper from '../react/table_list_view_wrapper';
import TaggingWrapperConnected from '../components/taggingWrapper';
import { TagView } from '../tagging';
import ToastList from '../components/toast-list/toast-list';
import TextualSummaryWrapper from '../react/textual_summary_wrapper';
import UsageTrendChart from '../components/provider-dashboard-charts/usage-network-image-charts';
import UtilizationChartGraph from '../components/provider-dashboard-charts/provider-dashboard-utilization-chart';
import VmServerRelationshipForm from '../components/vm-server-relationship-form';
import VmSnapshotForm from '../components/vm-snapshot-form/vm-snapshot-form';
import WorkersForm from '../components/workers-form/workers-form';
import PhysicalStorageForm from '../components/physical-storage-form';
import VisualSettingsForm from '../components/visual-settings-form';
import HostInitiatorForm from '../components/host-initiator-form';
import VolumeMappingForm from '../components/volume-mapping-form';

/**
* Add component definitions to this file.
* example of component definition:
* ManageIQ.component.addReact('ComponentName', props => <ComponentName {...props} />);
*/

ManageIQ.component.addReact('AggregateStatusCard', AggregateStatusCard);
ManageIQ.component.addReact('AnsibleCredentialsForm', AnsibleCredentialsForm);
ManageIQ.component.addReact('AuthKeypairCloudForm', AuthKeypairCloudForm);
ManageIQ.component.addReact('BreadcrumbsBar', BreadcrumbsBar);
ManageIQ.component.addReact('CatalogForm', CatalogForm);
ManageIQ.component.addReact('CloudNetworkForm', CloudNetworkForm);
ManageIQ.component.addReact('CloudTenantForm', CloudTenantForm);
ManageIQ.component.addReact('CloudVolumeForm', CloudVolumeForm);
ManageIQ.component.addReact('ProviderForm', ProviderForm);
ManageIQ.component.addReact('CopyCatalogForm', CopyCatalogForm);
ManageIQ.component.addReact('CopyDashboardForm', CopyDashboardForm);
ManageIQ.component.addReact('DashboardWidget', DashboardWidget);
ManageIQ.component.addReact('FirmwareRegistryForm', FirmwareRegistryForm);
ManageIQ.component.addReact('FlavorForm', FlavorForm);
ManageIQ.component.addReact('FormButtonsRedux', FormButtonsRedux);
ManageIQ.component.addReact('GenericGroup', GenericGroup);
ManageIQ.component.addReact('GenericGroupWrapper', GenericGroupWrapper);
ManageIQ.component.addReact('GtlView', GtlView);
ManageIQ.component.addReact('TreeViewRedux', TreeViewRedux);
ManageIQ.component.addReact('FonticonPicker', FonticonPicker);
ManageIQ.component.addReact('ImportDatastoreViaGit', ImportDatastoreViaGit);
ManageIQ.component.addReact('MiqAboutModal', MiqAboutModal);
ManageIQ.component.addReact('MiqToolbar', MiqToolbar);
ManageIQ.component.addReact('menu.MainMenu', MainMenu);
ManageIQ.component.addReact('menu.Navbar', Navbar);
ManageIQ.component.addReact('NotificationDrawer', NotificationDrawer);
ManageIQ.component.addReact('OpsTenantForm', OpsTenantForm);
ManageIQ.component.addReact('OptimizationList', OptimizationList);
ManageIQ.component.addReact('OrcherstrationTemplateForm', OrcherstrationTemplateForm);
ManageIQ.component.addReact('PxeImageForm', PxeImageForm);
ManageIQ.component.addReact('PxeCustomizationTemplateForm', PxeCustomizationTemplateForm);
ManageIQ.component.addReact('PxeServersForm', PxeServersForm);
ManageIQ.component.addReact('PerformanceChartWidget', PerformanceChartWidget);
ManageIQ.component.addReact('PodsTrendChart', PodsTrendChart);
ManageIQ.component.addReact('Quadicon', Quadicon);
ManageIQ.component.addReact('RecentHostGraph', RecentHostGraph);
ManageIQ.component.addReact('RecentVmGraph', RecentVmGraph);
ManageIQ.component.addReact('RegionForm', RegionForm);
ManageIQ.component.addReact('RemoveCatalogItemModal', RemoveCatalogItemModal);
ManageIQ.component.addReact('RemoveGenericItemModal', RemoveGenericItemModal);
ManageIQ.component.addReact('ReportChartWidget', ReportChartWidget);
ManageIQ.component.addReact('ReportDataTable', ReportDataTable);
ManageIQ.component.addReact('RetirementForm', RetirementForm);
ManageIQ.component.addReact('ServiceDialogFromForm', ServiceDialogFromForm);
ManageIQ.component.addReact('EditServiceForm', EditServiceForm);
ManageIQ.component.addReact('SetOwnershipForm', SetOwnershipForm);
ManageIQ.component.addReact('ServersDataChart', ServersDataChart);
ManageIQ.component.addReact('TableListView', TableListView);
ManageIQ.component.addReact('TableListViewWrapper', TableListViewWrapper);
ManageIQ.component.addReact('TagGroup', props => <TagGroup {...props} />);
ManageIQ.component.addReact('TagView', TagView);
ManageIQ.component.addReact('TaggingWrapperConnected', TaggingWrapperConnected);
ManageIQ.component.addReact('TextualSummaryWrapper', TextualSummaryWrapper);
ManageIQ.component.addReact('ToastList', ToastList);
ManageIQ.component.addReact('Toolbar', Toolbar);
ManageIQ.component.addReact('UsageTrendChart', UsageTrendChart);
ManageIQ.component.addReact('UtilizationChartGraph', UtilizationChartGraph);
ManageIQ.component.addReact('VmServerRelationshipForm', VmServerRelationshipForm);
ManageIQ.component.addReact('VmSnapshotForm', VmSnapshotForm);
ManageIQ.component.addReact('WorkersForm', WorkersForm);
ManageIQ.component.addReact('PhysicalStorageForm', PhysicalStorageForm);
ManageIQ.component.addReact('VisualSettingsForm', VisualSettingsForm);
ManageIQ.component.addReact('HostInitiatorForm', HostInitiatorForm);
ManageIQ.component.addReact('VolumeMappingForm', VolumeMappingForm);
<commit_msg>fix merge conflicts<commit_after>import React from 'react';

import { TagGroup, TableListView, GenericGroup } from '../components/textual_summary';
import { Quadicon } from '../components/quadicon';
import { Toolbar } from '../components/toolbar';

import AggregateStatusCard from '../components/aggregate_status_card';
import AnsibleCredentialsForm from '../components/ansible-credentials-form';
import AuthKeypairCloudForm from '../components/auth-key-pair-cloud';
import { BreadcrumbsBar } from '../components/breadcrumbs';
import CatalogForm from '../components/catalog-form/catalog-form';
import CloudNetworkForm from '../components/cloud-network-form/cloud-network-form';
import CloudTenantForm from '../components/cloud-tenant-form';
import CloudVolumeForm from '../components/cloud-volume-form';
import ProviderForm from '../components/provider-form';
import CopyCatalogForm from '../components/copy-catalog-form/copy-catalog-form';
import CopyDashboardForm from '../components/copy-dashboard-form/copy-dashboard-form';
import DashboardWidget from '../components/dashboard-charts';
import FlavorForm from '../components/flavor-form';
import FirmwareRegistryForm from '../components/firmware-registry/firmware-registry-form';
import FormButtonsRedux from '../forms/form-buttons-redux';
import GenericGroupWrapper from '../react/generic_group_wrapper';
import GtlView from  '../components/gtl-view';
import { TreeViewRedux } from '../components/tree-view';
import FonticonPicker from '../components/fonticon-picker';
import ImportDatastoreViaGit from '../components/automate-import-export-form/import-datastore-via-git';
import MiqAboutModal from '../components/miq-about-modal';
import MiqToolbar from '../components/miq-toolbar';
import { MainMenu, Navbar } from '../menu';
import NotificationDrawer from '../components/notification-drawer/notification-drawer';
import OptimizationList from '../optimization/optimization_list';
import OpsTenantForm from '../components/ops-tenant-form/ops-tenant-form';
import OrcherstrationTemplateForm from '../components/orchestration-template/orcherstration-template-form';
import PxeImageForm from '../components/pxe-image-type-form';
import PxeCustomizationTemplateForm from '../components/pxe-customization-template-form';
import PxeServersForm from '../components/pxe-servers-form/pxe-server-form';
import PerformanceChartWidget from '../components/performance-charts';
import PodsTrendChart from '../components/provider-dashboard-charts/pod-trend-charts';
import RecentHostGraph from '../components/provider-dashboard-charts/recent-host-chart';
import RecentVmGraph from '../components/provider-dashboard-charts/recent-vm-chart';
import RegionForm from '../components/region-form';
import RemoveCatalogItemModal from '../components/remove-catalog-item-modal';
import RemoveGenericItemModal from '../components/remove-generic-item-modal';
import ReportChartWidget from '../components/create-report-chart-form';
import ReportDataTable from '../components/report-data-table';
import RetirementForm from '../components/retirement-form';
import ServiceDialogFromForm from '../components/service-dialog-from-form/service-dialog-from';
import EditServiceForm from '../components/edit-service-form';
import SetOwnershipForm from '../components/set-ownership-form';
import ServersDataChart from '../components/provider-dashboard-charts/servers-pie-chart';
import TableListViewWrapper from '../react/table_list_view_wrapper';
import TaggingWrapperConnected from '../components/taggingWrapper';
import { TagView } from '../tagging';
import ToastList from '../components/toast-list/toast-list';
import TextualSummaryWrapper from '../react/textual_summary_wrapper';
import UsageTrendChart from '../components/provider-dashboard-charts/usage-network-image-charts';
import UtilizationChartGraph from '../components/provider-dashboard-charts/provider-dashboard-utilization-chart';
import VmServerRelationshipForm from '../components/vm-server-relationship-form';
import VmSnapshotForm from '../components/vm-snapshot-form/vm-snapshot-form';
import WorkersForm from '../components/workers-form/workers-form';
import PhysicalStorageForm from '../components/physical-storage-form';
import VisualSettingsForm from '../components/visual-settings-form';
import HostInitiatorForm from '../components/host-initiator-form';
import VolumeMappingForm from '../components/volume-mapping-form';

/**
* Add component definitions to this file.
* example of component definition:
* ManageIQ.component.addReact('ComponentName', props => <ComponentName {...props} />);
*/

ManageIQ.component.addReact('AggregateStatusCard', AggregateStatusCard);
ManageIQ.component.addReact('AnsibleCredentialsForm', AnsibleCredentialsForm);
ManageIQ.component.addReact('AuthKeypairCloudForm', AuthKeypairCloudForm);
ManageIQ.component.addReact('BreadcrumbsBar', BreadcrumbsBar);
ManageIQ.component.addReact('CatalogForm', CatalogForm);
ManageIQ.component.addReact('CloudNetworkForm', CloudNetworkForm);
ManageIQ.component.addReact('CloudTenantForm', CloudTenantForm);
ManageIQ.component.addReact('CloudVolumeForm', CloudVolumeForm);
ManageIQ.component.addReact('ProviderForm', ProviderForm);
ManageIQ.component.addReact('CopyCatalogForm', CopyCatalogForm);
ManageIQ.component.addReact('CopyDashboardForm', CopyDashboardForm);
ManageIQ.component.addReact('DashboardWidget', DashboardWidget);
ManageIQ.component.addReact('FirmwareRegistryForm', FirmwareRegistryForm);
ManageIQ.component.addReact('FlavorForm', FlavorForm);
ManageIQ.component.addReact('FormButtonsRedux', FormButtonsRedux);
ManageIQ.component.addReact('GenericGroup', GenericGroup);
ManageIQ.component.addReact('GenericGroupWrapper', GenericGroupWrapper);
ManageIQ.component.addReact('GtlView', GtlView);
ManageIQ.component.addReact('TreeViewRedux', TreeViewRedux);
ManageIQ.component.addReact('FonticonPicker', FonticonPicker);
ManageIQ.component.addReact('ImportDatastoreViaGit', ImportDatastoreViaGit);
ManageIQ.component.addReact('MiqAboutModal', MiqAboutModal);
ManageIQ.component.addReact('MiqToolbar', MiqToolbar);
ManageIQ.component.addReact('menu.MainMenu', MainMenu);
ManageIQ.component.addReact('menu.Navbar', Navbar);
ManageIQ.component.addReact('NotificationDrawer', NotificationDrawer);
ManageIQ.component.addReact('OpsTenantForm', OpsTenantForm);
ManageIQ.component.addReact('OptimizationList', OptimizationList);
ManageIQ.component.addReact('OrcherstrationTemplateForm', OrcherstrationTemplateForm);
ManageIQ.component.addReact('PxeImageForm', PxeImageForm);
ManageIQ.component.addReact('PxeCustomizationTemplateForm', PxeCustomizationTemplateForm);
ManageIQ.component.addReact('PxeServersForm', PxeServersForm);
ManageIQ.component.addReact('PerformanceChartWidget', PerformanceChartWidget);
ManageIQ.component.addReact('PodsTrendChart', PodsTrendChart);
ManageIQ.component.addReact('Quadicon', Quadicon);
ManageIQ.component.addReact('RecentHostGraph', RecentHostGraph);
ManageIQ.component.addReact('RecentVmGraph', RecentVmGraph);
ManageIQ.component.addReact('RegionForm', RegionForm);
ManageIQ.component.addReact('RemoveCatalogItemModal', RemoveCatalogItemModal);
ManageIQ.component.addReact('RemoveGenericItemModal', RemoveGenericItemModal);
ManageIQ.component.addReact('ReportChartWidget', ReportChartWidget);
ManageIQ.component.addReact('ReportDataTable', ReportDataTable);
ManageIQ.component.addReact('RetirementForm', RetirementForm);
ManageIQ.component.addReact('ServiceDialogFromForm', ServiceDialogFromForm);
ManageIQ.component.addReact('EditServiceForm', EditServiceForm);
ManageIQ.component.addReact('SetOwnershipForm', SetOwnershipForm);
ManageIQ.component.addReact('ServersDataChart', ServersDataChart);
ManageIQ.component.addReact('TableListView', TableListView);
ManageIQ.component.addReact('TableListViewWrapper', TableListViewWrapper);
ManageIQ.component.addReact('TagGroup', props => <TagGroup {...props} />);
ManageIQ.component.addReact('TagView', TagView);
ManageIQ.component.addReact('TaggingWrapperConnected', TaggingWrapperConnected);
ManageIQ.component.addReact('TextualSummaryWrapper', TextualSummaryWrapper);
ManageIQ.component.addReact('ToastList', ToastList);
ManageIQ.component.addReact('Toolbar', Toolbar);
ManageIQ.component.addReact('UsageTrendChart', UsageTrendChart);
ManageIQ.component.addReact('UtilizationChartGraph', UtilizationChartGraph);
ManageIQ.component.addReact('VmServerRelationshipForm', VmServerRelationshipForm);
ManageIQ.component.addReact('VmSnapshotForm', VmSnapshotForm);
ManageIQ.component.addReact('WorkersForm', WorkersForm);
ManageIQ.component.addReact('PhysicalStorageForm', PhysicalStorageForm);
ManageIQ.component.addReact('VisualSettingsForm', VisualSettingsForm);
ManageIQ.component.addReact('HostInitiatorForm', HostInitiatorForm);
ManageIQ.component.addReact('VolumeMappingForm', VolumeMappingForm);
<|endoftext|>


<commit_before>'use strict';

var CacheUniformApply = function ( state, program ) {
    this.modelWorldUniform = program._uniformsCache[ state.modelWorldMatrix.getName() ];
    this.viewUniform = program._uniformsCache[ state.viewMatrix.getName() ];

    this.apply = undefined;
    this.generateUniformsApplyMethods();
};

CacheUniformApply.prototype = {

    generateUniformsApplyMethods: function () {

        var functionStr = [ '//generated by RenderLeaf\n' ];
        functionStr.push( 'var gl = state.getGraphicContext();' );
        functionStr.push( 'var matrixModelViewChanged = state.applyModelViewMatrix( modelview );' );
        functionStr.push( 'state.applyProjectionMatrix( projection );' );

        if ( this.modelWorldUniform !== undefined ) {
            functionStr.push( 'if ( matrixModelViewChanged ) {' );
            functionStr.push( '    var modelWorldMatrix = state.modelWorldMatrix;' );
            functionStr.push( '    modelWorldMatrix.setInternalArray( modelworld );' );
            functionStr.push( '    modelWorldMatrix.apply( gl, this.modelWorldUniform);' );
            functionStr.push( '};' );
        }

        if ( this.viewUniform !== undefined ) {
            functionStr.push( 'if ( matrixModelViewChanged ) {' );
            functionStr.push( '    var viewMatrix = state.viewMatrix;' );
            functionStr.push( '    viewMatrix.setInternalArray( view );' );
            functionStr.push( '    viewMatrix.apply( gl, this.viewUniform);' );
            functionStr.push( '};' );
        }

        // I am the evil, so please bother someone else
        /*jshint evil: true */
        var func = new Function( 'state', 'modelview', 'modelworld', 'view', 'projection', functionStr.join( '\n' ) );
        /*jshint evil: false */

        this.apply = func;
    }
};

var RenderLeaf = function () {

    this._parent = undefined;
    this._geometry = undefined;
    this._depth = 0.0;

    this._projection = undefined;
    this._view = undefined;
    this._modelWorld = undefined;
    this._modelView = undefined;
};

RenderLeaf.prototype = {

    reset: function () {
        this._parent = undefined;
        this._geometry = undefined;
        this._depth = 0.0;

        this._projection = undefined;
        this._view = undefined;
        this._modelWorld = undefined;
        this._modelView = undefined;
    },

    init: function ( parent, geom, projection, view, modelView, modelWorld, depth ) {

        this._parent = parent;
        this._geometry = geom;
        this._depth = depth;

        this._projection = projection;
        this._view = view;
        this._modelWorld = modelWorld;
        this._modelView = modelView;

    },

    drawGeometry: ( function () {

        return function ( state ) {

            var program = state.getLastProgramApplied();
            var programInstanceID = program.getInstanceID();
            var cache = state.getCacheUniformsApplyRenderLeaf();
            var obj = cache[ programInstanceID ];

            if ( !obj ) {
                obj = new CacheUniformApply( state, program );
                cache[ programInstanceID ] = obj;
            }

            obj.apply( state, this._modelView, this._modelWorld, this._view, this._projection, this._normal );

            this._geometry.drawImplementation( state );

        };
    } )(),

    render: ( function () {
        var previousHash;

        return function ( state, previousLeaf ) {

            var prevRenderGraph;
            var prevRenderGraphParent;
            var rg;

            if ( previousLeaf !== undefined ) {

                // apply state if required.
                prevRenderGraph = previousLeaf._parent;
                prevRenderGraphParent = prevRenderGraph.parent;
                rg = this._parent;

                if ( prevRenderGraphParent !== rg.parent ) {

                    rg.moveStateGraph( state, prevRenderGraphParent, rg.parent );

                    // send state changes and matrix changes to OpenGL.

                    state.applyStateSet( rg.stateset );
                    previousHash = state.getStateSetStackHash();

                } else if ( rg !== prevRenderGraph ) {

                    // send state changes and matrix changes to OpenGL.
                    state.applyStateSet( rg.stateset );
                    previousHash = state.getStateSetStackHash();

                } else {

                    // in osg we call apply but actually we dont need
                    // except if the stateSetStack changed.
                    // for example if insert/remove StateSet has been used
                    var hash = state.getStateSetStackHash();
                    if ( previousHash !== hash ) {
                        this._parent.moveStateGraph( state, undefined, this._parent.parent );
                        state.applyStateSet( this._parent.stateset );
                        previousHash = hash;
                    }
                }

            } else {

                this._parent.moveStateGraph( state, undefined, this._parent.parent );
                state.applyStateSet( this._parent.stateset );
                previousHash = state.getStateSetStackHash();

            }

            this.drawGeometry( state );

        };
    } )()

};

module.exports = RenderLeaf;
<commit_msg>Removes extra pushStateSet when using insertStateSet<commit_after>'use strict';

var CacheUniformApply = function ( state, program ) {
    this.modelWorldUniform = program._uniformsCache[ state.modelWorldMatrix.getName() ];
    this.viewUniform = program._uniformsCache[ state.viewMatrix.getName() ];

    this.apply = undefined;
    this.generateUniformsApplyMethods();
};

CacheUniformApply.prototype = {

    generateUniformsApplyMethods: function () {

        var functionStr = [ '//generated by RenderLeaf\n' ];
        functionStr.push( 'var gl = state.getGraphicContext();' );
        functionStr.push( 'var matrixModelViewChanged = state.applyModelViewMatrix( modelview );' );
        functionStr.push( 'state.applyProjectionMatrix( projection );' );

        if ( this.modelWorldUniform !== undefined ) {
            functionStr.push( 'if ( matrixModelViewChanged ) {' );
            functionStr.push( '    var modelWorldMatrix = state.modelWorldMatrix;' );
            functionStr.push( '    modelWorldMatrix.setInternalArray( modelworld );' );
            functionStr.push( '    modelWorldMatrix.apply( gl, this.modelWorldUniform);' );
            functionStr.push( '};' );
        }

        if ( this.viewUniform !== undefined ) {
            functionStr.push( 'if ( matrixModelViewChanged ) {' );
            functionStr.push( '    var viewMatrix = state.viewMatrix;' );
            functionStr.push( '    viewMatrix.setInternalArray( view );' );
            functionStr.push( '    viewMatrix.apply( gl, this.viewUniform);' );
            functionStr.push( '};' );
        }

        // I am the evil, so please bother someone else
        /*jshint evil: true */
        var func = new Function( 'state', 'modelview', 'modelworld', 'view', 'projection', functionStr.join( '\n' ) );
        /*jshint evil: false */

        this.apply = func;
    }
};

var RenderLeaf = function () {

    this._parent = undefined;
    this._geometry = undefined;
    this._depth = 0.0;

    this._projection = undefined;
    this._view = undefined;
    this._modelWorld = undefined;
    this._modelView = undefined;
};

RenderLeaf.prototype = {

    reset: function () {
        this._parent = undefined;
        this._geometry = undefined;
        this._depth = 0.0;

        this._projection = undefined;
        this._view = undefined;
        this._modelWorld = undefined;
        this._modelView = undefined;
    },

    init: function ( parent, geom, projection, view, modelView, modelWorld, depth ) {

        this._parent = parent;
        this._geometry = geom;
        this._depth = depth;

        this._projection = projection;
        this._view = view;
        this._modelWorld = modelWorld;
        this._modelView = modelView;

    },

    drawGeometry: ( function () {

        return function ( state ) {

            var program = state.getLastProgramApplied();
            var programInstanceID = program.getInstanceID();
            var cache = state.getCacheUniformsApplyRenderLeaf();
            var obj = cache[ programInstanceID ];

            if ( !obj ) {
                obj = new CacheUniformApply( state, program );
                cache[ programInstanceID ] = obj;
            }

            obj.apply( state, this._modelView, this._modelWorld, this._view, this._projection, this._normal );

            this._geometry.drawImplementation( state );

        };
    } )(),

    render: ( function () {
        var previousHash;

        return function ( state, previousLeaf ) {

            var prevRenderGraph;
            var prevRenderGraphParent;
            var rg;

            if ( previousLeaf !== undefined ) {

                // apply state if required.
                prevRenderGraph = previousLeaf._parent;
                prevRenderGraphParent = prevRenderGraph.parent;
                rg = this._parent;

                if ( prevRenderGraphParent !== rg.parent ) {

                    rg.moveStateGraph( state, prevRenderGraphParent, rg.parent );

                    // send state changes and matrix changes to OpenGL.

                    state.applyStateSet( rg.stateset );
                    previousHash = state.getStateSetStackHash();

                } else if ( rg !== prevRenderGraph ) {

                    // send state changes and matrix changes to OpenGL.
                    state.applyStateSet( rg.stateset );
                    previousHash = state.getStateSetStackHash();

                } else {

                    // in osg we call apply but actually we dont need
                    // except if the stateSetStack changed.
                    // for example if insert/remove StateSet has been used
                    var hash = state.getStateSetStackHash();
                    if ( previousHash !== hash ) {
                        state.applyStateSet( this._parent.stateset );
                        previousHash = hash;
                    }
                }

            } else {

                this._parent.moveStateGraph( state, undefined, this._parent.parent );
                state.applyStateSet( this._parent.stateset );
                previousHash = state.getStateSetStackHash();

            }

            this.drawGeometry( state );

        };
    } )()

};

module.exports = RenderLeaf;
<|endoftext|>


<commit_before>RssFeed.publish( 'posts', function() {
  var feed = this;

  feed.setValue( 'title', feed.cdata( 'João Bordalo blog feed' ) );
  feed.setValue( 'description', feed.cdata( 'Latest posts by João Bordalo.' ) );
  feed.setValue( 'link', 'http://joaobordalo.com' );
  feed.setValue( 'lastBuildDate', new Date() );
  feed.setValue( 'pubDate', new Date() );
  feed.setValue( 'ttl', 1 );

  var posts = Posts.find({},{sort:{createdAt:-1}});
  posts.forEach( function(post) {
    //post.body  = post.body.replace(/allowfullscreen/gi,"allowfullscreen=''");
    //post.body  = post.body.replace(/&/gi,"&");
    //post.title = post.title.replace(/&/gi,"&");
    post.body = post.body.replace(/(\r\n|\n|\r)/gm,"");
    post.date = moment(post.createdAt, 'YYYY-MM-DD hh:mm:ss').format('ddd, DD MMM YYYY hh:mm:ss');
    feed.addItem({
      title: post.title,
      description: post.body,
      link: post.url,
      pubDate: post.date
    });
  });
});<commit_msg>rss feed now validates<commit_after>RssFeed.publish( 'posts', function() {
  var feed = this;

  feed.setValue( 'title', feed.cdata( 'João Bordalo blog feed' ) );
  feed.setValue( 'description', feed.cdata( 'Latest posts by João Bordalo.' ) );
  feed.setValue( 'link', 'http://joaobordalo.com' );
  feed.setValue( 'lastBuildDate', new Date() );
  feed.setValue( 'pubDate', new Date() );
  feed.setValue( 'ttl', 1 );

  var posts = Posts.find({},{sort:{createdAt:-1}});
  posts.forEach( function(post) {
    post.title = '<![CDATA[' + post.title + ']]>';
    post.body  = post.body.replace(/(\r\n|\n|\r)/gm,"");
    post.body  = '<![CDATA[' + post.body + ']]>';
    post.date  = moment(post.createdAt, 'YYYY-MM-DD hh:mm:ss').format('ddd, DD MMM YYYY hh:mm:ss') + ' GMT';
    feed.addItem({
      title:       post.title,
      description: post.body,
      link:        post.url,
      pubDate:     post.date
    });
  });
});<|endoftext|>


<commit_before>/*
    (c) 2014 Digital Humanities Lab, Faculty of Humanities, Utrecht University
    Author: Julian Gonggrijp, j.gonggrijp@uu.nl

    Automated text scraper for Spanish text corpora:
    http://corpus.rae.es/cordenet.html
    http://corpus.rae.es/creanet.html
    http://www.corpusdelespanol.org/
*/

(function ( ) {
    'use strict';

    var target,
        p = new DOMParser(),
        data = [],
        progress_steps,
        progress = 0,
        domain = {
            'www.corpusdelespanol.org': {
                init: function ( ) {
                    target = frames[6];
                    var navtable = target.document.querySelectorAll('#zabba table')[1],
                        navrow = navtable.querySelectorAll('td')[2],
                        anchor = navrow.querySelectorAll('a')[2];
                    progress_steps = Number(navrow.childNodes[4].nodeValue.split('/')[1]);
                },
                turnpage_then: function (doc, continuation, alternative) {
                    var navtable = doc.querySelectorAll('#zabba table')[1];
                    if (! navtable) {
                        alternative();
                        return;
                    }
                    var navrow = navtable.querySelectorAll('td')[2],
                        anchor = navrow.querySelectorAll('a')[2],
                        progress = navrow.childNodes[4].nodeValue.split('/'),
                        table = doc.querySelector('#zabba');
                    if (Number(progress[0]) < Number(progress[1])) {
                        window.jQuery.get(anchor.href, function (data) {
                            var next_doc = p.parseFromString(data, 'text/html');
                            continuation(next_doc);
                        });
                    } else {
                        alternative();
                    }
                },
                scrape1page: function (doc) {
                    for (var i = 1; i <= 100; ++i) {
                        var row = doc.querySelector('#t' + i);
                        if (! row) continue;
                        var anchors = row.querySelectorAll('a'),
                            field = row.querySelector('#texto_' + i),
                            rowdata = [];
                        if (!anchors || !field || !field.value) continue;
                        for (var j = 0; j < 3; ++j) {
                            rowdata.push(anchors[j].childNodes[0].nodeValue);
                        }
                        data.push(rowdata.concat(field.value.split(/|<\/u><\/b>/)));
                    }
                    update_statusbar();
                }
            },
            'corpus.rae.es': {
                init: function ( ) {
                    target = window;
                    var navnode = document.querySelector('td.texto[align="center"]');
                    progress_steps = Number(navnode.innerText.split(/[^0,1-9]+/)[2]) + 1;
                },
                turnpage_then: function (doc, continuation, alternative) {
                        progress = navnode.innerText.split(/[^0,1-9]+/);
                    var anchor = window.jQuery('td > a')[0],
                        navnode = window.jQuery('td.texto[align="center"]')[0],
                    if (! anchor || anchor.innerText != 'Siguiente') {
                        alternative();
                        return;
                    }
                    window.jQuery.get(anchor.href, function (data) {
                        var next_doc = p.parseFromString(data, 'text/html');
                        continuation(next_doc);
                    });
                },
                scrape1page: function (doc) {
                    var lines = document.querySelector('tt').innerHTML.split('\n');
                    for (var l = lines.length, i = 1; i < l; ++i) {
                        var pieces = lines[i].split(/\**\s{2,}||<\/a>/);
                        if (pieces.length < 10) continue;
                        var century = Number(pieces[4].match(/\d\d/)) + 1,
                            rowdata = [];
                        rowdata.push(pieces[0], century, pieces[6]);
                        for (var j = 1; j <= 3; ++j) rowdata.push(pieces[j]);
                        data.push(rowdata);
                    }
                    update_statusbar();
                }
            }
        }[window.location.hostname];

    if (! domain) return;

    function create_statusbar ( ) {
        var statuswidget = document.createElement('div');
        statuswidget.setAttribute('style', 'background: #fff; padding: 20px; border-radius: 10px; z-index: 10; position: fixed; top: 50px; right: 50px;');
        statuswidget.innerHTML = (
            '
'
            + '
'
            + '
'
        );
        target.document.body.appendChild(statuswidget);
    }

    function update_statusbar ( ) {
        var percentage = ++progress / progress_steps * 100;
        target.document.querySelector('#progress-fill').style.width = percentage + '%';
    }

    function insert_jquery_then (continuation) {
        var scriptnode = document.createElement('script');
        scriptnode.setAttribute('src', '//code.jquery.com/jquery-2.1.1.min.js');
        document.head.appendChild(scriptnode);
        scriptnode.addEventListener('load', continuation);
    }

    function scrape (doc) {
        domain.turnpage_then(doc, function (next_doc) {
            domain.scrape1page(next_doc);
            scrape(next_doc);
        }, data2csv);
    }

    function data2csv ( ) {
        console.log(data);
        // step below removes mysterious undefined elements that
        // creep into the array
        data = data.filter(function (elem) { return elem; });
        var text = '';
        for (var l = data.length, i = 0; i < l; ++i) {
            var a = data[i],
                m = a.length;
            if (m != 6) {
                console.log('Error: subarray of incorrect length.\n', a);
                continue;
            }
            text += a[0].trim() + ';' + a[1].trim();
            for (var j = 2; j < m; ++j) {
                text += ';"' + a[j].trim() + '"';
            }
            text += '\n';
        }
        document.write(
            'Scraping complete. Please copy the contents below ' +
            'into a plaintext document and give it a .csv extension.
' +
            '<textarea id="output" style="width: 50ex; height: 10em;">' +
            'number;century;text;contextLeft;sample;contextRight\n' +
            text +
            '</textarea>'
        );
        $('#output').focus().select();
    }

    domain.init();
    create_statusbar();
    domain.scrape1page(target.document);
    insert_jquery_then(function ( ) {
		update_statusbar();
		scrape(target.document);
	});
})();
<commit_msg>Clean up code after JSLint check<commit_after>/*
    (c) 2014 Digital Humanities Lab, Faculty of Humanities, Utrecht University
    Author: Julian Gonggrijp, j.gonggrijp@uu.nl

    Automated text scraper for Spanish text corpora:
    http://corpus.rae.es/cordenet.html
    http://corpus.rae.es/creanet.html
    http://www.corpusdelespanol.org/
*/

(function ( ) {
    'use strict';

    var target,
        p = new DOMParser(),
        data = [],
        progress_steps,
        progress = 0;

    function create_statusbar ( ) {
        var statuswidget = document.createElement('div');
        statuswidget.setAttribute('style', 'background: #fff; padding: 20px; border-radius: 10px; z-index: 10; position: fixed; top: 50px; right: 50px;');
        statuswidget.innerHTML = (
            '
'
            + '
'
            + '
'
        );
        target.document.body.appendChild(statuswidget);
    }

    function update_statusbar ( ) {
        var percentage = ++progress / progress_steps * 100;
        target.document.querySelector('#progress-fill').style.width = percentage + '%';
    }

    var domain = {
            'www.corpusdelespanol.org': {
                init: function ( ) {
                    target = frames[6];
                    var navtable = target.document.querySelectorAll('#zabba table')[1],
                        navrow = navtable.querySelectorAll('td')[2];
                    progress_steps = Number(navrow.childNodes[4].nodeValue.split('/')[1]);
                },
                turnpage_then: function (doc, continuation, alternative) {
                    var navtable = doc.querySelectorAll('#zabba table')[1];
                    if (! navtable) {
                        alternative();
                        return;
                    }
                    var navrow = navtable.querySelectorAll('td')[2],
                        anchor = navrow.querySelectorAll('a')[2],
                        progress = navrow.childNodes[4].nodeValue.split('/');
                    if (Number(progress[0]) < Number(progress[1])) {
                        window.jQuery.get(anchor.href, function (data) {
                            var next_doc = p.parseFromString(data, 'text/html');
                            continuation(next_doc);
                        });
                    } else {
                        alternative();
                    }
                },
                scrape1page: function (doc) {
                    for (var i = 1; i <= 100; ++i) {
                        var row = doc.querySelector('#t' + i);
                        if (! row) continue;
                        var anchors = row.querySelectorAll('a'),
                            field = row.querySelector('#texto_' + i),
                            rowdata = [];
                        if (!anchors || !field || !field.value) continue;
                        for (var j = 0; j < 3; ++j) {
                            rowdata.push(anchors[j].childNodes[0].nodeValue);
                        }
                        data.push(rowdata.concat(field.value.split(/|<\/u><\/b>/)));
                    }
                    update_statusbar();
                }
            },
            'corpus.rae.es': {
                init: function ( ) {
                    target = window;
                    var navnode = document.querySelector('td.texto[align="center"]');
                    progress_steps = Number(navnode.innerText.split(/[^0,1-9]+/)[2]) + 1;
                },
                turnpage_then: function (doc, continuation, alternative) {
                    var anchor = window.jQuery('td > a')[0];
                    if (! anchor || anchor.innerText != 'Siguiente') {
                        alternative();
                        return;
                    }
                    window.jQuery.get(anchor.href, function (data) {
                        var next_doc = p.parseFromString(data, 'text/html');
                        continuation(next_doc);
                    });
                },
                scrape1page: function (doc) {
                    var lines = document.querySelector('tt').innerHTML.split('\n');
                    for (var l = lines.length, i = 1; i < l; ++i) {
                        var pieces = lines[i].split(/\**\s{2,}||<\/a>/);
                        if (pieces.length < 10) continue;
                        var century = Number(pieces[4].match(/\d\d/)) + 1,
                            rowdata = [];
                        rowdata.push(pieces[0], century, pieces[6]);
                        for (var j = 1; j <= 3; ++j) rowdata.push(pieces[j]);
                        data.push(rowdata);
                    }
                    update_statusbar();
                }
            }
        }[window.location.hostname];

    if (! domain) return;

    function insert_jquery_then (continuation) {
        var scriptnode = document.createElement('script');
        scriptnode.setAttribute('src', '//code.jquery.com/jquery-2.1.1.min.js');
        document.head.appendChild(scriptnode);
        scriptnode.addEventListener('load', continuation);
    }

    function data2csv ( ) {
        console.log(data);
        // step below removes mysterious undefined elements that
        // creep into the array
        data = data.filter(function (elem) { return elem; });
        var text = '';
        for (var l = data.length, i = 0; i < l; ++i) {
            var a = data[i],
                m = a.length;
            if (m != 6) {
                console.log('Error: subarray of incorrect length.\n', a);
                continue;
            }
            text += a[0].trim() + ';' + a[1].trim();
            for (var j = 2; j < m; ++j) {
                text += ';"' + a[j].trim() + '"';
            }
            text += '\n';
        }
        document.write(
            'Scraping complete. Please copy the contents below ' +
            'into a plaintext document and give it a .csv extension.
' +
            '<textarea id="output" style="width: 50ex; height: 10em;">' +
            'number;century;text;contextLeft;sample;contextRight\n' +
            text +
            '</textarea>'
        );
        $('#output').focus().select();
    }

    function scrape (doc) {
        domain.turnpage_then(doc, function (next_doc) {
            domain.scrape1page(next_doc);
            scrape(next_doc);
        }, data2csv);
    }

    domain.init();
    create_statusbar();
    domain.scrape1page(target.document);
    insert_jquery_then(function ( ) {
		update_statusbar();
		scrape(target.document);
	});
}());
<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');
var run = require('run-sequence');
var spawn = require('spawn-local-bin');

var ROOT = path.join(__dirname, '..');

gulp.task('init', function(callback) {
    run('init-bower', 'init-yui', callback);
});

gulp.task('init-bower', function(callback) {
    var args = ['install'];
    var cmd = 'bower';
    var cwd = ROOT;

    spawn(cmd, args, cwd)
        .on('exit', function() {
            callback();
        });
});

gulp.task('init-yui', function() {
    return gulp.src('bower_components/yui3/build/**', { cwd: ROOT })
        .pipe(gulp.dest('build', { cwd: ROOT }));
});<commit_msg>AUI-1405 Replace the YUI module @VERSION@ in the build<commit_after>var alloy = require('../.alloy');
var gulp = require('gulp');
var path = require('path');
var replace = require('gulp-replace');
var run = require('run-sequence');
var spawn = require('spawn-local-bin');

var ROOT = path.join(__dirname, '..');

gulp.task('init', function(callback) {
    run('init-bower', 'init-yui', callback);
});

gulp.task('init-bower', function(callback) {
    var args = ['install'];
    var cmd = 'bower';
    var cwd = ROOT;

    spawn(cmd, args, cwd)
        .on('exit', function() {
            callback();
        });
});

gulp.task('init-yui', function() {
    return gulp.src('bower_components/yui3/build/**', { cwd: ROOT })
        .pipe(replace('@VERSION@', alloy.yuiversion))
        .pipe(gulp.dest('build', { cwd: ROOT }));
});<|endoftext|>


<commit_before>'use strict';

angular.module('bcdssApp').controller('ResultsController', function($rootScope, $scope, $state, Account,
														$q, DTOptionsBuilder, DTColumnBuilder, $compile,
														$stateParams, ClaimService, RatingService) {

	$scope.results = [];
	$scope.filters = {
		fromDate: null,
		toDate: null
	};
	$scope.dtInstance = {};
	$scope.selected = {};
	$scope.processIds = [];

	$scope.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
	   	 return new Promise( function(resolve, reject){
	            if ($scope.results)
	              resolve($scope.results);
	            else
	              resolve([]);
	          });
	   })
	   .withOption('createdRow', function(row, data, dataIndex) {
	               // Recompiling so we can bind Angular directive to the DT
	       $compile(angular.element(row).contents())($scope);
	   })
	   .withOption('headerCallback', function(header) {
	       if (!self.headerCompiled) {
	           // Use this headerCompiled field to only compile header once
	           self.headerCompiled = true;
	           $compile(angular.element(header).contents())($scope);
	           $compile(angular.element('.dt-buttons').contents())($scope);
	       }
	   });

	$scope.modelTypeOptions = [
		{ value:'knee',	label:'Knee'},
	    { value:'ear',	label:'Ear'},
	    { value:'leg',	label:'Leg'},
	];

	$scope.processResults = function(resultsArray){
		var results = [];
		angular.forEach(resultsArray,function(ele,id){
			var obj = {};
			angular.forEach(ele.claimRating, function(claimrating,id){
				obj.veteran = ele.veteran;
				obj.claim = claimrating.claim;
				obj.rating = claimrating.rating;
				results.push(obj);
			});
		});
		return results;
	};

	$scope.formatDate = function(date) {
        var date = new Date(date);
        return date.getFullYear() + '-' +
            ('0' + (date.getMonth()+1)).slice(-2) + '-' +
            ('0' + date.getDate()).slice(-2);
    };

    $scope.checkErr = function(startDate,endDate) {
        $scope.errMessage = '';
        $scope.frmResultsSearchFilter.$invalid = false;
        if(new Date(startDate) > new Date(endDate)){
          $scope.errMessage = 'To date should be greater than from date.';
          $scope.frmResultsSearchFilter.$invalid = true;
          return false;
        }
    };

    $scope.getProcessIds = function(){
    	$scope.processIds.push(1); //this is for test and needs to change..... it should come from process claims
    	return $scope.processIds;
    };

	$scope.getRatingResults = function(){
		var processIds = $scope.getProcessIds();
		if(processIds == null){
			alert("No processId found."); // need to change to validation message
			return;
		}
		$scope.filters = null;
		RatingService.findModelRatingResults(processIds, $scope.filters)
			.then(function(result){
				console.log('>>>successful');
				$scope.results = result.data;
				var promise = new Promise( function(resolve, reject){
	                if ($scope.results)
	                  resolve($scope.results);
	                else
	                  resolve([]);
	              });
	    		$scope.dtInstance.changeData(function() {
	                return promise;
	            });
		});
	};

	$scope.clear = function(){
    	$scope.results = [];
    	$scope.errMessage = '';
    	$scope.fromDate = null;
    	$scope.toDate = null;
    	$scope.filters.modelTypeOption = null;
        $scope.filters.modelResultId = null;
    };

     $scope.setSearchParameters = function(){
     	//case when no params or only model type
    	if(($scope.filters.modelResultId || $scope.filters.modelResultId == null) && $scope.fromDate == null && $scope.toDate == null){
    		var today = new Date();
    		$scope.filters.fromDate = $scope.formatDate(new Date());
    		$scope.filters.toDate = $scope.formatDate(new Date(today.getFullYear(), today.getMonth() + 12, today.getDate()));
   			$scope.processIds = [];
    	}

    	//case when only resultid
    	if(($scope.filters.modelResultId && $scope.filters.modelResultId != null) && $scope.fromDate == null && $scope.toDate == null){
    		$scope.filters.fromDate = null;
    		$scope.filters.toDate = null;
    		$scope.processIds.push($scope.filters.modelResultId);
    	}

    	//case when only dates and/or resultid/modeltype
    	if($scope.fromDate != null && $scope.toDate != null){
    		$scope.filters.fromDate = $scope.formatDate($scope.fromDate);
    		$scope.filters.toDate = $scope.formatDate($scope.toDate);
    		($scope.filters === null || $scope.filters.modelResultId === null) ? null : $scope.processIds.push($scope.filters.modelResultId);
    	}

		$scope.filters.modelTypeOption = ($scope.filters.modelTypeOption == null) ? null : $scope.filters.modelTypeOption;
	};

	$scope.searchRatingResults = function(){
		$scope.processIds = [];
		$scope.setSearchParameters();

		RatingService.findModelRatingResults($scope.processIds, $scope.filters)
			.then(function(result){
				console.log('>>>successful');
				$scope.results = result.data;
				var promise = new Promise( function(resolve, reject){
	                if ($scope.results)
	                  resolve($scope.results);
	                else
	                  resolve([]);
	              });
	    		$scope.dtInstance.changeData(function() {
	                return promise;
	            });
		});
    };

	 $scope.dtColumns = [
	        DTColumnBuilder.newColumn('veteran.veteranId').withTitle('Veteran ID'),
	        DTColumnBuilder.newColumn('veteran.veteranId').withTitle('Veteran Name').renderWith(function(data, type, full) {
	            return "
"+ data +"-veteran
"
	        }),
	        DTColumnBuilder.newColumn('claimId').withTitle('Claim ID'),
	        DTColumnBuilder.newColumn('modelType').withTitle('Model').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('processId').withTitle('Model Result ID').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('priorCDD').withTitle('Prior Rating').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('currentCDD').withTitle('Rater Evaluation').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('patternIndex.cdd').withTitle('Model Results').renderWith(function(data, type, full) {
	           return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('currentCDD').withTitle('RE/MR Match').renderWith(function(data, type, full) {
	            return "

"
	        }),
	        DTColumnBuilder.newColumn('patternIndex.cdd').withTitle('Pattern Rate of Use').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('patternIndex.accuracy').withTitle('Pattern Accuracy').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn(null).withTitle('Agree Y/N').notSortable().renderWith(function(data, type, full, meta) {
		     	$scope.selected[full.processId] = false;
		     	return 'select<input id="selectchk' + data.processId + '" type="checkbox" ng-model="selected[' + data.processId + ']" ng-click="toggleOne(selected)">';
			}),
	    ];

	 $rootScope.$on('ProcessClaims', function(event, data) {
		var inputObj = [];

		angular.forEach(data,function(ele,idx){
			var obj = {
   			      "veteran": {
   			        "veteranId": ele.veteranId,
   			        "veteranName": null,
   			        "dob": null
   			      },
   			      "claim": [
   			        {
   			          "claimId": ele.claimId,
   			          "profileDate": null,
   			          "productTypeCode": null,
   			          "claimDate": null,
   			          "contentionId": 0,
   			          "contentionClassificationId": null,
   			          "contentionBeginDate": null
   			        }
   			      ]
   			    }
			inputObj.push(obj);
		});
		$scope.results = []
		ClaimService.processClaims({},{
     		  			"veteranClaimInput": inputObj
     				},function(data){
     				//data = {"veteranClaimRatingOutput":[{"veteran":{"veteranId":244390,"veteranName":null,"dob":null},"claimRating":[{"claim":{"claimId":5614193,"profileDate":1147665600000,"productTypeCode":"020","claimDate":1091073600000,"contentionId":2991274,"contentionClassificationId":"6850","contentionBeginDate":null},"rating":{"claimantAge":20,"promulgationDate":null,"recentDate":null,"contationCount":2,"priorCdd":64,"quantPriorCdd":0,"currentCdd":0,"claimAge":20,"cddAge":20,"claimCount":1,"processId":18380497,"patternId":0,"processDate":null,"modelType":null,"modelContentionCount":0,"quantCdd":80,"ratingDecisions":{"processId":18380497,"kneeRatings":{"contentionKnee":0,"contentionLeft":0,"contentionRight":0,"contentionBilateral":0,"contentionLeg":0,"contentionAmputation":0,"decisionKnee":0,"decisionLeft":0,"decisionRight":0,"decisionBilateral":0,"decisionLimitation":0,"decisionImpairment":0,"decisionAnkyloses":0,"decisionAmputation":0},"earRatings":{"contentionLoss":0,"contentionTinitu":0,"decisionLoss":0,"decisionTinitu":0}},"status":[],"diagnosisCodeCounts":[],"contentionsCodeCounts":[]}}]}]};
     				var formattedResults = $scope.processResults(data.veteranClaimRatingOutput);
     				$scope.results = formattedResults;
     				//make api call using rating service to get rest of the column values and then populate results.
     	    		var promise = new Promise( function(resolve, reject){
     	                if ($scope.results)
     	                {
       	                    resolve($scope.results);
     	                }
     	                else
     	                {
     	                	 resolve([]);
     	                }

     	              });
     	    		$scope.dtInstance.changeData(function() {
     	                return promise;
     	            });

     			});
	 });
});<commit_msg>tooltips for headers-results grid<commit_after>'use strict';

angular.module('bcdssApp').controller('ResultsController', function($rootScope, $scope, $state, Account,
														$q, DTOptionsBuilder, DTColumnBuilder, $compile,
														$stateParams, ClaimService, RatingService) {

	$scope.results = [];
	$scope.filters = {
		fromDate: null,
		toDate: null
	};
	$scope.dtInstance = {};
	$scope.selected = {};
	$scope.processIds = [];

	$scope.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
	   	 return new Promise( function(resolve, reject){
	            if ($scope.results)
	              resolve($scope.results);
	            else
	              resolve([]);
	          });
	   })
	   .withOption('createdRow', function(row, data, dataIndex) {
	    	// Recompiling so we can bind Angular directive to the DT
	    	$compile(angular.element(row).contents())($scope);
	   })
	   .withOption('headerCallback', function(header) {
	    	angular.forEach(header.cells, function(cell){
	       		$(cell).attr('title', function (index, attr) {
				    return this.outerText;
				});
	    	})

	    	if (!self.headerCompiled) {
	           // Use this headerCompiled field to only compile header once
	           self.headerCompiled = true;
	           $compile(angular.element(header).contents())($scope);
	           $compile(angular.element('.dt-buttons').contents())($scope);
	       }
	   });

	$scope.modelTypeOptions = [
		{ value:'knee',	label:'Knee'},
	    { value:'ear',	label:'Ear'},
	    { value:'leg',	label:'Leg'},
	];

	$scope.processResults = function(resultsArray){
		var results = [];
		angular.forEach(resultsArray,function(ele,id){
			var obj = {};
			angular.forEach(ele.claimRating, function(claimrating,id){
				obj.veteran = ele.veteran;
				obj.claim = claimrating.claim;
				obj.rating = claimrating.rating;
				results.push(obj);
			});
		});
		return results;
	};

	$scope.formatDate = function(date) {
        var date = new Date(date);
        return date.getFullYear() + '-' +
            ('0' + (date.getMonth()+1)).slice(-2) + '-' +
            ('0' + date.getDate()).slice(-2);
    };

    $scope.checkErr = function(startDate,endDate) {
        $scope.errMessage = '';
        $scope.frmResultsSearchFilter.$invalid = false;
        if(new Date(startDate) > new Date(endDate)){
          $scope.errMessage = 'To date should be greater than from date.';
          $scope.frmResultsSearchFilter.$invalid = true;
          return false;
        }
    };

    $scope.getProcessIds = function(){
    	$scope.processIds.push(1); //this is for test and needs to change..... it should come from process claims
    	return $scope.processIds;
    };

	$scope.getRatingResults = function(){
		var processIds = $scope.getProcessIds();
		if(processIds == null){
			alert("No processId found."); // need to change to validation message
			return;
		}
		$scope.filters = null;
		RatingService.findModelRatingResults(processIds, $scope.filters)
			.then(function(result){
				console.log('>>>successful');
				$scope.results = result.data;
				var promise = new Promise( function(resolve, reject){
	                if ($scope.results)
	                  resolve($scope.results);
	                else
	                  resolve([]);
	              });
	    		$scope.dtInstance.changeData(function() {
	                return promise;
	            });
		});
	};

	$scope.clear = function(){
    	$scope.results = [];
    	$scope.errMessage = '';
    	$scope.fromDate = null;
    	$scope.toDate = null;
    	$scope.filters.modelTypeOption = null;
        $scope.filters.modelResultId = null;
    };

     $scope.setSearchParameters = function(){
     	//case when no params or only model type
    	if(($scope.filters.modelResultId || $scope.filters.modelResultId == null) && $scope.fromDate == null && $scope.toDate == null){
    		var today = new Date();
    		$scope.filters.fromDate = $scope.formatDate(new Date());
    		$scope.filters.toDate = $scope.formatDate(new Date(today.getFullYear(), today.getMonth() + 12, today.getDate()));
   			$scope.processIds = [];
    	}

    	//case when only resultid
    	if(($scope.filters.modelResultId && $scope.filters.modelResultId != null) && $scope.fromDate == null && $scope.toDate == null){
    		$scope.filters.fromDate = null;
    		$scope.filters.toDate = null;
    		$scope.processIds.push($scope.filters.modelResultId);
    	}

    	//case when only dates and/or resultid/modeltype
    	if($scope.fromDate != null && $scope.toDate != null){
    		$scope.filters.fromDate = $scope.formatDate($scope.fromDate);
    		$scope.filters.toDate = $scope.formatDate($scope.toDate);
    		($scope.filters === null || $scope.filters.modelResultId === null) ? null : $scope.processIds.push($scope.filters.modelResultId);
    	}

		$scope.filters.modelTypeOption = ($scope.filters.modelTypeOption == null) ? null : $scope.filters.modelTypeOption;
	};

	$scope.searchRatingResults = function(){
		$scope.processIds = [];
		$scope.setSearchParameters();

		RatingService.findModelRatingResults($scope.processIds, $scope.filters)
			.then(function(result){
				console.log('>>>successful');
				$scope.results = result.data;
				var promise = new Promise( function(resolve, reject){
	                if ($scope.results)
	                  resolve($scope.results);
	                else
	                  resolve([]);
	              });
	    		$scope.dtInstance.changeData(function() {
	                return promise;
	            });
		});
    };

	 $scope.dtColumns = [
	        DTColumnBuilder.newColumn('veteran.veteranId').withTitle('Veteran ID'),
	        DTColumnBuilder.newColumn('veteran.veteranId').withTitle('Veteran Name').renderWith(function(data, type, full) {
	            return "
"+ data +"-veteran
"
	        }),
	        DTColumnBuilder.newColumn('claimId').withTitle('Claim ID'),
	        DTColumnBuilder.newColumn('modelType').withTitle('Model').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('processId').withTitle('Model Result ID').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('priorCDD').withTitle('Prior Rating').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('currentCDD').withTitle('Rater Evaluation').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('patternIndex.cdd').withTitle('Model Results').renderWith(function(data, type, full) {
	           return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('currentCDD').withTitle('RE/MR Match').renderWith(function(data, type, full) {
	            return "

"
	        }),
	        DTColumnBuilder.newColumn('patternIndex.cdd').withTitle('Pattern Rate of Use').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn('patternIndex.accuracy').withTitle('Pattern Accuracy').renderWith(function(data, type, full) {
	            return "
"+data+"
"
	        }),
	        DTColumnBuilder.newColumn(null).withTitle('Agree Y/N').notSortable().renderWith(function(data, type, full, meta) {
		     	$scope.selected[full.processId] = false;
		     	return 'select<input id="selectchk' + data.processId + '" type="checkbox" ng-model="selected[' + data.processId + ']" ng-click="toggleOne(selected)">';
			}),
	    ];

	 $rootScope.$on('ProcessClaims', function(event, data) {
		var inputObj = [];

		angular.forEach(data,function(ele,idx){
			var obj = {
   			      "veteran": {
   			        "veteranId": ele.veteranId,
   			        "veteranName": null,
   			        "dob": null
   			      },
   			      "claim": [
   			        {
   			          "claimId": ele.claimId,
   			          "profileDate": null,
   			          "productTypeCode": null,
   			          "claimDate": null,
   			          "contentionId": 0,
   			          "contentionClassificationId": null,
   			          "contentionBeginDate": null
   			        }
   			      ]
   			    }
			inputObj.push(obj);
		});
		$scope.results = []
		ClaimService.processClaims({},{
     		  			"veteranClaimInput": inputObj
     				},function(data){
     				//data = {"veteranClaimRatingOutput":[{"veteran":{"veteranId":244390,"veteranName":null,"dob":null},"claimRating":[{"claim":{"claimId":5614193,"profileDate":1147665600000,"productTypeCode":"020","claimDate":1091073600000,"contentionId":2991274,"contentionClassificationId":"6850","contentionBeginDate":null},"rating":{"claimantAge":20,"promulgationDate":null,"recentDate":null,"contationCount":2,"priorCdd":64,"quantPriorCdd":0,"currentCdd":0,"claimAge":20,"cddAge":20,"claimCount":1,"processId":18380497,"patternId":0,"processDate":null,"modelType":null,"modelContentionCount":0,"quantCdd":80,"ratingDecisions":{"processId":18380497,"kneeRatings":{"contentionKnee":0,"contentionLeft":0,"contentionRight":0,"contentionBilateral":0,"contentionLeg":0,"contentionAmputation":0,"decisionKnee":0,"decisionLeft":0,"decisionRight":0,"decisionBilateral":0,"decisionLimitation":0,"decisionImpairment":0,"decisionAnkyloses":0,"decisionAmputation":0},"earRatings":{"contentionLoss":0,"contentionTinitu":0,"decisionLoss":0,"decisionTinitu":0}},"status":[],"diagnosisCodeCounts":[],"contentionsCodeCounts":[]}}]}]};
     				var formattedResults = $scope.processResults(data.veteranClaimRatingOutput);
     				$scope.results = formattedResults;
     				//make api call using rating service to get rest of the column values and then populate results.
     	    		var promise = new Promise( function(resolve, reject){
     	                if ($scope.results)
     	                {
       	                    resolve($scope.results);
     	                }
     	                else
     	                {
     	                	 resolve([]);
     	                }

     	              });
     	    		$scope.dtInstance.changeData(function() {
     	                return promise;
     	            });

     			});
	 });
});<|endoftext|>