<commit_before>(function () {
  window.SnakeGame = window.SnakeGame || {};

  var View = SnakeGame.View = function(el, options) {
    this.$el = $(el);
    this.$board = this.$el.find(".snake-game");
    this.board = new SnakeGame.Board(options);
    this.snake = this.board.snake;

    this.bindKeyHandlers();
  }

  View.prototype.start = function () {
    this.renderBoard();

    var render = function () {
      var pace = (7 + this.snake.segments.length);
      var score = this.board.score

      this.snake.move();
      this.renderSnake();
      this.renderApple();
      this.$el.find(".snake-score").text("Score: " + score);

      if (!this.board.isOver) {
        setTimeout(render.bind(this), 1000 / pace);
      }
    }
    setTimeout(render.bind(this), 1000 / 10);
  }

  View.prototype.renderBoard = function () {
    var board = this.board.render();

    board.forEach(function (row) {
      this.$board.append(row);
    }, this);
  }

  View.prototype.renderSnake = function () {
    this.$board.find("li").removeClass("snake");

    this.snake.segments.forEach(function (pos) {
      var id = "#" + pos[0] + "-" + pos[1];

      this.$board.find(id).addClass("snake");
    }, this);
  }

  View.prototype.renderApple = function () {
    this.$board.find("li").removeClass("apple");

    var applePos = this.board.applePos;
    var id = "#" + applePos[0] + "-" + applePos[1];
    this.$board.find(id).addClass("apple");
  }

  View.prototype.bindKeyHandlers = function () {
    var snake = this.snake;

    $("body").keydown(function (e) {
      e.preventDefault();

      if (e.keyCode == 38) {
        snake.changeDir("N");
      } else if (e.keyCode == 39) {
        snake.changeDir("E");
      } else if (e.keyCode == 40) {
        snake.changeDir("S");
      } else if (e.keyCode == 37) {
        snake.changeDir("W");
      }
    });
  }
})();
<commit_msg>Add ability to pause<commit_after>(function () {
  window.SnakeGame = window.SnakeGame || {};

  var View = SnakeGame.View = function(el, options) {
    this.$el = $(el);
    this.$board = this.$el.find(".snake-game");
    this.board = new SnakeGame.Board(options);
    this.snake = this.board.snake;
    this.paused = false;

    this.bindKeyHandlers();
  }

  View.prototype.start = function () {
    this.renderBoard();

    var render = function () {
      if (!this.paused) {
        var pace = (7 + this.snake.segments.length);
        var score = this.board.score

        this.snake.move();
        this.renderSnake();
        this.renderApple();
        this.$el.find(".snake-score").text("Score: " + score);
      }
      if (!this.board.isOver) {
        setTimeout(render.bind(this), 1000 / pace);
      }
    }
    setTimeout(render.bind(this), 1000 / 10);
  }

  View.prototype.renderBoard = function () {
    var board = this.board.render();

    board.forEach(function (row) {
      this.$board.append(row);
    }, this);
  }

  View.prototype.renderSnake = function () {
    this.$board.find("li").removeClass("snake");

    this.snake.segments.forEach(function (pos) {
      var id = "#" + pos[0] + "-" + pos[1];

      this.$board.find(id).addClass("snake");
    }, this);
  }

  View.prototype.renderApple = function () {
    this.$board.find("li").removeClass("apple");

    var applePos = this.board.applePos;
    var id = "#" + applePos[0] + "-" + applePos[1];
    this.$board.find(id).addClass("apple");
  }

  View.prototype.bindKeyHandlers = function () {
    var view = this;
    var snake = this.snake;

    $("body").keydown(function (e) {
      e.preventDefault();

      if (e.keyCode == 38) {
        snake.changeDir("N");
      } else if (e.keyCode == 39) {
        snake.changeDir("E");
      } else if (e.keyCode == 40) {
        snake.changeDir("S");
      } else if (e.keyCode == 37) {
        snake.changeDir("W");
      } else if (e.keyCode == 32) {
        view.paused = (view.paused ? false : true);
      }
    });
  }
})();
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

import Quill from 'quill';
import Delta from 'quill-delta';

import _ from 'lodash';

const toolbarOptions = [
  ['bold', 'italic', 'underline'],
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }],
  // [{ 'font': [] }],
  // ['blockquote', 'code-block'],
  // [{ 'header': 1 }, { 'header': 2 }],
  // [{ 'indent': '-1'}, { 'indent': '+1' }],
  // [{ 'direction': 'rtl' }],
  // [{ 'size': ['small', false, 'large', 'huge'] }],
  // [{ 'align': [] }],
  // ['clean'],
];

export default class QuillEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      // Editor contents
      value: props.value,
    };

    this.theme = props.theme;
    if (!props.theme || props.theme === '') this.theme = 'snow';

    this.readOnly = true;
    if (!props.disabled || props.disabled === false) this.readOnly = false;

    this.height = props.height;
    if (!props.height || props.height === '') this.height = '230px';

    this.toolbar = (props.toolbarSymbol || []).map(x => x.name);

    this.editor = false;
    this.id = _.uniqueId('quill-editor-');

    this.getContents = this.getContents.bind(this);
    this.updateEditorValue = this.updateEditorValue.bind(this);
    this.debouncedOnChange = _.debounce(this.props.onChange.bind(this), 300);
    this.onChange = this.onChange.bind(this);
  }

  componentWillMount() {
  }

  componentDidMount() {
    this.initQuill();
  }

  componentWillReceiveProps(nextProps) {
    const nextVal = nextProps.value;
    const oldContents = this.editor ? this.getContents() : null;

    if (oldContents && nextVal &&
      !_.isEqual(nextVal.ops, oldContents.ops)) {
      this.setState({ value: nextVal });
      const sel = this.editor.getSelection();
      this.editor.setContents(nextVal);
      if (sel) this.editor.setSelection(sel);
    }
  }

  componentWillUpdate() {
    this.componentWillUnmount();
  }

  componentDidUpdate() {
    this.componentDidMount();
  }

  componentWillUnmount() {
    // Don't set the state to null, it would generate a loop.
  }

  onChange(val) {
    this.props.onChange(val);
  }

  getContents() {
    if (this.editor) return this.editor.getContents();

    return null;
  }

  updateEditorValue(contents, bounce = true) {
    this.setState({
      value: contents,
    }, bounce ? this.debouncedOnChange(contents) : this.onChange(contents));
  }

  initQuill() {
    if (!this.editor) {
      const quillEditor = ReactDOM.findDOMNode(this.refs[this.id]);

      const quillOptions = {
        modules: {
          toolbar: `#toolbar-${this.id}`,
        },
        theme: this.theme,
        readOnly: this.readOnly,
      };

      // init Quill
      this.editor = new Quill(quillEditor, quillOptions);
      const { value } = this.state;
      if (value) this.editor.setContents(value);

      // Resolve compability with Grammarly Chrome add-on
      // Fromm https://github.com/quilljs/quill/issues/574
      // let GrammarlyInline = Quill.import('blots/inline');
      // GrammarlyInline.tagName = 'G';
      // GrammarlyInline.blotName = 'grammarly-inline';
      // GrammarlyInline.className = 'gr_';
      // Quill.register({'formats/grammarly-inline': GrammarlyInline})

      this.editor.on('text-change', (delta, oldDelta, source) => {
        if (source === 'user' && this.props.onChange) {
          const contents = this.getContents();
          this.updateEditorValue(contents);
        }
      });

      const updateEditorValue = this.updateEditorValue;
      const editor = this.editor;
      const id = this.id;
      const toolbarSymbol = this.props.toolbarSymbol;

      this.toolbar.forEach((element) => {
        const selector = `#toolbar-${id} #${element}_id`;
        const btn = document.querySelector(selector);

        btn.addEventListener('click', () => {
          const range = editor.getSelection();

          if (range) {
            let contents = editor.getContents();
            let elementOps = toolbarSymbol.find(x => x.name === element).ops;
            const insertDelta = new Delta(elementOps);
            elementOps = [{ retain: range.index }].concat(elementOps);
            const elementDelta = new Delta(elementOps);
            contents = contents.compose(elementDelta);

            editor.setContents(contents);

            range.length = 0;
            range.index += insertDelta.length();
            editor.setSelection(range);

            updateEditorValue(contents, false);
          }
        });
      });
    }
  }

  renderQuillToolbarGroup() {
    if (this.theme !== 'snow') return ();

    const quillToolbar = toolbarOptions.map((formatGroup, index) => {
      const groupElement = formatGroup.map((element) => {
        if (typeof element === 'string') {
          return (
            <button
              className={`ql-${element}`}
              key={`btnKey_${element}`}
            />
          );
        } else if (typeof element === 'object') {
          const elementName = Object.getOwnPropertyNames(element)[0];
          const elementValue = element[elementName];

          if (typeof elementValue === 'string') {
            return (
              <button
                className={`ql-${elementName}`}
                key={`btnKey_${elementValue}`}
                value={elementValue}
              />
            );
          } else if (Array.isArray(elementValue)) {
            const options = elementValue.map(e => <option value={e} key={`opt_${e}`} />);
            return (
              <select
                className={`ql-${elementName}`}
                key={`btnKey_${elementName}`}
              >
                {options}
              </select>
            );
          }
        }

        return ();
      });

      return (
        <span
          className="ql-formats"
          key={`sp_${index}`}
        >
          {groupElement}

      );
    });

    return quillToolbar;
  }

  renderCustomToolbar() {
    if (this.theme !== 'snow' || !this.toolbar || this.toolbar.length === 0) {
      return ();
    }

    const customToolbarElement = this.toolbar.map(element => (
      <button
        className={`icon-${element}`}
        key={`${element}_key`}
        id={`${element}_id`}
        style={{ margin: '0px 3px 3px 3px' }}
      />
    ));

    return (

        { customToolbarElement }

    );
  }

  render() {
    const quillToolbar = this.renderQuillToolbarGroup();

    return (

        <div id={`toolbar-${this.id}`}>
          {quillToolbar}
          {this.renderCustomToolbar()}

    );
  }
}

