<commit_before>

define (
	[
		'kbwidget',
		'bootstrap',
		'jquery',
		'kbaseAuthenticatedWidget',
		'kbaseTabs',
		'kbaseHistogram',
		'kbase-client-api',
		'kbaseTable',
		'jquery-dataTables',
		'kbaseReportView'
	], function(
		KBWidget,
		bootstrap,
		$,
		kbaseAuthenticatedWidget,
		kbaseTabs,
		kbaseHistogram,
		kbase_client_api,
		kbaseTable,
		jquery_dataTables,
		kbaseReportView
	) {

    'use strict';

    return KBWidget({

	    name: "kbaseExpressionSampleTableNew",
	    parent : kbaseAuthenticatedWidget,

        version: "1.0.0",
        options: {
            numBins : 50,
            minCutoff : 0.001,
        },

        _accessors : [
            {name: 'dataset', setter: 'setDataset'},
            //{name: 'barchartDataset', setter: 'setBarchartDataset'},
        ],

        getState : function() {
            return this.data('histogram').getState();
        },

        loadState : function(state) {
            this.data('histogram').loadState(state);
            this.data('histogram').renderHistogram();
        },

        setDataset : function setDataset(newDataset) {

            var rows = [];
            var barData = [];

            var min = Number.MAX_VALUE;
            var max = Number.MIN_VALUE;

            var exprKeys = [];
            if (newDataset.expression_levels != undefined) {
              exprKeys = Object.keys(newDataset.expression_levels).sort();

              $.each(
                  exprKeys,
                  function (i,k) {

                      var val = Math.round(newDataset.expression_levels[k] * 1000) / 1000;

                      var row = [k,val];
                      if (newDataset.tpm_expression_levels != undefined) {
                        var tpm = Math.round(newDataset.tpm_expression_levels[k] * 1000) / 1000 || 0;
                        row.push(tpm);
                      }

                      rows.push( row );

                      if (val < min) {
                          min = val;
                      }
                      if (val > max) {
                          max = val;
                      }
                      barData.push(val);

                      /*var bin = Math.floor(newDataset.expression_levels[k]);

                      if (barData[bin] == undefined) {
                          barData[bin] = 0;
                      }
                      barData[bin]++;*/

                  }
              );

              if (newDataset.tpm_expression_levels != undefined) {
                if (!this.hasTPMTab) {
                  this.data('container').addTab(
                    {
                      'tab' : 'TPM Histogram',
                      'content' : this.data('tpmHistElem')
                    }
                  );
                  this.hasTPMTab = true;
                }
                var tpm_min = Number.MAX_VALUE;
                var tpm_max = Number.MIN_VALUE;
                var tpmBarData = [];

                exprKeys = Object.keys(newDataset.tpm_expression_levels).sort();

                $.each(
                    exprKeys,
                    function (i,k) {

                        var val = Math.round(newDataset.tpm_expression_levels[k] * 1000) / 1000;

                        //rows.push( [k, val] );

                        if (val < tpm_min) {
                            tpm_min = val;
                        }
                        if (val > tpm_max) {
                            tpm_max = val;
                        }
                        tpmBarData.push(val);

                    }
                );
                this.data('tpmHistogram').setDataset(tpmBarData);

              }

              //this.setBarchartDataset(barData);
              this.data('histogram').setDataset(barData);
              //this.renderHistogram(this.options.numBins);

              var $dt = this.data('$dt');
              if ($dt == undefined) {

                var aoColumns = [
                    { title : 'Feature ID'},
                    { title : 'Feature Value : log2(FPKM + 1)'},
                ];
                if (newDataset.tpm_expression_levels != undefined) {
                  this.data('tableElem').find('th').css('display', '');
                  aoColumns.push({ title : 'Feature Value : log2(TPM + 1)'});
                }

                $dt = this.data('tableElem').dataTable({
                    aoColumns : aoColumns
                });

                this.data('$dt', $dt);
              }

              $dt.fnAddData(rows);
              this.data('loader').hide();
              this.data('containerElem').show();
            }
            else {
              this.loadExpression(newDataset.sample_expression_ids[0]);
              this.data('loader').hide();
                this.$elem.append($.jqElem('div')
                    .addClass('alert alert-danger')
                    .html("No expression levels available")
                )
            }

        },

        loadExpression : function(ref) {
          var $sam = this;
          this.data('containerElem').hide();
          this.data('loader').show();
          var ws = new Workspace(window.kbconfig.urls.workspace, {token : $sam.authToken()});

          var ws_params = {
              ref : ref
          };

          ws.get_objects([ws_params]).then(function (d) {
              $sam.setDataset(d[0].data);
          })
          .fail(function(d) {

              $sam.$elem.empty();
              $sam.$elem
                  .addClass('alert alert-danger')
                  .html("Could not load object : " + d.error.message);
          })
        },

        init : function init(options) {

          this._super(options);

          if (this.options.report_name != undefined) {

            var $div = $.jqElem('div');
            this.$elem.append($div);

            $div.kbaseReportView( this.options);
            return this;
          }

            this._super(options);

            var $self = this;

            var ws = new Workspace(window.kbconfig.urls.workspace, {token : $self.authToken()});
            //var ws = new Workspace('https://ci.kbase.us/services/ws', {token : $self.authToken()});

            var ws_params = {
                workspace : this.options.workspace,
                wsid : this.options.wsid,
                name : this.options.output
            };

            ws.get_objects([ws_params]).then(function (d) {

                var thing = d[0].data;
                if (thing.sample_expression_ids) {
                  $self.options.output = thing;

                  var promises = [];
                  $.each(
                    $self.options.output.sample_expression_ids,
                    function (i,v) {
                      promises.push(
                        ws.get_object_info([{ref : v}])
                      );
                    }
                  );

                  $.when.apply($, promises).then(function () {

                      var args = arguments;
                      $self.options.output.sample_expression_names = [];
                      $.each(
                        arguments,
                        function (i, v) {
                          $self.options.output.sample_expression_names.push(v[0][1]);
                        }
                      );

                      $self.appendUI($self.$elem);

                      if ($self.options.output.sample_expression_ids.length) {
                        $self.loadExpression($self.options.output.sample_expression_ids[0]);
                      }

                  })
                  .fail(function(d) {

                      $self.$elem.empty();
                      $self.$elem
                          .addClass('alert alert-danger')
                          .html("Could not load object : " + d.error.message);
                  });

                }
                else {
                  $self.appendUI($self.$elem);
                  $self.setDataset(d[0].data);
                }
            }).fail(function(d) {

                $self.$elem.empty();
                $self.$elem
                    .addClass('alert alert-danger')
                    .html("Could not load object : " + d.error.message);
            })

            return this;
        },

        appendUI : function appendUI($elem) {

            var $me = this;

            if (this.options.output.sample_expression_ids) {

              var $selector = $.jqElem('select').css('width', '500px')
                .on('change', function(e) {
                  $me.loadExpression( $selector.val() );
                }
              );

              $.each(
                this.options.output.sample_expression_ids,
                function (i,v) {
                  $selector.append(
                    $.jqElem('option')
                      .attr('value', v)
                      .append($me.options.output.sample_expression_names[i])
                  )
                }
              );

              this.$elem
                .append("
Please select expression level: ")
                .append($selector)
                .append("

");
            }

            var $tableElem = $.jqElem('table')
                .css('width', '95%')
                    .append(
                        $.jqElem('thead')
                            .append(
                                $.jqElem('tr')
                                    .append($.jqElem('th').append('Feature ID'))
                                    .append($.jqElem('th').append('Feature Value : log2(FPKM + 1)'))
                                    .append($.jqElem('th').css('display', 'none').append('Feature Value : log2(TPM + 1)'))
                            )
                    )
            ;

            var $histElem = $.jqElem('div').css({width : 800, height : 500});

            var $containerElem = $.jqElem('div').attr('id', 'containerElem').css('display', 'none');

            var $container =  new kbaseTabs($containerElem, {
                    tabs : [
                        {
                            tab : 'Overview',
                            content : $tableElem
                        },
                        {
                            tab : 'FPKM Histogram',
                            content : $histElem
                        }
                    ],
                    deleteTabCallback : function(tabName) {
                      if (tabName === 'TPM Histogram') {
                        delete this.tpmTab;
                      }
                    }
                }
            )

            var $tpmHistElem = $.jqElem('div').css({width : 800, height : 500});

            $container.$elem.find('[data-tab=Histogram]').on('click', function(e) {
                $histogram.renderXAxis();
                setTimeout(function() {$histogram.renderHistogram() }, 300);
            });

            $elem
                .append( $containerElem )
                .append(
                    $.jqElem('div')
                        .attr('id', 'loader')
                        .append('
 Loading data...
 please wait...')
                        .append($.jqElem('br'))
                        .append(
                            $.jqElem('div')
                                .attr('align', 'center')
                                .append($.jqElem('i').addClass('fa fa-spinner').addClass('fa fa-spin fa fa-4x'))
                        )
                )
            ;

            this._rewireIds($elem, this);

            var $histogram =
                 new kbaseHistogram($histElem, {
                        scaleAxes   : true,
                        xPadding : 60,
                        yPadding : 120,

                        xLabelRegion : 'yPadding',
                        yLabelRegion : 'xPadding',

                        xLabelOffset : 45,
                        yLabelOffset : -10,

                        yLabel : 'Number of Genes',
                        xLabel : 'Gene Expression Level log2(FPKM + 1)',
                        xAxisVerticalLabels : true,
                        useUniqueID : true,

                    }
                )
            ;

            var $tpmHistogram =
                 new kbaseHistogram($tpmHistElem, {
                        scaleAxes   : true,
                        xPadding : 60,
                        yPadding : 120,

                        xLabelRegion : 'yPadding',
                        yLabelRegion : 'xPadding',

                        xLabelOffset : 45,
                        yLabelOffset : -10,

                        yLabel : 'Number of Genes',
                        xLabel : 'Gene Expression Level TPM',
                        xAxisVerticalLabels : true,
                        useUniqueID : true,

                    }
                )
            ;

            this.data('tableElem', $tableElem);
            this.data('histElem',   $histElem);
            this.data('tpmHistElem',   $tpmHistElem);
            this.data('container', $container);
            this.data('histogram', $histogram);
            this.data('tpmHistogram', $tpmHistogram);

        },

    });

} );
<commit_msg>another bug fix<commit_after>

define (
	[
		'kbwidget',
		'bootstrap',
		'jquery',
		'kbaseAuthenticatedWidget',
		'kbaseTabs',
		'kbaseHistogram',
		'kbase-client-api',
		'kbaseTable',
		'jquery-dataTables-bootstrap',
		'kbaseReportView'
	], function(
		KBWidget,
		bootstrap,
		$,
		kbaseAuthenticatedWidget,
		kbaseTabs,
		kbaseHistogram,
		kbase_client_api,
		kbaseTable,
		jquery_dataTables,
		kbaseReportView
	) {

    'use strict';

    return KBWidget({

	    name: "kbaseExpressionSampleTableNew",
	    parent : kbaseAuthenticatedWidget,

        version: "1.0.0",
        options: {
            numBins : 50,
            minCutoff : 0.001,
        },

        _accessors : [
            {name: 'dataset', setter: 'setDataset'},
            //{name: 'barchartDataset', setter: 'setBarchartDataset'},
        ],

        getState : function() {
            return this.data('histogram').getState();
        },

        loadState : function(state) {
            this.data('histogram').loadState(state);
            this.data('histogram').renderHistogram();
        },

        setDataset : function setDataset(newDataset) {

            var rows = [];
            var barData = [];

            var min = Number.MAX_VALUE;
            var max = Number.MIN_VALUE;

            var exprKeys = [];
            if (newDataset.expression_levels != undefined) {
              exprKeys = Object.keys(newDataset.expression_levels).sort();

              $.each(
                  exprKeys,
                  function (i,k) {

                      var val = Math.round(newDataset.expression_levels[k] * 1000) / 1000;

                      var row = [k,val];
                      if (newDataset.tpm_expression_levels != undefined) {
                        var tpm = Math.round(newDataset.tpm_expression_levels[k] * 1000) / 1000 || 0;
                        row.push(tpm);
                      }

                      rows.push( row );

                      if (val < min) {
                          min = val;
                      }
                      if (val > max) {
                          max = val;
                      }
                      barData.push(val);

                      /*var bin = Math.floor(newDataset.expression_levels[k]);

                      if (barData[bin] == undefined) {
                          barData[bin] = 0;
                      }
                      barData[bin]++;*/

                  }
              );

              if (newDataset.tpm_expression_levels != undefined) {
                if (!this.hasTPMTab) {
                  this.data('container').addTab(
                    {
                      'tab' : 'TPM Histogram',
                      'content' : this.data('tpmHistElem')
                    }
                  );
                  this.hasTPMTab = true;
                }
                var tpm_min = Number.MAX_VALUE;
                var tpm_max = Number.MIN_VALUE;
                var tpmBarData = [];

                exprKeys = Object.keys(newDataset.tpm_expression_levels).sort();

                $.each(
                    exprKeys,
                    function (i,k) {

                        var val = Math.round(newDataset.tpm_expression_levels[k] * 1000) / 1000;

                        //rows.push( [k, val] );

                        if (val < tpm_min) {
                            tpm_min = val;
                        }
                        if (val > tpm_max) {
                            tpm_max = val;
                        }
                        tpmBarData.push(val);

                    }
                );
                this.data('tpmHistogram').setDataset(tpmBarData);

              }

              //this.setBarchartDataset(barData);
              this.data('histogram').setDataset(barData);
              //this.renderHistogram(this.options.numBins);

              var $dt = this.data('$dt');
              if ($dt == undefined) {

                var columns = [
                    { title : 'Feature ID'},
                    { title : 'Feature Value : log2(FPKM + 1)'},
                ];
                if (newDataset.tpm_expression_levels != undefined) {
                  this.data('tableElem').find('th').css('display', '');
                  columns.push({ title : 'Feature Value : log2(TPM + 1)'});
                }

                $dt = this.data('tableElem').DataTable({
                    columns : columns
                });

                this.data('$dt', $dt);
              }
              else {
                $dt.clear();
              }

              $dt.rows.add(rows).draw();
              this.data('loader').hide();
              this.data('containerElem').show();
            }
            else {
              this.loadExpression(newDataset.sample_expression_ids[0]);
              this.data('loader').hide();
                this.$elem.append($.jqElem('div')
                    .addClass('alert alert-danger')
                    .html("No expression levels available")
                )
            }

        },

        loadExpression : function(ref) {
          var $sam = this;
          this.data('containerElem').hide();
          this.data('loader').show();
          var ws = new Workspace(window.kbconfig.urls.workspace, {token : $sam.authToken()});

          var ws_params = {
              ref : ref
          };

          ws.get_objects([ws_params]).then(function (d) {
              $sam.setDataset(d[0].data);
          })
          .fail(function(d) {

              $sam.$elem.empty();
              $sam.$elem
                  .addClass('alert alert-danger')
                  .html("Could not load object : " + d.error.message);
          })
        },

        init : function init(options) {

          this._super(options);

          if (this.options.report_name != undefined) {

            var $div = $.jqElem('div');
            this.$elem.append($div);

            $div.kbaseReportView( this.options);
            return this;
          }

            this._super(options);

            var $self = this;

            var ws = new Workspace(window.kbconfig.urls.workspace, {token : $self.authToken()});
            //var ws = new Workspace('https://ci.kbase.us/services/ws', {token : $self.authToken()});

            var ws_params = {
                workspace : this.options.workspace,
                wsid : this.options.wsid,
                name : this.options.output
            };

            ws.get_objects([ws_params]).then(function (d) {

                var thing = d[0].data;
                if (thing.sample_expression_ids) {
                  $self.options.output = thing;

                  var promises = [];
                  $.each(
                    $self.options.output.sample_expression_ids,
                    function (i,v) {
                      promises.push(
                        ws.get_object_info([{ref : v}])
                      );
                    }
                  );

                  $.when.apply($, promises).then(function () {

                      var args = arguments;
                      $self.options.output.sample_expression_names = [];
                      $.each(
                        arguments,
                        function (i, v) {
                          $self.options.output.sample_expression_names.push(v[0][1]);
                        }
                      );

                      $self.appendUI($self.$elem);

                      if ($self.options.output.sample_expression_ids.length) {
                        $self.loadExpression($self.options.output.sample_expression_ids[0]);
                      }

                  })
                  .fail(function(d) {

                      $self.$elem.empty();
                      $self.$elem
                          .addClass('alert alert-danger')
                          .html("Could not load object : " + d.error.message);
                  });

                }
                else {
                  $self.appendUI($self.$elem);
                  $self.setDataset(d[0].data);
                }
            }).fail(function(d) {

                $self.$elem.empty();
                $self.$elem
                    .addClass('alert alert-danger')
                    .html("Could not load object : " + d.error.message);
            })

            return this;
        },

        appendUI : function appendUI($elem) {

            var $me = this;

            if (this.options.output.sample_expression_ids) {

              var $selector = $.jqElem('select').css('width', '500px')
                .on('change', function(e) {
                  $me.loadExpression( $selector.val() );
                }
              );

              $.each(
                this.options.output.sample_expression_ids,
                function (i,v) {
                  $selector.append(
                    $.jqElem('option')
                      .attr('value', v)
                      .append($me.options.output.sample_expression_names[i])
                  )
                }
              );

              this.$elem
                .append("
Please select expression level: ")
                .append($selector)
                .append("

");
            }

            var $tableElem = $.jqElem('table')
                .css('width', '95%')
                    .append(
                        $.jqElem('thead')
                            .append(
                                $.jqElem('tr')
                                    .append($.jqElem('th').append('Feature ID'))
                                    .append($.jqElem('th').append('Feature Value : log2(FPKM + 1)'))
                                    .append($.jqElem('th').css('display', 'none').append('Feature Value : log2(TPM + 1)'))
                            )
                    )
            ;

            var $histElem = $.jqElem('div').css({width : 800, height : 500});

            var $containerElem = $.jqElem('div').attr('id', 'containerElem').css('display', 'none');

            var $container =  new kbaseTabs($containerElem, {
                    tabs : [
                        {
                            tab : 'Overview',
                            content : $tableElem
                        },
                        {
                            tab : 'FPKM Histogram',
                            content : $histElem
                        }
                    ],
                    deleteTabCallback : function(tabName) {
                      if (tabName === 'TPM Histogram') {
                        delete this.tpmTab;
                      }
                    }
                }
            )

            var $tpmHistElem = $.jqElem('div').css({width : 800, height : 500});

            $container.$elem.find('[data-tab=Histogram]').on('click', function(e) {
                $histogram.renderXAxis();
                setTimeout(function() {$histogram.renderHistogram() }, 300);
            });

            $elem
                .append( $containerElem )
                .append(
                    $.jqElem('div')
                        .attr('id', 'loader')
                        .append('
 Loading data...
 please wait...')
                        .append($.jqElem('br'))
                        .append(
                            $.jqElem('div')
                                .attr('align', 'center')
                                .append($.jqElem('i').addClass('fa fa-spinner').addClass('fa fa-spin fa fa-4x'))
                        )
                )
            ;

            this._rewireIds($elem, this);

            var $histogram =
                 new kbaseHistogram($histElem, {
                        scaleAxes   : true,
                        xPadding : 60,
                        yPadding : 120,

                        xLabelRegion : 'yPadding',
                        yLabelRegion : 'xPadding',

                        xLabelOffset : 45,
                        yLabelOffset : -10,

                        yLabel : 'Number of Genes',
                        xLabel : 'Gene Expression Level log2(FPKM + 1)',
                        xAxisVerticalLabels : true,
                        useUniqueID : true,

                    }
                )
            ;

            var $tpmHistogram =
                 new kbaseHistogram($tpmHistElem, {
                        scaleAxes   : true,
                        xPadding : 60,
                        yPadding : 120,

                        xLabelRegion : 'yPadding',
                        yLabelRegion : 'xPadding',

                        xLabelOffset : 45,
                        yLabelOffset : -10,

                        yLabel : 'Number of Genes',
                        xLabel : 'Gene Expression Level TPM',
                        xAxisVerticalLabels : true,
                        useUniqueID : true,

                    }
                )
            ;

            this.data('tableElem', $tableElem);
            this.data('histElem',   $histElem);
            this.data('tpmHistElem',   $tpmHistElem);
            this.data('container', $container);
            this.data('histogram', $histogram);
            this.data('tpmHistogram', $tpmHistogram);

        },

    });

} );
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import Toast from '/views/components/toasts';

import './forgot.html';

Template.forgotPassphrase.events({
  'submit #forgotPassphrase'(event) {
    event.preventDefault();

    const form = event.target;
    const email = form.email.value;
    const { submit } = form;

    // Disable submit button
    submit.disabled = true;

    // Call forgot passphrase method
    Meteor.call('forgotPassphrase', email);

    // Tell user to check email regardless of result
    Toast({ text: 'Please check your email for next steps.' });
  },
});
<commit_msg>Forgot passphrase passes token to reset passphrase form<commit_after>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { Accounts } from 'meteor/accounts-base';
import History from '/views/history/history';
import Toast from '/views/components/toasts';

import './forgot.html';

const Token = new ReactiveVar('');

Template.forgotPassphrase.events({
  'submit #forgotPassphrase'(event) {
    event.preventDefault();

    const form = event.target;
    const email = form.email.value;
    const { submit } = form;

    // Disable submit button
    submit.disabled = true;

    // Call forgot passphrase method
    Meteor.call('forgotPassphrase', email);

    // Tell user to check email regardless of result
    Toast({ text: 'Please check your email for next steps.' });
    History.navigate('/');
  },
});

Accounts.onResetPasswordLink((token) => {
  Token.set(token);
  History.navigate('/reset-passphrase');
});

export default Token;
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var Events = require('./models/events');
var Iterator = require('./array_iterator');
var TestStatus = require('./models/test').Status;
var util = require('util');

var RunnerData = function() {
  this.hooks = [];
  this.tests = [];

  this.status = TestStatus.INITIALIZED;
  // TODO(lbayes): Update RunnerData.failure to the first found failure if
  // a failure was encountered.
  this.failure = null;
};

/**
 * Runs the provided Test (or Suite) by requesting all execution hooks as a
 * flattened Array and then executing each hook in order until all hooks
 * have been called.
 *
 * @see src/models/events.js For more details about the event stream that the
 *   Runner can emit.
 */
var Runner = function(testOrSuite) {
  EventEmitter.call(this);

  this._test = testOrSuite;
  this._completeHandler = null;
  this._isStarted = false;
  this.data = new RunnerData();
};

util.inherits(Runner, EventEmitter);

Runner.prototype.onRunnerStarted = function() {
  if (this._isStarted) {
    throw new Error('Runner can only be run once');
  }
  this._isStarted = true;
  this.emit(Events.RUNNER_STARTED);
};

/**
 * All Suites insert a hook at the beginning to notify the runner when they have
 * started.
 */
Runner.prototype.onSuiteStarted = function(suiteData) {
  this.emit(Events.SUITE_STARTED, suiteData);
};

/**
 * All Suites insert a hook at the end to notify the runner when they are
 * complete.
 */
Runner.prototype.onSuiteCompleted = function(suiteData) {
  this.emit(Events.SUITE_COMPLETED, suiteData);
};

/**
 * All Tests insert a hook at the beginning to notify the runner when they have
 * started.
 */
Runner.prototype.onTestStarted = function(testData) {
  this.emit(Events.TEST_STARTED, testData);
};

Runner.prototype.onTestFailed = function(testData) {
  this.emit(Events.TEST_FAILED, testData);
};

Runner.prototype.onTestSucceeded = function(testData) {
  this.emit(Events.TEST_SUCCEEDED, testData);
};

/**
 * All Tests insert a hook at the end to notify the runner when they are
 * complete.
 */
Runner.prototype.onTestCompleted = function(testData) {
  this.data.tests.push(testData);
  this.emit(Events.TEST_COMPLETED, testData);
};

/**
 * All user-defined hooks have been wrapped with functions that call this
 * method on the provided runner. This is how we balance the needs of fast
 * synchronous hooks and more complex asynchronous hooks.
 */
Runner.prototype.onHookStarted = function(hookData) {
  this.emit(Events.HOOK_STARTED, hookData);
};

Runner.prototype.onHookPaused = function(hookData) {
  this.emit(Events.HOOK_PAUSED, hookData);
};

Runner.prototype.onHookSucceeded = function(hookData) {
  this.emit(Events.HOOK_SUCCEEDED, hookData);
};

Runner.prototype.onHookFailed = function(hookData) {
  if (!this.data.failure) {
    this.data.failure = hookData.failure;
    this.data.status = TestStatus.FAILED;
  }
  this.emit(Events.HOOK_FAILED, hookData);
};

Runner.prototype.onHookSkipped = function(hookData) {
  this.emit(Events.HOOK_SKIPPED, hookData);
};

Runner.prototype.onHookCompleted = function(hookData) {
  this.data.hooks.push(hookData);
  this.emit(Events.HOOK_COMPLETED, hookData);
  this._runNext();
};

Runner.prototype.run = function(opt_completeHandler) {
  this._completeHandler = opt_completeHandler;

  this.onRunnerStarted();

  this._iterator = new Iterator(this._test.getHooks());
  this._runNext();
};

/**
 * Run the next hook by provided a reference to this runner and waiting for the
 * hook to call back into the Runner lifecycle methods before proceeding to the
 * next hook.
 *
 * If there are no more hooks, mark this Runner as completed and notify
 * listeners.
 */
Runner.prototype._runNext = function() {
  var itr = this._iterator;
  if (itr.hasNext()) {
    var hook = itr.next();
    hook(this);
  } else {
    this.emit(Events.RUNNER_COMPLETED, this.data);
    // Call the complete handler if one was provided to the `.run()` call.
    this._completeHandler && this._completeHandler(this.data.failure, this.data);
  }
};

/**
 * Create a new runner with the provided Test or Suite reference.
 */
Runner.create = function(testOrSuite) {
  return new Runner(testOrSuite);
};

module.exports = Runner;
<commit_msg>Finished file runner rename<commit_after>var EventEmitter = require('events').EventEmitter;
var Events = require('./models/events');
var Iterator = require('./array_iterator');
var TestStatus = require('./models/test').Status;
var util = require('util');

var RunnerData = function() {
  this.hooks = [];
  this.tests = [];

  this.status = TestStatus.INITIALIZED;
  // TODO(lbayes): Update RunnerData.failure to the first found failure if
  // a failure was encountered.
  this.failure = null;
};

/**
 * Runs the provided Test (or Suite) by requesting all execution hooks as a
 * flattened Array and then executing each hook in order until all hooks
 * have been called.
 *
 * @see src/models/events.js For more details about the event stream that the
 *   Runner can emit.
 */
var FileRunner = function(testOrSuite) {
  EventEmitter.call(this);

  this._test = testOrSuite;
  this._completeHandler = null;
  this._isStarted = false;
  this.data = new RunnerData();
};

util.inherits(FileRunner, EventEmitter);

FileRunner.prototype.onRunnerStarted = function() {
  if (this._isStarted) {
    throw new Error('FileRunner can only be run once');
  }
  this._isStarted = true;
  this.emit(Events.RUNNER_STARTED);
};

/**
 * All Suites insert a hook at the beginning to notify the runner when they have
 * started.
 */
FileRunner.prototype.onSuiteStarted = function(suiteData) {
  this.emit(Events.SUITE_STARTED, suiteData);
};

/**
 * All Suites insert a hook at the end to notify the runner when they are
 * complete.
 */
FileRunner.prototype.onSuiteCompleted = function(suiteData) {
  this.emit(Events.SUITE_COMPLETED, suiteData);
};

/**
 * All Tests insert a hook at the beginning to notify the runner when they have
 * started.
 */
FileRunner.prototype.onTestStarted = function(testData) {
  this.emit(Events.TEST_STARTED, testData);
};

FileRunner.prototype.onTestFailed = function(testData) {
  this.emit(Events.TEST_FAILED, testData);
};

FileRunner.prototype.onTestSucceeded = function(testData) {
  this.emit(Events.TEST_SUCCEEDED, testData);
};

/**
 * All Tests insert a hook at the end to notify the runner when they are
 * complete.
 */
FileRunner.prototype.onTestCompleted = function(testData) {
  this.data.tests.push(testData);
  this.emit(Events.TEST_COMPLETED, testData);
};

/**
 * All user-defined hooks have been wrapped with functions that call this
 * method on the provided runner. This is how we balance the needs of fast
 * synchronous hooks and more complex asynchronous hooks.
 */
FileRunner.prototype.onHookStarted = function(hookData) {
  this.emit(Events.HOOK_STARTED, hookData);
};

FileRunner.prototype.onHookPaused = function(hookData) {
  this.emit(Events.HOOK_PAUSED, hookData);
};

FileRunner.prototype.onHookSucceeded = function(hookData) {
  this.emit(Events.HOOK_SUCCEEDED, hookData);
};

FileRunner.prototype.onHookFailed = function(hookData) {
  if (!this.data.failure) {
    this.data.failure = hookData.failure;
    this.data.status = TestStatus.FAILED;
  }
  this.emit(Events.HOOK_FAILED, hookData);
};

FileRunner.prototype.onHookSkipped = function(hookData) {
  this.emit(Events.HOOK_SKIPPED, hookData);
};

FileRunner.prototype.onHookCompleted = function(hookData) {
  this.data.hooks.push(hookData);
  this.emit(Events.HOOK_COMPLETED, hookData);
  this._runNext();
};

FileRunner.prototype.run = function(opt_completeHandler) {
  this._completeHandler = opt_completeHandler;

  this.onRunnerStarted();

  this._iterator = new Iterator(this._test.getHooks());
  this._runNext();
};

/**
 * Run the next hook by provided a reference to this runner and waiting for the
 * hook to call back into the Runner lifecycle methods before proceeding to the
 * next hook.
 *
 * If there are no more hooks, mark this Runner as completed and notify
 * listeners.
 */
FileRunner.prototype._runNext = function() {
  var itr = this._iterator;
  if (itr.hasNext()) {
    var hook = itr.next();
    hook(this);
  } else {
    this.emit(Events.RUNNER_COMPLETED, this.data);
    // Call the complete handler if one was provided to the `.run()` call.
    this._completeHandler && this._completeHandler(this.data.failure, this.data);
  }
};

/**
 * Create a new runner with the provided Test or Suite reference.
 */
FileRunner.create = function(testOrSuite) {
  return new FileRunner(testOrSuite);
};

module.exports = FileRunner;
<|endoftext|>


<commit_before>//
// Put NPM into a CHROOT for `npm install`
//
// node chroot-npm-install.js chrootDir appDir
//
var daemon = require('daemon'),
    spawn = require('child_process').spawn,
    chrootDir = process.argv[2],
    appDir = process.argv[3];

daemon.chroot(chrootDir);

var npmInstall = spawn('npm', ['install'], {
  cwd:appDir
});

npmInstall.stdout.on('data', function (data) {
  process.stdout.write(data);
});

npmInstall.stderr.on('data', function (data) {
  process.stderr.write(data);
});

npmInstall.on('exit', function (code) {
  process.exit(code);
});<commit_msg>[fix] npm in chroot should handle install prefixes<commit_after>//
// Put NPM into a CHROOT for `npm install`
//
// node chroot-npm-install.js chrootDir appDir
//
var daemon = require('daemon'),
    spawn = require('child_process').spawn,
    chrootDir = process.argv[2],
    appDir = process.argv[3];

daemon.chroot(chrootDir);

var args = ['install'];
if (process.installPrefix) {
  args.push('--prefix', process.installPrefix);
}

var npmInstall = spawn('npm', args, {
  cwd:appDir
});

npmInstall.stdout.on('data', function (data) {
  process.stdout.write(data);
});

npmInstall.stderr.on('data', function (data) {
  process.stderr.write(data);
});

npmInstall.on('exit', function (code) {
  process.exit(code);
});<|endoftext|>


<commit_before>/* global _ */

/*
 * Complex scripted dashboard
 * This script generates a dashboard object that Grafana can load. It also takes a number of user
 * supplied URL parameters (int ARGS variable)
 */

// Accessable variables in this scope
var window, document, ARGS, $, jQuery, moment, kbn;

return function (callback) {
  'use strict';

  require(['getdash/getdash.conf'], function(getdashConf) {

    // Setup some variables
    var plugins = getdashConf.plugins;
    var datasourcesAll = getdashConf.datasources;
    var datasources = _.filter(datasourcesAll, function (ds) {
      return (!(ds.grafanaDB || ds.type !== 'influxdb'));
    });
    var dashboard;
    var getdashConfig = '/app/getdash/getdash.conf.js';

    // GET variables
    var displayHost = '';
    var displayMetric = '';
    var displayTime;

    if(!_.isUndefined(ARGS.host))
      displayHost = ARGS.host;

    if(!_.isUndefined(ARGS.metric))
      displayMetric = ARGS.metric;

    if(!_.isUndefined(ARGS.time))
      displayTime = ARGS.time;

    // Setup influxDB queries
// TODO: Implement query optimization with account for service groups
//    var influxdbQuery = (displayMetric) ? '&q=list series /\.' + displayHost + '\.(' +
//                    displayMetric.replace(',', '|') + ')/'
//                    : '&q=list series /\.' + displayHost + '\./';
    var influxdbQuery = 'list series /\.' + displayHost + '\./';

    // Intialize a skeleton with nothing but a rows array and service object
    dashboard = {
      'rows': [],
      'services': {}
    };

    // Set default time
    // time can be overriden in the url using from/to parameteres, but this is
    // handled automatically in grafana core during dashboard initialization

    // Dashboard time and interval setup function
    var getDashTimeInterval = function getDashTimeInterval (time) {
      var defaultTimeInterval = {
        'time': {
          'from': "now-6h",
          'to': "now"
        },
        'interval': '1m',
      };

      if (!time)
        return defaultTimeInterval;

      var timeM = 0;
      var interval = '';
      var regexpTime = /(\d+)(m|h|d)/;
      var rTime = regexpTime.exec(time);

      if (!rTime)
        return defaultTimeInterval;

      if (rTime[2] === 'm')
        timeM = parseInt(rTime[1]);
      else if (rTime[2] === 'h')
        timeM = parseInt(rTime[1]) * 60;
      else if (rTime[2] === 'd')
        timeM = parseInt(rTime[1]) * 60 * 24;

      if (timeM > 360)
        interval = (Math.ceil((Math.floor(timeM / 360) + 1) / 5) * 5).toString() + 'm';
      else if (timeM === 360)
        interval = '1m';
      else
        interval = '30s';

      return {
        'time': {
          'from': "now-" + time,
          'to': "now"
        },
        'interval': interval,
      };
    };

    var dashTimeInterval = getDashTimeInterval(displayTime);
    var interval = dashTimeInterval.interval;
    dashboard.time = dashTimeInterval.time;

    // Set a title
    dashboard.title = 'Grafana - Scripted Dashboard for ' + displayHost;

    // Object prototypes
    var targetProto = {
      'series': '',
      'alias': '',
      'column': 'value',
      'interval': interval,
      'function': 'mean',
    };

    var panelProto = {
      'title': 'Default Title',
      'type': 'graphite',
      'span': 12,
      'y_formats': [ 'none' ],
      'grid': { 'max': null, 'min': 0, 'leftMin': 0 },
      'lines': true,
      'fill': 1,
      'linewidth': 1,
      'nullPointMode': 'null',
      'targets': {},
      'aliasColors': {},
    };

    var rowProto = {
      'title': 'Default Row Title',
      'height': '250px',
      'panels': [],
    };

    // Dashboard setup helper functions
    var setupTarget = function setupTarget (target) {
      return _.merge({}, targetProto, target);
    };

    var genRandomColor = function genRandomColor () {
      return '#' + ((1 << 24) * Math.random() | 0).toString(16);
    };

    var genTargets = function genTargets (seriesArr, seriesAlias, pluginConf) {
      var targets = [];
      var aliasColors = {};
      var alias = '';

      _.each(pluginConf.graph, function (graph, match) {
        _.each(seriesArr, function (series) {
          var name = series.name;
          seriesAlias = (seriesAlias) ? seriesAlias : name.split('.')[2];

          if (name.lastIndexOf(match) !== name.length - match.length)
            return;

          if ((this.alias) && ('position' in this.alias))
            alias = seriesAlias + '.' + name.split('.')[this.alias.position];
          else if (graph.alias)
            alias = seriesAlias + '.' + graph.alias;
          else
            alias = seriesAlias + '.' + match;

          targets.push(setupTarget({
            'series': name,
            'alias': alias,
            'column': graph.column,
            'apply': graph.apply,
          }));

          if (graph.color)
            aliasColors[alias] = graph.color;
          else
            aliasColors[alias] = genRandomColor();

        }.bind(this));
      }.bind(pluginConf));

      return {
        'targets': targets,
        'aliasColors': aliasColors,
      };
    };

    var genPanelFactory = function genPanelFactory (series, seriesAlias, pluginPanel) {
      return function (source, series, seriesAlias, targets, span) {
        var panel = {
          'span': span,
          'datasource': source,
          'targets': targets.targets,
          'aliasColors': targets.aliasColors,
        };

        if (('title' in pluginPanel) && (pluginPanel.title.match('@metric')))
          return _.merge({}, panelProto, panel, pluginPanel,
              { 'title': pluginPanel.title.replace('@metric', series[0].name.split('.')[2]) });

        return _.merge({}, panelProto, panel, pluginPanel);
      };
    };

    var panelFactory = function panelFactory (pluginConf) {
      return function (series, seriesAlias, span) {
        var sourceSeries = _.groupBy(series, 'source');
        var sourceTargets = {};

        _.each(sourceSeries, function (series, source) {
          sourceTargets[source] = genTargets(series, seriesAlias, pluginConf);
        });

        var genPanel = genPanelFactory(series, seriesAlias, pluginConf.panel);
        var panels = _.map(sourceSeries, function (series, source) {
          return genPanel(source, series, seriesAlias, sourceTargets[source], span);
        });

        return panels;
     };
    };

    var setupRow = function setupRow (row) {
      return _.merge({}, rowProto, row);
    };

    var getExtendedMetrics = function getExtendedMetrics (series, prefix) {
      var metricsExt = [];
      var sufix = '';

      _.each(series, function (s) {
        if (s.name.indexOf(prefix) === 0) {
          sufix = s.name.slice(prefix.length);
          sufix = sufix.slice(0, sufix.indexOf('.'));
          if (metricsExt.indexOf(sufix) === -1)
            metricsExt.push(sufix);
        }
      });

      return metricsExt;
    };

    var setupDash = function setupDash (plugin) {
      return {
        func: _.map(plugin, function (metricConf) {
          return panelFactory(metricConf);
        }),
        config: plugin.config,
      };
    };

    var genDashs = function genDashs (metrics, plugins) {
      var dashs = {};

      if (!metrics) {
        _.each(plugins, function (plugin, name) {
          dashs[name] = setupDash(plugin);
        });
        return dashs;
      }

      _.each(metrics, function (metric) {
        if (metric in plugins) {
          dashs[metric] = setupDash(plugins[metric]);
        } else if (metric in plugins.groups) {
          var members = plugins.groups[metric];
          _.each(members, function (member) {
            if (!(member in dashs) && (member in plugins))
              dashs[member] = setupDash(plugins[member]);
          });
        }
      });
      return dashs;
    };

    var filterSeriesFactory = function filterSeriesFactory (prefix, metric, plugin, dash) {
      return function (dsSeries) {
        return ((dsSeries.name.indexOf(prefix + metric) === 0) &&
            (!('regexp' in dash[plugin].config) ||
             dash[plugin].config.regexp.test(dsSeries.name.split('.')[2])));
      };
    };

    var setupDashboard = function setupDashboard (hostSeries, plugins, displayMetric, dashboard) {
      if (!hostSeries.length)
        return;

      var displayMetrics = (displayMetric) ? displayMetric.split(',') : null;
      var showDashs = genDashs(displayMetrics, plugins);

      _.each(showDashs, function (plugin, name) {
        var metric = name;
        var seriesAlias = ('alias' in plugin.config) ? plugin.config.alias : null;
        var seriesPrefix = plugin.config.prefix + displayHost + '.';
        var matchedSeries = _.filter(hostSeries, filterSeriesFactory(seriesPrefix, metric, name, this));
        var matchedSeriesArr = [];

        if (plugin.config.multi) {
          var metricsExt = getExtendedMetrics(matchedSeries, seriesPrefix);
          matchedSeriesArr = _.map(metricsExt, function (metric) {
            return _.filter(hostSeries, filterSeriesFactory(seriesPrefix, metric, name, this));
          }.bind(this));
        } else {
          matchedSeriesArr.push(matchedSeries);
        }

        dashboard.rows = _.union(dashboard.rows, _.reduceRight(plugin.func, function (rows, func) {
          _.each(matchedSeriesArr, function (series) {
            var panels = func(series, seriesAlias, 12);
            rows = _.union(rows, _.map(panels, function (panel) {
              return setupRow({
                'title': metric.toUpperCase(),
                'panels': [ panel ],
              });
            }));
          });
          return rows;
        }, []));
      }.bind(showDashs));

      return dashboard;
    };

    // Get series from InfluxDB
    var getSeries = function getSeries (datasources, query, callback) {
      var dsQueries = _.map(datasources, function (ds) {
        return {
          'datasource': ds.name,
          'url': ds.url + '/series?u=' + ds.username + '&p=' + ds.password + '&q=' + query,
        };
      });

      var hostSeries = [];
      var gettingHostSeries = [];
      _.each(dsQueries, function (query) {
        gettingHostSeries.push($.getJSON(query.url, function (json) {
          hostSeries = _.union(hostSeries, _.map(json[0].points, function (point) {
            return {
              'source': query.datasource,
              'name': point[1],
            };
          }));
        }));
      });

      $.when.apply($, gettingHostSeries).done(function () {
        callback(hostSeries);
      });
    };

    var setupDefaultDashboard = function setupDashboard (allSeries, dashboard) {
      var hostsAll = _.uniq(_.map(_.pluck(allSeries, 'name'), function (series) {
        return series.split('.')[1];
      }));

      var hostsLinks = _.reduce(hostsAll, function (string, host) {
        return string + '\n\t\t\t
\n\t\t\t\t' +
          host + '\n\t\t\t
';
      }, '');

      var rowProto = {
        'title': 'Default',
        'height': '90px',
        'panels': [
          {
            'title': '',
            'span': 12,
            'type': 'text',
            'mode': 'html',
            'content': 'default',
          },
        ],
      };

      var rowDocs = _.merge({}, rowProto, {
        'title': 'Docs',
        'panels': [
          {
            'content': '
\n\t
\n\t\t
Grafana InfluxDB Scripted Dashboard Documentation
\n\t\t
\n\t\t\t
\n\t\t\t\tGitHub\n\t\t\t
\n\t
\n
',
          },
        ],
      });

      var rowHosts = _.merge({}, rowProto, {
        'title': 'Hosts',
        'panels': [
          {
            'content': '
\n\t
\n\t\t
Available Hosts
\n\t\t
' + hostsLinks + '\n\t\t
',
          },
        ],
      });

      dashboard.title = 'Grafana - Scripted Dashboard';
      console.log(rowDocs, rowHosts);
      dashboard.rows = [ rowDocs, rowHosts ];
      return dashboard;
    };

    if (!displayHost) {
      getSeries(datasources, 'list series /load\.load\.midterm/', function (series) {
        callback(setupDefaultDashboard(series, dashboard));
      });
      return;
    }
    getSeries(datasources, influxdbQuery, function (series) {
      callback(setupDashboard(series, plugins, displayMetric, dashboard));
    });

  });
};
<commit_msg>Better series fetching from backend.<commit_after>/* global _ */

/*
 * Complex scripted dashboard
 * This script generates a dashboard object that Grafana can load. It also takes a number of user
 * supplied URL parameters (int ARGS variable)
 */

// Accessable variables in this scope
var window, document, ARGS, $, jQuery, moment, kbn;

return function (callback) {
  'use strict';

  require(['getdash/getdash.conf'], function(getdashConf) {

    // Setup some variables
    var plugins = getdashConf.plugins;
    var datasourcesAll = getdashConf.datasources;
    var datasources = _.filter(datasourcesAll, function (ds) {
      return (!(ds.grafanaDB || ds.type !== 'influxdb'));
    });
    var dashboard;
    var getdashConfig = '/app/getdash/getdash.conf.js';

    // GET variables
    var displayHost = '';
    var displayMetric = '';
    var displayTime;

    if(!_.isUndefined(ARGS.host))
      displayHost = ARGS.host;

    if(!_.isUndefined(ARGS.metric))
      displayMetric = ARGS.metric;

    if(!_.isUndefined(ARGS.time))
      displayTime = ARGS.time;

    // Setup influxDB queries
// TODO: Implement query optimization with account for service groups
//    var influxdbQuery = (displayMetric) ? '&q=list series /\.' + displayHost + '\.(' +
//                    displayMetric.replace(',', '|') + ')/'
//                    : '&q=list series /\.' + displayHost + '\./';
    var influxdbQuery = 'list series /\\.' + displayHost + '\\./';

    // Intialize a skeleton with nothing but a rows array and service object
    dashboard = {
      'rows': [],
      'services': {}
    };

    // Set default time
    // time can be overriden in the url using from/to parameteres, but this is
    // handled automatically in grafana core during dashboard initialization

    // Dashboard time and interval setup function
    var getDashTimeInterval = function getDashTimeInterval (time) {
      var defaultTimeInterval = {
        'time': {
          'from': "now-6h",
          'to': "now"
        },
        'interval': '1m',
      };

      if (!time)
        return defaultTimeInterval;

      var timeM = 0;
      var interval = '';
      var regexpTime = /(\d+)(m|h|d)/;
      var rTime = regexpTime.exec(time);

      if (!rTime)
        return defaultTimeInterval;

      if (rTime[2] === 'm')
        timeM = parseInt(rTime[1]);
      else if (rTime[2] === 'h')
        timeM = parseInt(rTime[1]) * 60;
      else if (rTime[2] === 'd')
        timeM = parseInt(rTime[1]) * 60 * 24;

      if (timeM > 360)
        interval = (Math.ceil((Math.floor(timeM / 360) + 1) / 5) * 5).toString() + 'm';
      else if (timeM === 360)
        interval = '1m';
      else
        interval = '30s';

      return {
        'time': {
          'from': "now-" + time,
          'to': "now"
        },
        'interval': interval,
      };
    };

    var dashTimeInterval = getDashTimeInterval(displayTime);
    var interval = dashTimeInterval.interval;
    dashboard.time = dashTimeInterval.time;

    // Set a title
    dashboard.title = 'Grafana - Scripted Dashboard for ' + displayHost;

    // Object prototypes
    var targetProto = {
      'series': '',
      'alias': '',
      'column': 'value',
      'interval': interval,
      'function': 'mean',
    };

    var panelProto = {
      'title': 'Default Title',
      'type': 'graphite',
      'span': 12,
      'y_formats': [ 'none' ],
      'grid': { 'max': null, 'min': 0, 'leftMin': 0 },
      'lines': true,
      'fill': 1,
      'linewidth': 1,
      'nullPointMode': 'null',
      'targets': {},
      'aliasColors': {},
    };

    var rowProto = {
      'title': 'Default Row Title',
      'height': '250px',
      'panels': [],
    };

    // Dashboard setup helper functions
    var setupTarget = function setupTarget (target) {
      return _.merge({}, targetProto, target);
    };

    var genRandomColor = function genRandomColor () {
      return '#' + ((1 << 24) * Math.random() | 0).toString(16);
    };

    var genTargets = function genTargets (seriesArr, seriesAlias, pluginConf) {
      var targets = [];
      var aliasColors = {};
      var alias = '';

      _.each(pluginConf.graph, function (graph, match) {
        _.each(seriesArr, function (series) {
          var name = series.name;
          seriesAlias = (seriesAlias) ? seriesAlias : name.split('.')[2];

          if (name.lastIndexOf(match) !== name.length - match.length)
            return;

          if ((this.alias) && ('position' in this.alias))
            alias = seriesAlias + '.' + name.split('.')[this.alias.position];
          else if (graph.alias)
            alias = seriesAlias + '.' + graph.alias;
          else
            alias = seriesAlias + '.' + match;

          targets.push(setupTarget({
            'series': name,
            'alias': alias,
            'column': graph.column,
            'apply': graph.apply,
          }));

          if (graph.color)
            aliasColors[alias] = graph.color;
          else
            aliasColors[alias] = genRandomColor();

        }.bind(this));
      }.bind(pluginConf));

      return {
        'targets': targets,
        'aliasColors': aliasColors,
      };
    };

    var genPanelFactory = function genPanelFactory (series, seriesAlias, pluginPanel) {
      return function (source, series, seriesAlias, targets, span) {
        var panel = {
          'span': span,
          'datasource': source,
          'targets': targets.targets,
          'aliasColors': targets.aliasColors,
        };

        if (('title' in pluginPanel) && (pluginPanel.title.match('@metric')))
          return _.merge({}, panelProto, panel, pluginPanel,
              { 'title': pluginPanel.title.replace('@metric', series[0].name.split('.')[2]) });

        return _.merge({}, panelProto, panel, pluginPanel);
      };
    };

    var panelFactory = function panelFactory (pluginConf) {
      return function (series, seriesAlias, span) {
        var sourceSeries = _.groupBy(series, 'source');
        var sourceTargets = {};

        _.each(sourceSeries, function (series, source) {
          sourceTargets[source] = genTargets(series, seriesAlias, pluginConf);
        });

        var genPanel = genPanelFactory(series, seriesAlias, pluginConf.panel);
        var panels = _.map(sourceSeries, function (series, source) {
          return genPanel(source, series, seriesAlias, sourceTargets[source], span);
        });

        return panels;
     };
    };

    var setupRow = function setupRow (row) {
      return _.merge({}, rowProto, row);
    };

    var getExtendedMetrics = function getExtendedMetrics (series, prefix) {
      var metricsExt = [];
      var sufix = '';

      _.each(series, function (s) {
        if (s.name.indexOf(prefix) === 0) {
          sufix = s.name.slice(prefix.length);
          sufix = sufix.slice(0, sufix.indexOf('.'));
          if (metricsExt.indexOf(sufix) === -1)
            metricsExt.push(sufix);
        }
      });

      return metricsExt;
    };

    var setupDash = function setupDash (plugin) {
      return {
        func: _.map(plugin, function (metricConf) {
          return panelFactory(metricConf);
        }),
        config: plugin.config,
      };
    };

    var genDashs = function genDashs (metrics, plugins) {
      var dashs = {};

      if (!metrics) {
        _.each(plugins, function (plugin, name) {
          dashs[name] = setupDash(plugin);
        });
        return dashs;
      }

      _.each(metrics, function (metric) {
        if (metric in plugins) {
          dashs[metric] = setupDash(plugins[metric]);
        } else if (metric in plugins.groups) {
          var members = plugins.groups[metric];
          _.each(members, function (member) {
            if (!(member in dashs) && (member in plugins))
              dashs[member] = setupDash(plugins[member]);
          });
        }
      });
      return dashs;
    };

    var filterSeriesFactory = function filterSeriesFactory (prefix, metric, plugin, dash) {
      return function (dsSeries) {
        return ((dsSeries.name.indexOf(prefix + metric) === 0) &&
            (!('regexp' in dash[plugin].config) ||
             dash[plugin].config.regexp.test(dsSeries.name.split('.')[2])));
      };
    };

    var setupDashboard = function setupDashboard (hostSeries, plugins, displayMetric, dashboard) {
      if (!hostSeries.length)
        return;

      var displayMetrics = (displayMetric) ? displayMetric.split(',') : null;
      var showDashs = genDashs(displayMetrics, plugins);

      _.each(showDashs, function (plugin, name) {
        var metric = name;
        var seriesAlias = ('alias' in plugin.config) ? plugin.config.alias : null;
        var seriesPrefix = plugin.config.prefix + displayHost + '.';
        var matchedSeries = _.filter(hostSeries, filterSeriesFactory(seriesPrefix, metric, name, this));
        var matchedSeriesArr = [];

        if (plugin.config.multi) {
          var metricsExt = getExtendedMetrics(matchedSeries, seriesPrefix);
          matchedSeriesArr = _.map(metricsExt, function (metric) {
            return _.filter(hostSeries, filterSeriesFactory(seriesPrefix, metric, name, this));
          }.bind(this));
        } else {
          matchedSeriesArr.push(matchedSeries);
        }

        dashboard.rows = _.union(dashboard.rows, _.reduceRight(plugin.func, function (rows, func) {
          _.each(matchedSeriesArr, function (series) {
            var panels = func(series, seriesAlias, 12);
            rows = _.union(rows, _.map(panels, function (panel) {
              return setupRow({
                'title': metric.toUpperCase(),
                'panels': [ panel ],
              });
            }));
          });
          return rows;
        }, []));
      }.bind(showDashs));

      return dashboard;
    };

    // Get series from InfluxDB
    var getSeries = function getSeries (datasources, query, callback) {
      var dsQueries = _.map(datasources, function (ds) {
        return {
          'datasource': ds.name,
          'url': ds.url + '/series?u=' + ds.username + '&p=' + ds.password + '&q=' + query,
        };
      });

      var gettingDBData = _.map(dsQueries, function (query) {
        return $.getJSON(query.url);
      });

      Promise.all(gettingDBData).then(function (json) {
        var datasources = _.pluck(dsQueries, 'datasource');
        var points = _(json).flatten().pluck('points').value();
        var series = _(datasources).zip(points).map(function (dsPoints) {
          var ds = dsPoints[0];
          var points = dsPoints[1];
          return _.map(points, function (point) {
            return {
              'source': ds,
              'name': point[1],
            };
          });
        }).flatten().value();

        callback(series);
      });
    };

    var setupDefaultDashboard = function setupDashboard (allSeries, dashboard) {
      var hostsAll = _.uniq(_.map(_.pluck(allSeries, 'name'), function (series) {
        return series.split('.')[1];
      }));

      var hostsLinks = _.reduce(hostsAll, function (string, host) {
        return string + '\n\t\t\t
\n\t\t\t\t' +
          host + '\n\t\t\t
';
      }, '');

      var rowProto = {
        'title': 'Default',
        'height': '90px',
        'panels': [
          {
            'title': '',
            'span': 12,
            'type': 'text',
            'mode': 'html',
            'content': 'default',
          },
        ],
      };

      var rowDocs = _.merge({}, rowProto, {
        'title': 'Docs',
        'panels': [
          {
            'content': '
\n\t
\n\t\t
Grafana InfluxDB Scripted Dashboard Documentation
\n\t\t
\n\t\t\t
\n\t\t\t\tGitHub\n\t\t\t
\n\t
\n
',
          },
        ],
      });

      var rowHosts = _.merge({}, rowProto, {
        'title': 'Hosts',
        'panels': [
          {
            'content': '
\n\t
\n\t\t
Available Hosts
\n\t\t
' + hostsLinks + '\n\t\t
',
          },
        ],
      });

      dashboard.title = 'Grafana - Scripted Dashboard';
      dashboard.rows = [ rowDocs, rowHosts ];
      return dashboard;
    };

    if (!displayHost) {
      getSeries(datasources, 'list series /load\\.load\\.midterm/', function (series) {
        callback(setupDefaultDashboard(series, dashboard));
      });
      return;
    }
    getSeries(datasources, influxdbQuery, function (series) {
      callback(setupDashboard(series, plugins, displayMetric, dashboard));
    });

  });
};
<|endoftext|>


<commit_before>/* @flow */

import NoopReporter from '../src/reporters/base-reporter.js';
import makeTemp from './_temp';
import * as fs from '../src/util/fs.js';
const pkg = require('../package.json');

const path = require('path');
const exec = require('child_process').exec;

const fixturesLoc = path.join(__dirname, './fixtures/index');
const yarnBin = path.join(__dirname, '../bin/yarn.js');

jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;

async function execCommand(cmd: string, args: Array<string>, name: string, makeTempDir: ?boolean):
Promise<Array<?string>> {
  const srcDir = path.join(fixturesLoc, name);
  let workingDir = srcDir;
  if (makeTempDir) {
    workingDir = await makeTemp(name);
    await fs.copy(srcDir, workingDir, new NoopReporter());
  }

  return new Promise((resolve, reject) => {
    exec(`node "${yarnBin}" ${cmd} ${args.join(' ')}`, {cwd:workingDir, env:process.env}, (err, stdout) => {
      if (err) {
        reject(err);
      } else {
        const stdoutLines = stdout.toString()
          .split('\n')
          .map((line: ?string) => line && line.trim())
          .filter((line: ?string) => line);

        resolve(stdoutLines);
      }
    });
  });
}

function expectAddSuccessfullOutput(stdout, pkg) {
  const lastLines = stdout.slice(stdout.length - 4);
  expect(lastLines[0]).toEqual('success Saved lockfile.');
  expect(lastLines[1]).toEqual('success Saved 1 new dependency.');
  expect(lastLines[2]).toContain(pkg);
  expect(lastLines[3]).toContain('Done');
}

function expectAddSuccessfullOutputWithNoLockFile(stdout, pkg) {
  const lastLines = stdout.slice(stdout.length - 4);
  expect(lastLines[1]).toEqual('success Saved 1 new dependency.');
  expect(lastLines[2]).toContain(pkg);
  expect(lastLines[3]).toContain('Done');
}

function expectRunOutput(stdout) {
  const lastLines = stdout.slice(stdout.length - 2);
  expect(lastLines[0]).toMatch(/A message from custom script/);
  expect(lastLines[1]).toMatch(/^Done/);
}

function expectHelpOutput(stdout) {
  expect(stdout[0]).toEqual('Usage: yarn [command] [flags]');
  const lastLines = stdout.slice(stdout.length - 2);
  expect(lastLines[0]).toEqual('Run `yarn help COMMAND` for more information on specific commands.');
  expect(lastLines[1]).toEqual('Visit https://yarnpkg.com/en/docs/cli/ to learn more about Yarn.');
}

function expectHelpOutputAsSubcommand(stdout) {
  expect(stdout[0]).toEqual('Usage: yarn add [packages ...] [flags]');
  expect(stdout[stdout.length - 1])
    .toEqual('Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.');
}

function expectAnErrorMessage(command: Promise<Array<?string>>, error: string) : Promise<void> {
  return command.catch((reason) =>
    expect(reason.message).toContain(error),
  );
}

function expectInstallOutput(stdout) {
  expect(stdout[0]).toEqual(`yarn install v${pkg.version}`);
}

test.concurrent('should add package', async () => {
  const stdout = await execCommand('add', ['left-pad'], 'run-add', true);
  expectAddSuccessfullOutput(stdout, 'left-pad');
});

test.concurrent('should add package with no-lockfile option', async () => {
  const stdout = await execCommand('add', ['repeating', '--no-lockfile'], 'run-add-option', true);
  expectAddSuccessfullOutputWithNoLockFile(stdout, 'repeating');
});

test.concurrent('should add package with no-lockfile option in front', async () => {
  const stdout = await execCommand('add', ['--no-lockfile', 'split-lines'], 'run-add-option-in-front', true);
  expectAddSuccessfullOutputWithNoLockFile(stdout, 'split-lines');
});

test.concurrent('should add lockfile package', async () => {
  const stdout = await execCommand('add', ['lockfile'], 'run-add-lockfile', true);
  expectAddSuccessfullOutput(stdout, 'lockfile');
});

test.concurrent('should add progress package globally', async () => {
  const stdout = await execCommand('global',
    ['add', 'progress', '--global-folder', './global'],
    'run-add-progress-globally',
    true);

  const lastLine = stdout[stdout.length - 1];
  expect(lastLine).toMatch(/^Done/);
});

test.concurrent('should run custom script', async () => {
  const stdout = await execCommand('run', ['custom-script'], 'run-custom-script');
  expectRunOutput(stdout);
});

test.concurrent('should run custom script without run command', async () => {
  const stdout = await execCommand('custom-script', [], 'run-custom-script');
  expectRunOutput(stdout);
});

test.concurrent('should run help command', async () => {
  const stdout = await execCommand('help', [], 'run-help');
  expectHelpOutput(stdout);
});

test.concurrent('should run help command with --help', async () => {
  const stdout = await execCommand('--help', [], 'run-help');
  expectHelpOutput(stdout);
});

test.concurrent('should run help command with -h', async () => {
  const stdout = await execCommand('-h', [], 'run-help');
  expectHelpOutput(stdout);
});

test.concurrent('should run add command with help option', async () => {
  const stdout = await execCommand('add', ['--help'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run add command with h option', async () => {
  const stdout = await execCommand('add', ['-h'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run help command with add option', async () => {
  const stdout = await execCommand('help', ['add'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run --help command with add option', async () => {
  const stdout = await execCommand('--help', ['add'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run -h command with add option', async () => {
  const stdout = await execCommand('-h', ['add'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run version command', async () => {
  await expectAnErrorMessage(
    execCommand('version', [], 'run-version'),
    'Can\'t answer a question unless a user TTY',
  );
});

test.concurrent('should run --version command', async () => {
  const stdout = await execCommand('--version', [], 'run-version');
  expect(stdout[0]).toEqual(pkg.version);
});

test.concurrent('should install if no args', async () => {
  const stdout = await execCommand('', [], 'run-add', true);
  expectInstallOutput(stdout);
});

test.concurrent('should install if first arg looks like a flag', async () => {
  const stdout = await execCommand('--offline', [], 'run-add', true);
  expectInstallOutput(stdout);
});

test.concurrent('should interpolate aliases', async () => {
  await expectAnErrorMessage(
    execCommand('i', [], 'run-add', true),
    'Did you mean `yarn install`?',
  );
});

test.concurrent('should run help of run command if --help is before --', async () => {
  const stdout = await execCommand('run', ['custom-script', '--help', '--'], 'run-custom-script-with-arguments');
  expect(stdout[0]).toEqual('Usage: yarn [command] [flags]');
  expect(stdout[stdout.length - 1])
    .toEqual('Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.');
});

test.concurrent('should run help of custom-script if --help is after --', async () => {
  const stdout = await execCommand('run', ['custom-script', '--', '--help'], 'run-custom-script-with-arguments');
  expect(stdout[stdout.length - 2]).toEqual('A message from custom script with args --help');
});
<commit_msg>skip test in __tests__/index.js for win32 platform: it does some tricks in bash, it does not work with powershell (#2748)<commit_after>/* @flow */

import NoopReporter from '../src/reporters/base-reporter.js';
import makeTemp from './_temp';
import * as fs from '../src/util/fs.js';
const pkg = require('../package.json');

const path = require('path');
const exec = require('child_process').exec;

const fixturesLoc = path.join(__dirname, './fixtures/index');
const yarnBin = path.join(__dirname, '../bin/yarn.js');

jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;

async function execCommand(cmd: string, args: Array<string>, name: string, makeTempDir: ?boolean):
Promise<Array<?string>> {
  const srcDir = path.join(fixturesLoc, name);
  let workingDir = srcDir;
  if (makeTempDir) {
    workingDir = await makeTemp(name);
    await fs.copy(srcDir, workingDir, new NoopReporter());
  }

  return new Promise((resolve, reject) => {
    exec(`node "${yarnBin}" ${cmd} ${args.join(' ')}`, {cwd:workingDir, env:process.env}, (err, stdout) => {
      if (err) {
        reject(err);
      } else {
        const stdoutLines = stdout.toString()
          .split('\n')
          .map((line: ?string) => line && line.trim())
          .filter((line: ?string) => line);

        resolve(stdoutLines);
      }
    });
  });
}

function expectAddSuccessfullOutput(stdout, pkg) {
  const lastLines = stdout.slice(stdout.length - 4);
  expect(lastLines[0]).toEqual('success Saved lockfile.');
  expect(lastLines[1]).toEqual('success Saved 1 new dependency.');
  expect(lastLines[2]).toContain(pkg);
  expect(lastLines[3]).toContain('Done');
}

function expectAddSuccessfullOutputWithNoLockFile(stdout, pkg) {
  const lastLines = stdout.slice(stdout.length - 4);
  expect(lastLines[1]).toEqual('success Saved 1 new dependency.');
  expect(lastLines[2]).toContain(pkg);
  expect(lastLines[3]).toContain('Done');
}

function expectRunOutput(stdout) {
  const lastLines = stdout.slice(stdout.length - 2);
  expect(lastLines[0]).toMatch(/A message from custom script/);
  expect(lastLines[1]).toMatch(/^Done/);
}

function expectHelpOutput(stdout) {
  expect(stdout[0]).toEqual('Usage: yarn [command] [flags]');
  const lastLines = stdout.slice(stdout.length - 2);
  expect(lastLines[0]).toEqual('Run `yarn help COMMAND` for more information on specific commands.');
  expect(lastLines[1]).toEqual('Visit https://yarnpkg.com/en/docs/cli/ to learn more about Yarn.');
}

function expectHelpOutputAsSubcommand(stdout) {
  expect(stdout[0]).toEqual('Usage: yarn add [packages ...] [flags]');
  expect(stdout[stdout.length - 1])
    .toEqual('Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.');
}

function expectAnErrorMessage(command: Promise<Array<?string>>, error: string) : Promise<void> {
  return command.catch((reason) =>
    expect(reason.message).toContain(error),
  );
}

function expectInstallOutput(stdout) {
  expect(stdout[0]).toEqual(`yarn install v${pkg.version}`);
}

test.concurrent('should add package', async () => {
  const stdout = await execCommand('add', ['left-pad'], 'run-add', true);
  expectAddSuccessfullOutput(stdout, 'left-pad');
});

test.concurrent('should add package with no-lockfile option', async () => {
  const stdout = await execCommand('add', ['repeating', '--no-lockfile'], 'run-add-option', true);
  expectAddSuccessfullOutputWithNoLockFile(stdout, 'repeating');
});

test.concurrent('should add package with no-lockfile option in front', async () => {
  const stdout = await execCommand('add', ['--no-lockfile', 'split-lines'], 'run-add-option-in-front', true);
  expectAddSuccessfullOutputWithNoLockFile(stdout, 'split-lines');
});

test.concurrent('should add lockfile package', async () => {
  const stdout = await execCommand('add', ['lockfile'], 'run-add-lockfile', true);
  expectAddSuccessfullOutput(stdout, 'lockfile');
});

test.concurrent('should add progress package globally', async () => {
  const stdout = await execCommand('global',
    ['add', 'progress', '--global-folder', './global'],
    'run-add-progress-globally',
    true);

  const lastLine = stdout[stdout.length - 1];
  expect(lastLine).toMatch(/^Done/);
});

test.concurrent('should run custom script', async () => {
  const stdout = await execCommand('run', ['custom-script'], 'run-custom-script');
  expectRunOutput(stdout);
});

test.concurrent('should run custom script without run command', async () => {
  const stdout = await execCommand('custom-script', [], 'run-custom-script');
  expectRunOutput(stdout);
});

test.concurrent('should run help command', async () => {
  const stdout = await execCommand('help', [], 'run-help');
  expectHelpOutput(stdout);
});

test.concurrent('should run help command with --help', async () => {
  const stdout = await execCommand('--help', [], 'run-help');
  expectHelpOutput(stdout);
});

test.concurrent('should run help command with -h', async () => {
  const stdout = await execCommand('-h', [], 'run-help');
  expectHelpOutput(stdout);
});

test.concurrent('should run add command with help option', async () => {
  const stdout = await execCommand('add', ['--help'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run add command with h option', async () => {
  const stdout = await execCommand('add', ['-h'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run help command with add option', async () => {
  const stdout = await execCommand('help', ['add'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run --help command with add option', async () => {
  const stdout = await execCommand('--help', ['add'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run -h command with add option', async () => {
  const stdout = await execCommand('-h', ['add'], 'run-help');
  expectHelpOutputAsSubcommand(stdout);
});

test.concurrent('should run version command', async () => {
  await expectAnErrorMessage(
    execCommand('version', [], 'run-version'),
    'Can\'t answer a question unless a user TTY',
  );
});

test.concurrent('should run --version command', async () => {
  const stdout = await execCommand('--version', [], 'run-version');
  expect(stdout[0]).toEqual(pkg.version);
});

test.concurrent('should install if no args', async () => {
  const stdout = await execCommand('', [], 'run-add', true);
  expectInstallOutput(stdout);
});

test.concurrent('should install if first arg looks like a flag', async () => {
  const stdout = await execCommand('--offline', [], 'run-add', true);
  expectInstallOutput(stdout);
});

test.concurrent('should interpolate aliases', async () => {
  await expectAnErrorMessage(
    execCommand('i', [], 'run-add', true),
    'Did you mean `yarn install`?',
  );
});

test.concurrent('should run help of run command if --help is before --', async () => {
  const stdout = await execCommand('run', ['custom-script', '--help', '--'], 'run-custom-script-with-arguments');
  expect(stdout[0]).toEqual('Usage: yarn [command] [flags]');
  expect(stdout[stdout.length - 1])
    .toEqual('Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.');
});

if (process.platform !== 'win32') {
  test.concurrent('should run help of custom-script if --help is after --', async () => {
    const stdout = await execCommand('run', ['custom-script', '--', '--help'], 'run-custom-script-with-arguments');
    expect(stdout[stdout.length - 2]).toEqual('A message from custom script with args --help');
  });
}
<|endoftext|>