<commit_before>

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

    '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);

            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>updated to support kbasesets.expressionset<commit_after>

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

    '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);

            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 if (thing.items) {
                  $self.options.output = thing;
                  thing.sample_expression_ids = [];

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

                  $.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>"use strict";

var _ = require_vendor("underscore");
var template = require_core("server/template");
var context = require_core("server/context");
var packager = require_core("server/packager");
var Component = require_core("server/component");
var socket = require_core("server/socket");
var readfile = require_core("server/readfile");
var quick_hash = require_core("server/hash");

var async = require("async");
var less = require("less");
var stringify = require("json-stable-stringify");

function multi_pack(dir, extension, prepack) {
  var cache = {};
  return function() {
    var req = context("req");
    var res = context("res");

    var loaded = {};
    var modules = JSON.parse(req.query.m);

    function unpack(data, loaded) {
      if (_.isObject(data)) {
        _.each(data, function(v, k) {
          if (dir) {
            loaded[k.replace(dir + "/", '')] = v;
          } else {
            loaded[k] = v;
          }
        });
      } else {
        loaded[k] = v
      }
    }

    async.each(modules, function(module, done) {
      var filename = dir + "/" + module;

      if (cache[module]) {
        unpack(cache[module], loaded);
        done();
        return;
      }

      // Does an unwind and prepack, technically
      if (prepack) {
        prepack([filename], function(data) {
          unpack(data, loaded);
          cache[module] = data;
          done();
        });

      }
    }, function resolution(err) {
      res.set("Content-Type", "application/json");
      res.write(JSON.stringify(loaded));
      res.end();
    });
  };
}

var js = multi_pack("", "js", packager.js);
var css = multi_pack("app/static/styles", "css", packager.less);
var _js_prelude;
var _css_prelude;
var _socket_lib;

function get_socket_hash(after_read_socket_hash) {
  if (!_socket_lib) {
    _socket_lib = socket.get_socket_library();
  }
  after_read_socket_hash(quick_hash(_socket_lib));
}

function get_socket_library(after_read_socket) {
  if (!_socket_lib) {
    _socket_lib = socket.get_socket_library();
  }
  after_read_socket({ sockets: _socket_lib });
}

function get_js_prelude(after_read_prelude) {
  if (!_js_prelude) {
    _js_prelude = {};
    var data = readfile.core("core/client/prelude.json");

    data = JSON.parse(data);
    var filelist = data.vendor.concat(data.files);

    try {
      var app_data = readfile.app("app/client/prelude.json");
      if (app_data) {
        app_data = JSON.parse(app_data);
        filelist = filelist.concat(app_data.vendor.concat(app_data.files));
      }
    } catch (e) {
      console.log("Couldn't load app prelude", e);
    }

    // The files need to be ordered properly
    async.each(filelist,
      function(item, cb) {
        var data = readfile.both(item);
        var ret = data.toString();
        _js_prelude[item] = ret;

        cb();
      },
      after_read_prelude);
  } else {
    after_read_prelude();
  }
}

function get_css_prelude(after_read_prelude) {
  // Shrink wrap the prelude files
  var data = readfile.core("core/client/prelude.json");

  data = JSON.parse(data);

  var app_data;
  try {
    app_data = readfile.app("app/client/prelude.json");
    if (app_data) {
      app_data = JSON.parse(app_data);
    }
  } catch (e) {
    console.log("Couldn't load app prelude", e);
  }

  var styles_to_load = data.styles;
  if (app_data && app_data.styles) {
    styles_to_load = styles_to_load.concat(app_data.styles);
  }

  if (!_css_prelude) {
    _css_prelude = {};
    async.each(
      styles_to_load,
      function(file, cb) {
        var css_data = readfile(file);
        if (css_data) {
          less.render(css_data, function(err, data) {
            if (!err) {
              _css_prelude[file] = data;
            } else {
              console.log("Error lessing", file, ", sending uncompiled version");
              _css_prelude[file] = css_data.toString();
            }
          });
        } else {
          console.log("Error reading", file);
        }

        cb();
      },
      after_read_prelude);
  } else {
    after_read_prelude();
  }

}

function get_js_prelude_hash(cb) {
  get_js_prelude(function() {
    var str = stringify(_js_prelude);
    cb(quick_hash(str));
  });
}

function get_css_prelude_hash(cb) {
  get_css_prelude(function() {
    var str = stringify(_css_prelude);
    cb(quick_hash(str));
  });

}

var write_socket_library = function() {
  // Shrink wrap the prelude files
  var req = context("req");
  var res = context("res");

  res.set("Content-Type", "text/javascript");
  var maxAge = 60 * 1000 * 60 * 24 * 365;
  if (!res.getHeader('Cache-control')) {
    res.setHeader('Cache-control', 'public, max-age=' + (maxAge / 1000));
  }

  get_socket_library(function after_read_prelude() {
    res.write(_socket_lib);
    res.end();
  });
};

var write_js_prelude = function() {
  // Shrink wrap the prelude files
  var req = context("req");
  var res = context("res");

  res.set("Content-Type", "text/javascript");
  var maxAge = 60 * 1000 * 60 * 24 * 365;
  if (!res.getHeader('Cache-control')) {
    res.setHeader('Cache-control', 'public, max-age=' + (maxAge / 1000));
  }

  get_js_prelude(function after_read_prelude(err) {
    _.each(_js_prelude, function(data, file) {
      res.write(_js_prelude[file]);
    });
    res.end();
  });

};

var get_status = function() {
  var res = context("res");
  res.write("OK");
  res.end();
};

var write_css_prelude = function() {
  var res = context("res");

  res.set("Content-Type", "text/css");
  var maxAge = 60 * 1000 * 60 * 24 * 365;
  if (!res.getHeader('Cache-control')) {
    res.setHeader('Cache-control', 'public, max-age=' + (maxAge / 1000));
  }

  get_css_prelude(function after_read_prelude(err) {
    _.each(_css_prelude, function(data, file) {
      if (_css_prelude[file]) {
        res.write(_css_prelude[file]);
      }
    });
    res.end();
  });
};

var component = function() {
  var req = context("req");
  var res = context("res");

  var loaded = {};

  var modules = JSON.parse(req.query.m);
  async.each(
    modules,
    function(module, cb) {
      Component.build_package(module, function(ret) {
       loaded[module] = ret;
       cb();
      });
    }, function(err, results) {
      res.set("Content-Type", "application/json");

      res.end(JSON.stringify(loaded));
    });
};

function validate_versions(versions, socket, cb) {
  cb = cb || function() { };
  _.each(versions.css, function(old_hash, css) {
    var hash = quick_hash(readfile("app/static/styles/" + css + ".css"));
    if (hash !== old_hash) {
      socket.emit("update_version", 'css', css, old_hash, hash);
    }
  });
  _.each(versions.js, function(old_hash, js) {
    var hash = quick_hash(readfile.both(js + ".js"));
    if (hash !== old_hash) {
      socket.emit("update_version", 'js', js, old_hash, hash);
    }
  });

  if (!versions.pkg) {
    return cb();
  }

  var after = _.after(_.keys(versions.pkg).length, cb);
  _.each(versions.pkg, function(old_hash, pkg) {
    Component.build_package(pkg, function(ret) {
      if (!ret) {
        socket.emit("update_version", 'pkg', pkg, old_hash, null);
        return;
      }

      if (old_hash !== ret.signature) {
        socket.emit("update_version", 'pkg', pkg, old_hash, ret.signature);
      }

      after();
    });
  });
}

function add_packaging_endpoint(endpoint, handler) {
  module.exports.routes["/" + endpoint] = "handle_" + endpoint;
  module.exports["handle_" + endpoint] = handler;
}

module.exports = {
  js: js,
  css: css,
  get_socket_hash: get_socket_hash,
  get_js_prelude_hash: get_js_prelude_hash,
  get_css_prelude_hash: get_css_prelude_hash,
  write_js_prelude: write_js_prelude,
  write_css_prelude: write_css_prelude,
  write_socket_library: write_socket_library,
  component: component,
  get_status: get_status,
  validate_versions: validate_versions,
  add_packaging_endpoint: add_packaging_endpoint,

  routes: {
    "/status" : "get_status",
    "/css" : "css",
    "/js" : "js",
    "/component" : "component",
    "/prelude.js" : "write_js_prelude",
    "/prelude.css" : "write_css_prelude",
    "/socket" : "write_socket_library"
  }
};
<commit_msg>when modules are missing, packager should behave properly<commit_after>"use strict";

var _ = require_vendor("underscore");
var template = require_core("server/template");
var context = require_core("server/context");
var packager = require_core("server/packager");
var Component = require_core("server/component");
var socket = require_core("server/socket");
var readfile = require_core("server/readfile");
var quick_hash = require_core("server/hash");

var async = require("async");
var less = require("less");
var stringify = require("json-stable-stringify");

function multi_pack(dir, extension, prepack) {
  var cache = {};
  return function() {
    var req = context("req");
    var res = context("res");

    var loaded = {};
    var modules = JSON.parse(req.query.m);

    function unpack(data, loaded) {
      if (_.isObject(data)) {
        _.each(data, function(v, k) {
          if (dir) {
            loaded[k.replace(dir + "/", '')] = v;
          } else {
            loaded[k] = v;
          }
        });
      } else {
        loaded[module] = data;
      }
    }

    async.each(modules, function(module, done) {
      var filename = dir + "/" + module;

      if (cache[module]) {
        unpack(cache[module], loaded);
        done();
        return;
      }

      // Does an unwind and prepack, technically
      if (prepack) {
        prepack([filename], function(data) {
          unpack(data, loaded);
          cache[module] = data;
          done();
        });

      }
    }, function resolution(err) {
      res.set("Content-Type", "application/json");
      res.write(JSON.stringify(loaded));
      res.end();
    });
  };
}

var js = multi_pack("", "js", packager.js);
var css = multi_pack("app/static/styles", "css", packager.less);
var _js_prelude;
var _css_prelude;
var _socket_lib;

function get_socket_hash(after_read_socket_hash) {
  if (!_socket_lib) {
    _socket_lib = socket.get_socket_library();
  }
  after_read_socket_hash(quick_hash(_socket_lib));
}

function get_socket_library(after_read_socket) {
  if (!_socket_lib) {
    _socket_lib = socket.get_socket_library();
  }
  after_read_socket({ sockets: _socket_lib });
}

function get_js_prelude(after_read_prelude) {
  if (!_js_prelude) {
    _js_prelude = {};
    var data = readfile.core("core/client/prelude.json");

    data = JSON.parse(data);
    var filelist = data.vendor.concat(data.files);

    try {
      var app_data = readfile.app("app/client/prelude.json");
      if (app_data) {
        app_data = JSON.parse(app_data);
        filelist = filelist.concat(app_data.vendor.concat(app_data.files));
      }
    } catch (e) {
      console.log("Couldn't load app prelude", e);
    }

    // The files need to be ordered properly
    async.each(filelist,
      function(item, cb) {
        var data = readfile.both(item);
        var ret = data.toString();
        _js_prelude[item] = ret;

        cb();
      },
      after_read_prelude);
  } else {
    after_read_prelude();
  }
}

function get_css_prelude(after_read_prelude) {
  // Shrink wrap the prelude files
  var data = readfile.core("core/client/prelude.json");

  data = JSON.parse(data);

  var app_data;
  try {
    app_data = readfile.app("app/client/prelude.json");
    if (app_data) {
      app_data = JSON.parse(app_data);
    }
  } catch (e) {
    console.log("Couldn't load app prelude", e);
  }

  var styles_to_load = data.styles;
  if (app_data && app_data.styles) {
    styles_to_load = styles_to_load.concat(app_data.styles);
  }

  if (!_css_prelude) {
    _css_prelude = {};
    async.each(
      styles_to_load,
      function(file, cb) {
        var css_data = readfile(file);
        if (css_data) {
          less.render(css_data, function(err, data) {
            if (!err) {
              _css_prelude[file] = data;
            } else {
              console.log("Error lessing", file, ", sending uncompiled version");
              _css_prelude[file] = css_data.toString();
            }
          });
        } else {
          console.log("Error reading", file);
        }

        cb();
      },
      after_read_prelude);
  } else {
    after_read_prelude();
  }

}

function get_js_prelude_hash(cb) {
  get_js_prelude(function() {
    var str = stringify(_js_prelude);
    cb(quick_hash(str));
  });
}

function get_css_prelude_hash(cb) {
  get_css_prelude(function() {
    var str = stringify(_css_prelude);
    cb(quick_hash(str));
  });

}

var write_socket_library = function() {
  // Shrink wrap the prelude files
  var req = context("req");
  var res = context("res");

  res.set("Content-Type", "text/javascript");
  var maxAge = 60 * 1000 * 60 * 24 * 365;
  if (!res.getHeader('Cache-control')) {
    res.setHeader('Cache-control', 'public, max-age=' + (maxAge / 1000));
  }

  get_socket_library(function after_read_prelude() {
    res.write(_socket_lib);
    res.end();
  });
};

var write_js_prelude = function() {
  // Shrink wrap the prelude files
  var req = context("req");
  var res = context("res");

  res.set("Content-Type", "text/javascript");
  var maxAge = 60 * 1000 * 60 * 24 * 365;
  if (!res.getHeader('Cache-control')) {
    res.setHeader('Cache-control', 'public, max-age=' + (maxAge / 1000));
  }

  get_js_prelude(function after_read_prelude(err) {
    _.each(_js_prelude, function(data, file) {
      res.write(_js_prelude[file]);
    });
    res.end();
  });

};

var get_status = function() {
  var res = context("res");
  res.write("OK");
  res.end();
};

var write_css_prelude = function() {
  var res = context("res");

  res.set("Content-Type", "text/css");
  var maxAge = 60 * 1000 * 60 * 24 * 365;
  if (!res.getHeader('Cache-control')) {
    res.setHeader('Cache-control', 'public, max-age=' + (maxAge / 1000));
  }

  get_css_prelude(function after_read_prelude(err) {
    _.each(_css_prelude, function(data, file) {
      if (_css_prelude[file]) {
        res.write(_css_prelude[file]);
      }
    });
    res.end();
  });
};

var component = function() {
  var req = context("req");
  var res = context("res");

  var loaded = {};

  var modules = JSON.parse(req.query.m);
  async.each(
    modules,
    function(module, cb) {
      Component.build_package(module, function(ret) {
       loaded[module] = ret;
       cb();
      });
    }, function(err, results) {
      res.set("Content-Type", "application/json");

      res.end(JSON.stringify(loaded));
    });
};

function validate_versions(versions, socket, cb) {
  cb = cb || function() { };
  _.each(versions.css, function(old_hash, css) {
    var hash = quick_hash(readfile("app/static/styles/" + css + ".css"));
    if (hash !== old_hash) {
      socket.emit("update_version", 'css', css, old_hash, hash);
    }
  });
  _.each(versions.js, function(old_hash, js) {
    var hash = quick_hash(readfile.both(js + ".js"));
    if (hash !== old_hash) {
      socket.emit("update_version", 'js', js, old_hash, hash);
    }
  });

  if (!versions.pkg) {
    return cb();
  }

  var after = _.after(_.keys(versions.pkg).length, cb);
  _.each(versions.pkg, function(old_hash, pkg) {
    Component.build_package(pkg, function(ret) {
      if (!ret) {
        socket.emit("update_version", 'pkg', pkg, old_hash, null);
        return;
      }

      if (old_hash !== ret.signature) {
        socket.emit("update_version", 'pkg', pkg, old_hash, ret.signature);
      }

      after();
    });
  });
}

function add_packaging_endpoint(endpoint, handler) {
  module.exports.routes["/" + endpoint] = "handle_" + endpoint;
  module.exports["handle_" + endpoint] = handler;
}

module.exports = {
  js: js,
  css: css,
  get_socket_hash: get_socket_hash,
  get_js_prelude_hash: get_js_prelude_hash,
  get_css_prelude_hash: get_css_prelude_hash,
  write_js_prelude: write_js_prelude,
  write_css_prelude: write_css_prelude,
  write_socket_library: write_socket_library,
  component: component,
  get_status: get_status,
  validate_versions: validate_versions,
  add_packaging_endpoint: add_packaging_endpoint,

  routes: {
    "/status" : "get_status",
    "/css" : "css",
    "/js" : "js",
    "/component" : "component",
    "/prelude.js" : "write_js_prelude",
    "/prelude.css" : "write_css_prelude",
    "/socket" : "write_socket_library"
  }
};
<|endoftext|>


<commit_before>
var margin = {top: 20, right: 20, bottom: 70, left: 80},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10, "");

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.csv("aprendo.tsv", type, function(error, data) {
  x.domain(data.map(function(d) { return d.name; }));
  y.domain([0, d3.max(data, function(d) { return d.value; })]);

  svg.append("g")
      .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-1em")
        .attr("dy", "-1em")
        .attr("transform", "rotate(-90)");

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("MXN");

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.name); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.value); })
        .attr("height", function(d) { return height - y(d.value); });

});