QuillEditor.propTypes = {
  value: React.PropTypes.object,
  toolbarSymbol: React.PropTypes.array,
  theme: React.PropTypes.string,
  height: React.PropTypes.string,
  disabled: React.PropTypes.bool,
  onChange: React.PropTypes.func,
};

QuillEditor.defaultProps = {
  value: {},
  toolbarSymbol: [],
  theme: 'snow',
  height: '230px',
  disabled: true,
  onChange: null,
};
<commit_msg>Enable QuillEditor by default<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

import Quill from 'quill';
import Delta from 'quill-delta';

import _ from 'lodash';

const toolbarOptions = [
  ['bold', 'italic', 'underline'],
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }],
  // [{ 'font': [] }],
  // ['blockquote', 'code-block'],
  // [{ 'header': 1 }, { 'header': 2 }],
  // [{ 'indent': '-1'}, { 'indent': '+1' }],
  // [{ 'direction': 'rtl' }],
  // [{ 'size': ['small', false, 'large', 'huge'] }],
  // [{ 'align': [] }],
  // ['clean'],
];

export default class QuillEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      // Editor contents
      value: props.value,
    };

    this.theme = props.theme;
    if (!props.theme || props.theme === '') this.theme = 'snow';

    this.readOnly = true;
    if (!props.disabled || props.disabled === false) this.readOnly = false;

    this.height = props.height;
    if (!props.height || props.height === '') this.height = '230px';

    this.toolbar = (props.toolbarSymbol || []).map(x => x.name);

    this.editor = false;
    this.id = _.uniqueId('quill-editor-');

    this.getContents = this.getContents.bind(this);
    this.updateEditorValue = this.updateEditorValue.bind(this);
    this.debouncedOnChange = _.debounce(this.props.onChange.bind(this), 300);
    this.onChange = this.onChange.bind(this);
  }

  componentWillMount() {
  }

  componentDidMount() {
    this.initQuill();
  }

  componentWillReceiveProps(nextProps) {
    const nextVal = nextProps.value;
    const oldContents = this.editor ? this.getContents() : null;

    if (oldContents && nextVal &&
      !_.isEqual(nextVal.ops, oldContents.ops)) {
      this.setState({ value: nextVal });
      const sel = this.editor.getSelection();
      this.editor.setContents(nextVal);
      if (sel) this.editor.setSelection(sel);
    }
  }

  componentWillUpdate() {
    this.componentWillUnmount();
  }

  componentDidUpdate() {
    this.componentDidMount();
  }

  componentWillUnmount() {
    // Don't set the state to null, it would generate a loop.
  }

  onChange(val) {
    this.props.onChange(val);
  }

  getContents() {
    if (this.editor) return this.editor.getContents();

    return null;
  }

  updateEditorValue(contents, bounce = true) {
    this.setState({
      value: contents,
    }, bounce ? this.debouncedOnChange(contents) : this.onChange(contents));
  }

  initQuill() {
    if (!this.editor) {
      const quillEditor = ReactDOM.findDOMNode(this.refs[this.id]);

      const quillOptions = {
        modules: {
          toolbar: `#toolbar-${this.id}`,
        },
        theme: this.theme,
        readOnly: this.readOnly,
      };

      // init Quill
      this.editor = new Quill(quillEditor, quillOptions);
      const { value } = this.state;
      if (value) this.editor.setContents(value);

      // Resolve compability with Grammarly Chrome add-on
      // Fromm https://github.com/quilljs/quill/issues/574
      // let GrammarlyInline = Quill.import('blots/inline');
      // GrammarlyInline.tagName = 'G';
      // GrammarlyInline.blotName = 'grammarly-inline';
      // GrammarlyInline.className = 'gr_';
      // Quill.register({'formats/grammarly-inline': GrammarlyInline})

      this.editor.on('text-change', (delta, oldDelta, source) => {
        if (source === 'user' && this.props.onChange) {
          const contents = this.getContents();
          this.updateEditorValue(contents);
        }
      });

      const updateEditorValue = this.updateEditorValue;
      const editor = this.editor;
      const id = this.id;
      const toolbarSymbol = this.props.toolbarSymbol;

      this.toolbar.forEach((element) => {
        const selector = `#toolbar-${id} #${element}_id`;
        const btn = document.querySelector(selector);

        btn.addEventListener('click', () => {
          const range = editor.getSelection();

          if (range) {
            let contents = editor.getContents();
            let elementOps = toolbarSymbol.find(x => x.name === element).ops;
            const insertDelta = new Delta(elementOps);
            elementOps = [{ retain: range.index }].concat(elementOps);
            const elementDelta = new Delta(elementOps);
            contents = contents.compose(elementDelta);

            editor.setContents(contents);

            range.length = 0;
            range.index += insertDelta.length();
            editor.setSelection(range);

            updateEditorValue(contents, false);
          }
        });
      });
    }
  }

  renderQuillToolbarGroup() {
    if (this.theme !== 'snow') return ();

    const quillToolbar = toolbarOptions.map((formatGroup, index) => {
      const groupElement = formatGroup.map((element) => {
        if (typeof element === 'string') {
          return (
            <button
              className={`ql-${element}`}
              key={`btnKey_${element}`}
            />
          );
        } else if (typeof element === 'object') {
          const elementName = Object.getOwnPropertyNames(element)[0];
          const elementValue = element[elementName];

          if (typeof elementValue === 'string') {
            return (
              <button
                className={`ql-${elementName}`}
                key={`btnKey_${elementValue}`}
                value={elementValue}
              />
            );
          } else if (Array.isArray(elementValue)) {
            const options = elementValue.map(e => <option value={e} key={`opt_${e}`} />);
            return (
              <select
                className={`ql-${elementName}`}
                key={`btnKey_${elementName}`}
              >
                {options}
              </select>
            );
          }
        }

        return ();
      });

      return (
        <span
          className="ql-formats"
          key={`sp_${index}`}
        >
          {groupElement}

      );
    });

    return quillToolbar;
  }

  renderCustomToolbar() {
    if (this.theme !== 'snow' || !this.toolbar || this.toolbar.length === 0) {
      return ();
    }

    const customToolbarElement = this.toolbar.map(element => (
      <button
        className={`icon-${element}`}
        key={`${element}_key`}
        id={`${element}_id`}
        style={{ margin: '0px 3px 3px 3px' }}
      />
    ));

    return (

        { customToolbarElement }

    );
  }

  render() {
    const quillToolbar = this.renderQuillToolbarGroup();

    return (

        <div id={`toolbar-${this.id}`}>
          {quillToolbar}
          {this.renderCustomToolbar()}

    );
  }
}

QuillEditor.propTypes = {
  value: React.PropTypes.object,
  toolbarSymbol: React.PropTypes.array,
  theme: React.PropTypes.string,
  height: React.PropTypes.string,
  disabled: React.PropTypes.bool,
  onChange: React.PropTypes.func,
};

QuillEditor.defaultProps = {
  value: {},
  toolbarSymbol: [],
  theme: 'snow',
  height: '230px',
  disabled: false,
  onChange: null,
};
<|endoftext|>


<commit_before>var tree = {
  "objects": [
    {
      "type": "Rectangle",
      "attributes": [
        {
          "type": "NumericLiteral",
          "name": "width",
          "value": 364
        },
        {
          "type": "NumericLiteral",
          "name": "x",
          "value": 20
        },
        {
          "type": "StringLiteral",
          "name": "color",
          "value": "red"
        }
      ]
    },
    {
      "type": "Rectangle",
      "attributes": [
        {
          "type": "NumericLiteral",
          "name": "height",
          "value": 140
        },
        {
          "type": "StringLiteral",
          "name": "color",
          "value": "blue"
        },
        {
          "type": "Expression",
          "name": "y",
          "value": "this.x * 2"
        }
      ]
    }
  ],
  "imports": []
};

// TODO: Generic version, more useful returns
// TODO: Put inside module once tidied up
var getProperty = function(arr, key, keyField, valueField) {
  for(var i = 0; i < arr.length; i++) {
    if(arr[i][keyField] === key) {
      return arr[i][valueField];
    }
  }
  return null;
};

