<commit_before>/**
 * The Analysis view.
 *
 * @return Analysis view (extends Widget.View)
 */
define([
  'd3',
  'underscore',
  'handlebars',
  'map/views/Widget',
  'map/presenters/AnalysisToolPresenter',
  'text!map/templates/analysisTool.handlebars'
], function(d3, _, Handlebars, Widget, Presenter, tpl) {

  'use strict';

  var AnalysisToolView = Widget.extend({

    className: 'widget widget-analysis-tool',

    template: Handlebars.compile(tpl),

    options: {
      hidden: false,
      boxHidden: true,
      boxClosed: false,
      boxDraggable: false
    },

    events: function(){
      return _.extend({}, AnalysisToolView.__super__.events, {
        'click #analysis': 'onClickAnalysis',
        'click #done': '_onClickDone',
        'click #cancel': '_onClickCancel'
      });
    },

    initialize: function(map) {
      _.bindAll(this, '_onOverlayComplete');
      this.map = map;
      this.presenter = new Presenter(this);
      this._setStyle();
      this.$htmlbody = $('html,body');
      AnalysisToolView.__super__.initialize.apply(this);
    },

    _cacheSelector: function() {
      AnalysisToolView.__super__._cacheSelector.apply(this);
      this.$cancel = this.$el.find('#cancel');
      this.$done = this.$el.find('#done');
    },

    /**
     * Triggered when the user clicks on the analysis button.
     */
    onClickAnalysis: function() {
      this._startDrawingManager();
      this.presenter.startDrawing();
      this.model.set('boxHidden', false);
      this.$done.addClass('disabled');
      this.toggleWidgetBtn(true);
      ga('send', 'event', 'Map', 'Analysis', 'Perform an analysis');
    },

    /**
     * Star drawing manager and add an overlaycomplete
     * listener.
     */
    _startDrawingManager: function() {
      this.drawingManager = new google.maps.drawing.DrawingManager({
        drawingControl: false,
        drawingMode: google.maps.drawing.OverlayType.POLYGON,
        polygonOptions: _.extend({
          editable: true
        }, this.style),
        panControl: false,
        map: this.map
      });
      // cache cartodb infowindows
      this.$infowindows = $('.cartodb-infowindow');
      this.$infowindows.addClass('hidden');

      google.maps.event.addListener(this.drawingManager,
        'overlaycomplete', this._onOverlayComplete);
    },

    /**
     * Triggered when the user finished drawing a polygon.
     *
     * @param  {Object} e event
     */
    _onOverlayComplete: function(e) {
      this.presenter.onOverlayComplete(e);
      this.$done.removeClass('disabled');
      this.$htmlbody.animate({ scrollTop: 200 },200);
    },

    /**
     * Triggered when the user clicks on done
     * to get the analysis of the new polygon.
     */
    _onClickDone: function() {
      this.$infowindows.hide(0).removeClass('hidden');
      this._stopDrawing();
      this.presenter.doneDrawing();
    },

    /**
     * Triggered when the user clicks on cancel
     * to stop drawing a polygon.
     */
    _onClickCancel: function() {
      this.$infowindows.hide(0).removeClass('hidden');
      this._stopDrawing();
      this.presenter.deleteAnalysis();
    },

    /**
     * Stop drawing manager, set drawing box to hidden.
     */
    _stopDrawing: function() {
      if (this.drawingManager) {
        this.drawingManager.setDrawingMode(null);
        this.drawingManager.setMap(null);
      }

      this.model.set({boxHidden: true});
      this.presenter.stopDrawing();
    },

    /**
     * Deletes a overlay from the map.
     *
     * @param  {object} resource overlay/multipolygon
     */
    deleteGeom: function(resource) {
      if (resource.overlay) {
        resource.overlay.setMap(null);
        resource.overlay = null;
      }

      if (resource.multipolygon) {
        this.map.data.remove(resource.multipolygon);
      }
    },

    setEditable: function(overlay, to) {
      overlay.setEditable(to);
    },

    /**
     * Draw Geojson polygon on the map.
     *
     * @param  {String} geojson Geojson polygon as a string
     */
    drawPaths: function(paths) {
      var overlay = new google.maps.Polygon(
        _.extend({}, {paths: paths}, this.style));

      overlay.setMap(this.map);
      this.presenter.setOverlay(overlay);
    },

    /**
     * Draw a multypoligon on the map.
     *
     * @param  {Object} topojson
     */
    drawMultipolygon: function(geojson) {
      var multipolygon = this.map.data.addGeoJson(geojson)[0];
      this.presenter.setMultipolygon(multipolygon, geojson);
    },

    toggleWidgetBtn: function(to) {
      this.$widgetBtn.toggleClass('disabled', to);
    },

    /**
     * Set geojson style.
     */
    _setStyle: function() {
      this.style = {
        strokeWeight: 2,
        fillOpacity: 0.45,
        fillColor: '#FFF',
        strokeColor: '#A2BC28',
        icon: new google.maps.MarkerImage(
          '/assets/icons/marker_exclamation.png',
          new google.maps.Size(36, 36), // size
          new google.maps.Point(0, 0), // offset
          new google.maps.Point(18, 18) // anchor
        )
      };

      this.map.data.setStyle(this.style);
    }

  });

  return AnalysisToolView;

});

<commit_msg>Fix to call one time the reset function<commit_after>/**
 * The Analysis view.
 *
 * @return Analysis view (extends Widget.View)
 */
define([
  'd3',
  'underscore',
  'handlebars',
  'map/views/Widget',
  'map/presenters/AnalysisToolPresenter',
  'text!map/templates/analysisTool.handlebars'
], function(d3, _, Handlebars, Widget, Presenter, tpl) {

  'use strict';

  var AnalysisToolView = Widget.extend({

    className: 'widget widget-analysis-tool',

    template: Handlebars.compile(tpl),

    options: {
      hidden: false,
      boxHidden: true,
      boxClosed: false,
      boxDraggable: false
    },

    events: function(){
      return _.extend({}, AnalysisToolView.__super__.events, {
        'click #analysis': 'onClickAnalysis',
        'click #done': '_onClickDone',
        'click #cancel': '_onClickCancel'
      });
    },

    initialize: function(map) {
      _.bindAll(this, '_onOverlayComplete');
      this.map = map;
      this.presenter = new Presenter(this);
      this._setStyle();
      this.$htmlbody = $('html,body');
      AnalysisToolView.__super__.initialize.apply(this);
    },

    _cacheSelector: function() {
      AnalysisToolView.__super__._cacheSelector.apply(this);
      this.$cancel = this.$el.find('#cancel');
      this.$done = this.$el.find('#done');
    },

    /**
     * Triggered when the user clicks on the analysis button.
     */
    onClickAnalysis: function() {
      this._startDrawingManager();
      this.presenter.startDrawing();
      this.model.set('boxHidden', false);
      this.$done.addClass('disabled');
      this.toggleWidgetBtn(true);
      ga('send', 'event', 'Map', 'Analysis', 'Perform an analysis');
    },

    /**
     * Star drawing manager and add an overlaycomplete
     * listener.
     */
    _startDrawingManager: function() {
      this.drawingManager = new google.maps.drawing.DrawingManager({
        drawingControl: false,
        drawingMode: google.maps.drawing.OverlayType.POLYGON,
        polygonOptions: _.extend({
          editable: true
        }, this.style),
        panControl: false,
        map: this.map
      });
      // cache cartodb infowindows
      this.$infowindows = $('.cartodb-infowindow');
      this.$infowindows.addClass('hidden');

      google.maps.event.addListener(this.drawingManager,
        'overlaycomplete', this._onOverlayComplete);
    },

    /**
     * Triggered when the user finished drawing a polygon.
     *
     * @param  {Object} e event
     */
    _onOverlayComplete: function(e) {
      this.presenter.onOverlayComplete(e);
      this.$done.removeClass('disabled');
      this.$htmlbody.animate({ scrollTop: 200 },200);
    },

    /**
     * Triggered when the user clicks on done
     * to get the analysis of the new polygon.
     */
    _onClickDone: function() {
      this._stopDrawing();
      this.presenter.doneDrawing();
    },

    /**
     * Triggered when the user clicks on cancel
     * to stop drawing a polygon.
     */
    _onClickCancel: function() {
      this._stopDrawing();
      this.presenter.deleteAnalysis();
    },

    /**
     * Stop drawing manager, set drawing box to hidden.
     */
    _stopDrawing: function() {
      this.$infowindows.hide(0).removeClass('hidden');
      if (this.drawingManager) {
        this.drawingManager.setDrawingMode(null);
        this.drawingManager.setMap(null);
      }

      this.model.set({boxHidden: true});
      this.presenter.stopDrawing();
    },

    /**
     * Deletes a overlay from the map.
     *
     * @param  {object} resource overlay/multipolygon
     */
    deleteGeom: function(resource) {
      if (resource.overlay) {
        resource.overlay.setMap(null);
        resource.overlay = null;
      }

      if (resource.multipolygon) {
        this.map.data.remove(resource.multipolygon);
      }
    },

    setEditable: function(overlay, to) {
      overlay.setEditable(to);
    },

    /**
     * Draw Geojson polygon on the map.
     *
     * @param  {String} geojson Geojson polygon as a string
     */
    drawPaths: function(paths) {
      var overlay = new google.maps.Polygon(
        _.extend({}, {paths: paths}, this.style));

      overlay.setMap(this.map);
      this.presenter.setOverlay(overlay);
    },

    /**
     * Draw a multypoligon on the map.
     *
     * @param  {Object} topojson
     */
    drawMultipolygon: function(geojson) {
      var multipolygon = this.map.data.addGeoJson(geojson)[0];
      this.presenter.setMultipolygon(multipolygon, geojson);
    },

    toggleWidgetBtn: function(to) {
      this.$widgetBtn.toggleClass('disabled', to);
    },

    /**
     * Set geojson style.
     */
    _setStyle: function() {
      this.style = {
        strokeWeight: 2,
        fillOpacity: 0.45,
        fillColor: '#FFF',
        strokeColor: '#A2BC28',
        icon: new google.maps.MarkerImage(
          '/assets/icons/marker_exclamation.png',
          new google.maps.Size(36, 36), // size
          new google.maps.Point(0, 0), // offset
          new google.maps.Point(18, 18) // anchor
        )
      };

      this.map.data.setStyle(this.style);
    }

  });

  return AnalysisToolView;

});