function type(d) {
  d.value = +d.value;
  return d;
}
<commit_msg>no usare este plot de d3<commit_after><|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('app.components')
    .factory('alert', alert);

  alert.$inject = ['$mdToast'];
  function alert($mdToast) {
    var service = {
      success: success,
      error: error,
      info: {
        noData: {
          visitor: infoNoDataVisitor,
          owner: infoNoDataOwner
        },
        longTime: infoLongTime,
        generic: info
      }
    };

    return service;

    ///////////////////

    function success(message) {
      toast('success', message);
    }

    function error(message) {
      toast('error', message);
    }

    function infoNoDataVisitor() {
      info('Woha! This kit has still not published any data yet. Leave a \
      comment to its owner to make him/ her know',
      10000,
      {
        button: 'Leave comment',
        buttonAttributes: 'analytics-on="click" analytics-event="click"\
          analytics-category="Offline Kit Comment Link"',
        href: '#disqus_thread'
      });
    }
    function infoNoDataOwner(kitID) {
      info('Woha! This kit has still not published any data yet. Please, check its settings or reach the support team', 10000, {button: 'Kit settings', href: '/kits/edit/' + kitID});
    }

    function infoLongTime() {
      info('😅 It looks like this post has not posted any data since long time ago. Leave a comment to its owner to make him/ her know', 10000, {button: 'Leave comment'});
    }

    function info(message, delay, options) {
      if(options.button) {
        toast('infoButton', message, options, undefined, delay);
      } else {
        toast('info', message, options, undefined, delay);
      }
    }

    function toast(type, message, options, position, delay) {
      position = position === undefined ? 'top': position;
      delay = delay === undefined ? 5000 : delay;

       $mdToast.show({
        controller: 'AlertController',
        controllerAs: 'vm',
        templateUrl: 'app/components/alert/alert' + type + '.html',
        hideDelay: delay,
        position: position,
        locals: {
          message: message,
          button: options && options.button,
          buttonAttributes: options && options.buttonAttributes,
          href: options && options.href
        }
      });
    }
  }
})();
<commit_msg>fix: removed bad EOL scaping<commit_after>(function() {
  'use strict';

  angular.module('app.components')
    .factory('alert', alert);

  alert.$inject = ['$mdToast'];
  function alert($mdToast) {
    var service = {
      success: success,
      error: error,
      info: {
        noData: {
          visitor: infoNoDataVisitor,
          owner: infoNoDataOwner
        },
        longTime: infoLongTime,
        generic: info
      }
    };

    return service;

    ///////////////////

    function success(message) {
      toast('success', message);
    }

    function error(message) {
      toast('error', message);
    }

    function infoNoDataVisitor() {
      info('Woha! This kit has still not published any data yet. Leave a ' +
        'comment to its owner to make him/ her know',
      10000,
      {
        button: 'Leave comment',
        buttonAttributes: 'analytics-on="click" analytics-event="click" ' +
          'analytics-category="Offline Kit Comment Link"',
        href: '#disqus_thread'
      });
    }
    function infoNoDataOwner(kitID) {
      info('Woha! This kit has still not published any data yet. Please, check its settings or reach the support team', 10000, {button: 'Kit settings', href: '/kits/edit/' + kitID});
    }

    function infoLongTime() {
      info('😅 It looks like this post has not posted any data since long time ago. Leave a comment to its owner to make him/ her know', 10000, {button: 'Leave comment'});
    }

    function info(message, delay, options) {
      if(options.button) {
        toast('infoButton', message, options, undefined, delay);
      } else {
        toast('info', message, options, undefined, delay);
      }
    }

    function toast(type, message, options, position, delay) {
      position = position === undefined ? 'top': position;
      delay = delay === undefined ? 5000 : delay;

       $mdToast.show({
        controller: 'AlertController',
        controllerAs: 'vm',
        templateUrl: 'app/components/alert/alert' + type + '.html',
        hideDelay: delay,
        position: position,
        locals: {
          message: message,
          button: options && options.button,
          buttonAttributes: options && options.buttonAttributes,
          href: options && options.href
        }
      });
    }
  }
})();
<|endoftext|>