(function(window, document, undefined) {
  "use strict";

  var HQML = window.HQML || (window.HQML = {});

  var QObjects = {};

  QObjects.create = function(config) {
    var type = config.type,
        attr = config.attributes;

    if(!(type in QObjects)) {
      throw new TypeError(type + ' is not a valid QML Object');
    }

    // Inherit or create new
    var obj;
    if(QObjects[type].inherits) {
      obj = QObjects.create({
        type: QObjects[type].inherits,
        attributes: attr
      });
      for(var func in QObjects[type]) {
        obj[func] = QObjects[type][func];
      }
    }
    else {
      obj = Object.create(QObjects[type]);
    }

    // Add observable properties to object
    // Public access by name, private implementer on _
    if(!obj._) {
      Object.defineProperty(obj, '_', { value: {} });
    }

    for(var prop in QObjects[type].defaultProperties) {
      // TODO: When building AST, make bare references point to this /
      //       alternately combine AST in this stage to make sure references are valid
      // TODO: Handle properties with '.' in the name by created nested object
      // TODO: Create a computed if attribute type is an expression
      var isExpression = getProperty(attr, prop, 'name', 'type') === 'Expression',
          value = getProperty(attr, prop, 'name', 'value');
      if(isExpression) {
        (function(propName) {
          obj._[propName] = ko.computed({
            // TODO: Smarter generation of read
            read: new Function("return " + value),
            // Write function kills this computed and replaces it with an observable
            // TODO: Adding computed expressions at runtime must be done via Qt.binding
            write: function(v) {
              var oldExpr = this._[propName];
              this._[propName] = ko.observable(v);
              Object.defineProperty(this, propName, {
                get: this._[propName],
                set: this._[propName]
              });

              // Use the old computed to force subscribers to rebind on new observable
              oldExpr.notifySubscribers(v);
              oldExpr.dispose();
            },
            owner: obj,
            deferEvaluation: true
          });
        })(prop);
      }
      else {
        obj._[prop] = ko.observable(value !== null ? value : QObjects[type].defaultProperties[prop]);
      }

      Object.defineProperty(obj, prop, {
        enumerable: true,
        configurable: true,
        get: obj._[prop],
        set: obj._[prop]
      });
    }

    // Make 'update' a self-observer
    // TODO: Just implement this same as other QML expressions
    if(typeof QObjects[type].update === 'function') {
      obj.update = ko.computed({
        read: QObjects[type].update,
        owner: obj,
        deferEvaluation: true
      });
    }

    return obj;
  }

  // ---------------------- // TODO: Complete implementation / Document
  // QML Item
  QObjects.Item = {
    // TODO: Init function defining a layer, update which can move/resize it
  }

  Object.defineProperties(QObjects.Item, {
    defaultProperties: {
      value: {
        x: 0,
        y: 0,
        width: 100,
        height: 100
      }
    }
  });

  // ---------------------- // TODO: Complete implementation / Document
  // QML Rectangle
  QObjects.Rectangle = {
    // TODO: Layer should be created/managed by Rectangle, not passed in
    init: function(layer) {
      this._.kRect = new Kinetic.Rect({});
      layer.add(this._.kRect);
      this._.kLayer = layer;
    },
    update: function() {
      // TODO: Maybe QObjects.create should automatically create subscribers for simple props?
      this._.kRect.setX(this.x);
      this._.kRect.setY(this.y);
      this._.kRect.setWidth(this.width);
      this._.kRect.setHeight(this.height);
      this._.kRect.setFill(this.color);
      this._.kRect.setCornerRadius(this.radius);
      this._.kLayer.batchDraw();
    }
  }

  Object.defineProperties(QObjects.Rectangle, {
    inherits: {
      value: 'Item'
    },
    defaultProperties: {
      value: {
        color: 'black',
        radius: 0
      }
    }
  });

  // Exports
  HQML.load = function() {
    var stage = new Kinetic.Stage({
      container: 'container',
      width: 800,
      height: 600
    });

    var layer = new Kinetic.Layer();

    tree.objects.forEach(function(obj) {
      if(obj.type in QObjects) {

        var thisObj = QObjects.create(obj);

        thisObj.init(layer);
        thisObj.update();
        // TODO: init/update should be fired by QObjects.create at end of inheritance chain

        window.r = thisObj;
      }
    });

    // add the layer to the stage
    stage.add(layer);
  }

})(window, document);

// TODO: onload
HQML.load();
<commit_msg>Prepare objects for hierarchal structure<commit_after>var tree = {
  "objects": [
    {
      "attributes": [
        {
          "type": "NumericLiteral",
          "name": "y",
          "value": 20
        },
        {
          "type": "NumericLiteral",
          "name": "width",
          "value": 300
        },
        {
          "type": "NumericLiteral",
          "name": "height",
          "value": 300
        },
        {
          "type": "StringLiteral",
          "name": "color",
          "value": "blue"
        },
        {
          "type": "NumericLiteral",
          "name": "x",
          "value": 30
        }
      ],
      "children": [
        {
          "attributes": [
            {
              "type": "NumericLiteral",
              "name": "width",
              "value": 100
            },
            {
              "type": "NumericLiteral",
              "name": "height",
              "value": 100
            },
            {
              "type": "StringLiteral",
              "name": "color",
              "value": "green"
            },
            {
              "type": "NumericLiteral",
              "name": "x",
              "value": 40
            }
          ],
          "type": "Rectangle"
        }
      ],
      "type": "Rectangle"
    }
  ],
  "imports": [
    {
      "name": "QtQuick",
      "version": "2.0",
      "as": ""
    }
  ]
};

// TODO: Generic version, more useful returns
// TODO: Put inside module once tidied up
var getProperty = function(arr, key, keyField, valueField) {
  for(var i = 0; i < arr.length; i++) {
    if(arr[i][keyField] === key) {
      return arr[i][valueField];
    }
  }
  return null;
};

(function(window, document, undefined) {
  "use strict";

  var HQML = window.HQML || (window.HQML = {});

  var QObjects = {};

  QObjects.create = function(config) {
    var type = config.type,
        attr = config.attributes;

    if(!(type in QObjects)) {
      throw new TypeError(type + ' is not a valid QML Object');
    }

    // Inherit or create new
    var obj;
    if(QObjects[type].inherits) {
      obj = QObjects.create({
        type: QObjects[type].inherits,
        attributes: attr
      });
      for(var func in QObjects[type]) {
        obj[func] = QObjects[type][func];
      }
    }
    else {
      obj = Object.create(QObjects[type]);
    }

    // Add observable properties to object
    // Public access by name, private implementer on _
    if(!obj._) {
      Object.defineProperty(obj, '_', { value: {} });
    }

    for(var prop in QObjects[type].defaultProperties) {
      // TODO: When building AST, make bare references point to this /
      //       alternately combine AST in this stage to make sure references are valid
      // TODO: Handle properties with '.' in the name by created nested object
      // TODO: Create a computed if attribute type is an expression
      var isExpression = getProperty(attr, prop, 'name', 'type') === 'Expression',
          value = getProperty(attr, prop, 'name', 'value');
      if(isExpression) {
        (function(propName) {
          obj._[propName] = ko.computed({
            // TODO: Smarter generation of read
            read: new Function("return " + value),
            // Write function kills this computed and replaces it with an observable
            // TODO: Adding computed expressions at runtime must be done via Qt.binding
            write: function(v) {
              var oldExpr = this._[propName];
              this._[propName] = ko.observable(v);
              Object.defineProperty(this, propName, {
                get: this._[propName],
                set: this._[propName]
              });

              // Use the old computed to force subscribers to rebind on new observable
              oldExpr.notifySubscribers(v);
              oldExpr.dispose();
            },
            owner: obj,
            deferEvaluation: true
          });
        })(prop);
      }
      else {
        obj._[prop] = ko.observable(value !== null ? value : QObjects[type].defaultProperties[prop]);
      }

      Object.defineProperty(obj, prop, {
        enumerable: true,
        configurable: true,
        get: obj._[prop],
        set: obj._[prop]
      });
    }

    // Make 'update' a self-observer
    // TODO: Just implement this same as other QML expressions
    if(typeof QObjects[type].update === 'function') {
      obj.update = ko.computed({
        read: QObjects[type].update,
        owner: obj,
        deferEvaluation: true
      });
    }

    return obj;
  }

  // ---------------------- // TODO: Complete implementation / Document
  // QML Item
  QObjects.Item = {
    // TODO: Init function defining a layer, update which can move/resize it
  }

  Object.defineProperties(QObjects.Item, {
    defaultProperties: {
      value: {
        x: 0,
        y: 0,
        width: 100,
        height: 100
      }
    }
  });

  // ---------------------- // TODO: Complete implementation / Document
  // QML Rectangle
  QObjects.Rectangle = {
    init: function() {
      // TODO: Should this be group or layer? infer based on anim etc?
      this._.kNode = new Kinetic.Group();
      this._.kRect = new Kinetic.Rect();
      this._.kNode.add(this._.kRect);
      try {
        this.parent._.kNode.add(this._.kNode);
      }
      catch (e) {
        // Throw 'Rectangle cannot be child of parent.type'
      }
      this.update();
    },
    update: function() {
      // TODO: Maybe QObjects.create should automatically create subscribers for simple props?
      this._.kNode.setX(this.x);
      this._.kNode.setY(this.y);

      this._.kRect.setWidth(this.width);
      this._.kRect.setHeight(this.height);
      this._.kRect.setFill(this.color);
      this._.kRect.setCornerRadius(this.radius);

      this.draw();
    },
    draw: function() {
      this.parent.draw();
    }
  }

  Object.defineProperties(QObjects.Rectangle, {
    inherits: {
      value: 'Item'
    },
    defaultProperties: {
      value: {
        color: 'black',
        radius: 0
      }
    }
  });

  // Exports
  HQML.load = function() {
    // TODO: Move root definition into module, use init params for dimensions/name
    var root = {
      init: function() {
        // TODO: User definable name, width, height
        var stage = new Kinetic.Stage({
          container: 'container',
          width: 800,
          height: 600
        });
        this._ = { kNode: new Kinetic.Layer() };
        stage.add(this._.kNode);
      },
      draw: function() {
        this._.kNode.batchDraw();
      }
    }

    root.init();

    window.q = []; // TMP
    tree.objects.forEach(function(obj) {
      if(obj.type in QObjects) {

        var thisObj = QObjects.create(obj);

        thisObj.parent = root;
        thisObj.init();
        // TODO: init/parent assignment should be done by QObjects.create at end of inheritance chain

        // TMP: Expose to outside world
        window.q.push(thisObj);
      }
    });
  }

})(window, document);

// TODO: onload
HQML.load();
<|endoftext|>