<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

jest.mock('../../Documentation');

import { expression, statement } from '../../../tests/utils';

describe('defaultPropsHandler', () => {
  let documentation;
  let displayNameHandler;

  beforeEach(() => {
    documentation = new (require('../../Documentation'))();
    displayNameHandler = require('../displayNameHandler').default;
  });

  it('extracts the displayName', () => {
    let definition = expression('({displayName: "FooBar"})');
    displayNameHandler(documentation, definition);
    expect(documentation.displayName).toBe('FooBar');

    definition = statement(`
      class Foo {
        static displayName = "BarFoo";
      }
    `);
    displayNameHandler(documentation, definition);
    expect(documentation.displayName).toBe('BarFoo');
  });

  it('resolves identifiers', () => {
    let definition = statement(`
      ({displayName: name})
      var name = 'abc';
    `).get('expression');
    displayNameHandler(documentation, definition);
    expect(documentation.displayName).toBe('abc');

    definition = statement(`
      class Foo {
        static displayName = name;
      }
      var name = 'xyz';
    `);
    displayNameHandler(documentation, definition);
    expect(documentation.displayName).toBe('xyz');
  });

  it('ignores non-literal names', () => {
    let definition = expression('({displayName: foo.bar})');
    expect(() => displayNameHandler(documentation, definition)).not.toThrow();
    expect(documentation.displayName).not.toBeDefined();

    definition = statement(`
      class Foo {
        static displayName = foo.bar;
      }
    `);
    expect(() => displayNameHandler(documentation, definition)).not.toThrow();
    expect(documentation.displayName).not.toBeDefined();
  });

  describe('ClassDeclaration', () => {
    it('considers the class name', () => {
      const definition = statement(`
        class Foo {
        }
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName class property', () => {
      const definition = statement(`
        class Foo {
          static displayName = 'foo';
        }
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('foo');
    });

    it('considers static displayName getter', () => {
      const definition = statement(`
        class Foo {
          static get displayName() {
            return 'foo';
          }
        }
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('foo');
    });

    it('resolves variables in displayName getter', () => {
      const definition = statement(`
        class Foo {
          static get displayName() {
            return abc;
          }
        }
        const abc = 'bar';
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('bar');
    });
  });

  describe('FunctionDeclaration', () => {
    it('considers the function name', () => {
      const definition = statement('function Foo () {}');
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName object property', () => {
      const definition = statement(`
        function Foo () {}
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });
  });

  describe('FunctionExpression', () => {
    it('considers the variable name', () => {
      const definition = statement('var Foo = function () {};').get(
        'declarations',
        0,
        'init',
      );
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign', () => {
      const definition = statement('Foo = function () {};').get(
        'expression',
        'right',
      );
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName object property over variable name', () => {
      const definition = statement(`
        var Foo = function () {};
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });
  });

  describe('ArrowFunctionExpression', () => {
    it('considers the variable name', () => {
      const definition = statement('var Foo = () => {};').get(
        'declarations',
        0,
        'init',
      );
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name even if wrapped', () => {
      const definition = statement('var Foo = React.forwardRef(() => {});').get(
        'declarations',
        0,
        'init',
        'arguments',
        0,
      );
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name when handling forwardRef', () => {
      const definition = statement(
        [
          'var Foo = React.forwardRef(() => {});',
          'import React from "react";',
        ].join('\n'),
      ).get('declarations', 0, 'init');
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign', () => {
      const definition = statement('Foo = () => {};').get(
        'expression',
        'right',
      );
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign even if wrapped', () => {
      const definition = statement('Foo = React.forwardRef(() => {});').get(
        'expression',
        'right',
        'arguments',
        0,
      );
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign when handling forwardRef call', () => {
      const definition = statement(
        [
          'Foo = React.forwardRef(() => {});',
          'import React from "react";',
        ].join('\n'),
      ).get('expression', 'right');
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName object property over variable name', () => {
      const definition = statement(`
        var Foo = () => {};
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('considers a static displayName object property over variable name even if wrapped', () => {
      const definition = statement(`
        var Foo = React.forwardRef(() => {});
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('ignores assignment to non-literal/identifier', () => {
      const definition = statement('Foo.Bar = () => {};').get(
        'expression',
        'right',
      );
      expect(() => displayNameHandler(documentation, definition)).not.toThrow();
      expect(documentation.displayName).not.toBeDefined();
    });
  });
});
<commit_msg>Add tests for importer with displayNameHandler<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

jest.mock('../../Documentation');

import { expression, statement, noopImporter, makeMockImporter } from '../../../tests/utils';

describe('defaultPropsHandler', () => {
  let documentation;
  let displayNameHandler;

  beforeEach(() => {
    documentation = new (require('../../Documentation'))();
    displayNameHandler = require('../displayNameHandler').default;
  });

  const mockImporter = makeMockImporter({
    foobarbaz: statement(`
      export default "FooBarBaz"
    `).get('declaration'),

    foo: statement(`
      export default {bar: 'baz'};
    `).get('declaration'),

    bar: statement(`
      export default {baz: 'foo'};
    `).get('declaration'),
  });

  it('extracts the displayName', () => {
    let definition = expression('({displayName: "FooBar"})');
    displayNameHandler(documentation, definition, noopImporter);
    expect(documentation.displayName).toBe('FooBar');

    definition = statement(`
      ({displayName: foobarbaz});
      import foobarbaz from 'foobarbaz';
    `).get('expression');
    displayNameHandler(documentation, definition, mockImporter);
    expect(documentation.displayName).toBe('FooBarBaz');

    definition = statement(`
      class Foo {
        static displayName = "BarFoo";
      }
    `);
    displayNameHandler(documentation, definition, noopImporter);
    expect(documentation.displayName).toBe('BarFoo');

    definition = statement(`
      class Foo {
        static displayName = foobarbaz;
      }
      import foobarbaz from 'foobarbaz';
    `);
    displayNameHandler(documentation, definition, mockImporter);
    expect(documentation.displayName).toBe('FooBarBaz');
  });

  it('resolves identifiers', () => {
    let definition = statement(`
      ({displayName: name})
      var name = 'abc';
    `).get('expression');
    displayNameHandler(documentation, definition, noopImporter);
    expect(documentation.displayName).toBe('abc');

    definition = statement(`
      ({displayName: name})
      import foobarbaz from 'foobarbaz';
      var name = foobarbaz;
    `).get('expression');
    displayNameHandler(documentation, definition, mockImporter);
    expect(documentation.displayName).toBe('FooBarBaz');

    definition = statement(`
      class Foo {
        static displayName = name;
      }
      var name = 'xyz';
    `);
    displayNameHandler(documentation, definition, noopImporter);
    expect(documentation.displayName).toBe('xyz');

    definition = statement(`
      class Foo {
        static displayName = name;
      }
      import foobarbaz from 'foobarbaz';
      var name = foobarbaz;
    `);
    displayNameHandler(documentation, definition, mockImporter);
    expect(documentation.displayName).toBe('FooBarBaz');
  });

  it('ignores non-literal names', () => {
    let definition = expression('({displayName: foo.bar})');
    expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
    expect(documentation.displayName).not.toBeDefined();

    definition = statement(`
      class Foo {
        static displayName = foo.bar;
      }
    `);
    expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
    expect(documentation.displayName).not.toBeDefined();
  });

  it('can resolve non-literal names with appropriate importer', () => {
    let definition = statement(`
      ({displayName: foo.bar});
      import foo from 'foo';
    `).get('expression');
    displayNameHandler(documentation, definition, mockImporter);
    expect(documentation.displayName).toBe('baz');

    definition = statement(`
      class Foo {
        static displayName = bar.baz;
      }
      import bar from 'bar';
    `);
    displayNameHandler(documentation, definition, mockImporter);
    expect(documentation.displayName).toBe('foo');
  });

  describe('ClassDeclaration', () => {
    it('considers the class name', () => {
      const definition = statement(`
        class Foo {
        }
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName class property', () => {
      const definition = statement(`
        class Foo {
          static displayName = 'foo';
        }
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('foo');
    });

    it('considers static displayName getter', () => {
      const definition = statement(`
        class Foo {
          static get displayName() {
            return 'foo';
          }
        }
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('foo');
    });

    it('resolves variables in displayName getter', () => {
      const definition = statement(`
        class Foo {
          static get displayName() {
            return abc;
          }
        }
        const abc = 'bar';
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('bar');
    });

    it('resolves imported variables in displayName getter', () => {
      let definition = statement(`
        class Foo {
          static get displayName() {
            return foobarbaz;
          }
        }
        import foobarbaz from 'foobarbaz';
      `);
      displayNameHandler(documentation, definition, mockImporter);
      expect(documentation.displayName).toBe('FooBarBaz');

      definition = statement(`
        class Foo {
          static get displayName() {
            return foo.bar;
          }
        }
        import foo from 'foo';
      `);
      displayNameHandler(documentation, definition, mockImporter);
      expect(documentation.displayName).toBe('baz');
    });
  });

  describe('FunctionDeclaration', () => {
    it('considers the function name', () => {
      const definition = statement('function Foo () {}');
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName object property', () => {
      const definition = statement(`
        function Foo () {}
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves variable assigned to displayName object property', () => {
      const definition = statement(`
        function Foo () {}
        Foo.displayName = bar;
        var bar = 'Bar';
      `);
      displayNameHandler(documentation, definition, noopImporter);
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves imported variable assigned to displayName object property', () => {
      let definition = statement(`
        function Foo () {}
        import foobarbaz from 'foobarbaz';
        Foo.displayName = foobarbaz;
      `);
      displayNameHandler(documentation, definition, mockImporter);
      expect(documentation.displayName).toBe('FooBarBaz');

      definition = statement(`
        function Foo () {}
        import foo from 'foo';
        Foo.displayName = foo.bar;
      `);
      displayNameHandler(documentation, definition, mockImporter);
      expect(documentation.displayName).toBe('baz');
    });
  });

  describe('FunctionExpression', () => {
    it('considers the variable name', () => {
      const definition = statement('var Foo = function () {};').get(
        'declarations',
        0,
        'init',
      );
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign', () => {
      const definition = statement('Foo = function () {};').get(
        'expression',
        'right',
      );
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName object property over variable name', () => {
      const definition = statement(`
        var Foo = function () {};
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves variable assigned to displayName object property over variable name', () => {
      const definition = statement(`
        var Foo = function () {};
        Foo.displayName = bar;
        var bar = 'Bar';
      `);
      displayNameHandler(documentation, definition, noopImporter);
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves imported variable assigned to displayName object property over variable name', () => {
      let definition = statement(`
        var Foo = function () {};
        import foobarbaz from 'foobarbaz';
        Foo.displayName = foobarbaz;
      `);
      displayNameHandler(documentation, definition, mockImporter);
      expect(documentation.displayName).toBe('FooBarBaz');

      definition = statement(`
        var Foo = function () {};
        import foo from 'foo';
        Foo.displayName = foo.bar;
      `);
      displayNameHandler(documentation, definition, mockImporter);
      expect(documentation.displayName).toBe('baz');
    });
  });

  describe('ArrowFunctionExpression', () => {
    it('considers the variable name', () => {
      const definition = statement('var Foo = () => {};').get(
        'declarations',
        0,
        'init',
      );
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name even if wrapped', () => {
      const definition = statement('var Foo = React.forwardRef(() => {});').get(
        'declarations',
        0,
        'init',
        'arguments',
        0,
      );
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name when handling forwardRef', () => {
      const definition = statement(`
        var Foo = React.forwardRef(() => {});
        import React from "react";
      `).get('declarations', 0, 'init');
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign', () => {
      const definition = statement('Foo = () => {};').get(
        'expression',
        'right',
      );
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign even if wrapped', () => {
      const definition = statement('Foo = React.forwardRef(() => {});').get(
        'expression',
        'right',
        'arguments',
        0,
      );
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers the variable name on assign when handling forwardRef call', () => {
      const definition = statement(`
        Foo = React.forwardRef(() => {});
        import React from "react";
      `).get('expression', 'right');
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Foo');
    });

    it('considers a static displayName object property over variable name', () => {
      const definition = statement(`
        var Foo = () => {};
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves a variable assigned to displayName object property over variable name', () => {
      const definition = statement(`
        var Foo = () => {};
        Foo.displayName = bar;
        var bar = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves imported variable assigned to displayName object property over variable name', () => {
      let definition = statement(`
        var Foo = () => {};
        import foobarbaz from 'foobarbaz';
        Foo.displayName = foobarbaz;
      `);
      expect(() => displayNameHandler(documentation, definition, mockImporter)).not.toThrow();
      expect(documentation.displayName).toBe('FooBarBaz');

      definition = statement(`
        var Foo = () => {};
        import foo from 'foo';
        Foo.displayName = foo.bar;
      `);
      expect(() => displayNameHandler(documentation, definition, mockImporter)).not.toThrow();
      expect(documentation.displayName).toBe('baz');
    });

    it('considers a static displayName object property over variable name even if wrapped', () => {
      const definition = statement(`
        var Foo = React.forwardRef(() => {});
        Foo.displayName = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves a variable assigned to displayName object property over variable name even if wrapped', () => {
      const definition = statement(`
        var Foo = React.forwardRef(() => {});
        Foo.displayName = bar;
        var bar = 'Bar';
      `);
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).toBe('Bar');
    });

    it('resolves imported variable assigned to displayName object property over variable name even if wrapped', () => {
      let definition = statement(`
        var Foo = React.forwardRef(() => {});
        import foobarbaz from 'foobarbaz';
        Foo.displayName = foobarbaz;
      `);
      expect(() => displayNameHandler(documentation, definition, mockImporter)).not.toThrow();
      expect(documentation.displayName).toBe('FooBarBaz');

      definition = statement(`
        var Foo = React.forwardRef(() => {});
        import foo from 'foo';
        Foo.displayName = foo.bar;
      `);
      expect(() => displayNameHandler(documentation, definition, mockImporter)).not.toThrow();
      expect(documentation.displayName).toBe('baz');
    });

    it('ignores assignment to non-literal/identifier', () => {
      const definition = statement('Foo.Bar = () => {};').get(
        'expression',
        'right',
      );
      expect(() => displayNameHandler(documentation, definition, noopImporter)).not.toThrow();
      expect(documentation.displayName).not.toBeDefined();
    });
  });
});
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//----------------------------------------------------------------------------------

var guid = require('node-uuid');
var util = require('util');
var storage = require('azure-storage');
var config = require('./config');
var fs = require('fs');

function advancedSamples() {
  return scenarios = [
    {
        action: leaseBlob,
        message: 'Blob Lease Sample Completed\n'
    },
    {
        action: leaseContainer,
        message: 'Container Lease Sample Completed\n'
    },
    {
        action: setCorsRules,
        message: 'Cors Rules Sample Completed\n'
    },
    {
        action: basicContainerOperations,
        message: 'Containers Sample Completed\n'
    },
    {
        action: copyBlob,
        message: 'Copy Blob Sample Completed\n'
    }
  ];
}

/**
* Copies one blob from one location to another in the same subscription.
*
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise null as no result is returned from this function.
*/
function copyBlob(callback) {
    var blobService = storage.createBlobService(config.connectionString);

    var containerName = "demoblobcontainer-" + guid.v1();

    console.log('1. Creating Container');
    blobService.createContainerIfNotExists(containerName, function (error) {
        if (error) return callback(error);

        console.log('2. Creating Text Blob');
        blobService.createBlockBlobFromText(containerName, 'sourceBlob', 'sample data', function(error) {
            if(error) return callback(error);

            var sourceBlobUrl = blobService.getUrl(containerName, 'sourceBlob');

            console.log('3. Copying Text Blob');
            blobService.startCopyBlob(sourceBlobUrl, containerName, 'targetBlob', function(error, result) {
                if(error) return callback(error);

                console.log('status ' + result.copy.status);

                if(result.copy.status === 'pending') {
                    console.log('4. Aborting Text Blob Copy');

                    blobService.abortCopyBlob(containerName, 'targetBlob', result.copy.id, function(error) {
                        if(error) callback(error);

                        console.log('Copy operation aborted');

                        //Delete container
                        console.log('5. Delete Container');
                        blobService.deleteContainerIfExists(containerName, function (error) {
                          callback(error);
                        })
                    })
                } else {
                  //Delete container
                  console.log('4. Delete Container');
                  blobService.deleteContainerIfExists(containerName, function (error) {
                    callback(error);
                  })
                }
            })
        })
    });
}

/**
* Uploads a file using a Page Blob.
*
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise null as no result is returned from this function.
*/
function uploadFileWithPageBlob(callback) {
    // Create a blob client for interacting with the blob service from connection string
    // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
    var blobService = storage.createBlobService(config.connectionString);

    var fileToUpload = "HelloPage.dat";
    var pageBlobContainerName = "demopageblobcontainer-" + guid.v1();
    var pageBlobName = "demopageblob-" + fileToUpload;

    console.log('Page Blob Sample');

    // Create a container for organizing blobs within the storage account.
    console.log('1. Creating Container');
    blobService.createContainerIfNotExists(pageBlobContainerName, function (error) {
        if (error) return callback(error);

        // Upload a PageBlob to the newly created container
        console.log('2. Creating Page Blob');
        blobService.createPageBlob(pageBlobContainerName, pageBlobName, 1024 * 1024, function(error) {
          if(error) return callback(error);

            // Get an stream to upload the file
            console.log('3. Uploading File to Page Blob');
            var stream = fs.createReadStream(fileToUpload)
              .pipe(blobService.createWriteStreamToExistingPageBlob(pageBlobContainerName, pageBlobName));

            stream.on('finish', function () {
                // List all the pages in the blob
                console.log('4. Listing pages in Page Blob');
                blobService.listPageRanges(pageBlobContainerName, pageBlobName, function(error, pages) {
                pages.forEach(function(page, index) {
                  console.log(util.format('page number %s -start %s -end %s', index, page.start, page.end));
                })

                //Delete container
                console.log('4. Delete Container');
                blobService.deleteContainerIfExists(pageBlobContainerName, function (error) {
                  callback(error);
                })
              })
            });
        });
  });
}

/**
* Basic operations with containers.
*
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise null as no result is returned from this function.
*/
function basicContainerOperations(callback) {
   // Create a blob client for interacting with the blob service from connection string
  // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
  var blobService = storage.createBlobService(config.connectionString);

  var containerName = "demoblobcontainer-" + guid.v1();

  console.log('1. Creating Container');

  blobService.createContainerIfNotExists(containerName, function (error) {
    if (error) return callback(error);

    // List all the containers within the storage account.
    console.log('2. List Container');
    listContainers(blobService, null, null, function (error, results) {
      if (error) return callback(error);

      for (var i = 0; i < results.length; i++) {
        console.log(util.format('   - %s'), results[i].name);
      }

      //Delete container
      console.log('3. Delete Container');
      blobService.deleteContainerIfExists(containerName, function (error) {
        callback(error);
      });
    });
  });
}

/**
* Set Cors rules for a blob. These rules are used by a browser for a call that involves Cors.
*
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise null as no result is returned from this function.
*/
function setCorsRules(callback) {
   // Create a blob client for interacting with the blob service from connection string
  // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
  var blobService = storage.createBlobService(config.connectionString);

  blobService.getServiceProperties(function(error, properties) {
    if(error) return callback(error);

    properties.Cors = {
        CorsRule: [{
          AllowedOrigins: ['*'],
          AllowedMethods: ['POST', 'GET'],
          AllowedHeaders: ['*'],
          ExposedHeaders: ['*'],
          MaxAgeInSeconds: 3600
        }]
    };

    blobService.setServiceProperties(properties, function(error) {
      return callback(error);
    });
  });
}

/**
* Acquires a lease for exclusive write permissions on a container.
*
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise null as no result is returned from this function.
*/
function leaseContainer(callback) {
   // Create a blob client for interacting with the blob service from connection string
  // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
  var blobService = storage.createBlobService(config.connectionString);

  var containerName = "demoleaseblobcontainer-" + guid.v1();

  console.log('1. Create Container');

  blobService.createContainerIfNotExists(containerName, function (error) {
    if (error) return callback(error);

    console.log('2. Acquire Lease on container');
    blobService.acquireLease(containerName, null, { leaseDuration : 15 }, function(error, leaseResult) {
      if(error) return callback(error);

      console.log('3. Delete Container without lease');
      blobService.deleteContainer(containerName, function(error) {
        if(error) {
          console.log('The container can not be deleted. A lease was not specified. ' + error.message);
        }

        console.log('4. Delete Container with lease ' + leaseResult.id);
        blobService.deleteContainer(containerName, { leaseId: leaseResult.id }, function(error){
          return callback(error);
        })
      });
    });
  });
}

/**
* Acquires a lease for exclusive write permissions on a blob.
*
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise null as no result is returned from this function.
*/
function leaseBlob(callback) {
   // Create a blob client for interacting with the blob service from connection string
  // How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
  var blobService = storage.createBlobService(config.connectionString);

  var containerName = "demoleaseblobcontainer-" + guid.v1();
  var blobName = 'exclusive';

  console.log('1. Create Container');
  blobService.createContainerIfNotExists(containerName, function (error) {
    if (error) return callback(error);

    console.log('2. Create blob');
    blobService.createBlockBlobFromText(containerName, blobName, 'blob created', function(error) {
      if(error) return callback(error);

      console.log('3. Acquire lease on blob');
      blobService.acquireLease(containerName, blobName, { leaseDuration: 15 }, function(error, leaseResult) {
        if(error) return callback(error);

        console.log('4. Delete blob without a lease');
        blobService.deleteBlob(containerName, blobName, function(error) {
          if(error) {
            console.log('The blob can not be deleted. A lease was not specified. ' + error.message);
          }

          console.log('5. Delete blob with lease id ' + leaseResult.id);
          blobService.deleteBlob(containerName, blobName, { leaseId: leaseResult.id }, function(error) {
            if(error) return callback(error);

            console.log('6. Delete container');
            blobService.deleteContainer(containerName, function(error) {
              return callback(error);
            })
          })
        })
      })
    })
  });
}

/**
* Lists containers in the subscription.
*
* @param {BlobService}        blobService                         The blob service client.
* @param {object}             token                               A continuation token returned by a previous listing operation.
*                                                                 Please use 'null' or 'undefined' if this is the first operation.
* @param {object}             [options]                           The request options.
* @param {LocationMode}       [options.locationMode]                      Specifies the location mode used to decide which location the request should be sent to.
*                                                                         Please see StorageUtilities.LocationMode for the possible values.
* @param {int}                [options.maxResults]                        Specifies the maximum number of containers to return per call to Azure storage.
* @param {string}             [options.include]                           Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata')
*                                                                         **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {int}                [options.timeoutIntervalInMs]               The server timeout interval, in milliseconds, to use for the request.
* @param {int}                [options.maximumExecutionTimeInMs]          The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
*                                                                         The maximum execution time interval begins at the time that the client begins building the request. The maximum
*                                                                         execution time is checked intermittently while performing requests, and before executing retries.
* @param {string}             [options.clientRequestId]                   A string that represents the client request ID with a 1KB character limit.
* @param {bool}               [options.useNagleAlgorithm]                 Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
*
* @param {errorOrResult}      callback                            `error` will contain information
*                                                                 if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
*                                                                 `entries`  gives a list of directories and the `continuationToken` is used for the next listing operation.
*                                                                 `response` will contain information related to this operation.
*/
function listContainers (blobService, token, options, callback) {
  var containers = [];

  blobService.listContainersSegmented(token, options, function(error, result) {
    containers.push.apply(containers, result.entries);
    var token = result.continuationToken;
    if (token) {
      console.log('   Received a page of results. There are ' + result.entries.length + ' containers on this page.');
      listBlobs(blobService, token, options, callback);
    } else {
      console.log('   Completed listing. There are ' + containers.length + ' containers.');
      callback(null, containers);
    }
  });
}

module.exports = advancedSamples();
<commit_msg>Removed file pushed by mistake<commit_after><|endoftext|>


<commit_before>/* $This file is distributed under the terms of the license in /doc/license.txt$ */

$(document).ready(function(){

  $("#photoUploadContainer").removeClass("hidden");

  $('#photoUploadForm form').submit(function() {
    if ($("#datafile").val() == '') {
      alert('Please browse and select a photo.');
      return false;
    }
  });

  $('a.delete').click(function(){
    var answer = confirm('Are you sure you want to '+ jQuery(this).attr('title') +'?' );
    // jQuery(this).attr('title') gets anchor title attribute
    return answer;
  });

});<commit_msg>NIHVIVO-577: Deleted js function<commit_after>/* $This file is distributed under the terms of the license in /doc/license.txt$ */

$(document).ready(function(){

  $("#photoUploadContainer").removeClass("hidden");

  $('a.delete').click(function(){
   // var answer = confirm('Are you sure you want to '+ jQuery(this).attr('title') +'?' );
   var answer = confirm('Are you sure you want to delete your photo?');
    // jQuery(this).attr('title') gets anchor title attribute
    return answer;
  });

});<|endoftext|>


<commit_before>import { keys } from "lodash/fp";

const DOC_BASE_LINK = "https://help.idseq.net/hc/en-us/articles/";

export const SAMPLE_TABLE_COLUMNS_V2 = {
  sample: {
    tooltip: `The user-defined sample name.`,
  },
  createdAt: {
    tooltip: "The date on which the sample was initially uploaded to IDseq.",
  },
  host: {
    tooltip: `User-selected organism from which this sample was collected; this
      value is selected by the user at sample upload and dictates which
      genomes are used for initial host subtraction pipeline steps.`,
    link: DOC_BASE_LINK + "360035296613-Project-Page#metrics-meanings",
  },
  collectionLocationV2: {
    tooltip: "User-defined location from which the sample was collected.",
  },
  totalReads: {
    tooltip: "The total number of single-end reads uploaded.",
  },
  nonHostReads: {
    tooltip: `The percentage of reads that came out of step (8) of the host filtration
    and QC steps as compared to what went in at step (1).`,
    link: DOC_BASE_LINK + "360034790554-Pipeline-Details#passed-filters",
  },
  qcPercent: {
    tooltip: `The percentage of reads that came out of PriceSeq, step (3) of the host
    filtration and QC steps, compared to what went in to Trimmomatic, step (2).`,
    link: DOC_BASE_LINK + "360034790554-Pipeline-Details#passed-qc",
  },
  duplicateCompressionRatio: {
    tooltip: `Duplicate Compression Ratio is the ratio of sequences present prior to
    running cd-hit-dup (duplicate removal) vs after duplicate removal.
    High values indicate the presence of more duplicate reads, indicating lower
    library complexity.`,
    link: DOC_BASE_LINK + "360035296613-Project-Page#metrics-meanings",
  },
  erccReads: {
    tooltip: `The total number of reads aligning to ERCC (External RNA Controls
      Consortium) sequences.`,
    link: DOC_BASE_LINK + "360034790834-How-to-Interpret-ERCC-Quality",
  },
  notes: {
    tooltip: "User-supplied notes.",
  },
  nucleotideType: {
    tooltip:
      "User-selected metadata field indicating the nucleotide type (RNA, DNA).",
  },
  sampleType: {
    tooltip: "User-supplied metadata field indicating the sample type.",
  },
  subsampledFraction: {
    tooltip: `After host filtration and QC, the remaining reads are subsampled to 1
    million fragments (2 million paired reads). This field indicates the ratio of
    subsampled reads to total reads passing host filtration and QC steps.`,
    link: DOC_BASE_LINK + "360035296613-Project-Page#metrics-meanings",
  },
  totalRuntime: {
    tooltip: `The total time required by the IDseq pipeline to process .fastq files into
    IDseq reports.`,
  },
  waterControl: {
    tooltip: "Whether a sample is water-only as a control.",
  },
  meanInsertSize: {
    tooltip:
      "Mean length of the fragmented nucleic acid sequences input for sequencing.",
    link: DOC_BASE_LINK + "360034790554#mean-insert-size",
  },
};

// DEPRECATED
export const SAMPLE_TABLE_COLUMNS = {
  total_reads: {
    display_name: "Total reads",
    type: "pipeline_data",
  },
  nonhost_reads: {
    display_name: "Passed filters",
    type: "pipeline_data",
  },
  total_ercc_reads: {
    display_name: "ERCC reads",
    type: "pipeline_data",
  },
  fraction_subsampled: {
    display_name: "Subsampled fraction",
    type: "pipeline_data",
  },
  quality_control: {
    display_name: "Passed QC",
    tooltip: "Passed quality control",
    type: "pipeline_data",
  },
  compression_ratio: {
    display_name: "DCR",
    tooltip: "Duplicate compression ratio",
    type: "pipeline_data",
  },
  pipeline_status: {
    display_name: "Status",
    type: "pipeline_data",
  },
  nucleotide_type: {
    display_name: "Nucleotide type",
    type: "metadata",
  },
  collection_location: {
    display_name: "Collection Location",
    type: "metadata",
  },
  host_genome: {
    display_name: "Host",
    type: "sampleMetadata",
  },
  sample_type: {
    display_name: "Sample type",
    type: "metadata",
  },
  notes: {
    display_name: "Notes",
    type: "sampleMetadata",
  },
  insert_size_mean: {
    display_name: "Mean Insert Size",
    type: "metadata",
  },
};

export const INITIAL_COLUMNS = [
  "total_reads",
  "nonhost_reads",
  "quality_control",
  "compression_ratio",
  "host_genome",
  "collection_location",
  "pipeline_status",
];

export const ALL_COLUMNS = keys(SAMPLE_TABLE_COLUMNS);
<commit_msg>IDSEQ-2514: Update DCR tooltip (#3231)<commit_after>import { keys } from "lodash/fp";

const DOC_BASE_LINK = "https://help.idseq.net/hc/en-us/articles/";

export const SAMPLE_TABLE_COLUMNS_V2 = {
  sample: {
    tooltip: `The user-defined sample name.`,
  },
  createdAt: {
    tooltip: "The date on which the sample was initially uploaded to IDseq.",
  },
  host: {
    tooltip: `User-selected organism from which this sample was collected; this
      value is selected by the user at sample upload and dictates which
      genomes are used for initial host subtraction pipeline steps.`,
    link: DOC_BASE_LINK + "360035296613-Project-Page#metrics-meanings",
  },
  collectionLocationV2: {
    tooltip: "User-defined location from which the sample was collected.",
  },
  totalReads: {
    tooltip: "The total number of single-end reads uploaded.",
  },
  nonHostReads: {
    tooltip: `The percentage of reads that came out of step (8) of the host filtration
    and QC steps as compared to what went in at step (1).`,
    link: DOC_BASE_LINK + "360034790554-Pipeline-Details#passed-filters",
  },
  qcPercent: {
    tooltip: `The percentage of reads that came out of PriceSeq, step (3) of the host
    filtration and QC steps, compared to what went in to Trimmomatic, step (2).`,
    link: DOC_BASE_LINK + "360034790554-Pipeline-Details#passed-qc",
  },
  duplicateCompressionRatio: {
    tooltip: `Duplicate Compression Ratio is the ratio of the total number of
    sequences present prior to running cd-hit-dup (duplicate identification) vs
    the number of unique sequences.`,
    link: DOC_BASE_LINK + "360035296613-Project-Page#metrics-meanings",
  },
  erccReads: {
    tooltip: `The total number of reads aligning to ERCC (External RNA Controls
      Consortium) sequences.`,
    link: DOC_BASE_LINK + "360034790834-How-to-Interpret-ERCC-Quality",
  },
  notes: {
    tooltip: "User-supplied notes.",
  },
  nucleotideType: {
    tooltip:
      "User-selected metadata field indicating the nucleotide type (RNA, DNA).",
  },
  sampleType: {
    tooltip: "User-supplied metadata field indicating the sample type.",
  },
  subsampledFraction: {
    tooltip: `After host filtration and QC, the remaining reads are subsampled to 1
    million fragments (2 million paired reads). This field indicates the ratio of
    subsampled reads to total reads passing host filtration and QC steps.`,
    link: DOC_BASE_LINK + "360035296613-Project-Page#metrics-meanings",
  },
  totalRuntime: {
    tooltip: `The total time required by the IDseq pipeline to process .fastq files into
    IDseq reports.`,
  },
  waterControl: {
    tooltip: "Whether a sample is water-only as a control.",
  },
  meanInsertSize: {
    tooltip:
      "Mean length of the fragmented nucleic acid sequences input for sequencing.",
    link: DOC_BASE_LINK + "360034790554#mean-insert-size",
  },
};

// DEPRECATED
export const SAMPLE_TABLE_COLUMNS = {
  total_reads: {
    display_name: "Total reads",
    type: "pipeline_data",
  },
  nonhost_reads: {
    display_name: "Passed filters",
    type: "pipeline_data",
  },
  total_ercc_reads: {
    display_name: "ERCC reads",
    type: "pipeline_data",
  },
  fraction_subsampled: {
    display_name: "Subsampled fraction",
    type: "pipeline_data",
  },
  quality_control: {
    display_name: "Passed QC",
    tooltip: "Passed quality control",
    type: "pipeline_data",
  },
  compression_ratio: {
    display_name: "DCR",
    tooltip: "Duplicate compression ratio",
    type: "pipeline_data",
  },
  pipeline_status: {
    display_name: "Status",
    type: "pipeline_data",
  },
  nucleotide_type: {
    display_name: "Nucleotide type",
    type: "metadata",
  },
  collection_location: {
    display_name: "Collection Location",
    type: "metadata",
  },
  host_genome: {
    display_name: "Host",
    type: "sampleMetadata",
  },
  sample_type: {
    display_name: "Sample type",
    type: "metadata",
  },
  notes: {
    display_name: "Notes",
    type: "sampleMetadata",
  },
  insert_size_mean: {
    display_name: "Mean Insert Size",
    type: "metadata",
  },
};

export const INITIAL_COLUMNS = [
  "total_reads",
  "nonhost_reads",
  "quality_control",
  "compression_ratio",
  "host_genome",
  "collection_location",
  "pipeline_status",
];

export const ALL_COLUMNS = keys(SAMPLE_TABLE_COLUMNS);
<|endoftext|>


<commit_before>import React from "react";
import { Text } from "react-native";
import renderer from "react-test-renderer";
import PropTypes from "prop-types";
import { withTrackEvents } from "../tracking";
import withTrackingContext from "./test-tracking-context";

describe("TrackEvents", () => {
  const TestComponent = ({
    event1 = () => ({}),
    event2 = () => ({}),
    ...props
  }) => {
    event1("event1 arg");
    event2("event2 arg");
    return <Text>{props.someProp}</Text>;
  };
  TestComponent.propTypes = {
    someProp: PropTypes.string,
    event1: PropTypes.func.isRequired,
    event2: PropTypes.func.isRequired
  };
  TestComponent.defaultProps = { someProp: "foo" };
  TestComponent.someStatic = { foo: "bar" };

  it("renders when tracking context is missing", () => {
    const WithTracking = withTrackEvents(TestComponent, {
      analyticsEvents: [{ eventName: "event1", actionName: "event1ed" }]
    });

    const tree = renderer.create(<WithTracking />).toJSON();

    expect(tree).toMatchSnapshot();
  });

  it("ignores events not exposed by tracked component", () => {
    const reporter = jest.fn();

    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "unknownEvent", actionName: "happened" }]
      })
    );

    renderer.create(<WithTrackingAndContext analyticsStream={reporter} />);

    expect(reporter).not.toHaveBeenCalled();
  });

  it("tracks specified child events", () => {
    const reporter = jest.fn();
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "event1", actionName: "event1ed" }]
      })
    );

    renderer.create(<WithTrackingAndContext analyticsStream={reporter} />);

    expect(reporter).toHaveBeenCalledWith({
      action: "event1ed",
      attrs: {},
      component: "TestComponent"
    });
  });

  it("raises error when trying to track the same event more than once", () => {
    const addTracking = () =>
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          { eventName: "event1", actionName: "event1ed" },
          { eventName: "event1", actionName: "event1ed" }
        ]
      });

    expect(addTracking).toThrowErrorMatchingSnapshot();
  });

  it("raises error when action name is not set", () => {
    const addTracking = () =>
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "event1" }]
      });

    expect(addTracking).toThrowErrorMatchingSnapshot();
  });

  it("raises error when event name is not set", () => {
    const addTracking = () =>
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ actionName: "event1ed" }]
      });

    expect(addTracking).toThrowErrorMatchingSnapshot();
  });

  it("accepts component name override", () => {
    const reporter = jest.fn();
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          {
            eventName: "event1",
            actionName: "event1ed",
            trackingName: "OverriddenName"
          }
        ]
      })
    );

    renderer.create(<WithTrackingAndContext analyticsStream={reporter} />);

    expect(reporter).toHaveBeenCalledWith(
      expect.objectContaining({ component: "OverriddenName" })
    );
  });

  it("applies tracking attrs", () => {
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          {
            eventName: "event1",
            actionName: "event1ed",
            getAttrs: (props, eventArgs) => ({
              fromProps: props.aProp,
              static: "value",
              args: eventArgs
            })
          }
        ]
      })
    );
    const reporter = jest.fn();

    renderer.create(
      <WithTrackingAndContext aProp="propValue" analyticsStream={reporter} />
    );

    expect(reporter).toHaveBeenCalledWith(
      expect.objectContaining({
        attrs: expect.objectContaining({
          fromProps: "propValue",
          static: "value",
          args: ["event1 arg"]
        })
      })
    );
  });

  it("tracks multiple events", () => {
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          {
            eventName: "event1",
            actionName: "event1ed",
            getAttrs: (props, eventArgs) => ({
              fromProps: props.aProp,
              static: "value",
              args: eventArgs
            })
          },
          {
            eventName: "event2",
            actionName: "event2ed",
            getAttrs: (props, eventArgs) => ({
              fromProps: props.aProp,
              static: "otherValue",
              args: eventArgs
            })
          }
        ]
      })
    );
    const reporter = jest.fn();

    renderer.create(
      <WithTrackingAndContext aProp="propValue" analyticsStream={reporter} />
    );

    expect(reporter.mock.calls).toMatchSnapshot();
  });

  it("supports handling of tracked events", () => {
    const handler = jest.fn();
    const reporter = jest.fn();
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "event1", actionName: "event1ed" }]
      })
    );

    renderer.create(
      <WithTrackingAndContext analyticsStream={reporter} event1={handler} />
    );

    expect(reporter).toHaveBeenCalled();
    expect(handler).toHaveBeenCalledWith("event1 arg");
  });

  it("forwards props to wrapped component", () => {
    const WithTracking = withTrackEvents(TestComponent);
    const tree = renderer.create(<WithTracking someProp="bar" />);

    expect(tree).toMatchSnapshot();
  });

  it("hoists wrapped propTypes", () => {
    const WithTracking = withTrackEvents(TestComponent);

    expect(WithTracking.propTypes).toEqual(TestComponent.propTypes);
  });

  it("hoists wrapped defaultProps", () => {
    const WithTracking = withTrackEvents(TestComponent);

    expect(WithTracking.defaultProps).toEqual(TestComponent.defaultProps);
  });

  it("hoists wrapped statics", () => {
    const WithTracking = withTrackEvents(TestComponent);

    expect(WithTracking.someStatic).toEqual(TestComponent.someStatic);
  });
});
<commit_msg>tests: remove props warnings<commit_after>import React from "react";
import { Text } from "react-native";
import renderer from "react-test-renderer";
import PropTypes from "prop-types";
import { withTrackEvents } from "../tracking";
import withTrackingContext from "./test-tracking-context";

describe("TrackEvents", () => {
  const TestComponent = ({ event1, event2, ...props }) => {
    event1("event1 arg");
    event2("event2 arg");
    return <Text>{props.someProp}</Text>;
  };
  TestComponent.propTypes = {
    someProp: PropTypes.string,
    event1: PropTypes.func,
    event2: PropTypes.func
  };
  TestComponent.defaultProps = {
    someProp: "foo",
    event1: () => {},
    event2: () => {}
  };
  TestComponent.someStatic = { foo: "bar" };

  it("renders when tracking context is missing", () => {
    const WithTracking = withTrackEvents(TestComponent, {
      analyticsEvents: [{ eventName: "event1", actionName: "event1ed" }]
    });

    const tree = renderer.create(<WithTracking />).toJSON();

    expect(tree).toMatchSnapshot();
  });

  it("ignores events not exposed by tracked component", () => {
    const reporter = jest.fn();

    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "unknownEvent", actionName: "happened" }]
      })
    );

    renderer.create(<WithTrackingAndContext analyticsStream={reporter} />);

    expect(reporter).not.toHaveBeenCalled();
  });

  it("tracks specified child events", () => {
    const reporter = jest.fn();
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "event1", actionName: "event1ed" }]
      })
    );

    renderer.create(<WithTrackingAndContext analyticsStream={reporter} />);

    expect(reporter).toHaveBeenCalledWith({
      action: "event1ed",
      attrs: {},
      component: "TestComponent"
    });
  });

  it("raises error when trying to track the same event more than once", () => {
    const addTracking = () =>
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          { eventName: "event1", actionName: "event1ed" },
          { eventName: "event1", actionName: "event1ed" }
        ]
      });

    expect(addTracking).toThrowErrorMatchingSnapshot();
  });

  it("raises error when action name is not set", () => {
    const addTracking = () =>
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "event1" }]
      });

    expect(addTracking).toThrowErrorMatchingSnapshot();
  });

  it("raises error when event name is not set", () => {
    const addTracking = () =>
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ actionName: "event1ed" }]
      });

    expect(addTracking).toThrowErrorMatchingSnapshot();
  });

  it("accepts component name override", () => {
    const reporter = jest.fn();
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          {
            eventName: "event1",
            actionName: "event1ed",
            trackingName: "OverriddenName"
          }
        ]
      })
    );

    renderer.create(<WithTrackingAndContext analyticsStream={reporter} />);

    expect(reporter).toHaveBeenCalledWith(
      expect.objectContaining({ component: "OverriddenName" })
    );
  });

  it("applies tracking attrs", () => {
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          {
            eventName: "event1",
            actionName: "event1ed",
            getAttrs: (props, eventArgs) => ({
              fromProps: props.aProp,
              static: "value",
              args: eventArgs
            })
          }
        ]
      })
    );
    const reporter = jest.fn();

    renderer.create(
      <WithTrackingAndContext aProp="propValue" analyticsStream={reporter} />
    );

    expect(reporter).toHaveBeenCalledWith(
      expect.objectContaining({
        attrs: expect.objectContaining({
          fromProps: "propValue",
          static: "value",
          args: ["event1 arg"]
        })
      })
    );
  });

  it("tracks multiple events", () => {
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [
          {
            eventName: "event1",
            actionName: "event1ed",
            getAttrs: (props, eventArgs) => ({
              fromProps: props.aProp,
              static: "value",
              args: eventArgs
            })
          },
          {
            eventName: "event2",
            actionName: "event2ed",
            getAttrs: (props, eventArgs) => ({
              fromProps: props.aProp,
              static: "otherValue",
              args: eventArgs
            })
          }
        ]
      })
    );
    const reporter = jest.fn();

    renderer.create(
      <WithTrackingAndContext aProp="propValue" analyticsStream={reporter} />
    );

    expect(reporter.mock.calls).toMatchSnapshot();
  });

  it("supports handling of tracked events", () => {
    const handler = jest.fn();
    const reporter = jest.fn();
    const WithTrackingAndContext = withTrackingContext(
      withTrackEvents(TestComponent, {
        analyticsEvents: [{ eventName: "event1", actionName: "event1ed" }]
      })
    );

    renderer.create(
      <WithTrackingAndContext analyticsStream={reporter} event1={handler} />
    );

    expect(reporter).toHaveBeenCalled();
    expect(handler).toHaveBeenCalledWith("event1 arg");
  });

  it("forwards props to wrapped component", () => {
    const WithTracking = withTrackEvents(TestComponent);
    const tree = renderer.create(<WithTracking someProp="bar" />);

    expect(tree).toMatchSnapshot();
  });

  it("hoists wrapped propTypes", () => {
    const WithTracking = withTrackEvents(TestComponent);

    expect(WithTracking.propTypes).toEqual(TestComponent.propTypes);
  });

  it("hoists wrapped defaultProps", () => {
    const WithTracking = withTrackEvents(TestComponent);

    expect(WithTracking.defaultProps).toEqual(TestComponent.defaultProps);
  });

  it("hoists wrapped statics", () => {
    const WithTracking = withTrackEvents(TestComponent);

    expect(WithTracking.someStatic).toEqual(TestComponent.someStatic);
  });
});
<|endoftext|>


<commit_before>'use strict'
/**
 * Created by tungtouch on 2/9/15.
 */

var http = require("http"), server, i;
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe ban kinh dai bakbakabk efefe");
var redis_client = require("redis").createClient();
var r = 0;
server = http.createServer(function (request, response) {
    r++;
    response.writeHead(200, {
        "Content-Type": "text/plain"
    });
    console.log("Insert data", r);
    for(i=0; i<1000000; i++){
        redis_client.hset("raw", "data"+i, message, redis_client.print);
    }
}).listen(6666);

server.on('error', function(err){
    console.log(err);
    process.exit(1);
});<commit_msg>change port 3000<commit_after>'use strict'
/**
 * Created by tungtouch on 2/9/15.
 */

var http = require("http"), server, i;
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe ban kinh dai bakbakabk efefe");
var redis_client = require("redis").createClient();
var r = 0;
server = http.createServer(function (request, response) {
    r++;
    response.writeHead(200, {
        "Content-Type": "text/plain"
    });
    console.log("Insert data", r);
    for(i=0; i<100000; i++){
        redis_client.hset("raw", "data"+i, message, redis_client.print);
    }
}).listen(6666);

server.on('error', function(err){
    console.log(err);
    process.exit(1);
});<|endoftext|>


<commit_before>pw.component.register('content-editor-media', function (view, config, name, id) {
  var self = this;

  var uri = '/console/media';
  var channel = 'media:' + id;
  var blinder, media;

  var input = view.node.querySelector('input');
  var icon = view.node.querySelector('i').cloneNode(true);

  this.inited = function () {
    setTimeout(function () {
      if (input.value && input.value != '') {
        self.transform(JSON.parse(input.value));
      }
    });
  };

  this.listen(channel + ':navigator:enter', function (response) {
    if (!blinder) {
      blinder = document.createElement('DIV');
      blinder.classList.add('ui-media-blinder');

      media = document.createElement('DIV');
      media.classList.add('ui-media');

      blinder.appendChild(media);
      document.body.appendChild(blinder);

      blinder.addEventListener('click', function (evt) {
        if (evt.target === blinder) {
          evt.preventDefault();
          self.close();

          var uri = window.location.pathname;

          var opts = {
            uri: uri
          };

          window.history.pushState(opts, uri, uri);
        }
      });
    }

    media.innerHTML = response.body;
    pw.component.findAndInit(blinder);

    blinder.classList.add('ui-appear');
  });

  this.listen(channel + ':navigator:exit', function () {
    self.close();
  });

  this.listen(channel + ':navigator:boot', function () {
    // FIXME: this is never being triggered; related to load order of scripts; modal works?
    self.load();
  });

  view.node.addEventListener('click', function (evt) {
    evt.preventDefault();
    self.load();
  });

  this.load = function () {
    if (!window.socket) {
      // TODO: not sure what we can do here
      return;
    }

    var items;
    if (input.value && input.value != '') {
      items = JSON.parse(input.value);
    }

    var opts = {
      uri: uri,
      context: channel,
      container: 'default',
      items: items
    }

    window.history.pushState(opts, uri, uri);

    // listen for a choice to be made
    self.listen('media-editor:changed', function (items) {
      self.transform(items);
    });
  };

  this.close = function () {
    self.ignore('media-editor:changed');
    pw.node.remove(blinder);
    blinder = null;
    media = null;
  };

  this.transform = function (items) {
    var i = view.node.querySelector('i');

    if (items.length == 0) {
      if (!i) {
        pw.node.append(view.node, icon.cloneNode(true));
      }

      view.node.style.backgroundImage = null;
    } else if (items.length == 1) {
      if (i) {
        pw.node.remove(i);
      }

      var firstItem = items[0];

      var constraints = pw.node.scope(view.node).constraints;
      if (constraints) {
        var resizedScaleFactor = constraints.width / view.node.offsetWidth;
        var constrainedHeight = constraints.height / resizedScaleFactor;
        view.node.style.height = (constrainedHeight) + 'px';
        view.node.style.backgroundImage = "url('" + firstItem.thumb + "?w=" + view.node.offsetWidth + "&h=" + constrainedHeight + "')";
      }
    } else {
      //TODO decide how to display slideshows
    }

    view.node.querySelector('input').value = JSON.stringify(items);

    pw.component.broadcast('content-editor:changed');
  };
});
<commit_msg>Fix bug preventing modal from closing<commit_after>pw.component.register('content-editor-media', function (view, config, name, id) {
  var self = this;

  var uri = '/console/media';
  var channel = 'media:' + id;
  var blinder, media;

  var input = view.node.querySelector('input');
  var icon = view.node.querySelector('i').cloneNode(true);

  this.inited = function () {
    setTimeout(function () {
      if (input.value && input.value != '') {
        self.transform(JSON.parse(input.value));
      }
    });
  };

  this.listen(channel + ':navigator:enter', function (response) {
    if (!blinder) {
      blinder = document.createElement('DIV');
      blinder.classList.add('ui-media-blinder');

      media = document.createElement('DIV');
      media.classList.add('ui-media');

      blinder.appendChild(media);
      document.body.appendChild(blinder);

      blinder.addEventListener('click', function (evt) {
        if (evt.target === blinder) {
          evt.preventDefault();
          self.close();

          var uri = window.location.pathname;

          var opts = {
            uri: uri
          };

          window.history.pushState(opts, uri, uri);
        }
      });
    }

    media.innerHTML = response.body;
    pw.component.findAndInit(blinder);

    blinder.classList.add('ui-appear');
  });

  this.listen(channel + ':navigator:exit', function () {
    self.close();
  });

  this.listen(channel + ':navigator:boot', function () {
    // FIXME: this is never being triggered; related to load order of scripts; modal works?
    self.load();
  });

  view.node.addEventListener('click', function (evt) {
    evt.preventDefault();
    self.load();
  });

  this.load = function () {
    if (!window.socket) {
      // TODO: not sure what we can do here
      return;
    }

    var items;
    if (input.value && input.value != '') {
      items = JSON.parse(input.value);
    }

    var opts = {
      uri: uri,
      context: channel,
      container: 'default',
      items: items || []
    }

    window.history.pushState(opts, uri, uri);

    // listen for a choice to be made
    self.listen('media-editor:changed', function (items) {
      self.transform(items);
    });
  };

  this.close = function () {
    self.ignore('media-editor:changed');

    if (blinder) {
      pw.node.remove(blinder);
      blinder = null;
    }

    media = null;
  };

  this.transform = function (items) {
    var i = view.node.querySelector('i');

    if (items.length == 0) {
      if (!i) {
        pw.node.append(view.node, icon.cloneNode(true));
      }

      view.node.style.backgroundImage = null;
    } else if (items.length == 1) {
      if (i) {
        pw.node.remove(i);
      }

      var firstItem = items[0];

      var constraints = pw.node.scope(view.node).constraints;
      if (constraints) {
        var resizedScaleFactor = constraints.width / view.node.offsetWidth;
        var constrainedHeight = constraints.height / resizedScaleFactor;
        view.node.style.height = (constrainedHeight) + 'px';
        view.node.style.backgroundImage = "url('" + firstItem.thumb + "?w=" + view.node.offsetWidth + "&h=" + constrainedHeight + "')";
      }
    } else {
      //TODO decide how to display slideshows
    }

    view.node.querySelector('input').value = JSON.stringify(items);

    pw.component.broadcast('content-editor:changed');
  };
});
<|endoftext|>