<commit_before>var hue = require("node-hue-api");
var constants = require('./constants');
var api = new hue.HueApi(constants.ip, constants.username);
var particle = require('./lib/Particle');
var lightState = hue.lightState;
var _ = require('underscore');
var huelib = require('./lib/Hue');
var lightName = require('./lib/LightName');

var main = function() {

	if (process.argv.length < 3) {
		usage();
		process.exit(0);
	}

	var lights = lightName.lightsFromNames(process.argv.slice(2));

	var firstOn = lightState.create().on(true).hsb(100, 30, 0);
	var on = lightState.create().on(true).hsb(100, 30, 50).transition(3000);
	var low = lightState.create().on(true).hsb(250, 100, 0).transition(10000);
	var off = lightState.create().on(false);

	var timerID = 0;
	var stateOn = true;

	setInterval(function() {
		particle.getMotion()
		.then(function(reply) {
			if (reply.result !== 0 && stateOn === false) {
				clearTimeout(timerID);
				_.each(lights, function(light) {
					api.setLightState(light.id, firstOn);
				});
				stateOn = true;
			}
			if (reply.result !== 0 && stateOn === true) {
				_.each(lights, function(light) {
					api.setLightState(light.id, on);
				});
			}
			if (reply.result === 0 && stateOn === true) {
				_.each(lights, function(light) {
					api.setLightState(light.id, low);
				});
				timerID = setTimeout(function() {
					_.each(lights, function(light) {
					api.setLightState(light.id, off);
				});
				}, 10*60*1000);
				stateOn = false;
			}
		})
	}, 1000);
}