<commit_before>const text = (function () {
  function getCurrentTimeZoneData(time, timeZoneData) {
    const utcHours = time.getUTCHours();

    if (utcHours >= 5 && utcHours <= 23) {
      return timeZoneData[ 17 - utcHours ];
    }
    else {
      return timeZoneData[ -7 - utcHours ]
    }
  }

  function replaceSpacesWithPlus(string) {
    return string.replace(/\s/g, '+');
  }

  function getGoogleMapsLink(city, country) {
    return `https://www.google.com.au/maps/search/${replaceSpacesWithPlus(city)},+${replaceSpacesWithPlus(country)}`;
  }

  function setAnswerAndPhrase(time, timeZoneData) {
    const answer = document.querySelector('#answer');
    const phraseEl = document.querySelector('#phrase');

    if (tools.isPastBeerOClock(time)) {
      answer.innerHTML = `<strong>It's well past beer o'clock where you're now, mate!</strong>`;
      phraseEl.innerText = 'Get your drink on! Cheers!';
    } else {
      const { city, country, phrase, lang } = getCurrentTimeZoneData(time, timeZoneData);
      answer.innerHTML = `<strong>It's beer o'clock in <a role="link" href="${getGoogleMapsLink(city, country)}" rel="_blank" rel="noopener nofollow">${city}, ${country}</a></strong>.`;
      phraseEl.innerText = `${phrase} (That's "Cheers!" in ${lang})!`;
    }
  }

  return {
    setAnswerAndPhrase,
    init(time, timeZoneData) {
      setTimeout(() => tools.fadeIn('#answer'), 1000);
      setTimeout(() => tools.fadeIn('#phrase'), 1500);

      setAnswerAndPhrase(time, timeZoneData);
    }
  }
})();
<commit_msg>open maps link in new tab<commit_after>const text = (function () {
  function getCurrentTimeZoneData(time, timeZoneData) {
    const utcHours = time.getUTCHours();

    if (utcHours >= 5 && utcHours <= 23) {
      return timeZoneData[ 17 - utcHours ];
    }
    else {
      return timeZoneData[ -7 - utcHours ]
    }
  }

  function replaceSpacesWithPlus(string) {
    return string.replace(/\s/g, '+');
  }

  function getGoogleMapsLink(city, country) {
    return `https://www.google.com.au/maps/search/${replaceSpacesWithPlus(city)},+${replaceSpacesWithPlus(country)}`;
  }

  function setAnswerAndPhrase(time, timeZoneData) {
    const answer = document.querySelector('#answer');
    const phraseEl = document.querySelector('#phrase');

    if (tools.isPastBeerOClock(time)) {
      answer.innerHTML = `<strong>It's well past beer o'clock where you're now, mate!</strong>`;
      phraseEl.innerText = 'Get your drink on! Cheers!';
    } else {
      const { city, country, phrase, lang } = getCurrentTimeZoneData(time, timeZoneData);
      answer.innerHTML = `<strong>It's beer o'clock in <a role="link" href="${getGoogleMapsLink(city, country)}" target="_blank" rel="noopener nofollow">${city}, ${country}</a></strong>.`;
      phraseEl.innerText = `${phrase} (That's "Cheers!" in ${lang})!`;
    }
  }

  return {
    setAnswerAndPhrase,
    init(time, timeZoneData) {
      setTimeout(() => tools.fadeIn('#answer'), 1000);
      setTimeout(() => tools.fadeIn('#phrase'), 1500);

      setAnswerAndPhrase(time, timeZoneData);
    }
  }
})();
<|endoftext|>


<commit_before>// tick.js - time formatting library
// author: Ben Meier (AstromechZA)
//
// The goal of this library is to provide a small and simplified
// date time display library.

(function(undefined){
	var tick,
		globalScope = typeof global !== 'undefined' ? global : this,
		longDays = [
			'Sunday',
			'Monday',
			'Tuesday',
			'Wednesday',
			'Thursday',
			'Friday',
			'Saturday'
		],
		longMonths = [
			'January',
			'February',
			'March',
			'April',
			'May',
			'June',
			'July',
			'August',
			'September',
			'October',
			'November',
			'December'
		]

	function Tick(input) {
		this._d = buildFrom(input);
		this._YYYY = this._d.getFullYear();
		this._MM = zeroPad(this._d.getMonth()+1, 2);
		this._D = ''+this._d.getDate();
		this._DD = zeroPad(this._d.getDate(), 2);
		this._hh = zeroPad(this._d.getHours(), 2);
		this._mm = zeroPad(this._d.getMinutes(), 2);
		this._ss = zeroPad(this._d.getSeconds(), 2);
		this._zzz = zeroPad(this._d.getMilliseconds(), 3);
		this._tz = timeZone(this._d.getTimezoneOffset());
		this._day = longDays[this._d.getDay()];
		this._month = longMonths[this._d.getMonth()];
	}

	Tick.prototype.toString = function(format) {
		if (format === undefined) format = '%dd %month %YYYY %hh:%mm:%ss.%zzz %tz'

		ns = format.replace('%YYYY', this._YYYY)
		ns = ns.replace('%MM', this._MM)
		ns = ns.replace('%dd', this._D)
		ns = ns.replace('%DD', this._DD)
		ns = ns.replace('%hh', this._hh)
		ns = ns.replace('%mm', this._mm)
		ns = ns.replace('%ss', this._ss)
		ns = ns.replace('%zzz', this._zzz)
		ns = ns.replace('%tz', this._tz)
		ns = ns.replace('%dayofweek', this._day)
		return ns.replace('%month', this._month)
	};

	Tick.prototype.toISO8601 = function() {
		return "" + this._YYYY + "-" + this._MM + "-" + this._DD +
			"T" + this._hh + ":" + this._mm + ":" + this._ss + "." + this._zzz + this._tz;
	}

	Tick.prototype.eq = function(other) {
		if (typeof(input) == 'string') return new Date(other).valueOf() == this.valueOf();

		return other.valueOf() == this.valueOf();
	}

	Tick.prototype.valueOf = function() {
		return this._d.valueOf();
	}

	// copy to new object, shift display values to specific timezone
	Tick.prototype.shiftTo = function(tzoffset) {
		ms = this.valueOf() + this._d.getTimezoneOffset() * 60000 - tzoffset * 60000
		r = new Tick(ms)
		r._d = new Date(this.valueOf())
		r._tz = timeZone(tzoffset)
		return r
	}

	Tick.prototype.add = function(milliseconds) {
		return new Tick(this.valueOf() + milliseconds)
	}

	Tick.prototype.subtract = function(milliseconds) {
		return this.add(-milliseconds)
	}

	function timeZone(offset) {
		if (offset == 0) return '+00:00';
		v = Math.abs(offset);
		return ((offset > 0) ? "-" : "+") + zeroPad(v / 60, 2) + ":" + zeroPad(v % 60, 2);
	}

	function buildFrom(input) {
		if(input === undefined) {
			return new Date();
		} else if (isDate(input)) {
			return new Date(+input);
		} else if (typeof(input) == 'number') {
			return new Date(input);
		} else if (typeof(input) == 'string') {
			return new Date(input);
		}
	}

	function isDate(input) {
        return  Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
    }

    function zeroPad(n, l) {
    	n = n + '';
    	nl = n.length;
    	return nl >= l ? n : new Array(l-nl+1).join('0') + n;
    }

	tick = function(input) {
		return new Tick(input);
	}

	globalScope.tick = tick
}).call(this);<commit_msg>added timezone code name infrastructure<commit_after>// tick.js - time formatting library
// author: Ben Meier (AstromechZA)
//
// The goal of this library is to provide a small and simplified
// date time display library.

(function(undefined){
	var tick,
		globalScope = typeof global !== 'undefined' ? global : this,
		longDays = [
			'Sunday',
			'Monday',
			'Tuesday',
			'Wednesday',
			'Thursday',
			'Friday',
			'Saturday'
		],
		longMonths = [
			'January',
			'February',
			'March',
			'April',
			'May',
			'June',
			'July',
			'August',
			'September',
			'October',
			'November',
			'December'
		],
		parsableTZ = /((?:UTC)|(?:GMT))(?:([+-])(\d\d?)(?::(\d\d))?)?/,
		otherTZs = {
			'PST' : 480,
			'SAST' : -120,
			'PDT' : 420
		}

	function Tick(input) {
		this._d = buildFrom(input)
		this._YYYY = this._d.getFullYear()
		this._MM = zeroPad(this._d.getMonth()+1, 2)
		this._D = ''+this._d.getDate()
		this._DD = zeroPad(this._d.getDate(), 2)
		this._hh = zeroPad(this._d.getHours(), 2)
		this._mm = zeroPad(this._d.getMinutes(), 2)
		this._ss = zeroPad(this._d.getSeconds(), 2)
		this._zzz = zeroPad(this._d.getMilliseconds(), 3)
		this._tz = timeZone(this._d.getTimezoneOffset())
		this._day = longDays[this._d.getDay()]
		this._month = longMonths[this._d.getMonth()]

		this._knownTimezoneOffset = this._d.getTimezoneOffset()
	}

	Tick.prototype.toString = function(format) {
		if (format === undefined) format = '%dd %month %YYYY %hh:%mm:%ss.%zzz %tz'

		ns = format.replace('%YYYY', this._YYYY)
		ns = ns.replace('%MM', this._MM)
		ns = ns.replace('%dd', this._D)
		ns = ns.replace('%DD', this._DD)
		ns = ns.replace('%hh', this._hh)
		ns = ns.replace('%mm', this._mm)
		ns = ns.replace('%ss', this._ss)
		ns = ns.replace('%zzz', this._zzz)
		ns = ns.replace('%tz', this._tz)
		ns = ns.replace('%dayofweek', this._day)
		return ns.replace('%month', this._month)
	};

	Tick.prototype.toISO8601 = function() {
		return "" + this._YYYY + "-" + this._MM + "-" + this._DD +
			"T" + this._hh + ":" + this._mm + ":" + this._ss + "." + this._zzz + this._tz;
	}

	Tick.prototype.eq = function(other) {
		if (typeof(input) == 'string') return new Date(other).valueOf() == this.valueOf();

		return other.valueOf() == this.valueOf();
	}

	Tick.prototype.valueOf = function() {
		return this._d.valueOf();
	}

	// copy to new object, shift display values to specific timezone with the given offset minutes
	Tick.prototype.shiftToOffset = function(tzoffset) {
		if (typeof tzoffset != 'number') return null
		r = new Tick(this.valueOf() + this._knownTimezoneOffset * 60000 - tzoffset * 60000)
		r._d = new Date(this.valueOf())
		r._tz = timeZone(tzoffset)
		r._knownTimezoneOffset = tzoffset
		return r
	}

	Tick.prototype.shiftToTZ = function(tzstring) {
		m = parsableTZ.exec(tzstring)
		if (m != null) {
			m[2] = m[2] || ''
			m[3] = m[3] || ''
			m[4] = m[4] || ''
			offset = ((m[2] == '+') ? -1 : 1) * Number(m[3]) * 60 + Number(m[4])
			return this.shiftToOffset(offset)
		}
		if (tzstring in otherTZs) return this.shiftToOffset(otherTZs[tzstring])
		return null;
	}

	Tick.prototype.add = function(milliseconds) {
		return new Tick(this.valueOf() + milliseconds)
	}

	Tick.prototype.subtract = function(milliseconds) {
		return this.add(-milliseconds)
	}

	function timeZone(offset) {
		if (offset == 0) return '+00:00';
		v = Math.abs(offset);
		return ((offset > 0) ? "-" : "+") + zeroPad(Math.floor(v / 60), 2) + ":" + zeroPad(v % 60, 2);
	}

	function buildFrom(input) {
		if(input === undefined) {
			return new Date();
		} else if (isDate(input)) {
			return new Date(+input);
		} else if (typeof(input) == 'number') {
			return new Date(input);
		} else if (typeof(input) == 'string') {
			return new Date(input);
		}
	}

	function isDate(input) {
        return  Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
    }

    function zeroPad(n, l) {
    	n = n + '';
    	nl = n.length;
    	return nl >= l ? n : new Array(l-nl+1).join('0') + n;
    }

	tick = function(input) {
		return new Tick(input);
	}

	globalScope.tick = tick
}).call(this);<|endoftext|>


<commit_before>var io = require('socket.io');
var express = require('express');
var connect = require('connect');
var routes = require('routes');
var http = require('http');
var cookie = require('express/node_modules/cookie');
var parseSignedCookie = connect.utils.parseSignedCookie;
var fs = require('fs');
var util = require('util');
var uuid = require('node-uuid');
var url = require('url');

var cookiesecret = "SOMERANDOMCHARACTERS";

function HTTPServer() {
  var self = this;
  this.permissions = {};
  this.permissionsReqStartsWith = {};
  this.userSockets = {};
  this.uploadPath = "html/img/photo/raw/"

  this.http = express();
  this.http.configure(function(){
    self.http.use(express.compress());
    self.http.use(express.static('html'));

    self.http.use(express.bodyParser());
    self.http.use(express.methodOverride());

    self.http.use(express.cookieParser());
    self.http.use(express.session({secret: cookiesecret, key: 'sid'}));

  });

  this.http.configure('development', function(){
    self.http.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  this.http.configure('production', function(){
    self.http.use(express.errorHandler());
  });

  this.httpserver = http.createServer(this.http).listen(7777);
  this.socketio = io.listen(this.httpserver, { log: false });

  this.socketio.on('connection', function (socket) {
  });
<commit_msg>added a few request handler to http interface<commit_after>var io = require('socket.io');
var express = require('express');
var connect = require('connect');
var routes = require('routes');
var http = require('http');
var cookie = require('express/node_modules/cookie');
var parseSignedCookie = connect.utils.parseSignedCookie;
var fs = require('fs');
var util = require('util');
var uuid = require('node-uuid');
var url = require('url');

var cookiesecret = "SOMERANDOMCHARACTERS";

function HTTPServer() {
  var self = this;
  this.permissions = {};
  this.permissionsReqStartsWith = {};
  this.userSockets = {};
  this.uploadPath = "html/img/photo/raw/"

  this.http = express();
  this.http.configure(function(){
    self.http.use(express.compress());
    self.http.use(express.static('html'));

    self.http.use(express.bodyParser());
    self.http.use(express.methodOverride());

    self.http.use(express.cookieParser());
    self.http.use(express.session({secret: cookiesecret, key: 'sid'}));

  });

  this.http.configure('development', function(){
    self.http.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  });

  this.http.configure('production', function(){
    self.http.use(express.errorHandler());
  });

  this.httpserver = http.createServer(this.http).listen(7777);
  this.socketio = io.listen(this.httpserver, { log: false });

  this.socketio.on('connection', function (socket) {
  });

  self.http.post("/api/newuser", function(req, res) {
    console.log("newuser: " + req.body.name);
    if (req.body.name) {
      app.redis.get("mpd:" + req.body.name, function (err, obj) {
         if (obj === null) {
           app.redis.set("mpd:" + req.body.name, {}, function (err, obj) {
             res.send("ok");
           });
         }
         else {
           res.send("notok");
         }
      });
    }
    else {
      res.send("notok");
    }
  });

  self.http.get("/api/getplaylist", function(req, res) {
    res.send({ songs: app.playlist.songs });
  });

  self.http.get("/api/getcurrentsong", function(req, res) {
    res.send(app.player.currentsong);
  });

  self.http.get("/api/getwishlist", function(req, res) {
    res.send({ songs: app.wishlist.globalWishlist });
  });

  self.http.get("/api/getphotowishlist", function(req, res) {
    res.send({ photos: app.photowishlist.wishlist });
  });

  self.http.post("/api/search", function(req, res) {
    app.search.search(req.body.query, function(result) {
      console.log(result);

      res.send(result);
    });
  });

}
module.exports = new HTTPServer();
<|endoftext|>


<commit_before>/**
* KBase Reads viewer.
* A widget for viewing info about a KBaseFile.PairedEndLibrary or KBaseFile.SingleEndLibrary
* @public
*/
define ([
    'bluebird',
    'kbwidget',
    'bootstrap',
    'jquery',
    'kbaseAuthenticatedWidget',
    'narrativeConfig',
    'kbase-client-api',
    'util/string',
    'util/display',
    'kbase-generic-client-api'
], function (
    Promise,
    KBWidget,
    bootstrap,
    $,
    kbaseAuthenticatedWidget,
    Config,
    KBaseClientApi,
    StringUtil,
    DisplayUtil,
    GenericClient
) {
    'use strict';
    return KBWidget({
        /*
        * (required) Your widget should be named in CamelCase.
        */
        name: 'kbaseDefaultNarrativeOutput',
        parent : kbaseAuthenticatedWidget,
        version: "1.0.0",
        token: null,
        width: 1150,
        options: {
            wsId: null,
            wsName: null,
            objId: null,
            jobId: null,
            data: null
        },

        init: function(options) {
            this._super(options);
//            this.wsUrl = Config.url('workspace');
            return this;
        },

        render: function() {
            if (this.options._obj_info) {
                this.reference =  this.options.wsName + '/' + this.options.objId + '/' + this.options._obj_info['version'];
            } else {
                this.reference =  this.options.wsName + '/' + this.options.objId;
            }
 //           Promise.resolve(this.wsClient.get_objects([{ref: this.reference}]))
 //          Promise.resolve(this.client.get_reads_info_all([{ref: this.reference}]))
            Promise.resolve(this.client.sync_call("ReadsAPI.get_reads_info_all_formatted",[{workspace_obj_ref: this.reference}]))
            .then(function(results) {
                this.reads = results[0];
                //		this.$elem.append('
' + JSON.stringify(this.reads) + '
');
                this.renderBasicTable();
            }.bind(this))
            .catch(function(error) {
                var errorMsg = 'No further information available',
                    errorTrace = undefined;
                console.error("Render Function Error : ", error);
                if (error && typeof error === 'object') {
                    if(error.error) {
                        errorMsg = JSON.stringify(error.error);
                        if(error.error.message) {
                            errorMsg = error.error.message;
                            if(error.error.error) {
                                errorTrace = error.error.error;
                            }
                        } else {
                            errorMsg = JSON.stringify(error.error);
                        }
                    } else {
                        errorMsg = error.message;
                    }
                }
                else {
                    errorMsg = "Undefined error";
                }
                this.$elem.append(
                    DisplayUtil.createError(
                        'Sorry, an error occurred while retrieving your data',
                        errorMsg,
                        errorTrace
                    ));
            }.bind(this));

            return this;
        },

        renderBasicTable: function() {
            var $container = this.$elem,
                reads_type = '',
                tab_ids = {
                    'overview': 'reads-overview-' + StringUtil.uuid(),
                    'stats': 'reads-stats-' + StringUtil.uuid()
                },
                $tabs = $('
' +
                    '
Overview
' +
                    '
Stats
' +
                    '
'
                ),
                $divs = $('
'),
                $overviewTable = $('
').append($('<colgroup>').append('<col span="1" style="width: 25%">')),
                $statsTable = $('
').append($('<colgroup>').append('<col span="1" style="width: 25%">'));

            function get_table_row(key, value) {
                return $('
').append($('').append($('' + key + ''))).append($('').append(value));
            }
            // Build the overview table

            $overviewTable.append(get_table_row(
                'Name',
                '' +
                this.reads["Name"] +''
            ));
            // leave out version for now, because that is not passed into data widgets

            $overviewTable.append(get_table_row('Number of Reads', this.reads['Number_of_Reads']));
            $statsTable.append(get_table_row('Number of Reads', this.reads['Number_of_Reads']));

            $overviewTable.append(get_table_row('Type', this.reads["Type"]));

            /* KEEP COMMENTED OUT UNTIL UPLOADER WEB FORM ALLOWS THE USER TO SPECIFY
            if(this.reads["data"].hasOwnProperty("read_size")){
                $overviewTable.append(get_table_row('Read Size', this.reads["data"]['read_size'].toLocaleString() ));
            }else{
                $overviewTable.append(get_table_row('Read Size', "Not Specified"));
            }
            if (this.reads["data"].hasOwnProperty("strain")) {
                $overviewTable.append(get_table_row('Species/Taxa', this.reads["data"]['strain']['genus'] + " " +
                this.reads["data"]['strain']['species'] + " " +
                this.reads["data"]['strain']['strain'] ));
            }
            else {
                $overviewTable.append(get_table_row('Species/Taxa', 'Not specified' ));
            }
 *///Put in end comments

            $overviewTable.append(get_table_row('Platform', this.reads['Platform'] ));
            $overviewTable.append(get_table_row('Single Genome', this.reads['Single_Genome'] ));

            if (this.reads["Type"] === "Paired End") {
                $overviewTable.append(get_table_row('Insert Size Mean', this.reads['Insert_Size_Mean'] ));
                $overviewTable.append(get_table_row('Insert Size Std Dev', this.reads['Insert_Size_Std_Dev'] ));
                $overviewTable.append(get_table_row('Outward Read Orientation', this.reads['Outward_Read_Orientation'] ));
            }
            $divs.append($('
').append($overviewTable));

            //Stats portion
            $statsTable.append(get_table_row('Total Number of Bases', this.reads['Total_Number_of_Bases']));
            $statsTable.append(get_table_row('Mean Read Length', this.reads['Mean_Read_Length']));
            $statsTable.append(get_table_row('Read Length Std Dev', this.reads['Read_Length_Std_Dev']));
            $statsTable.append(get_table_row('Number of Duplicate Reads(%)',this.reads['Number_of_Duplicate_Reads']));
            $statsTable.append(get_table_row('Phred Type', this.reads['Phred_Type']));
            $statsTable.append(get_table_row('Quality Score Mean (Std Dev)',this.reads['Quality_Score_Mean_Std_Dev']));
            $statsTable.append(get_table_row('Quality Score (Min/Max)',this.reads['Quality_Score_Min_Max']));
            $statsTable.append(get_table_row('GC Percentage', this.reads['GC_Percentage']));
            $statsTable.append(get_table_row('Base Percentages', this.reads['Base_Percentages']));

            $divs.append($('
').append($statsTable));
            $container.append($tabs);
            $container.append($divs);

        },

        loggedInCallback: function(event, auth) {
            this.token = auth.token;

//            this.wsClient = new Workspace(this.wsUrl, auth);
            this.url = Config.url('service_wizard');
            this.client = new GenericClient(this.url, auth); // just put this where the workspace client init code is
            this.render();
            return this;
        },

        loggedOutCallback: function(event, auth) {
            this.token = null;
            this.render();
            return this;
        },

    });
});
<commit_msg>Reads viewer now uses reads API<commit_after>/**
* KBase Reads viewer.
* A widget for viewing info about a KBaseFile.PairedEndLibrary or KBaseFile.SingleEndLibrary
* @public
*/
define ([
    'bluebird',
    'kbwidget',
    'bootstrap',
    'jquery',
    'kbaseAuthenticatedWidget',
    'narrativeConfig',
    'kbase-client-api',
    'util/string',
    'util/display',
    'kbase-generic-client-api'
], function (
    Promise,
    KBWidget,
    bootstrap,
    $,
    kbaseAuthenticatedWidget,
    Config,
    KBaseClientApi,
    StringUtil,
    DisplayUtil,
    GenericClient
) {
    'use strict';
    return KBWidget({
        /*
        * (required) Your widget should be named in CamelCase.
        */
        name: 'kbaseDefaultNarrativeOutput',
        parent : kbaseAuthenticatedWidget,
        version: "1.0.0",
        token: null,
        width: 1150,
        options: {
            wsId: null,
            wsName: null,
            objId: null,
            jobId: null,
            data: null
        },

        init: function(options) {
            this._super(options);
            return this;
        },

        render: function() {
            if (this.options._obj_info) {
                this.reference =  this.options.wsName + '/' + this.options.objId + '/' + this.options._obj_info['version'];
            } else {
                this.reference =  this.options.wsName + '/' + this.options.objId;
            }
            Promise.resolve(this.client.sync_call("ReadsAPI.get_reads_info_all_formatted",[{workspace_obj_ref: this.reference}]))
            .then(function(results) {
                this.reads = results[0];
                //		this.$elem.append('
' + JSON.stringify(this.reads) + '
');
                this.renderBasicTable();
            }.bind(this))
            .catch(function(error) {
                var errorMsg = 'No further information available',
                    errorTrace = undefined;
                console.error("Render Function Error : ", error);
                if (error && typeof error === 'object') {
                    if(error.error) {
                        errorMsg = JSON.stringify(error.error);
                        if(error.error.message) {
                            errorMsg = error.error.message;
                            if(error.error.error) {
                                errorTrace = error.error.error;
                            }
                        } else {
                            errorMsg = JSON.stringify(error.error);
                        }
                    } else {
                        errorMsg = error.message;
                    }
                }
                else {
                    errorMsg = "Undefined error";
                }
                this.$elem.append(
                    DisplayUtil.createError(
                        'Sorry, an error occurred while retrieving your data',
                        errorMsg,
                        errorTrace
                    ));
            }.bind(this));

            return this;
        },

        renderBasicTable: function() {
            var $container = this.$elem,
                reads_type = '',
                tab_ids = {
                    'overview': 'reads-overview-' + StringUtil.uuid(),
                    'stats': 'reads-stats-' + StringUtil.uuid()
                },
                $tabs = $('
' +
                    '
Overview
' +
                    '
Stats
' +
                    '
'
                ),
                $divs = $('
'),
                $overviewTable = $('
').append($('<colgroup>').append('<col span="1" style="width: 25%">')),
                $statsTable = $('
').append($('<colgroup>').append('<col span="1" style="width: 25%">'));

            function get_table_row(key, value) {
                return $('
').append($('').append($('' + key + ''))).append($('').append(value));
            }
            // Build the overview table

            $overviewTable.append(get_table_row(
                'Name',
                '' +
                this.reads["Name"] +''
            ));
            // leave out version for now, because that is not passed into data widgets

            $overviewTable.append(get_table_row('Number of Reads', this.reads['Number_of_Reads']));
            $statsTable.append(get_table_row('Number of Reads', this.reads['Number_of_Reads']));

            $overviewTable.append(get_table_row('Type', this.reads["Type"]));

            /* KEEP COMMENTED OUT UNTIL UPLOADER WEB FORM ALLOWS THE USER TO SPECIFY
            if(this.reads["data"].hasOwnProperty("read_size")){
                $overviewTable.append(get_table_row('Read Size', this.reads["data"]['read_size'].toLocaleString() ));
            }else{
                $overviewTable.append(get_table_row('Read Size', "Not Specified"));
            }
            if (this.reads["data"].hasOwnProperty("strain")) {
                $overviewTable.append(get_table_row('Species/Taxa', this.reads["data"]['strain']['genus'] + " " +
                this.reads["data"]['strain']['species'] + " " +
                this.reads["data"]['strain']['strain'] ));
            }
            else {
                $overviewTable.append(get_table_row('Species/Taxa', 'Not specified' ));
            }
            */

            $overviewTable.append(get_table_row('Platform', this.reads['Platform'] ));
            $overviewTable.append(get_table_row('Single Genome', this.reads['Single_Genome'] ));

            if (this.reads["Type"] === "Paired End") {
                $overviewTable.append(get_table_row('Insert Size Mean', this.reads['Insert_Size_Mean'] ));
                $overviewTable.append(get_table_row('Insert Size Std Dev', this.reads['Insert_Size_Std_Dev'] ));
                $overviewTable.append(get_table_row('Outward Read Orientation', this.reads['Outward_Read_Orientation'] ));
            }
            $divs.append($('
').append($overviewTable));

            //Stats portion
            $statsTable.append(get_table_row('Total Number of Bases', this.reads['Total_Number_of_Bases']));
            $statsTable.append(get_table_row('Mean Read Length', this.reads['Mean_Read_Length']));
            $statsTable.append(get_table_row('Read Length Std Dev', this.reads['Read_Length_Std_Dev']));
            $statsTable.append(get_table_row('Number of Duplicate Reads(%)',this.reads['Number_of_Duplicate_Reads']));
            $statsTable.append(get_table_row('Phred Type', this.reads['Phred_Type']));
            $statsTable.append(get_table_row('Quality Score Mean (Std Dev)',this.reads['Quality_Score_Mean_Std_Dev']));
            $statsTable.append(get_table_row('Quality Score (Min/Max)',this.reads['Quality_Score_Min_Max']));
            $statsTable.append(get_table_row('GC Percentage', this.reads['GC_Percentage']));
            $statsTable.append(get_table_row('Base Percentages', this.reads['Base_Percentages']));

            $divs.append($('
').append($statsTable));
            $container.append($tabs);
            $container.append($divs);

        },

        loggedInCallback: function(event, auth) {
            this.token = auth.token;

            this.url = Config.url('service_wizard');
            this.client = new GenericClient(this.url, auth); // just put this where the workspace client init code is
            this.render();
            return this;
        },

        loggedOutCallback: function(event, auth) {
            this.token = null;
            this.render();
            return this;
        },

    });
});
<|endoftext|>


<commit_before>var capturePhoto = (function(app) {
    "use strict";

    app.Views.OsmSelect = Backbone.Layout.extend({
        template: "#osm-selector-page",

        afterRender: function() {
            // Adding {manage: true} to BB.Form failed, hence this manual subview
            var form = new Backbone.Form({model: app.models.pic, fields: ['osmid']});
            this.$el.find('.osm-selector').empty().append(form.render().$el);
        }
    });

    app.Views.Capture = Backbone.View.extend({
        manage: true,

        initialize : function() {
            this.template = _.template($('#capture-template').html());
        },

        events: {
			"click button#capture": "capturePhoto",
			"click button#save" : "savePhoto",
			"click button#captureEdit": "capturePhotoEdit",
			"click button#getphotoFromLibrary": "getPhoto"
        },

        capturePhoto: function() {
			// Take picture using device camera and retrieve image as base64-encoded string
            navigator.camera.getPicture(app.utils.onPhotoDataSuccess, app.utils.onFail, {
                quality: 50,
                destinationType: navigator.camera.DestinationType.DATA_URL
            });
        },

        savePhoto: function() {
            navigator.camera.getPicture(app.utils.onPhotoFileSuccess, app.utils.onFail, {
                quality: 50,
                destinationType: navigator.camera.DestinationType.FILE_URI
            });
        },

        capturePhotoEdit : function() {
            // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
            navigator.camera.getPicture(app.utils.onPhotoDataSuccess, app.utils.onFail, {
                quality: 20,
                allowEdit: true,
                destinationType: navigator.camera.DestinationType.DATA_URL
            });
        },

        getPhoto : function() {
            // Retrieve image file location from specified source
            navigator.camera.getPicture(app.utils.onPhotoURISuccess, app.utils.onFail, {
                quality: 50,
                destinationType: navigator.camera.DestinationType.FILE_URI,
                sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
            });
        }
    });

    return app;
})(capturePhoto);<commit_msg>Enable or disable capture button depending on feature selection state<commit_after>var capturePhoto = (function(app) {
    "use strict";

    app.Views.OsmSelect = Backbone.Layout.extend({
        template: "#osm-selector-page",

        afterRender: function() {
            // Adding {manage: true} to BB.Form failed, hence this manual subview
            var form = new Backbone.Form({model: app.models.pic, fields: ['osmid']});
            form.on('osmid:change', _.bind(this.onOsmSelectChange, this));
            this.$el.find('.osm-selector').empty().append(form.render().$el);
        },

        onOsmSelectChange: function(form, editor) {
            var val = editor.getValue();
            this.$el.find('.osm-selector-buttons button').prop('disabled', (val === null));
        }
    });

    app.Views.Capture = Backbone.View.extend({
        manage: true,

        initialize : function() {
            this.template = _.template($('#capture-template').html());
        },

        events: {
			"click button#capture": "capturePhoto",
			"click button#save" : "savePhoto",
			"click button#captureEdit": "capturePhotoEdit",
			"click button#getphotoFromLibrary": "getPhoto"
        },

        capturePhoto: function() {
			// Take picture using device camera and retrieve image as base64-encoded string
            navigator.camera.getPicture(app.utils.onPhotoDataSuccess, app.utils.onFail, {
                quality: 50,
                destinationType: navigator.camera.DestinationType.DATA_URL
            });
        },

        savePhoto: function() {
            navigator.camera.getPicture(app.utils.onPhotoFileSuccess, app.utils.onFail, {
                quality: 50,
                destinationType: navigator.camera.DestinationType.FILE_URI
            });
        },

        capturePhotoEdit : function() {
            // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
            navigator.camera.getPicture(app.utils.onPhotoDataSuccess, app.utils.onFail, {
                quality: 20,
                allowEdit: true,
                destinationType: navigator.camera.DestinationType.DATA_URL
            });
        },

        getPhoto : function() {
            // Retrieve image file location from specified source
            navigator.camera.getPicture(app.utils.onPhotoURISuccess, app.utils.onFail, {
                quality: 50,
                destinationType: navigator.camera.DestinationType.FILE_URI,
                sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
            });
        }
    });

    return app;
})(capturePhoto);<|endoftext|>


<commit_before>// phantomjs script to convert any html to quill compliant html.
//
// @input
//   a filename containing the input markup as the first argument to the script
//
// @output
//   the converted html printed to stdout
//
// @example
//   $ phantomjs quill_format.js /tmp/content.html

var system = require('system');
var fs = require('fs');
var Quill = require('../../../../vendor/assets/bower_components/quill/quill.js');

// create a div to initialize quill
var container = document.createElement('div');
document.body.appendChild(container);

// the input is read from the file provided by the first argument
var content = fs.read(system.args[1]);

// use quill's api to convert the html
var quill = new Quill(container);
content = quill.clipboard.dangerouslyPasteHTML(content, 'silent');
quill.update();

// output the result to stdout
console.log(quill.root.innerHTML);

phantom.exit();
<commit_msg>use react npm path for quill.js in format script<commit_after>// phantomjs script to convert any html to quill compliant html.
//
// @input
//   a filename containing the input markup as the first argument to the script
//
// @output
//   the converted html printed to stdout
//
// @example
//   $ phantomjs quill_format.js /tmp/content.html

var system = require('system');
var fs = require('fs');
var Quill = require('../../../../client/node_modules/quill/dist/quill.js');

// create a div to initialize quill
var container = document.createElement('div');
document.body.appendChild(container);

// the input is read from the file provided by the first argument
var content = fs.read(system.args[1]);

// use quill's api to convert the html
var quill = new Quill(container);
content = quill.clipboard.dangerouslyPasteHTML(content, 'silent');
quill.update();

// output the result to stdout
console.log(quill.root.innerHTML);

phantom.exit();
<|endoftext|>


<commit_before>/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */

//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2010
//
// tier.js: (try) to encapsulate the functionality of a browser tier.
//

var __tier_idSeed = 0;

function DasTier(browser, source, viewport, background)
{
    var thisTier = this;

    this.id = 'tier' + (++__tier_idSeed);
    this.browser = browser;
    this.dasSource = new DASSource(source);
    this.viewport = viewport;
    this.background = background;
    this.req = null;
    this.layoutHeight = 50;
    this.bumped = true;
    if (this.dasSource.collapseSuperGroups) {
        this.bumped = false;
    }
    this.y = 0;

    if (this.dasSource.tier_type == 'sequence') {
	this.refreshTier = refreshTier_sequence;
    } else {
	this.refreshTier = refreshTier_features;
    }

    this.layoutWasDone = false;

    var fs;
    if (this.dasSource.bwgURI) {
        fs = new BWGFeatureSource(this.dasSource.bwgURI);
    } else {
        fs = new DASFeatureSource(this.dasSource);
    }

    if (this.dasSource.mapping) {
        fs = new MappedFeatureSource(fs, this.browser.chains[this.dasSource.mapping]);
    }

    this.featureSource = fs;
}

DasTier.prototype.toString = function() {
    return this.id;
}

DasTier.prototype.init = function() {
    var tier = this;

    if (tier.dasSource.bwgURI) {
        makeBwgFromURL(tier.dasSource.bwgURI, function(bwg) {
            tier.bwg = bwg;

            if (tier.dasSource.uri || tier.dasSource.stylesheet_uri) {
                tier.status = 'Fetching stylesheet';
                tier.dasSource.stylesheet(function(stylesheet) {
	            tier.stylesheet = stylesheet;
	            // tier.refreshTier();
                }, function() {
	            // tier.error = 'No stylesheet';
                    tier.stylesheet = new DASStylesheet();
                    var defStyle = new DASStyle();
                    defStyle.glyph = 'BOX';
                    defStyle.BGCOLOR = 'blue';
                    defStyle.FGCOLOR = 'black';
                    tier.stylesheet.pushStyle('default', null, defStyle);

	            // tier.refreshTier();
                });
            } else  if (tier.bwg.type == 'bigbed') {
                tier.stylesheet = new DASStylesheet();

                var wigStyle = new DASStyle();
                wigStyle.glyph = 'BOX';
                wigStyle.FGCOLOR = 'black';
                wigStyle.BGCOLOR = 'red'
                wigStyle.HEIGHT = 12;
                wigStyle.BUMP = true;
                wigStyle.LABEL = true;
                wigStyle.ZINDEX = 20;
                tier.stylesheet.pushStyle({type: 'default'}, null, wigStyle);

                var tsStyle = new DASStyle();
                tsStyle.glyph = 'BOX';
                tsStyle.FGCOLOR = 'black';
                tsStyle.BGCOLOR = 'white';
                tsStyle.ZINDEX = 10;
                tsStyle.BUMP = true;
                tier.stylesheet.pushStyle({type: 'bb-transcript'}, null, tsStyle);

                // tier.refreshTier();
            } else {
                tier.stylesheet = new DASStylesheet();
                var wigStyle = new DASStyle();
                wigStyle.glyph = 'HISTOGRAM';
                wigStyle.COLOR1 = 'white';
                wigStyle.COLOR2 = 'black';
                tier.stylesheet.pushStyle('default', null, wigStyle);

                // tier.refreshTier();
            }
        });
    } else {
        tier.status = 'Fetching stylesheet';
        this.dasSource.stylesheet(function(stylesheet) {
	    tier.stylesheet = stylesheet;
	    // tier.refreshTier();
        }, function() {
	    // tier.error = 'No stylesheet';
            tier.stylesheet = new DASStylesheet();
            var defStyle = new DASStyle();
            defStyle.glyph = 'BOX';
            defStyle.BGCOLOR = 'blue';
            defStyle.FGCOLOR = 'black';
            tier.stylesheet.pushStyle('default', null, defStyle);
	    // tier.refreshTier();
        });
    }
}

DasTier.prototype.styles = function(scale) {
    // alert('Old SS code called');
    if (this.stylesheet == null) {
	return null;
    } else if (this.browser.scale > 0.2) {
	return this.stylesheet.highZoomStyles;
    } else if (this.browser.scale > 0.01) {
	return this.stylesheet.mediumZoomStyles;
    } else {
	return this.stylesheet.lowZoomStyles;
    }
}

DasTier.prototype.getSource = function() {
    return this.featureSource;
}

DasTier.prototype.getDesiredTypes = function(scale) {
    return null;
}

DasTier.prototype.setStatus = function(status) {
    dlog(status);
}

DasTier.prototype.viewFeatures = function(chr, min, max, scale, features) {
    this.currentFeatures = features;
    this.knownStart = min; this.knownEnd = max;
    this.status = null; this.error = null;
    dasRequestComplete(this);
}

function refreshTier_sequence()
{
    var fetchStart = this.browser.knownStart;
    var fetchEnd = this.browser.knownEnd;
    if (this.browser.scale >= 1) {
	var tier = this;
        this.dasSource.sequence(
            new DASSegment(this.browser.chr, fetchStart, fetchEnd),
            function(seqs) {
                tier.knownStart = fetchStart; tier.knownEnd = fetchEnd;
                drawSeqTier(tier, seqs[0]);  // FIXME: check array.
                tier.setBackground();
		tier.originHaxx = 0;
            }
        );
    } else {
        this.knownStart = fetchStart; this.knownEnd = fetchEnd;
        drawSeqTier(this);
        this.setBackground();
	this.originHaxx = 0;
    }
}

function zoomForScale(scale) {
    var ssScale;
    if (scale > 0.2) {
        ssScale = 'high';
    } else if (scale > 0.01) {
        ssScale = 'medium';
    } else  {
        ssScale = 'low';
    }
    return ssScale;
}

function refreshTier_features()
{
    throw "refreshTier_features called"

    // var stylesheet = this.styles(this.browser.scale);
    var fetchTypes = [];
    var inclusive = false;
    var ssScale = zoomForScale(this.browser.scale);

    if (this.stylesheet) {
        var ss = this.stylesheet.styles;
        for (var si = 0; si < ss.length; ++si) {
            var sh = ss[si];
            if (!sh.zoom || sh.zoom == ssScale) {
                if (!sh.type || sh.type == 'default') {
                    inclusive = true;
                    break;
                } else {
                    pushnew(fetchTypes, sh.type);
                }
            }
        }
    }

    var scaledQuantRes = this.browser.targetQuantRes / this.browser.scale;
    var maxBins = 1 + (((this.browser.knownEnd - this.browser.knownStart) / scaledQuantRes) | 0);
    var fetchStart = this.browser.knownStart;
    var fetchEnd = this.browser.knownEnd;

    if (inclusive || fetchTypes.length > 0) {
	var tier = this;
	this.status = 'Fetching features';

        if (this.dasSource.bwgURI) {
            if (this.bwg) {
                this.bwg.readWigData(this.browser.chr, fetchStart, fetchEnd, function(features) {
                    dlog('got ' + features.length + ' features');
                    if (tier.bwg.type == 'bigwig' && features.length > maxBins) {
                        features = downsample(features, scaledQuantRes);
                        dlog('downsampled to ' + features.length);
                    }

                    tier.currentFeatures = features;
                    tier.error = null; tier.status = null;
                    tier.knownStart = fetchStart; tier.knownEnd = fetchEnd;
                    dasRequestComplete(tier);
                });
            }
        } else if (this.dasSource.mapping) {
            var mapping = this.browser.chains[this.dasSource.mapping];
            mapping.sourceBlocksForRange(this.browser.chr, fetchStart, fetchEnd, function(mseg) {
                if (mseg.length == 0) {
                    tier.currentFeatures = [];
                    tier.status = "No mapping available for this regions";
                    dasRequestComplete(tier);
                } else {
                    tier.dasSource.features(
                        mseg[0],
                        {type: (inclusive ? null : fetchTypes), maxbins: maxBins},
	                function(features, status) {
		            if (status) {
		                tier.error = status;
		            } else {
		                tier.error = null; tier.status = null;
		            }

                            var mappedFeatures = [];
                            for (var fi = 0; fi < features.length; ++fi) {
                                var f = features[fi];
                                var mmin = mapping.mapPoint(f.segment, f.min);
                                var mmax = mapping.mapPoint(f.segment, f.max);
                                if (!mmin || !mmax || mmin.seq != mmax.seq || mmin.seq != tier.browser.chr) {
                                    // Discard feature.
                                } else {
                                    f.segment = mmin.seq;
                                    f.min = mmin.pos;
                                    f.max = mmax.pos;
                                    if (f.min > f.max) {
                                        var tmp = f.max;
                                        f.max = f.min;
                                        f.min = tmp;
                                    }
                                    if (mmin.flipped) {
                                        if (f.orientation == '-') {
                                            f.orientation = '+';
                                            alert(miniJSONify(f));
                                        } else if (f.orientation == '+') {
                                            f.orientation = '-';
                                        }
                                    }
                                    mappedFeatures.push(f);
                                }
                            }
                            tier.currentFeatures = mappedFeatures;
                            tier.knownStart = fetchStart; tier.knownEnd = fetchEnd;
                            dasRequestComplete(tier);
	                }
                    );
                }
            });
        } else {
            this.dasSource.features(
	        new DASSegment(this.browser.chr, fetchStart, fetchEnd),
	        {type: (inclusive ? null : fetchTypes), maxbins: maxBins},
	        function(features, status) {
		    if (status) {
		        tier.error = status;
		    } else {
		        tier.error = null; tier.status = null;
		    }
                    tier.currentFeatures = features;
                    tier.knownStart = fetchStart; tier.knownEnd = fetchEnd;
                    dasRequestComplete(tier);
	        }
            );
        }
    } else {
	this.status = 'Nothing to show at this zoom level';
	this.currentFeatures = [];
	dasRequestComplete(this);
    }
}

DasTier.prototype.setBackground = function() {
    if (this.knownStart) {
        this.background.setAttribute('x', (this.knownStart - this.browser.origin) * this.browser.scale);
        this.background.setAttribute('width', (this.knownEnd - this.knownStart + 1) * this.browser.scale);
    }
}

function dasRequestComplete(tier)
{
    drawFeatureTier(tier);
    tier.originHaxx = 0;
    tier.setBackground();
    tier.browser.arrangeTiers();
}
<commit_msg>Clean up dead code from old refresh system.<commit_after>/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */

//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2010
//
// tier.js: (try) to encapsulate the functionality of a browser tier.
//

var __tier_idSeed = 0;

function DasTier(browser, source, viewport, background)
{
    var thisTier = this;

    this.id = 'tier' + (++__tier_idSeed);
    this.browser = browser;
    this.dasSource = new DASSource(source);
    this.viewport = viewport;
    this.background = background;
    this.req = null;
    this.layoutHeight = 50;
    this.bumped = true;
    if (this.dasSource.collapseSuperGroups) {
        this.bumped = false;
    }
    this.y = 0;

/*
    if (this.dasSource.tier_type == 'sequence') {
	this.refreshTier = refreshTier_sequence;
    } else {
	this.refreshTier = refreshTier_features;
    } */

    this.layoutWasDone = false;

    var fs;
    if (this.dasSource.bwgURI) {
        fs = new BWGFeatureSource(this.dasSource.bwgURI);

        if (!this.dasSource.uri && !this.dasSource.stylesheet_uri) {
            fs.bwgHolder.await(function(bwg) {
                if (bwg.type == 'bigbed') {
                    thisTier.stylesheet = new DASStylesheet();

                    var wigStyle = new DASStyle();
                    wigStyle.glyph = 'BOX';
                    wigStyle.FGCOLOR = 'black';
                    wigStyle.BGCOLOR = 'red'
                    wigStyle.HEIGHT = 12;
                    wigStyle.BUMP = true;
                    wigStyle.LABEL = true;
                    wigStyle.ZINDEX = 20;
                    thisTier.stylesheet.pushStyle({type: 'default'}, null, wigStyle);

                    var tsStyle = new DASStyle();
                    tsStyle.glyph = 'BOX';
                    tsStyle.FGCOLOR = 'black';
                    tsStyle.BGCOLOR = 'white';
                    tsStyle.ZINDEX = 10;
                    tsStyle.BUMP = true;
                    thisTier.stylesheet.pushStyle({type: 'bb-transcript'}, null, tsStyle);
                } else {
                    thisTier.stylesheet = new DASStylesheet();
                    var wigStyle = new DASStyle();
                    wigStyle.glyph = 'HISTOGRAM';
                    wigStyle.COLOR1 = 'white';
                    wigStyle.COLOR2 = 'black';
                    thisTier.stylesheet.pushStyle('default', null, wigStyle);
                }
            });
        }
    } else {
        fs = new DASFeatureSource(this.dasSource);
    }

    if (this.dasSource.mapping) {
        fs = new MappedFeatureSource(fs, this.browser.chains[this.dasSource.mapping]);
    }

    this.featureSource = fs;
}

DasTier.prototype.toString = function() {
    return this.id;
}

DasTier.prototype.init = function() {
    var tier = this;

    if (tier.dasSource.uri || tier.dasSource.stylesheet_uri) {
        tier.status = 'Fetching stylesheet';
        this.dasSource.stylesheet(function(stylesheet) {
	    tier.stylesheet = stylesheet;
        }, function() {
	    // tier.error = 'No stylesheet';
            tier.stylesheet = new DASStylesheet();
            var defStyle = new DASStyle();
            defStyle.glyph = 'BOX';
            defStyle.BGCOLOR = 'blue';
            defStyle.FGCOLOR = 'black';
            tier.stylesheet.pushStyle('default', null, defStyle);
        });
    }
}

DasTier.prototype.styles = function(scale) {
    // alert('Old SS code called');
    if (this.stylesheet == null) {
	return null;
    } else if (this.browser.scale > 0.2) {
	return this.stylesheet.highZoomStyles;
    } else if (this.browser.scale > 0.01) {
	return this.stylesheet.mediumZoomStyles;
    } else {
	return this.stylesheet.lowZoomStyles;
    }
}

DasTier.prototype.getSource = function() {
    return this.featureSource;
}

DasTier.prototype.getDesiredTypes = function(scale) {
    return null;
}

DasTier.prototype.setStatus = function(status) {
    dlog(status);
}

DasTier.prototype.viewFeatures = function(chr, min, max, scale, features) {
    this.currentFeatures = features;
    this.knownStart = min; this.knownEnd = max;
    this.status = null; this.error = null;
    dasRequestComplete(this);
}

function refreshTier_sequence()
{
    var fetchStart = this.browser.knownStart;
    var fetchEnd = this.browser.knownEnd;
    if (this.browser.scale >= 1) {
	var tier = this;
        this.dasSource.sequence(
            new DASSegment(this.browser.chr, fetchStart, fetchEnd),
            function(seqs) {
                tier.knownStart = fetchStart; tier.knownEnd = fetchEnd;
                drawSeqTier(tier, seqs[0]);  // FIXME: check array.
                tier.setBackground();
		tier.originHaxx = 0;
            }
        );
    } else {
        this.knownStart = fetchStart; this.knownEnd = fetchEnd;
        drawSeqTier(this);
        this.setBackground();
	this.originHaxx = 0;
    }
}

function zoomForScale(scale) {
    var ssScale;
    if (scale > 0.2) {
        ssScale = 'high';
    } else if (scale > 0.01) {
        ssScale = 'medium';
    } else  {
        ssScale = 'low';
    }
    return ssScale;
}

DasTier.prototype.setBackground = function() {
    if (this.knownStart) {
        this.background.setAttribute('x', (this.knownStart - this.browser.origin) * this.browser.scale);
        this.background.setAttribute('width', (this.knownEnd - this.knownStart + 1) * this.browser.scale);
    }
}

function dasRequestComplete(tier)
{
    drawFeatureTier(tier);
    tier.originHaxx = 0;
    tier.setBackground();
    tier.browser.arrangeTiers();
}
<|endoftext|>