var usage = function() {
	console.log("usage: node " + __filename + " LIGHTNAME LIGHTNAME ...");
	console.log("Each LIGHTNAME is the name of a light defined in constants.js:");
	var lightNames = _.pluck(constants.lights, 'name').join(", ");
	console.log('"' + lightNames + '"');
}

main();

<commit_msg>changing light colors<commit_after>var hue = require("node-hue-api");
var constants = require('./constants');
var api = new hue.HueApi(constants.ip, constants.username);
var particle = require('./lib/Particle');
var lightState = hue.lightState;
var _ = require('underscore');
var huelib = require('./lib/Hue');
var lightName = require('./lib/LightName');

var main = function() {

	if (process.argv.length < 3) {
		usage();
		process.exit(0);
	}

	var lights = lightName.lightsFromNamesOrExit(process.argv.slice(2));

	var firstOn = lightState.create().on(true).hsb(100, 30, 0);
	var on = lightState.create().on(true).white(275, 50).transition(3000);
	var low = lightState.create().on(true).hsb(250, 100, 0).transition(10000);
	var off = lightState.create().on(false);

	var timerID = 0;
	var stateOn = true;

	setInterval(function() {
		particle.getMotion()
		.then(function(reply) {
			if (reply.result !== 0 && stateOn === false) {
				clearTimeout(timerID);
				_.each(lights, function(light) {
					api.setLightState(light.id, firstOn);
				});
				stateOn = true;
			}
			if (reply.result !== 0 && stateOn === true) {
				_.each(lights, function(light) {
					api.setLightState(light.id, on);
				});
			}
			if (reply.result === 0 && stateOn === true) {
				_.each(lights, function(light) {
					api.setLightState(light.id, low);
				});
				timerID = setTimeout(function() {
					_.each(lights, function(light) {
					api.setLightState(light.id, off);
				});
				}, 10*60*1000);
				stateOn = false;
			}
		})
	}, 1000);
}

var usage = function() {
	console.log("usage: node " + __filename + " LIGHTNAME LIGHTNAME ...");
	console.log("Each LIGHTNAME is the name of a light defined in constants.js:");
	var lightNames = _.pluck(constants.lights, 'name').join(", ");
	console.log('"' + lightNames + '"');
}

main();

<|endoftext|>


<commit_before>import State from './src/State';
import Observer from './src/Observer';

export {
  State,
  Observer
};
<commit_msg>IMPROVE change re-export to proper es6 syntax<commit_after>export { default as State } from './src/State';
export { default as Observer } from './src/Observer';

<|endoftext|>


<commit_before>import {axisBottom, axisLeft} from "d3-axis";
import {scaleLinear} from "d3-scale";
import {select} from "d3-selection";
import {area} from "d3-shape";
import {map, sortBy} from "lodash-es";
import PropTypes from "prop-types";
import React from "react";
import {fillEntries, removeOutlierByIQR} from "../../utils";
import {createBlob, formatSvg, getPng, getSvgAttr} from "./Download";

const createChart = (element, data, length, meta, yMax, xMin, showYAxis, isCrop = false) => {

    let svg = select(element).append("svg");

    const margin = {
        top: 10,
        left: 15 + (showYAxis ? 30 : 0),
        bottom: 50,
        right: 10
    };

    svg.append("text").text(yMax.toString())
        .remove();

    svg.remove();

    const height = 200 - margin.top - margin.bottom;

    let width = length > 800 ? length / 5 : length;

    if (width < xMin) {
        width = xMin;
    }

    width -= (margin.left + margin.right);

    const x = scaleLinear()
        .range([0, width])
        .domain([0, length]);

    const y = scaleLinear()
        .range([height, 0])
        .domain([0, yMax]);

    const xAxis = axisBottom(x);

    // Construct the SVG canvas.
    svg = select(element).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`);

    if (data) {
        // Extend original data so there is a coordinate data point for each base along x-axis
        const filledData = fillEntries(data);

        const sortedY = sortBy(filledData, ["val"]);

        const trimDataY = removeOutlierByIQR(sortedY);

        const reorderTrimY = sortBy(trimDataY, ["key"]);

        const dataCrop = map(reorderTrimY, (entry) => [entry.key, entry.val]);

        const useData = isCrop ? dataCrop : data;

        const areaDrawer = area()
            .x(d => x(d[0]))
            .y0(d => y(d[1]))
            .y1(height);

        svg.append("path")
            .datum(useData)
            .attr("class", "depth-area")
            .attr("d", areaDrawer);
    }

    // Set-up a y-axis that will appear at the top of the chart.
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", `translate(0,${height})`)
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-0.8em")
        .attr("dy", "0.15em")
        .attr("transform", "rotate(-65)");

    if (showYAxis) {
        svg.append("g")
            .attr("class", "y axis")
            .call(axisLeft(y));
    }

    svg.append("text")
        .attr("class", "coverage-label small")
        .attr("transform", "translate(4,10)")
        .text(`${meta.id} - ${meta.definition}`);

    svg.append("text")
        .attr("class", "download-overlay")
        .attr("transform", `translate(${(width - margin.left - margin.right) / 3}, ${height / 2})`)
        .text("Click to download");
};

export default class CoverageChart extends React.Component {

    static propTypes = {
        id: PropTypes.string,
        definition: PropTypes.string,
        yMax: PropTypes.number,
        data: PropTypes.array,
        length: PropTypes.number,
        title: PropTypes.string,
        showYAxis: PropTypes.bool,
        isCrop: PropTypes.bool
    };

    componentDidMount () {
        window.addEventListener("resize", this.renderChart);
        this.renderChart({}, this.props.isCrop);
    }

    shouldComponentUpdate (nextProps) {
        if (nextProps.isCrop !== this.props.isCrop) {
            this.renderChart({}, nextProps.isCrop);
        }
        return false;
    }

    componentWillUnmount () {
        window.removeEventListener("resize", this.renderChart);
    }

    renderChart = (e, isCrop = false) => {

        while (this.chartNode.firstChild) {
            this.chartNode.removeChild(this.chartNode.firstChild);
        }

        const { id, definition } = this.props;

        createChart(
            this.chartNode,
            this.props.data,
            this.props.length,
            { id, definition },
            this.props.yMax,
            this.chartNode.offsetWidth,
            this.props.showYAxis,
            isCrop
        );
    };

    handleClick = () => {
        const svg = select(this.chartNode).select("svg");

        formatSvg(svg, "hidden");

        const url = createBlob(svg.node());
        const { width, height, filename } = getSvgAttr(svg);

        getPng({ width, height, url, filename });

        formatSvg(svg, "visible");
    }

    render () {

        return (
            <div
                className="coverage-chart"
                ref={(node) => this.chartNode = node}
                onClick={this.handleClick}
            />
        );
    }
}
<commit_msg>Remove outlier calculations from Coverage component<commit_after>import {axisBottom, axisLeft} from "d3-axis";
import {scaleLinear} from "d3-scale";
import {select} from "d3-selection";
import {area} from "d3-shape";
import PropTypes from "prop-types";
import React from "react";
import {createBlob, formatSvg, getPng, getSvgAttr} from "./Download";

const createChart = (element, data, length, meta, yMax, xMin, showYAxis) => {

    let svg = select(element).append("svg");

    const margin = {
        top: 10,
        left: 15 + (showYAxis ? 30 : 0),
        bottom: 50,
        right: 10
    };

    svg.append("text").text(yMax.toString())
        .remove();

    svg.remove();

    const height = 200 - margin.top - margin.bottom;

    let width = length > 800 ? length / 5 : length;

    if (width < xMin) {
        width = xMin;
    }

    width -= (margin.left + margin.right);

    const x = scaleLinear()
        .range([0, width])
        .domain([0, length]);

    const y = scaleLinear()
        .range([height, 0])
        .domain([0, yMax]);

    const xAxis = axisBottom(x);

    // Construct the SVG canvas.
    svg = select(element).append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`);

    if (data) {

        const areaDrawer = area()
            .x(d => x(d[0]))
            .y0(d => y(d[1]))
            .y1(height);

        svg.append("path")
            .datum(data)
            .attr("class", "depth-area")
            .attr("d", areaDrawer);
    }

    // Set-up a y-axis that will appear at the top of the chart.
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", `translate(0,${height})`)
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-0.8em")
        .attr("dy", "0.15em")
        .attr("transform", "rotate(-65)");

    if (showYAxis) {
        svg.append("g")
            .attr("class", "y axis")
            .call(axisLeft(y));
    }

    svg.append("text")
        .attr("class", "coverage-label small")
        .attr("transform", "translate(4,10)")
        .text(`${meta.id} - ${meta.definition}`);

    svg.append("text")
        .attr("class", "download-overlay")
        .attr("transform", `translate(${(width - margin.left - margin.right) / 3}, ${height / 2})`)
        .text("Click to download");
};

export default class CoverageChart extends React.Component {

    static propTypes = {
        id: PropTypes.string,
        definition: PropTypes.string,
        yMax: PropTypes.number,
        data: PropTypes.array,
        length: PropTypes.number,
        title: PropTypes.string,
        showYAxis: PropTypes.bool
    };

    componentDidMount () {
        window.addEventListener("resize", this.renderChart);
        this.renderChart();
    }

    shouldComponentUpdate () {
        return false;
    }

    componentWillUnmount () {
        window.removeEventListener("resize", this.renderChart);
    }

    renderChart = () => {

        while (this.chartNode.firstChild) {
            this.chartNode.removeChild(this.chartNode.firstChild);
        }

        const { id, definition } = this.props;

        createChart(
            this.chartNode,
            this.props.data,
            this.props.length,
            { id, definition },
            this.props.yMax,
            this.chartNode.offsetWidth,
            this.props.showYAxis
        );
    };

    handleClick = () => {
        const svg = select(this.chartNode).select("svg");

        formatSvg(svg, "hidden");

        const url = createBlob(svg.node());
        const { width, height, filename } = getSvgAttr(svg);

        getPng({ width, height, url, filename });

        formatSvg(svg, "visible");
    };

    render () {

        return (
            <div
                className="coverage-chart"
                ref={(node) => this.chartNode = node}
                onClick={this.handleClick}
            />
        );
    }
}
<|endoftext|>


<commit_before>require('dotenv').config();
var googleapis = require('googleapis'),
    OAuth2Client = googleapis.auth.OAuth2,
    client = '185629692675-jsqjmmqp6c11unoa18vf0ck8ibncdm99.apps.googleusercontent.com',
    redirect = 'http://localhost:3000/google/auth',
    oauth2Client = new OAuth2Client(client, process.env.GOOGLE_APIS_SEC, redirect);

// generate a url that asks permissions for Google+ and Google Calendar scopes
var scopes = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/calendar',
  'https://www.googleapis.com/auth/userinfo.email',
  'https://www.googleapis.com/auth/contacts.readonly'
];

var url = oauth2Client.generateAuthUrl({
  access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
  scope: scopes // If you only need one scope you can pass it as string
});

exports.google = googleapis;
exports.client = oauth2Client;
exports.url = url;
<commit_msg>refactor:shorten google env variable<commit_after>require('dotenv').config();
var googleapis = require('googleapis'),
    OAuth2Client = googleapis.auth.OAuth2,
    client = '185629692675-jsqjmmqp6c11unoa18vf0ck8ibncdm99.apps.googleusercontent.com',
    redirect = 'http://localhost:3000/google/auth',
    oauth2Client = new OAuth2Client(client, process.env.GAPIS_SEC, redirect);

// generate a url that asks permissions for Google+ and Google Calendar scopes
var scopes = [
  'https://www.googleapis.com/auth/plus.me',
  'https://www.googleapis.com/auth/calendar',
  'https://www.googleapis.com/auth/userinfo.email',
  'https://www.googleapis.com/auth/contacts.readonly'
];

var url = oauth2Client.generateAuthUrl({
  access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
  scope: scopes // If you only need one scope you can pass it as string
});

exports.google = googleapis;
exports.client = oauth2Client;
exports.url = url;
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.events.genes')
    .config(addVariantGroupConfig)
    .controller('AddVariantGroupController', AddVariantGroupController);

  // @ngInject
  function addVariantGroupConfig($stateProvider) {
    $stateProvider
      .state('events.genes.summary.addVariantGroup', {
        url: '/addVariantGroup',
        templateUrl: 'app/views/events/genes/addVariantGroup/addVariantGroup.tpl.html',
        controller: 'AddVariantGroupController',
        resolve: {
          'VariantGroups': 'VariantGroups'
        },
        deepStateRedirect: [ 'geneId' ],
        data: {
          titleExp: '"Add Variant Group"',
          navMode: 'sub'
        }
      });
  }

  // @ngInject
  function AddVariantGroupController($scope,
                                     $stateParams,
                                     formConfig,
                                     VariantGroups,
                                     Genes,
                                     Datatables,
                                     Security) {
    console.log('AddVariantGroupController called.');

    var vm = $scope.vm = {};

    vm.isEditor = Security.isEditor();
    vm.isAuthenticated = Security.isAuthenticated();

    vm.showForm = true;
    vm.showSuccessMessage = false;
    vm.showInstructions = true;

    vm.formErrors = {};
    vm.formMessages = {};
    vm.errorMessages = formConfig.errorMessages;
    vm.errorPrompts = formConfig.errorPrompts;

    vm.variantGroup = {
      gene_id: $stateParams.geneId,
      name: '',
      description: '',
      variants: [{id: 0, name:''}]
    };

    vm.variantGroupFields = [
      {
        key: 'name',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Name',
          disabled: false,
          value: vm.variantGroup.name
        }
      },
      {
        key: 'description',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 8,
          label: 'Description',
          value: 'vm.variantGroup.description',
          focus: true,
          minLength: 32
        }
      },
      {
        key: 'variants',
        type: 'multiInput',
        templateOptions: {
          label: 'Variants',
          entityName: 'Variant',
          helpText: 'Click the an X button to delete a variant, click the + button to add variant. Note that variants must be known to CIViC to be available for including here. New variants may be added as part of an evidence item using the the Add Evidence form.',
          inputOptions: {
            type: 'typeahead',
            wrapper: null,
            templateOptions: {
              formatter: 'model[options.key].name',
              typeahead: 'item as item.name for item in options.data.typeaheadSearch($viewValue)'
            },
            data: {
              typeaheadSearch: function(val) {
                var request = {
                  mode: 'variants',
                  count: 5,
                  page: 0,
                  'filter[variant]': val
                };
                return Datatables.query(request)
                  .then(function(response) {
                    return _.map(response.result, function(event) {
                      return { name: event.entrez_gene + ' - ' + event.variant, id: event.variant_id };
                    });
                  });
              }
            }
          }
        }
      }
    ];

    vm.add = function(newVariantGroup, options) {
      VariantGroups.add(newVariantGroup)
        .then(function(response) {
          console.log('new variant group created!');
          vm.formMessages.submitSuccess = true;
          vm.showInstructions = false;
          vm.showForm = false;
          vm.showSuccessMessage = true;

          // update parent Gene object to refresh variant menu
          Genes.queryVariantGroups(Genes.data.item.id);
        })
        .catch(function(error) {
          console.error('revision submit error!');
          vm.formErrors[error.status] = true;
        })
        .finally(function(){
          console.log('revision submit done!');
        });
    }

  }

})();
<commit_msg>added help text to Add Variant Group form<commit_after>(function() {
  'use strict';
  angular.module('civic.events.genes')
    .config(addVariantGroupConfig)
    .controller('AddVariantGroupController', AddVariantGroupController);

  // @ngInject
  function addVariantGroupConfig($stateProvider) {
    $stateProvider
      .state('events.genes.summary.addVariantGroup', {
        url: '/addVariantGroup',
        templateUrl: 'app/views/events/genes/addVariantGroup/addVariantGroup.tpl.html',
        controller: 'AddVariantGroupController',
        resolve: {
          'VariantGroups': 'VariantGroups'
        },
        deepStateRedirect: [ 'geneId' ],
        data: {
          titleExp: '"Add Variant Group"',
          navMode: 'sub'
        }
      });
  }

  // @ngInject
  function AddVariantGroupController($scope,
                                     $stateParams,
                                     formConfig,
                                     VariantGroups,
                                     Genes,
                                     Datatables,
                                     Security) {
    console.log('AddVariantGroupController called.');

    var vm = $scope.vm = {};

    vm.isEditor = Security.isEditor();
    vm.isAuthenticated = Security.isAuthenticated();

    vm.showForm = true;
    vm.showSuccessMessage = false;
    vm.showInstructions = true;

    vm.formErrors = {};
    vm.formMessages = {};
    vm.errorMessages = formConfig.errorMessages;
    vm.errorPrompts = formConfig.errorPrompts;

    vm.variantGroup = {
      gene_id: $stateParams.geneId,
      name: '',
      description: '',
      variants: [{id: 0, name:''}]
    };

    vm.variantGroupFields = [
      {
        key: 'name',
        type: 'horizontalInputHelp',
        templateOptions: {
          label: 'Name',
          disabled: false,
          value: vm.variantGroup.name,
          helpText: 'A brief and meaninful name for the new variant group.'
        }
      },
      {
        key: 'description',
        type: 'horizontalTextareaHelp',
        templateOptions: {
          rows: 8,
          label: 'Description',
          value: 'vm.variantGroup.description',
          focus: true,
          minLength: 32,
          helpText: 'A brief description of this new variant group.'
        }
      },
      {
        key: 'variants',
        type: 'multiInput',
        templateOptions: {
          label: 'Variants',
          entityName: 'Variant',
          helpText: 'Click the an X button to delete a variant, click the + button to add variant. Note that variants must be known to CIViC to be available for including here. New variants may be added as part of an evidence item using the the Add Evidence form.',
          inputOptions: {
            type: 'typeahead',
            wrapper: null,
            templateOptions: {
              formatter: 'model[options.key].name',
              typeahead: 'item as item.name for item in options.data.typeaheadSearch($viewValue)'
            },
            data: {
              typeaheadSearch: function(val) {
                var request = {
                  mode: 'variants',
                  count: 5,
                  page: 0,
                  'filter[variant]': val
                };
                return Datatables.query(request)
                  .then(function(response) {
                    return _.map(response.result, function(event) {
                      return { name: event.entrez_gene + ' - ' + event.variant, id: event.variant_id };
                    });
                  });
              }
            }
          }
        }
      }
    ];

    vm.add = function(newVariantGroup, options) {
      VariantGroups.add(newVariantGroup)
        .then(function(response) {
          console.log('new variant group created!');
          vm.formMessages.submitSuccess = true;
          vm.showInstructions = false;
          vm.showForm = false;
          vm.showSuccessMessage = true;

          // update parent Gene object to refresh variant menu
          Genes.queryVariantGroups(Genes.data.item.id);
        })
        .catch(function(error) {
          console.error('revision submit error!');
          vm.formErrors[error.status] = true;
        })
        .finally(function(){
          console.log('revision submit done!');
        });
    }

  }

})();
<|endoftext|>


<commit_before>var nodeIds, shadowState, nodesArray, nodes, edgesArray, edges, network;

var activatedColor = {
                        background: '#66ff66',
                        border: '#00b300',
                        highlight: {
                                background: '#b3ffb3',
                                border: '#00ff00'
                            }
                        };
var sensorColor = {
                        background: '#ff9900',
                        border: '#b36b00',
                        highlight: {
                            background: '#ffc266',
                            border: '#b36b00'
                        }
                    }

    function startNetwork() {
        // this list is kept to remove a random node.. we do not add node 1 here because it's used for changes
        shadowState = false;
        currentNodeId = -1;

        // create an array with nodes and sensors
        nodesBaseArray = [
            {id: '1', label: 'Elsa', group: 'nodes'},
            {id: '2', label: 'Belle', group: 'sensors'},
            {id: '3', label: 'Aurora', group: 'sensors'}
        ];
        nodes = new vis.DataSet(nodesBaseArray);

        // create an array with edges
        edgesArray = [
            {id: '1', from: '1', to: '2' },
            {id: '2', from: '2', to: '3' }
        ];
        edges = new vis.DataSet(edgesArray);

        // create a network
        var container = document.getElementById('mynetwork');
        var data = {
            nodes: nodes,
            edges: edges
        };

        var options = {
            physics: {
                enabled: false
            },
            edges: {
                dashes: true, smooth: {
                    enabled: false
                }
            },
            groups: {
                nodes: {
                    shape: 'circle'
                },
                sensors: {
                    shape: 'box',
                    color: sensorColor
                }
            }
        };

        network = new vis.Network(container, data, options);
        //network.addEventListener('selectNode', connectNode);
        network.addEventListener('doubleClick', dblclick);
        network.addEventListener('deselectNode', deselectNode);
    }

    function dblclick(data){
        console.log('dblclick');
        //addNode(data.pointer.canvas.x, data.pointer.canvas.y);
    }

    //Select node or add node to canvas if not already in network
    function nodeSelect(data){
        console.log(data.id + 'selected');
        var nodesWithId = nodes.get({ filter: function (item) { return item.id == data.id;}});
        if(nodesWithId.length!=0){
            network.selectNodes(data.id);
            return;
        }

        //Create Node
        //TODO add node on next click instead of at fixed locale
        addNode(data.id, data.group, data.label, 200, -200);
    }

    function activateCurrentNode(){
        var selectedNodeIds = network.getSelectedNodes();
        if(selectedNodeIds==0){return;}
        setNodeColor(selectedNodeIds[0], activatedColor);
        $.post('/', {command: 'Activate Node', node: selectedNodeIds[0]});
    }

    function deactivateNode(nodeId){
        nodes.update({
            id: nodeId,
            color: null
        });
    }

    function setNodeColor(nodeId, color){
        nodes.update({
            id: nodeId,
            color: color
        });
    }

    //Add a node at this location
    function addNode(id, group, label, x, y) {
        console.log('Add Node');
        nodes.add({id:id, group: group,  label: label, x: x, y: y});
    }

    //Fires when a node is deselected
    function deselectNode(data){
        if(data.nodes.length == 0){console.log('No selection'); return;}
        //if a new node was selected at same time connect the nodes
        connectNodes(data.previousSelection.nodes[0], data.nodes[0]);
    }

    //Connects two nodes using IDs
    function connectNodes(from, to){
        //Get all edges that go to and from these two nodes
        console.log('Attempt to connect : ' + from + " : " + to);
        var edgesExist = edges.get({ filter: function (item) { return ((item.from == from && item.to == to) || (item.from == to && item.to  == from)); }});
        console.log('Already Existing edges : ' + edgesExist);
        //If edge already exists return
        if(edgesExist != 0){return;}
        //Add edge to list
        edges.add({id: 'e'+edges.length+1, from: from, to: to});
    }

    function changeOptions() {
        shadowState = !shadowState;
        network.setOptions({nodes:{shadow:shadowState},edges:{shadow:shadowState}});
    }

    function resetAllNodes() {
        nodes.clear();
        edges.clear();
        nodes.add(nodesArray);
        edges.add(edgesArray);
    }

    function resetAllNodesStabilize() {
        resetAllNodes();
        network.stabilize();
    }

    function setTheData() {
        nodes = new vis.DataSet(nodesArray);
        edges = new vis.DataSet(edgesArray);
        network.setData({nodes:nodes, edges:edges})
    }

    function resetAll() {
        if (network !== null) {
            network.destroy();
            network = null;
        }
        startNetwork();
    }

    startNetwork();<commit_msg>Added comments for color and nodeId<commit_after>var nodeIds, shadowState, nodesArray, nodes, edgesArray, edges, network;

var activatedColor = {
                        background: '#66ff66',
                        border: '#00b300',
                        highlight: {
                                background: '#b3ffb3',
                                border: '#00ff00'
                            }
                        };
var sensorColor = {
                        background: '#ff9900',
                        border: '#b36b00',
                        highlight: {
                            background: '#ffc266',
                            border: '#b36b00'
                        }
                    }

    function startNetwork() {
        // this list is kept to remove a random node.. we do not add node 1 here because it's used for changes
        shadowState = false;
        currentNodeId = -1;

        // create an array with nodes and sensors
        nodesBaseArray = [
            {id: '1', label: 'Elsa', group: 'nodes'},
            {id: '2', label: 'Belle', group: 'sensors'},
            {id: '3', label: 'Aurora', group: 'sensors'}
        ];
        nodes = new vis.DataSet(nodesBaseArray);

        // create an array with edges
        edgesArray = [
            {id: '1', from: '1', to: '2' },
            {id: '2', from: '2', to: '3' }
        ];
        edges = new vis.DataSet(edgesArray);

        // create a network
        var container = document.getElementById('mynetwork');
        var data = {
            nodes: nodes,
            edges: edges
        };

        var options = {
            physics: {
                enabled: false
            },
            edges: {
                dashes: true, smooth: {
                    enabled: false
                }
            },
            groups: {
                nodes: {
                    shape: 'circle'
                },
                sensors: {
                    shape: 'box',
                    color: sensorColor
                }
            }
        };

        network = new vis.Network(container, data, options);
        //network.addEventListener('selectNode', connectNode);
        network.addEventListener('doubleClick', dblclick);
        network.addEventListener('deselectNode', deselectNode);
    }

    function dblclick(data){
        console.log('dblclick');
        //addNode(data.pointer.canvas.x, data.pointer.canvas.y);
    }

    //Select node or add node to canvas if not already in network
    function nodeSelect(data){
        console.log(data.id + 'selected');
        var nodesWithId = nodes.get({ filter: function (item) { return item.id == data.id;}});
        if(nodesWithId.length!=0){
            network.selectNodes(data.id);
            return;
        }

        //Create Node
        //TODO add node on next click instead of at fixed locale
        addNode(data.id, data.group, data.label, 200, -200);
    }

    function activateCurrentNode(){
        var selectedNodeIds = network.getSelectedNodes();
        if(selectedNodeIds==0){return;}
        setNodeColor(selectedNodeIds[0], activatedColor);
        $.post('/', {command: 'Activate Node', node: selectedNodeIds[0]});
    }

    function deactivateNode(nodeId){
        nodes.update({
            id: nodeId,
            color: null //null color means that the node will use group default
        });
    }

    //Set specific node color
    //nodeId: ID as stored in nodes DataSet
    //Color should contain { background, border, highlight{ background, color } as hex strings
    function setNodeColor(nodeId, color){
        nodes.update({
            id: nodeId,
            color: color
        });
    }

    //Add a node at this location
    function addNode(id, group, label, x, y) {
        console.log('Add Node');
        nodes.add({id:id, group: group,  label: label, x: x, y: y});
    }

    //Fires when a node is deselected
    function deselectNode(data){
        if(data.nodes.length == 0){console.log('No selection'); return;}
        //if a new node was selected at same time connect the nodes
        connectNodes(data.previousSelection.nodes[0], data.nodes[0]);
    }

    //Connects two nodes using IDs
    function connectNodes(from, to){
        //Get all edges that go to and from these two nodes
        console.log('Attempt to connect : ' + from + " : " + to);
        var edgesExist = edges.get({ filter: function (item) { return ((item.from == from && item.to == to) || (item.from == to && item.to  == from)); }});
        console.log('Already Existing edges : ' + edgesExist);
        //If edge already exists return
        if(edgesExist != 0){return;}
        //Add edge to list
        edges.add({id: 'e'+edges.length+1, from: from, to: to});
    }

    function changeOptions() {
        shadowState = !shadowState;
        network.setOptions({nodes:{shadow:shadowState},edges:{shadow:shadowState}});
    }

    function resetAllNodes() {
        nodes.clear();
        edges.clear();
        nodes.add(nodesArray);
        edges.add(edgesArray);
    }

    function resetAllNodesStabilize() {
        resetAllNodes();
        network.stabilize();
    }

    function setTheData() {
        nodes = new vis.DataSet(nodesArray);
        edges = new vis.DataSet(edgesArray);
        network.setData({nodes:nodes, edges:edges})
    }

    function resetAll() {
        if (network !== null) {
            network.destroy();
            network = null;
        }
        startNetwork();
    }

    startNetwork();
<|endoftext|>


<commit_before>/**
 * Entry module for custom-sticky example.
 */
/* global window, document */
/* eslint-disable import/no-unresolved, import/extensions */
import { initializeParallax } from './parallax';
import { createCustomSticky, CSDirection } from './custom-sticky';

window.addEventListener('DOMContentLoaded', () => {
  const mainSelector = '.main';
  const mainElement = document.querySelector(mainSelector);
  const navContainer = document.querySelector('.navigation-container');

  initializeParallax(mainElement);

  const csBehaviors = [
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-ttb',
      target: '.cs-ctr',
      direction: CSDirection.down,
      transform: y => `translateX(-50%) translateY(${y}px)`
    }),
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-ltr',
      target: '.cs-ctr',
      direction: CSDirection.right
    }),
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-rtl',
      target: '.cs-ctr',
      direction: CSDirection.left
    }),
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-end',
      target: () => {
        const cRect = mainElement.getBoundingClientRect();
        const leftEdgeRect = {
          left: cRect.left,
          right: cRect.left,
          top: cRect.top,
          bottom: cRect.bottom,
          width: 0,
          height: cRect.height
        };
        return leftEdgeRect;
      },
      transform: (x) => {
        const value = x <= 16 ? '-50%' : `${-x}px`;
        return `translateX(${value})`;
      },
      direction: CSDirection.left
    })
  ];

  createCustomSticky({
    scrollSelector: mainSelector,
    movingSelector: '.navigation-container',
    target: 'header',
    animationLength: () => navContainer.getBoundingClientRect().top,
    notify: () => {
      document.querySelector('header').classList.toggle('tint');
    },
    direction: CSDirection.up
  }).start(csBehaviors);
}, {
  once: true
});
<commit_msg>update values in demo<commit_after>/**
 * Entry module for custom-sticky example.
 */
/* global window, document */
/* eslint-disable import/no-unresolved, import/extensions */
import { initializeParallax } from './parallax';
import { createCustomSticky, CSDirection } from './custom-sticky';

window.addEventListener('DOMContentLoaded', () => {
  const mainSelector = '.main';
  const mainElement = document.querySelector(mainSelector);
  const navContainer = document.querySelector('.navigation-container');
  const blockAnimationLength =
    (document.querySelector('.cs-ctr').getBoundingClientRect().bottom -
    document.querySelector('.cs-ttb').getBoundingClientRect().bottom) * 1.2;

  initializeParallax(mainElement);

  const csBehaviors = [
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-ttb',
      target: '.cs-ctr',
      animationLength: () => blockAnimationLength,
      direction: CSDirection.down,
      transform: y => `translateX(-50%) translateY(${y}px)`
    }),
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-ltr',
      target: '.cs-ctr',
      animationLength: () => blockAnimationLength,
      direction: CSDirection.right
    }),
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-rtl',
      target: '.cs-ctr',
      animationLength: () => blockAnimationLength,
      direction: CSDirection.left
    }),
    createCustomSticky({
      scrollSelector: mainSelector,
      movingSelector: '.cs-end',
      target: () => {
        const cRect = mainElement.getBoundingClientRect();
        const leftEdgeRect = {
          left: cRect.left,
          right: cRect.left,
          top: cRect.top,
          bottom: cRect.bottom,
          width: 0,
          height: cRect.height
        };
        return leftEdgeRect;
      },
      transform: (x) => {
        const value = x <= 16 ? '-50%' : `${-x}px`;
        return `translateX(${value})`;
      },
      direction: CSDirection.left
    })
  ];

  createCustomSticky({
    scrollSelector: mainSelector,
    movingSelector: '.navigation-container',
    target: 'header',
    animationLength: () => navContainer.getBoundingClientRect().top,
    notify: () => {
      document.querySelector('header').classList.toggle('tint');
    },
    direction: CSDirection.up
  }).start(csBehaviors);
}, {
  once: true
});
<|endoftext|>


<commit_before>'use strict';
const should = require("should");
const sinon = require("sinon");
const sinonAsPromised = require('sinon-as-promised');
const Discord = require("discord.js");

import ping from "../src/commands/ping.js"

/*describe ('message event', function () {
  it('should be called only once', function (done) {
    let spy = sinon.spy();
    let bot = new Discord.Client();
    bot.on('message', spy);
    bot.emit('message');
    spy.called.should.equal.true;
    done();
  });
});

describe ('bot commands', function () {
  it ('should get the command from the message', function (done) {
    let stub = sinon.stub();
    let bot = new Discord.Client();
    let message = {
      content: "!ping"
    };
    bot.on('message', stub);
    bot.emit('message');
    let spy = sinon.spy(ping);
    stub.resolves(message);

    done();
  });
  it('should execute pong command', function (done) {
    let stub = sinon.stub();
    let bot = new Discord.Client();
    let message = {
      content: "!toto"
    };
    bot.on('message', stub);
    bot.emit('message');
    let spy = sinon.spy(ping);
    stub.resolves(message);
    spy.calledOnce.should.equal.true;
    stub().then(function(value) {
        console.log(message === value);
    })
    done();
  });
});*/<commit_msg>erasing old spec file<commit_after><|endoftext|>