<commit_before>/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Layout code for a vertical variant of the flyout.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.module('Blockly.VerticalFlyout');
goog.module.declareLegacyNamespace();

/* eslint-disable-next-line no-unused-vars */
const Coordinate = goog.requireType('Blockly.utils.Coordinate');
const DropDownDiv = goog.require('Blockly.DropDownDiv');
const Flyout = goog.require('Blockly.Flyout');
/* eslint-disable-next-line no-unused-vars */
const Options = goog.requireType('Blockly.Options');
const Rect = goog.require('Blockly.utils.Rect');
const Scrollbar = goog.require('Blockly.Scrollbar');
const WidgetDiv = goog.require('Blockly.WidgetDiv');
const registry = goog.require('Blockly.registry');
const {Position} = goog.require('Blockly.utils.toolbox');
const {getScrollDeltaPixels} = goog.require('Blockly.utils');
const {inherits} = goog.require('Blockly.utils.object');
/** @suppress {extraRequire} */
goog.require('Blockly.Block');
/** @suppress {extraRequire} */
goog.require('Blockly.constants');

/**
 * Class for a flyout.
 * @param {!Options} workspaceOptions Dictionary of options for the
 *     workspace.
 * @extends {Flyout}
 * @constructor
 */
const VerticalFlyout = function(workspaceOptions) {
  VerticalFlyout.superClass_.constructor.call(this, workspaceOptions);
};
inherits(VerticalFlyout, Flyout);

/**
 * The name of the vertical flyout in the registry.
 * @type {string}
 */
VerticalFlyout.registryName = 'verticalFlyout';

/**
 * Sets the translation of the flyout to match the scrollbars.
 * @param {!{x:number,y:number}} xyRatio Contains a y property which is a float
 *     between 0 and 1 specifying the degree of scrolling and a
 *     similar x property.
 * @protected
 */
VerticalFlyout.prototype.setMetrics_ = function(xyRatio) {
  if (!this.isVisible()) {
    return;
  }
  const metricsManager = this.workspace_.getMetricsManager();
  const scrollMetrics = metricsManager.getScrollMetrics();
  const viewMetrics = metricsManager.getViewMetrics();
  const absoluteMetrics = metricsManager.getAbsoluteMetrics();

  if (typeof xyRatio.y == 'number') {
    this.workspace_.scrollY =
        -(scrollMetrics.top +
            (scrollMetrics.height - viewMetrics.height) * xyRatio.y);
  }
  this.workspace_.translate(this.workspace_.scrollX + absoluteMetrics.left,
      this.workspace_.scrollY + absoluteMetrics.top);
};

/**
 * Calculates the x coordinate for the flyout position.
 * @return {number} X coordinate.
 */
VerticalFlyout.prototype.getX = function() {
  if (!this.isVisible()) {
    return 0;
  }
  const metricsManager = this.targetWorkspace.getMetricsManager();
  const absoluteMetrics = metricsManager.getAbsoluteMetrics();
  const viewMetrics = metricsManager.getViewMetrics();
  const toolboxMetrics = metricsManager.getToolboxMetrics();
  let x = 0;

  // If this flyout is not the trashcan flyout (e.g. toolbox or mutator).
  if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_) {
    // If there is a category toolbox.
    if (this.targetWorkspace.getToolbox()) {
      if (this.toolboxPosition_ == Position.LEFT) {
        x = toolboxMetrics.width;
      } else {
        x = viewMetrics.width - this.width_;
      }
      // Simple (flyout-only) toolbox.
    } else {
      if (this.toolboxPosition_ == Position.LEFT) {
        x = 0;
      } else {
        // The simple flyout does not cover the workspace.
        x = viewMetrics.width;
      }
    }
    // Trashcan flyout is opposite the main flyout.
  } else {
    if (this.toolboxPosition_ == Position.LEFT) {
      x = 0;
    } else {
      // Because the anchor point of the flyout is on the left, but we want
      // to align the right edge of the flyout with the right edge of the
      // blocklyDiv, we calculate the full width of the div minus the width
      // of the flyout.
      x = viewMetrics.width + absoluteMetrics.left - this.width_;
    }
  }

  return x;
};

/**
 * Calculates the y coordinate for the flyout position.
 * @return {number} Y coordinate.
 */
VerticalFlyout.prototype.getY = function() {
  // Y is always 0 since this is a vertical flyout.
  return 0;
};

/**
 * Move the flyout to the edge of the workspace.
 */
VerticalFlyout.prototype.position = function() {
  if (!this.isVisible() || !this.targetWorkspace.isVisible()) {
    return;
  }
  const metricsManager = this.targetWorkspace.getMetricsManager();
  const targetWorkspaceViewMetrics = metricsManager.getViewMetrics();

  // Record the height for workspace metrics.
  this.height_ = targetWorkspaceViewMetrics.height;

  const edgeWidth = this.width_ - this.CORNER_RADIUS;
  const edgeHeight = targetWorkspaceViewMetrics.height - 2 * this.CORNER_RADIUS;
  this.setBackgroundPath_(edgeWidth, edgeHeight);

  const x = this.getX();
  const y = this.getY();

  this.positionAt_(this.width_, this.height_, x, y);
};

/**
 * Create and set the path for the visible boundaries of the flyout.
 * @param {number} width The width of the flyout, not including the
 *     rounded corners.
 * @param {number} height The height of the flyout, not including
 *     rounded corners.
 * @private
 */
VerticalFlyout.prototype.setBackgroundPath_ = function(width, height) {
  const atRight = this.toolboxPosition_ == Position.RIGHT;
  const totalWidth = width + this.CORNER_RADIUS;

  // Decide whether to start on the left or right.
  const path = ['M ' + (atRight ? totalWidth : 0) + ',0'];
  // Top.
  path.push('h', atRight ? -width : width);
  // Rounded corner.
  path.push('a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0,
      atRight ? 0 : 1,
      atRight ? -this.CORNER_RADIUS : this.CORNER_RADIUS,
      this.CORNER_RADIUS);
  // Side closest to workspace.
  path.push('v', Math.max(0, height));
  // Rounded corner.
  path.push('a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0,
      atRight ? 0 : 1,
      atRight ? this.CORNER_RADIUS : -this.CORNER_RADIUS,
      this.CORNER_RADIUS);
  // Bottom.
  path.push('h', atRight ? width : -width);
  path.push('z');
  this.svgBackground_.setAttribute('d', path.join(' '));
};

/**
 * Scroll the flyout to the top.
 */
VerticalFlyout.prototype.scrollToStart = function() {
  this.workspace_.scrollbar.setY(0);
};

/**
 * Scroll the flyout.
 * @param {!Event} e Mouse wheel scroll event.
 * @protected
 */
VerticalFlyout.prototype.wheel_ = function(e) {
  const scrollDelta = getScrollDeltaPixels(e);

  if (scrollDelta.y) {
    const metricsManager = this.workspace_.getMetricsManager();
    const scrollMetrics = metricsManager.getScrollMetrics();
    const viewMetrics = metricsManager.getViewMetrics();
    const pos = (viewMetrics.top - scrollMetrics.top) + scrollDelta.y;

    this.workspace_.scrollbar.setY(pos);
    // When the flyout moves from a wheel event, hide WidgetDiv and DropDownDiv.
    WidgetDiv.hide();
    DropDownDiv.hideWithoutAnimation();
  }

  // Don't scroll the page.
  e.preventDefault();
  // Don't propagate mousewheel event (zooming).
  e.stopPropagation();
};

/**
 * Lay out the blocks in the flyout.
 * @param {!Array<!Object>} contents The blocks and buttons to lay out.
 * @param {!Array<number>} gaps The visible gaps between blocks.
 * @protected
 */
VerticalFlyout.prototype.layout_ = function(contents, gaps) {
  this.workspace_.scale = this.targetWorkspace.scale;
  const margin = this.MARGIN;
  const cursorX = this.RTL ? margin : margin + this.tabWidth_;
  let cursorY = margin;

  for (let i = 0, item; (item = contents[i]); i++) {
    if (item.type == 'block') {
      const block = item.block;
      const allBlocks = block.getDescendants(false);
      for (let j = 0, child; (child = allBlocks[j]); j++) {
        // Mark blocks as being inside a flyout.  This is used to detect and
        // prevent the closure of the flyout if the user right-clicks on such a
        // block.
        child.isInFlyout = true;
      }
      block.render();
      const root = block.getSvgRoot();
      const blockHW = block.getHeightWidth();
      const moveX = block.outputConnection ? cursorX - this.tabWidth_ : cursorX;
      block.moveBy(moveX, cursorY);

      const rect = this.createRect_(block,
          this.RTL ? moveX - blockHW.width : moveX, cursorY, blockHW, i);

      this.addBlockListeners_(root, block, rect);

      cursorY += blockHW.height + gaps[i];
    } else if (item.type == 'button') {
      this.initFlyoutButton_(item.button, cursorX, cursorY);
      cursorY += item.button.height + gaps[i];
    }
  }
};

/**
 * Determine if a drag delta is toward the workspace, based on the position
 * and orientation of the flyout. This is used in determineDragIntention_ to
 * determine if a new block should be created or if the flyout should scroll.
 * @param {!Coordinate} currentDragDeltaXY How far the pointer has
 *     moved from the position at mouse down, in pixel units.
 * @return {boolean} True if the drag is toward the workspace.
 * @package
 */
VerticalFlyout.prototype.isDragTowardWorkspace = function(
    currentDragDeltaXY) {
  const dx = currentDragDeltaXY.x;
  const dy = currentDragDeltaXY.y;
  // Direction goes from -180 to 180, with 0 toward the right and 90 on top.
  const dragDirection = Math.atan2(dy, dx) / Math.PI * 180;

  const range = this.dragAngleRange_;
  // Check for left or right dragging.
  if ((dragDirection < range && dragDirection > -range) ||
      (dragDirection < -180 + range || dragDirection > 180 - range)) {
    return true;
  }
  return false;
};

/**
 * Returns the bounding rectangle of the drag target area in pixel units
 * relative to viewport.
 * @return {?Rect} The component's bounding box. Null if drag
 *   target area should be ignored.
 */
VerticalFlyout.prototype.getClientRect = function() {
  if (!this.svgGroup_ || this.autoClose || !this.isVisible()) {
    // The bounding rectangle won't compute correctly if the flyout is closed
    // and auto-close flyouts aren't valid drag targets (or delete areas).
    return null;
  }

  const flyoutRect = this.svgGroup_.getBoundingClientRect();
  // BIG_NUM is offscreen padding so that blocks dragged beyond the shown flyout
  // area are still deleted.  Must be larger than the largest screen size,
  // but be smaller than half Number.MAX_SAFE_INTEGER (not available on IE).
  const BIG_NUM = 1000000000;
  const left = flyoutRect.left;

  if (this.toolboxPosition_ == Position.LEFT) {
    const width = flyoutRect.width;
    return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, left + width);
  } else {  // Right
    return new Rect(-BIG_NUM, BIG_NUM, left, BIG_NUM);
  }
};

/**
 * Compute width of flyout.  Position mat under each block.
 * For RTL: Lay out the blocks and buttons to be right-aligned.
 * @protected
 */
VerticalFlyout.prototype.reflowInternal_ = function() {
  this.workspace_.scale = this.getFlyoutScale();
  let flyoutWidth = 0;
  const blocks = this.workspace_.getTopBlocks(false);
  for (let i = 0, block; (block = blocks[i]); i++) {
    let width = block.getHeightWidth().width;
    if (block.outputConnection) {
      width -= this.tabWidth_;
    }
    flyoutWidth = Math.max(flyoutWidth, width);
  }
  for (let i = 0, button; (button = this.buttons_[i]); i++) {
    flyoutWidth = Math.max(flyoutWidth, button.width);
  }
  flyoutWidth += this.MARGIN * 1.5 + this.tabWidth_;
  flyoutWidth *= this.workspace_.scale;
  flyoutWidth += Scrollbar.scrollbarThickness;

  if (this.width_ != flyoutWidth) {
    for (let i = 0, block; (block = blocks[i]); i++) {
      if (this.RTL) {
        // With the flyoutWidth known, right-align the blocks.
        const oldX = block.getRelativeToSurfaceXY().x;
        let newX = flyoutWidth / this.workspace_.scale - this.MARGIN;
        if (!block.outputConnection) {
          newX -= this.tabWidth_;
        }
        block.moveBy(newX - oldX, 0);
      }
      if (block.flyoutRect_) {
        this.moveRectToBlock_(block.flyoutRect_, block);
      }
    }
    if (this.RTL) {
      // With the flyoutWidth known, right-align the buttons.
      for (let i = 0, button; (button = this.buttons_[i]); i++) {
        const y = button.getPosition().y;
        const x = flyoutWidth / this.workspace_.scale - button.width -
            this.MARGIN - this.tabWidth_;
        button.moveTo(x, y);
      }
    }

    if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_ &&
        this.toolboxPosition_ == Position.LEFT &&
        !this.targetWorkspace.getToolbox()) {
      // This flyout is a simple toolbox. Reposition the workspace so that (0,0)
      // is in the correct position relative to the new absolute edge (ie
      // toolbox edge).
      this.targetWorkspace.translate(
          this.targetWorkspace.scrollX + flyoutWidth, this.targetWorkspace.scrollY);
    }

    // Record the width for workspace metrics and .position.
    this.width_ = flyoutWidth;
    this.position();
    this.targetWorkspace.recordDragTargets();
  }
};

registry.register(registry.Type.FLYOUTS_VERTICAL_TOOLBOX,
    registry.DEFAULT, VerticalFlyout);

exports = VerticalFlyout;
<commit_msg>clang-format core/flyout_vertical.js<commit_after>/**
 * @license
 * Copyright 2017 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Layout code for a vertical variant of the flyout.
 * @author fenichel@google.com (Rachel Fenichel)
 */
'use strict';

goog.module('Blockly.VerticalFlyout');
goog.module.declareLegacyNamespace();

/* eslint-disable-next-line no-unused-vars */
const Coordinate = goog.requireType('Blockly.utils.Coordinate');
const DropDownDiv = goog.require('Blockly.DropDownDiv');
const Flyout = goog.require('Blockly.Flyout');
/* eslint-disable-next-line no-unused-vars */
const Options = goog.requireType('Blockly.Options');
const Rect = goog.require('Blockly.utils.Rect');
const Scrollbar = goog.require('Blockly.Scrollbar');
const WidgetDiv = goog.require('Blockly.WidgetDiv');
const registry = goog.require('Blockly.registry');
const {Position} = goog.require('Blockly.utils.toolbox');
const {getScrollDeltaPixels} = goog.require('Blockly.utils');
const {inherits} = goog.require('Blockly.utils.object');
/** @suppress {extraRequire} */
goog.require('Blockly.Block');
/** @suppress {extraRequire} */
goog.require('Blockly.constants');

/**
 * Class for a flyout.
 * @param {!Options} workspaceOptions Dictionary of options for the
 *     workspace.
 * @extends {Flyout}
 * @constructor
 */
const VerticalFlyout = function(workspaceOptions) {
  VerticalFlyout.superClass_.constructor.call(this, workspaceOptions);
};
inherits(VerticalFlyout, Flyout);

/**
 * The name of the vertical flyout in the registry.
 * @type {string}
 */
VerticalFlyout.registryName = 'verticalFlyout';

/**
 * Sets the translation of the flyout to match the scrollbars.
 * @param {!{x:number,y:number}} xyRatio Contains a y property which is a float
 *     between 0 and 1 specifying the degree of scrolling and a
 *     similar x property.
 * @protected
 */
VerticalFlyout.prototype.setMetrics_ = function(xyRatio) {
  if (!this.isVisible()) {
    return;
  }
  const metricsManager = this.workspace_.getMetricsManager();
  const scrollMetrics = metricsManager.getScrollMetrics();
  const viewMetrics = metricsManager.getViewMetrics();
  const absoluteMetrics = metricsManager.getAbsoluteMetrics();

  if (typeof xyRatio.y == 'number') {
    this.workspace_.scrollY =
        -(scrollMetrics.top +
          (scrollMetrics.height - viewMetrics.height) * xyRatio.y);
  }
  this.workspace_.translate(
      this.workspace_.scrollX + absoluteMetrics.left,
      this.workspace_.scrollY + absoluteMetrics.top);
};

/**
 * Calculates the x coordinate for the flyout position.
 * @return {number} X coordinate.
 */
VerticalFlyout.prototype.getX = function() {
  if (!this.isVisible()) {
    return 0;
  }
  const metricsManager = this.targetWorkspace.getMetricsManager();
  const absoluteMetrics = metricsManager.getAbsoluteMetrics();
  const viewMetrics = metricsManager.getViewMetrics();
  const toolboxMetrics = metricsManager.getToolboxMetrics();
  let x = 0;

  // If this flyout is not the trashcan flyout (e.g. toolbox or mutator).
  if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_) {
    // If there is a category toolbox.
    if (this.targetWorkspace.getToolbox()) {
      if (this.toolboxPosition_ == Position.LEFT) {
        x = toolboxMetrics.width;
      } else {
        x = viewMetrics.width - this.width_;
      }
      // Simple (flyout-only) toolbox.
    } else {
      if (this.toolboxPosition_ == Position.LEFT) {
        x = 0;
      } else {
        // The simple flyout does not cover the workspace.
        x = viewMetrics.width;
      }
    }
    // Trashcan flyout is opposite the main flyout.
  } else {
    if (this.toolboxPosition_ == Position.LEFT) {
      x = 0;
    } else {
      // Because the anchor point of the flyout is on the left, but we want
      // to align the right edge of the flyout with the right edge of the
      // blocklyDiv, we calculate the full width of the div minus the width
      // of the flyout.
      x = viewMetrics.width + absoluteMetrics.left - this.width_;
    }
  }

  return x;
};

/**
 * Calculates the y coordinate for the flyout position.
 * @return {number} Y coordinate.
 */
VerticalFlyout.prototype.getY = function() {
  // Y is always 0 since this is a vertical flyout.
  return 0;
};

/**
 * Move the flyout to the edge of the workspace.
 */
VerticalFlyout.prototype.position = function() {
  if (!this.isVisible() || !this.targetWorkspace.isVisible()) {
    return;
  }
  const metricsManager = this.targetWorkspace.getMetricsManager();
  const targetWorkspaceViewMetrics = metricsManager.getViewMetrics();

  // Record the height for workspace metrics.
  this.height_ = targetWorkspaceViewMetrics.height;

  const edgeWidth = this.width_ - this.CORNER_RADIUS;
  const edgeHeight = targetWorkspaceViewMetrics.height - 2 * this.CORNER_RADIUS;
  this.setBackgroundPath_(edgeWidth, edgeHeight);

  const x = this.getX();
  const y = this.getY();

  this.positionAt_(this.width_, this.height_, x, y);
};

/**
 * Create and set the path for the visible boundaries of the flyout.
 * @param {number} width The width of the flyout, not including the
 *     rounded corners.
 * @param {number} height The height of the flyout, not including
 *     rounded corners.
 * @private
 */
VerticalFlyout.prototype.setBackgroundPath_ = function(width, height) {
  const atRight = this.toolboxPosition_ == Position.RIGHT;
  const totalWidth = width + this.CORNER_RADIUS;

  // Decide whether to start on the left or right.
  const path = ['M ' + (atRight ? totalWidth : 0) + ',0'];
  // Top.
  path.push('h', atRight ? -width : width);
  // Rounded corner.
  path.push(
      'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1,
      atRight ? -this.CORNER_RADIUS : this.CORNER_RADIUS, this.CORNER_RADIUS);
  // Side closest to workspace.
  path.push('v', Math.max(0, height));
  // Rounded corner.
  path.push(
      'a', this.CORNER_RADIUS, this.CORNER_RADIUS, 0, 0, atRight ? 0 : 1,
      atRight ? this.CORNER_RADIUS : -this.CORNER_RADIUS, this.CORNER_RADIUS);
  // Bottom.
  path.push('h', atRight ? width : -width);
  path.push('z');
  this.svgBackground_.setAttribute('d', path.join(' '));
};

/**
 * Scroll the flyout to the top.
 */
VerticalFlyout.prototype.scrollToStart = function() {
  this.workspace_.scrollbar.setY(0);
};

/**
 * Scroll the flyout.
 * @param {!Event} e Mouse wheel scroll event.
 * @protected
 */
VerticalFlyout.prototype.wheel_ = function(e) {
  const scrollDelta = getScrollDeltaPixels(e);

  if (scrollDelta.y) {
    const metricsManager = this.workspace_.getMetricsManager();
    const scrollMetrics = metricsManager.getScrollMetrics();
    const viewMetrics = metricsManager.getViewMetrics();
    const pos = (viewMetrics.top - scrollMetrics.top) + scrollDelta.y;

    this.workspace_.scrollbar.setY(pos);
    // When the flyout moves from a wheel event, hide WidgetDiv and DropDownDiv.
    WidgetDiv.hide();
    DropDownDiv.hideWithoutAnimation();
  }

  // Don't scroll the page.
  e.preventDefault();
  // Don't propagate mousewheel event (zooming).
  e.stopPropagation();
};

/**
 * Lay out the blocks in the flyout.
 * @param {!Array<!Object>} contents The blocks and buttons to lay out.
 * @param {!Array<number>} gaps The visible gaps between blocks.
 * @protected
 */
VerticalFlyout.prototype.layout_ = function(contents, gaps) {
  this.workspace_.scale = this.targetWorkspace.scale;
  const margin = this.MARGIN;
  const cursorX = this.RTL ? margin : margin + this.tabWidth_;
  let cursorY = margin;

  for (let i = 0, item; (item = contents[i]); i++) {
    if (item.type == 'block') {
      const block = item.block;
      const allBlocks = block.getDescendants(false);
      for (let j = 0, child; (child = allBlocks[j]); j++) {
        // Mark blocks as being inside a flyout.  This is used to detect and
        // prevent the closure of the flyout if the user right-clicks on such a
        // block.
        child.isInFlyout = true;
      }
      block.render();
      const root = block.getSvgRoot();
      const blockHW = block.getHeightWidth();
      const moveX = block.outputConnection ? cursorX - this.tabWidth_ : cursorX;
      block.moveBy(moveX, cursorY);

      const rect = this.createRect_(
          block, this.RTL ? moveX - blockHW.width : moveX, cursorY, blockHW, i);

      this.addBlockListeners_(root, block, rect);

      cursorY += blockHW.height + gaps[i];
    } else if (item.type == 'button') {
      this.initFlyoutButton_(item.button, cursorX, cursorY);
      cursorY += item.button.height + gaps[i];
    }
  }
};

/**
 * Determine if a drag delta is toward the workspace, based on the position
 * and orientation of the flyout. This is used in determineDragIntention_ to
 * determine if a new block should be created or if the flyout should scroll.
 * @param {!Coordinate} currentDragDeltaXY How far the pointer has
 *     moved from the position at mouse down, in pixel units.
 * @return {boolean} True if the drag is toward the workspace.
 * @package
 */
VerticalFlyout.prototype.isDragTowardWorkspace = function(currentDragDeltaXY) {
  const dx = currentDragDeltaXY.x;
  const dy = currentDragDeltaXY.y;
  // Direction goes from -180 to 180, with 0 toward the right and 90 on top.
  const dragDirection = Math.atan2(dy, dx) / Math.PI * 180;

  const range = this.dragAngleRange_;
  // Check for left or right dragging.
  if ((dragDirection < range && dragDirection > -range) ||
      (dragDirection < -180 + range || dragDirection > 180 - range)) {
    return true;
  }
  return false;
};

/**
 * Returns the bounding rectangle of the drag target area in pixel units
 * relative to viewport.
 * @return {?Rect} The component's bounding box. Null if drag
 *   target area should be ignored.
 */
VerticalFlyout.prototype.getClientRect = function() {
  if (!this.svgGroup_ || this.autoClose || !this.isVisible()) {
    // The bounding rectangle won't compute correctly if the flyout is closed
    // and auto-close flyouts aren't valid drag targets (or delete areas).
    return null;
  }

  const flyoutRect = this.svgGroup_.getBoundingClientRect();
  // BIG_NUM is offscreen padding so that blocks dragged beyond the shown flyout
  // area are still deleted.  Must be larger than the largest screen size,
  // but be smaller than half Number.MAX_SAFE_INTEGER (not available on IE).
  const BIG_NUM = 1000000000;
  const left = flyoutRect.left;

  if (this.toolboxPosition_ == Position.LEFT) {
    const width = flyoutRect.width;
    return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, left + width);
  } else {  // Right
    return new Rect(-BIG_NUM, BIG_NUM, left, BIG_NUM);
  }
};

/**
 * Compute width of flyout.  Position mat under each block.
 * For RTL: Lay out the blocks and buttons to be right-aligned.
 * @protected
 */
VerticalFlyout.prototype.reflowInternal_ = function() {
  this.workspace_.scale = this.getFlyoutScale();
  let flyoutWidth = 0;
  const blocks = this.workspace_.getTopBlocks(false);
  for (let i = 0, block; (block = blocks[i]); i++) {
    let width = block.getHeightWidth().width;
    if (block.outputConnection) {
      width -= this.tabWidth_;
    }
    flyoutWidth = Math.max(flyoutWidth, width);
  }
  for (let i = 0, button; (button = this.buttons_[i]); i++) {
    flyoutWidth = Math.max(flyoutWidth, button.width);
  }
  flyoutWidth += this.MARGIN * 1.5 + this.tabWidth_;
  flyoutWidth *= this.workspace_.scale;
  flyoutWidth += Scrollbar.scrollbarThickness;

  if (this.width_ != flyoutWidth) {
    for (let i = 0, block; (block = blocks[i]); i++) {
      if (this.RTL) {
        // With the flyoutWidth known, right-align the blocks.
        const oldX = block.getRelativeToSurfaceXY().x;
        let newX = flyoutWidth / this.workspace_.scale - this.MARGIN;
        if (!block.outputConnection) {
          newX -= this.tabWidth_;
        }
        block.moveBy(newX - oldX, 0);
      }
      if (block.flyoutRect_) {
        this.moveRectToBlock_(block.flyoutRect_, block);
      }
    }
    if (this.RTL) {
      // With the flyoutWidth known, right-align the buttons.
      for (let i = 0, button; (button = this.buttons_[i]); i++) {
        const y = button.getPosition().y;
        const x = flyoutWidth / this.workspace_.scale - button.width -
            this.MARGIN - this.tabWidth_;
        button.moveTo(x, y);
      }
    }

    if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_ &&
        this.toolboxPosition_ == Position.LEFT &&
        !this.targetWorkspace.getToolbox()) {
      // This flyout is a simple toolbox. Reposition the workspace so that (0,0)
      // is in the correct position relative to the new absolute edge (ie
      // toolbox edge).
      this.targetWorkspace.translate(
          this.targetWorkspace.scrollX + flyoutWidth,
          this.targetWorkspace.scrollY);
    }

    // Record the width for workspace metrics and .position.
    this.width_ = flyoutWidth;
    this.position();
    this.targetWorkspace.recordDragTargets();
  }
};

registry.register(
    registry.Type.FLYOUTS_VERTICAL_TOOLBOX, registry.DEFAULT, VerticalFlyout);

exports = VerticalFlyout;
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

// ************************************************************************************************
// Command Line APIs

function createFirebugCommandLine(context, win2)
{
    var win = FBL.unwrapObject(win2);

var _FirebugCommandLine =
{
    initFirebugCommandLine: function()
    {
        // Define console functions.
        var commands = ["$", "$$", "$x", "$n", "cd", "clear", "inspect", "keys",
            "values", "debug", "undebug", "monitor", "unmonitor", "traceCalls", "untraceCalls",
            "traceAll", "untraceAll", "monitorEvents", "unmonitorEvents", "profile", "profileEnd", "copy"];
        for (var i=0; i<commands.length; i++)
        {
            var command = commands[i];

            // If the method is already defined, don't override it.
            if (win[command])
                continue;

            //this[command] = new Function(
            //    "return _FirebugCommandLine.notifyFirebug(arguments, '" + command +
            // "', 'firebugExecuteCommand');");

            function createCommandHandler(cmd) {
                return function() {
                    return _FirebugCommandLine.notifyFirebug(arguments, cmd, 'firebugExecuteCommand');
                }
            }

            this[command] = createCommandHandler(command);
        }

        // Define console shortcuts
        var consoleShortcuts = ["dir", "dirxml", "table"];
        for (var i=0; i<consoleShortcuts.length; i++)
        {
            var command = consoleShortcuts[i];

            // If the method is already defined, don't override it.
            if (win[command])
                continue;

            //this[command] = new Function("return window.console." + command +
            //    ".apply(window.console, arguments)");

            function createShortcutHandler(cmd) {
                return function() {
                    return win.console[cmd].apply(win.console, arguments);
                }
            }

            this[command] = createShortcutHandler(command);
        }

        // Define console variables.
        var props = ["$0", "$1"];
        for (var j=0; j<props.length; j++)
        {
            var prop = props[j];
            if (win[prop])
                continue;

            this.__defineGetter__(prop, new Function(
                "return _FirebugCommandLine.notifyFirebug(arguments, '" + prop + "', 'firebugExecuteCommand');"));
        }

        this.attachCommandLine();
    },

    attachCommandLine: function()
    {
        // DBG window.dump("attachCommandLine "+window.location+"\n");
        if (!win.console)
        {
            // DBG     debugger;
            var console = createFirebugConsole(context, win2);
            win2.wrappedJSObject.console = console;
        }
        var self = this;

        this._firebugEvalEvent = function _firebugEvalEvent(event)
        {
            // DBG window.dump("attachCommandLine firebugCommandLine "+window.location+"\n");
            var expr = win.document.getUserData("firebug-expr"); // see commandLine.js
            self.evaluate(expr);
            // DBG window.dump("attachCommandLine did evaluate on "+expr+"\n");
        }

        win.document.addEventListener("firebugCommandLine",this._firebugEvalEvent, true);
        win.document.setUserData("firebug-CommandLineAttached", "true", null);
        // DBG window.dump("Added listener for firebugCommandLine event "+window.location+"\n");
    },

    detachCommandLine: function()
    {
         win.document.removeEventListener("firebugCommandLine", this._firebugEvalEvent, true);
         delete win._FirebugCommandLine; // suicide!
         // DBG window.dump("detachCommmandLine<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n")
    },

    evaluate: function _firebugInjectedEvaluate(expr)
    {
        try
        {
            var result = win.eval(expr);
            _FirebugCommandLine.notifyFirebug([result], "evaluated", "firebugAppendConsole");
        }
        catch(exc)
        {
            var result = exc;
            result.source = expr;
            _FirebugCommandLine.notifyFirebug([result], "evaluateError", "firebugAppendConsole");
        }
    },

    notifyFirebug: function _notifyFirebug(objs, methodName, eventID)
    {
        var event = win.document.createEvent("Events");
        event.initEvent(eventID, true, false);

        _FirebugCommandLine.userObjects = [];
        for (var i=0; i<objs.length; i++)
            _FirebugCommandLine.userObjects.push(objs[i]);

        var length = _FirebugCommandLine.userObjects.length;
        win.document.setUserData("firebug-methodName", methodName, null);

        win.document.dispatchEvent(event);

        // DBG dump("FirebugConsole dispatched event "+methodName+" via "+eventID+" with "+length+ " user objects, [0]:"+console.userObjects[0]+"\n");

        var result;
        if (win.document.getUserData("firebug-retValueType") == "array")
            result = [];

        if (!result && _FirebugCommandLine.userObjects.length == length+1)
            return _FirebugCommandLine.userObjects[length];

        for (var i=length; i<_FirebugCommandLine.userObjects.length && result; i++)
            result.push(_FirebugCommandLine.userObjects[i]);

        return result;
    }
};

// DBG window.dump("_FirebugCommandLine init console is "+window.console+" in "+window.location+"\n");
_FirebugCommandLine.initFirebugCommandLine();

return _FirebugCommandLine;
};
<commit_msg>[1.8] remove wrappedJSObject<commit_after>/* See license.txt for terms of usage */

// ************************************************************************************************
// Command Line APIs

function createFirebugCommandLine(context, win)
{
    var contentView = FBL.getContentView(win);
    if(!contentView)
    {
        if (FBTrace.DBG_COMMANDLINE || FBTrace.DBG_ERRORS)
            FBTrace.sysout("createFirebugCommandLine ERROR no contentView "+context.getName())
            return null;
    }

    var _FirebugCommandLine =
    {
        initFirebugCommandLine: function()
        {
            // Define console functions.
            var commands = ["$", "$$", "$x", "$n", "cd", "clear", "inspect", "keys",
                "values", "debug", "undebug", "monitor", "unmonitor", "traceCalls", "untraceCalls",
                "traceAll", "untraceAll", "monitorEvents", "unmonitorEvents", "profile", "profileEnd", "copy"];

            for (var i=0; i<commands.length; i++)
            {
                var command = commands[i];

                // If the method is already defined, don't override it.
                if (contentView[command])
                    continue;

                //this[command] = new Function(
                //    "return _FirebugCommandLine.notifyFirebug(arguments, '" + command +
                // "', 'firebugExecuteCommand');");

                function createCommandHandler(cmd) {
                    return function() {
                        return _FirebugCommandLine.notifyFirebug(arguments, cmd, 'firebugExecuteCommand');
                    }
                }

                this[command] = createCommandHandler(command);
            }

            // Define console shortcuts
            var consoleShortcuts = ["dir", "dirxml", "table"];
            for (var i=0; i<consoleShortcuts.length; i++)
            {
                var command = consoleShortcuts[i];

                // If the method is already defined, don't override it.
                if (contentView[command])
                    continue;

                //this[command] = new Function("return window.console." + command +
                //    ".apply(window.console, arguments)");

                function createShortcutHandler(cmd) {
                    return function() {
                        return contentView.console[cmd].apply(contentView.console, arguments);
                    }
                }

                this[command] = createShortcutHandler(command);
            }

            // Define console variables.
            var props = ["$0", "$1"];
            for (var j=0; j<props.length; j++)
            {
                var prop = props[j];
                if (contentView[prop])
                    continue;

                this.__defineGetter__(prop, new Function(
                    "return _FirebugCommandLine.notifyFirebug(arguments, '" + prop + "', 'firebugExecuteCommand');"));
            }

            this.attachCommandLine();
        },

        attachCommandLine: function()
        {
            // DBG window.dump("attachCommandLine "+window.location+"\n");
            if (!contentView.console)
            {
                var console = createFirebugConsole(context, win);
                contentView.console = console;
            }
            var self = this;

            this._firebugEvalEvent = function _firebugEvalEvent(event)
            {
                // DBG window.dump("attachCommandLine firebugCommandLine "+window.location+"\n");
                var expr = contentView.document.getUserData("firebug-expr"); // see commandLine.js
                self.evaluate(expr);
                window.dump("attachCommandLine did evaluate on "+expr+"\n");
            }

            contentView.document.addEventListener("firebugCommandLine",this._firebugEvalEvent, true);
            contentView.document.setUserData("firebug-CommandLineAttached", "true", null);
            // DBG window.dump("Added listener for firebugCommandLine event "+window.location+"\n");
        },

        detachCommandLine: function()
        {
             contentView.document.removeEventListener("firebugCommandLine", this._firebugEvalEvent, true);
             delete contentView._FirebugCommandLine; // suicide!
             // DBG window.dump("detachCommmandLine<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n")
        },

        evaluate: function _firebugInjectedEvaluate(expr)
        {
            try
            {
                var result = contentView.eval(expr);
                _FirebugCommandLine.notifyFirebug([result], "evaluated", "firebugAppendConsole");
            }
            catch(exc)
            {
                var result = exc;
                result.source = expr;
                _FirebugCommandLine.notifyFirebug([result], "evaluateError", "firebugAppendConsole");
            }
        },

        notifyFirebug: function _notifyFirebug(objs, methodName, eventID)
        {
            var event = contentView.document.createEvent("Events");
            event.initEvent(eventID, true, false);

            _FirebugCommandLine.userObjects = [];
            for (var i=0; i<objs.length; i++)
                _FirebugCommandLine.userObjects.push(objs[i]);

            var length = _FirebugCommandLine.userObjects.length;
            contentView.document.setUserData("firebug-methodName", methodName, null);

            contentView.document.dispatchEvent(event);

            // DBG dump("FirebugConsole dispatched event "+methodName+" via "+eventID+" with "+length+ " user objects, [0]:"+console.userObjects[0]+"\n");

            var result;
            if (contentView.document.getUserData("firebug-retValueType") == "array")
                result = [];

            if (!result && _FirebugCommandLine.userObjects.length == length+1)
                return _FirebugCommandLine.userObjects[length];

            for (var i=length; i<_FirebugCommandLine.userObjects.length && result; i++)
                result.push(_FirebugCommandLine.userObjects[i]);

            return result;
        }
    };

 // DBG window.dump("_FirebugCommandLine init console is "+window.console+" in "+window.location+"\n");
    _FirebugCommandLine.initFirebugCommandLine();

    return _FirebugCommandLine;
};
<|endoftext|>


<commit_before>'use strict';

// eslint-disable-next-line no-undef
module.exports = function (environment) {
  let ENV = {
    modulePrefix: '@cardstack/web-client',
    environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. EMBER_NATIVE_DECORATOR_SUPPORT: true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false,
      },
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },
    chains: {
      layer1: process.env.LAYER_1_CHAIN || 'keth', // set to "eth" for production
      layer2: process.env.LAYER_2_CHAIN || 'sokol', // set to "xdai" for production,
    },
    infuraId: process.env.INFURA_ID,
    urls: {
      appStoreLink: undefined,
      googlePlayStoreLink: undefined,
    },
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';
    ENV.chains.layer1 = 'test';
    ENV.chains.layer2 = 'test';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.autoboot = false;
  }

  if (environment === 'production') {
    // here you can enable a production-specific feature
  }

  return ENV;
};
<commit_msg>add infura id for staging<commit_after>'use strict';

const infuraIdsByTarget = {
  staging: '558ee533522a468e9d421d818e06fadb', // this infura id is specific to https://app-staging.stack.cards/
};

// eslint-disable-next-line no-undef
module.exports = function (environment) {
  let ENV = {
    modulePrefix: '@cardstack/web-client',
    environment,
    rootURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. EMBER_NATIVE_DECORATOR_SUPPORT: true
      },
      EXTEND_PROTOTYPES: {
        // Prevent Ember Data from overriding Date.parse.
        Date: false,
      },
    },

    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    },
    chains: {
      layer1: process.env.LAYER_1_CHAIN || 'keth', // set to "eth" for production
      layer2: process.env.LAYER_2_CHAIN || 'sokol', // set to "xdai" for production,
    },
    infuraId:
      infuraIdsByTarget[process.env.DEPLOY_TARGET] ?? process.env.INFURA_ID,
    urls: {
      appStoreLink: undefined,
      googlePlayStoreLink: undefined,
    },
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';
    ENV.chains.layer1 = 'test';
    ENV.chains.layer2 = 'test';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.APP.autoboot = false;
  }

  if (environment === 'production') {
    // here you can enable a production-specific feature
  }

  return ENV;
};
<|endoftext|>


<commit_before>Ext.onReady(function(){
    Ext.QuickTips.init();

    // Apply a set of config properties to the singleton
    Ext.apply(Ext.QuickTips.getQuickTip(), {
        showDelay: 0
        ,trackMouse: true
        ,mouseOffset: [-60,20] // otherwise Delete tt overruns browser win
        ,autoWidth: true
        ,dismissDelay: 0
    });

    var rowRecord = Ext.data.Record.create([
        { name: 'mimosa_sequence_set_id' },
        { name: 'shortname' },
        { name: 'title' },
        { name: 'description' },
        { name: 'alphabet' },
        { name: 'source_spec' },
        { name: 'lookup_spec' },
        { name: 'info_url' },
        { name: 'update_interval' },
        { name: 'is_public' }
    ]);

    // create the Data Store
    var store = new Ext.data.JsonStore({
        url: '/autocrud/site/default/schema/bcs/source/mimosa_sequence_set/list',
        root          : 'rows',
        fields        : rowRecord,
        remoteSort    : true,
        autoLoad      : true,
    });
    store.filter('is_public', 1, false, false);

    // sort sequence sets by title
    store.setDefaultSort('title', 'DESC');

    // create the Grid
    var xg = Ext.grid;
    var sm = new xg.CheckboxSelectionModel({
        listeners: {
            selectionchange: function(sm) {
                if (sm.getCount()) { // clicking an unselected checkbox
                    // This only gets the first selection
                    var selected_data = sm.getSelected().data;
                    jQuery("#mimosa_sequence_set_id").html( selected_data['mimosa_sequence_set_id'] );
                } else { // clicking an already selected checkbox
                    // Replace the default of 0, which means "no sequence sets are selected"
                    jQuery("#mimosa_sequence_set_id").html( 0 );
                }
            }
        }
    });
    var grid = new xg.GridPanel({
        columns: [
            sm,
            {
                id       :'mimosa_sequence_set_id',
                header   : 'Sequence Set ID',
                sortable : true,
                dataIndex: 'mimosa_sequence_set_id'
            },
            {
                id       :'shortname',
                header   : 'Short Name',
                sortable : true,
                dataIndex: 'shortname'
            },
            {
                id       :'title',
                header   : 'Title',
                sortable : true,
                width    : 100,
                dataIndex: 'title'
            },
            {
                id       :'description',
                header   : 'Description',
                sortable : true,
                width    : 250,
                dataIndex: 'description'
            },
            {
                id       :'alphabet',
                header   : 'Alphabet',
                sortable : true,
                dataIndex: 'alphabet'
            },
            {
                id       :'info_url',
                header   : 'Info URL',
                sortable : true,
                dataIndex: 'info_url'
            },
            {
                id       :'update_interval',
                header   : 'Update interval',
                sortable : true,
                dataIndex: 'update_interval'
            }
            // This should only be shown if the current user is logged in
            // and can view private sets
            //{
            //    id       :'is_public',
            //    header   : 'Public?',
            //    sortable : true,
            //    dataIndex: 'is_public'
            //},
        ],
        animCollapse: true,
        // autoExpandColumn: 'shortname',
        collapsible: true,
        columnLines: true,
        frame: true,
        iconCls:'icon-grid',
        sm: sm,
        store: store,
        stripeRows: true,
        height: 350,
        title: 'Available Sequence Sets',
        width: '100%',

        // config options for stateful behavior
        stateful: true,
        stateId: 'grid'
    });

    // render the grid to the specified div in the page
    grid.render('mimosa-grid');

});
<commit_msg>Show only title, description and alphabet for sequence sets, by default<commit_after>Ext.onReady(function(){
    Ext.QuickTips.init();

    // Apply a set of config properties to the singleton
    Ext.apply(Ext.QuickTips.getQuickTip(), {
        showDelay: 0
        ,trackMouse: true
        ,mouseOffset: [-60,20] // otherwise Delete tt overruns browser win
        ,autoWidth: true
        ,dismissDelay: 0
    });

    var rowRecord = Ext.data.Record.create([
        { name: 'mimosa_sequence_set_id' },
        { name: 'shortname' },
        { name: 'title' },
        { name: 'description' },
        { name: 'alphabet' },
        { name: 'source_spec' },
        { name: 'lookup_spec' },
        { name: 'info_url' },
        { name: 'update_interval' },
        { name: 'is_public' }
    ]);

    // create the Data Store
    var store = new Ext.data.JsonStore({
        url: '/autocrud/site/default/schema/bcs/source/mimosa_sequence_set/list',
        root          : 'rows',
        fields        : rowRecord,
        remoteSort    : true,
        autoLoad      : true,
    });
    store.filter('is_public', 1, false, false);

    // sort sequence sets by title
    store.setDefaultSort('title', 'DESC');

    // create the Grid
    var xg = Ext.grid;
    var sm = new xg.CheckboxSelectionModel({
        listeners: {
            selectionchange: function(sm) {
                if (sm.getCount()) { // clicking an unselected checkbox
                    // This only gets the first selection
                    var selected_data = sm.getSelected().data;
                    jQuery("#mimosa_sequence_set_id").html( selected_data['mimosa_sequence_set_id'] );
                } else { // clicking an already selected checkbox
                    // Replace the default of 0, which means "no sequence sets are selected"
                    jQuery("#mimosa_sequence_set_id").html( 0 );
                }
            }
        }
    });
    var grid = new xg.GridPanel({
        columns: [
            sm,
            {
                id       :'title',
                header   : 'Title',
                sortable : true,
                width    : 100,
                dataIndex: 'title'
            },
            {
                id       :'description',
                header   : 'Description',
                sortable : true,
                width    : 400,
                dataIndex: 'description'
            },
            {
                id       :'alphabet',
                header   : 'Alphabet',
                sortable : true,
                dataIndex: 'alphabet'
            }
            // This should only be shown if the current user is logged in
            // and can view private sets
            //{
            //    id       :'is_public',
            //    header   : 'Public?',
            //    sortable : true,
            //    dataIndex: 'is_public'
            //},
        ],
        animCollapse: true,
        // autoExpandColumn: 'shortname',
        collapsible: true,
        columnLines: true,
        frame: true,
        iconCls:'icon-grid',
        sm: sm,
        store: store,
        stripeRows: true,
        height: 350,
        title: 'Available Sequence Sets',
        width: '100%',

        // config options for stateful behavior
        stateful: true,
        stateId: 'grid'
    });

    // render the grid to the specified div in the page
    grid.render('mimosa-grid');

});
<|endoftext|>


<commit_before>/**
 * Create tQuery.Scene
*/
tQuery.register('createTVSnowTexture', function(opts){
	// handle parameters
	opts	= tQuery.extend(opts, {
		loop		: tQuery.world.loop(),
		width		: 256,
		height		: 256,
		nCanvases	: 10
	});
	/**
	 * Create a canvas with tv-like snow.
	 *
	 * May be better with some aliasing
	*/
	var createSnowCanvas	= function(width, height){
		var canvas	= document.createElement('canvas');
		var context	= canvas.getContext('2d');
		canvas.width	= width;
		canvas.height	= height;

		var imageData	= context.createImageData(canvas.width, canvas.height);
		var pix		= imageData.data;
		// Loop over each pixel and set a transparent red.
		for(var i = 0; i < pix.length; i += 4){
			var intensity	= Math.floor(Math.random() * 256);
			pix[i  ] = intensity;
			pix[i+1] = intensity;
			pix[i+2] = intensity;
			pix[i+3] = 255;
		}
		context.putImageData(imageData, 0,0);
		return canvas;
	}
	// create all the snows canvases
	var canvases	= [];
	for( var i = 0; i < opts.nCanvases; i++ ){
		var canvas	= createSnowCanvas(opts.width, opts.height);
		canvases.push(canvas)
	}

	// create destination canvas
	var canvas	= document.createElement('canvas');
	var context	= canvas.getContext('2d');
	canvas.width	= opts.width;
	canvas.height	= opts.height;

	// create the texture
	var texture	= new THREE.Texture(canvas)
	// make the canvases loop
	var canvasIdx	= 0;
	opts.loop.hook(function(){
		context.drawImage(canvases[canvasIdx], 0, 0);
		canvasIdx	= (canvasIdx+1) %  canvases.length;
		texture.needsUpdate	= true;
	})
	// return the texture
	return texture;
});

<commit_msg>more comment for tQuery.createtvsnowtexture.js<commit_after>/**
 * Create tQuery.Scene.
 *
 * TODO to optim with a sprite sheet. currently it push a change the canvas
 * at every frame. a spritesheet will allow to only change the UV
*/
tQuery.register('createTVSnowTexture', function(opts){
	// handle parameters
	opts	= tQuery.extend(opts, {
		loop		: tQuery.world.loop(),
		width		: 256,
		height		: 256,
		nCanvases	: 10
	});
	/**
	 * Create a canvas with tv-like snow.
	 *
	 * May be better with some aliasing
	*/
	var createSnowCanvas	= function(width, height){
		var canvas	= document.createElement('canvas');
		var context	= canvas.getContext('2d');
		canvas.width	= width;
		canvas.height	= height;

		var imageData	= context.createImageData(canvas.width, canvas.height);
		var pix		= imageData.data;
		// Loop over each pixel and set a transparent red.
		for(var i = 0; i < pix.length; i += 4){
			var intensity	= Math.floor(Math.random() * 256);
			pix[i  ] = intensity;
			pix[i+1] = intensity;
			pix[i+2] = intensity;
			pix[i+3] = 255;
		}
		context.putImageData(imageData, 0,0);
		return canvas;
	}
	// create all the snows canvases
	var canvases	= [];
	for( var i = 0; i < opts.nCanvases; i++ ){
		var canvas	= createSnowCanvas(opts.width, opts.height);
		canvases.push(canvas)
	}

	// create destination canvas
	var canvas	= document.createElement('canvas');
	var context	= canvas.getContext('2d');
	canvas.width	= opts.width;
	canvas.height	= opts.height;

	// create the texture
	var texture	= new THREE.Texture(canvas)
	// make the canvases loop
	var canvasIdx	= 0;
	opts.loop.hook(function(){
		context.drawImage(canvases[canvasIdx], 0, 0);
		canvasIdx	= (canvasIdx+1) %  canvases.length;
		texture.needsUpdate	= true;
	})
	// return the texture
	return texture;
});

<|endoftext|>


<commit_before>import lz from "lznext";

import { files, initialize } from "./stores.js";

let current;

const PROMPT = `
/* Here's some simple examples to get you started! */

/* Selector Scoping */
.fooga { color: red; }

/* Selector composition */
.booga {
    composes: fooga;

    background: blue;
}

/* Values */
@value fgColor: green;

.wooga {
    color: fgColor;
}
`.trim();

const initial = () => {
    const name = "/main.mcss";

    return [ name, PROMPT ];
};

const decode = (hash) => {
    hash = hash.replace(/^#/, "");

    let data;

    try {
        console.log(lz.decompressFromEncodedURIComponent(hash));

        data = JSON.parse(
            lz.decompressFromEncodedURIComponent(hash)
        );

        if(!data) {
            data = [];

            data.push(initial());
        }
    } catch(e) {
        if(hash.length) {
            // eslint-disable-next-line no-console
            console.warn("Unable to parse hash:", e);
        }

        data = initial();
    }

    return data;
};

// Grab initial state from location.hash, or create it from nothing
const setup = async () => {
    const data = decode(location.hash);

    await initialize(data);

    // Update location.hash with hashed file data whenever it changes
    files.subscribe((names) => {
        const content = [ ...names.entries() ].map(([ file, contents ]) => ([
            file,
            contents,
        ]));

        const hashed = lz.compressToEncodedURIComponent(JSON.stringify(content));

        const next = `#${hashed}`;

        if(current === next) {
            return;
        }

        window.location = next;
        current = next;
    });

    // Listen for hash change events, compare against our current hash
    // and re-initialize everything if different
    window.addEventListener("hashchange", () => {
        if(location.hash === current) {
            return;
        }

        const decoded = decode(location.hash);

        initialize(decoded);
    });
};

export default setup;
<commit_msg>chore: remove errant log<commit_after>import lz from "lznext";

import { files, initialize } from "./stores.js";

let current;

const PROMPT = `
/* Here's some simple examples to get you started! */

/* Selector Scoping */
.fooga { color: red; }

/* Selector composition */
.booga {
    composes: fooga;

    background: blue;
}

/* Values */
@value fgColor: green;

.wooga {
    color: fgColor;
}
`.trim();

const initial = () => {
    const name = "/main.mcss";

    return [ name, PROMPT ];
};

const decode = (hash) => {
    hash = hash.replace(/^#/, "");

    let data;

    try {
        data = JSON.parse(
            lz.decompressFromEncodedURIComponent(hash)
        );

        if(!data) {
            data = [];

            data.push(initial());
        }
    } catch(e) {
        if(hash.length) {
            // eslint-disable-next-line no-console
            console.warn("Unable to parse hash:", e);
        }

        data = initial();
    }

    return data;
};

// Grab initial state from location.hash, or create it from nothing
const setup = async () => {
    const data = decode(location.hash);

    await initialize(data);

    // Update location.hash with hashed file data whenever it changes
    files.subscribe((names) => {
        const content = [ ...names.entries() ].map(([ file, contents ]) => ([
            file,
            contents,
        ]));

        const hashed = lz.compressToEncodedURIComponent(JSON.stringify(content));

        const next = `#${hashed}`;

        if(current === next) {
            return;
        }

        window.location = next;
        current = next;
    });

    // Listen for hash change events, compare against our current hash
    // and re-initialize everything if different
    window.addEventListener("hashchange", () => {
        if(location.hash === current) {
            return;
        }

        const decoded = decode(location.hash);

        initialize(decoded);
    });
};

export default setup;
<|endoftext|>


<commit_before>var _ = require('lodash'),
    Q = require('q'),
    request = require('request'),
    token = process.env.META_RESOLVER_VIMEO_ACCESS_TOKEN,
    pattern = /^https:\/\/vimeo.com\/([0-9]+)/ig,
    endpoint = 'https://api.vimeo.com/videos/';

function _andReject(deferred, item) {
  deferred.reject(item);
  return deferred.promise;
}

function _fetchVimeoMeta(id, cb) {
  var options = {
    url: endpoint + id,
    method: 'GET',
    auth: {
      bearer: token
    },
    json: true
  }

  request(options, function(err, res, body) {
    if(err || res.statusCode != 200) {
      return cb(err || body);
    }

    cb(null, body);
  });
}

function _getBestPicture(pictures) {
  if(!pictures || !pictures.sizes) {
    return undefined;
  }

  return _(pictures.sizes)
    .chain()
    .sortBy(function(t) { return t.width; })
    .map(function(t) { return t.link; })
    .last()
    .value();
}

function _normalizeMeta(id, meta) {
  return {
    id: id,
    title: meta.name,
    description: meta.description,
    createdAt: meta.created_time,
    previewImage: _getBestPicture(meta.pictures),
    plays: meta.stats.plays,
    likes: meta.metadata.connections.likes.total
  };
}

module.exports = function(item) {
  var deferred = Q.defer();
  if(!pattern.test(item.url)) {
    return _andReject(deferred, item);
  }

  pattern.lastIndex = 0;
  var videoId = _(pattern.exec(item.url)).last();

  _fetchVimeoMeta(videoId, function(err, meta) {
    if(err) {
      console.log('[VIMEO] Error:'.red, err);
      return _andReject(deferred, item);
    }

    deferred.resolve(_.extend(item, {
      type: 'vimeo',
      resolved: true,
      meta: _normalizeMeta(videoId, meta)
    }));
  });

  return deferred.promise;
};
<commit_msg>Update vimeo.js<commit_after>var _ = require('lodash'),
    Q = require('q'),
    request = require('request'),
    token = process.env.META_RESOLVER_VIMEO_ACCESS_TOKEN,
    pattern = /^https:\/\/vimeo.com\/([0-9]+)/ig,
    endpoint = 'https://api.vimeo.com/videos/';

function _andReject(deferred, item) {
  deferred.reject(item);
  return deferred.promise;
}

function _fetchVimeoMeta(id, cb) {
  var options = {
    url: endpoint + id,
    method: 'GET',
    auth: {
      bearer: token
    },
    json: true
  }

  request(options, function(err, res, body) {
    if(err || res.statusCode != 200) {
      return cb(err || body);
    }

    cb(null, body);
  });
}

function _getBestPicture(pictures) {
  if(!pictures || !pictures.sizes) {
    return undefined;
  }

  return _(pictures.sizes)
    .chain()
    .sortBy(function(t) { return t.width; })
    .map(function(t) { return t.link; })
    .last()
    .value();
}

function _normalizeMeta(id, meta) {
  return {
    id: id,
    title: meta.name,
    description: meta.description,
    createdAt: meta.created_time,
    previewImage: _getBestPicture(meta.pictures),
    plays: meta.stats.plays,
    likes: meta.metadata.connections.likes.total,
    duration: meta.duration * 1000
  };
}

module.exports = function(item) {
  var deferred = Q.defer();
  if(!pattern.test(item.url)) {
    return _andReject(deferred, item);
  }

  pattern.lastIndex = 0;
  var videoId = _(pattern.exec(item.url)).last();

  _fetchVimeoMeta(videoId, function(err, meta) {
    if(err) {
      console.log('[VIMEO] Error:'.red, err);
      return _andReject(deferred, item);
    }

    deferred.resolve(_.extend(item, {
      type: 'vimeo',
      resolved: true,
      meta: _normalizeMeta(videoId, meta)
    }));
  });

  return deferred.promise;
};
<|endoftext|>


<commit_before>const isExisty = function(value) {
  return value !== null && value !== undefined;
};

const isEmpty = function(value) {
  return value === '';
};

const validations = {
  required(values, value) {
    return value !== undefined && value !== '';
  },
  isExisty(values, value) {
    return isExisty(value);
  },
  matchRegex(values, value, regexp) {
    return !isExisty(value) || isEmpty(value) || regexp.test(value);
  },
  isUndefined(values, value) {
    return value === undefined;
  },
  isEmptyString(values, value) {
    return isEmpty(value);
  },
  isEmail(values, value) {
    return validations.matchRegex(
      values,
      value,
      /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i
    );
  },
  isUrl(values, value) {
    return validations.matchRegex(
      values,
      value,
      /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)|\/|\?)*)?$/i
    );
  },
  isTrue(values, value) {
    return value === true;
  },
  isFalse(values, value) {
    return value === false;
  },
  isNumeric(values, value) {
    if (typeof value === 'number') {
      return true;
    }
    return validations.matchRegex(values, value, /^[-+]?(?:\d*[.])?\d+$/);
  },
  isInt(values, value) {
    return validations.matchRegex(values, value, /^(?:[-+]?(?:0|[1-9]\d*))$/);
  },
  isFloat(values, value) {
    return validations.matchRegex(
      values,
      value,
      /^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][\+\-]?(?:\d+))?$/
    );
  },
  isLength(values, value, length) {
    return !isExisty(value) || isEmpty(value) || value.length === length;
  },
  equals(values, value, eql) {
    /* eslint-disable eqeqeq */
    return !isExisty(value) || isEmpty(value) || value == eql;
  },
  equalsField(values, value, field) {
    return value == values[field];
    /* eslint-enable eqeqeq */
  },
  maxLength(values, value, length) {
    return !isExisty(value) || value.length <= length;
  },
  minLength(values, value, length) {
    return !isExisty(value) || isEmpty(value) || value.length >= length;
  }
};

export default validations;
<commit_msg>fix: change require validation<commit_after>const isExisty = function(value) {
  return value !== null && value !== undefined;
};

const isEmpty = function(value) {
  return value === '';
};

const validations = {
  required(values, value) {
    return isExisty(value) && !isEmpty(value);
  },
  isExisty(values, value) {
    return isExisty(value);
  },
  matchRegex(values, value, regexp) {
    return !isExisty(value) || isEmpty(value) || regexp.test(value);
  },
  isUndefined(values, value) {
    return value === undefined;
  },
  isEmptyString(values, value) {
    return isEmpty(value);
  },
  isEmail(values, value) {
    return validations.matchRegex(
      values,
      value,
      /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i
    );
  },
  isUrl(values, value) {
    return validations.matchRegex(
      values,
      value,
      /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,=]|:|@)|\/|\?)*)?$/i
    );
  },
  isTrue(values, value) {
    return value === true;
  },
  isFalse(values, value) {
    return value === false;
  },
  isNumeric(values, value) {
    if (typeof value === 'number') {
      return true;
    }
    return validations.matchRegex(values, value, /^[-+]?(?:\d*[.])?\d+$/);
  },
  isInt(values, value) {
    return validations.matchRegex(values, value, /^(?:[-+]?(?:0|[1-9]\d*))$/);
  },
  isFloat(values, value) {
    return validations.matchRegex(
      values,
      value,
      /^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][\+\-]?(?:\d+))?$/
    );
  },
  isLength(values, value, length) {
    return !isExisty(value) || isEmpty(value) || value.length === length;
  },
  equals(values, value, eql) {
    /* eslint-disable eqeqeq */
    return !isExisty(value) || isEmpty(value) || value == eql;
  },
  equalsField(values, value, field) {
    return value == values[field];
    /* eslint-enable eqeqeq */
  },
  maxLength(values, value, length) {
    return !isExisty(value) || value.length <= length;
  },
  minLength(values, value, length) {
    return !isExisty(value) || isEmpty(value) || value.length >= length;
  }
};

export default validations;
<|endoftext|>


<commit_before>#!/usr/bin/env node

const HELP =
"bible --help" +
"\nusage: bible [options]" +
"\n" +
"\nRead the Holy Bible using a NPM application." +
"\n" +
"\noptions:" +
"\n  --v, --version          print the version" +
"\n  --lang, --language      set the Bible language" +
"\n  --ref, --reference      the verse references that you want to read" +
"\n  --help                  print this output" +
"\n" +
"\nDocumentation can be found at https://github.com/BibleJS/BibleApp";

// dependencies
var Bible = require ("bible.js")
  , Yargs = require('yargs').usage(HELP)
  , argv = Yargs.argv
  , language = argv.lang || argv.language
  , reference = argv.reference || argv.ref
  ;

if (argv.v || argv.version) {
    return console.log(require ("./package").version);
}

if (argv.help || !language || !reference) {
    return console.log(Yargs.help());
}

console.log("You are reading " + reference);
console.log("----------------");

// get the verses
(new Bible({language: language})).get(reference, function (err, verses) {

    // handle error
    if (err) {
        console.log("Error: ", err);
        return;
    }

    // no verses
    if (!verses || !verses.length) {
        console.log("Verses not found");
    }

    // output each verse
    for (var i in verses) {
        var cVerse = verses[i];
        console.log(cVerse.bookname + " " + cVerse.chapter + ":" + cVerse.verse + " | " + cVerse.text);
    }
    console.log("----------------");
});
<commit_msg>Added comments<commit_after>#!/usr/bin/env node

const HELP =
"bible --help" +
"\nusage: bible [options]" +
"\n" +
"\nRead the Holy Bible using a NPM application." +
"\n" +
"\noptions:" +
"\n  --v, --version          print the version" +
"\n  --lang, --language      set the Bible language" +
"\n  --ref, --reference      the verse references that you want to read" +
"\n  --help                  print this output" +
"\n" +
"\nDocumentation can be found at https://github.com/BibleJS/BibleApp";

// dependencies
var Bible = require ("bible.js")
  , Yargs = require('yargs').usage(HELP)
  , argv = Yargs.argv
  , language = argv.lang || argv.language
  , reference = argv.reference || argv.ref
  ;

// show version
if (argv.v || argv.version) {
    return console.log(require ("./package").version);
}

// show help
if (argv.help || !language || !reference) {
    return console.log(Yargs.help());
}

// output
console.log("You are reading " + reference);
console.log("----------------");

// get the verses
(new Bible({language: language})).get(reference, function (err, verses) {

    // handle error
    if (err) {
        console.log("Error: ", err);
        return;
    }

    // no verses
    if (!verses || !verses.length) {
        console.log("Verses not found");
    }

    // output each verse
    for (var i in verses) {
        var cVerse = verses[i];
        console.log(cVerse.bookname + " " + cVerse.chapter + ":" + cVerse.verse + " | " + cVerse.text);
    }
    console.log("----------------");
});
<|endoftext|>


<commit_before>/*!
 * Copyright 2015 mifort.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Andrew Voitov
 */
var csvStringify = require('csv-stringify');
var fs = require('fs');
var shortid = require('shortid');

var db = require('./libs/mongodb_settings');
var log = require('./libs/logger');
var utils = require('./libs/utils');

var projects = require('./project');

//Rest API
exports.restCommonReport = function(req, res, next) {
    var filterObj = req.body;
    log.debug('-REST call: common report. Company id: %s', filterObj.companyId.toHexString());

    projects.findProjectIdsByCompanyId(filterObj.companyId, function(err, projectIds) {
        if(err) {
            next(err);
            return;
        }
        var projectIdArray = projectIds.map(function(object) {
            return object._id;
        });
        var query = convertFiltersToQuery(filterObj.filters);
        var sortObj = makeSortObject(filterObj.sort);
        var page = filterObj.page;

        if(page == 1) {
            var timelogCollection = db.timelogCollection();
            timelogCollection.find(query)
                .count(function(err, count) {
                    res.append('X-Total-Count', count);
                    filterTimelog(query, sortObj, page, filterObj.pageSize, res,
                        function() {
                            log.debug('-REST result: common report. Company id: %s',
                                filterObj.companyId.toHexString());
                        });
                });
        } else {
            filterTimelog(query, sortObj, page, filterObj.pageSize, res,
                function() {
                    log.debug('-REST result: common report. Company id: %s',
                        filterObj.companyId.toHexString());
                });
        }

    });
};

var columns = {
    date: 'Date',
    userName: 'User',
    projectName: 'Project',
    role: 'Role',
    time: 'Time'
};
//need to extract common parts to separate method!!!!
exports.restConstructCSV = function(req, res, next) {
    var filterObj = req.body;
    log.debug('-REST call: Download common report. Company id: %s',
        filterObj.companyId.toHexString());

    var timelogCollection = db.timelogCollection();
    projects.findProjectIdsByCompanyId(filterObj.companyId, function(err, projectIds) {
        if(err) {
            next(err);
            return;
        }
        var projectIdArray = projectIds.map(function(object) {
            return object._id;
        });
        var query = convertFiltersToQuery(filterObj.filters);
        var sortObj = makeSortObject(filterObj.sort);

        var cursorStream = timelogCollection.find(query)
            .sort(sortObj)
            .stream({
                transform: function(doc) {
                    if(doc.date) {
                        doc.date = utils.formatDate(doc.date);
                    }
                    return doc;
                }
            });
        var csvStringifier = csvStringify({ header: true, columns: columns });
        var fileName = 'report_' + shortid.generate() + '.csv';
        var writeStream = fs.createWriteStream('./report_files/' + fileName,
            {defaultEncoding: 'utf8'});

        cursorStream.pipe(csvStringifier).pipe(writeStream);

        cursorStream.on('end', function() {
            log.debug('-REST Result: Download common report. CSV file is generated. Company id: %s',
                filterObj.companyId.toHexString());
            res.json({url: '/report/download/' + fileName});
        });

        writeStream.on('error', function (err) {
            log.error(err);
        });
    });
};

exports.restDownloadFile = function(req, res, next) {
    var fileName = utils.getFileName(req);
    log.debug('-REST Call: Download file. File is downloaded. %s', fileName);

    res.download('./report_files/' + fileName, 'report.csv', function(err) {
        if(err) {
            next(err);
            return;
        }
        log.debug('-REST Result: Download file. File is downloaded. %s', fileName);
    })
};

exports.restGetFilterValues = function(req, res, next) {
    var companyId = utils.getCompanyId(req);
    log.debug('-REST call: Get filter values. Company id: %s', companyId.toHexString());

    var timelogCollection = db.timelogCollection();
    var filterValues = [];

    projects.findProjectIdsByCompanyId(companyId, function(err, projectIds) {
        if(err) {
            next(err);
            return;
        }

        var projectIdArray = projectIds.map(function(object) {
            return object._id;
        });
        timelogCollection.distinct('userName', {projectId : {$in: projectIdArray}},
            function(err, userNames){
                if(err) {
                    next(err);
                    return;
                }
                filterValues.push({field:'userName', value: userNames});

                timelogCollection.distinct('projectName', {projectId : {$in: projectIdArray}},
                    function(err, projectNames){
                        if(err) {
                            next(err);
                            return;
                        }
                        filterValues.push({field:'projectName', value: projectNames});

                        timelogCollection.distinct('role', {projectId : {$in: projectIdArray}},
                            function(err, roles){
                                if(err) {
                                    next(err);
                                    return;
                                }
                                filterValues.push({field:'role', value: roles});
                                res.json(filterValues);
                                log.debug('-REST result: Report filters returned. Company id: %s',
                                    companyId.toHexString());
                            });
                    });
            });
    });

};

//Private
function convertFiltersToQuery(filters){
    var query = {};
    if(filters) {
        filters.forEach(function(filter) {
            switch(filter.field) {
                case 'date':
                    query.date = {$gte: filter.start,
                                  $lte: filter.end};
                    break;
                default:
                    query[filter.field] = {$in: filter.value};

            }
        });
    }

    return query;
}

function makeSortObject(sort) {
    var sortObj = {};
    if(sort) {
        sortObj[sort.field] = (sort.asc ? 1 : -1);
    }

    return sortObj;
}

function filterTimelog(query, sortObj, page, pageSize, res, callback) {
    var timelogCollection = db.timelogCollection();
    timelogCollection.find(query)
        .sort(sortObj)
        .skip((page-1)*pageSize) // not efficient way but It's just for the first implementation
        .limit(pageSize)
        .toArray(function(err, timelogs) {
            res.json(timelogs);
            callback();
        });
}
<commit_msg>Delete report file improvement<commit_after>/*!
 * Copyright 2015 mifort.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Andrew Voitov
 */
var csvStringify = require('csv-stringify');
var fs = require('fs');
var shortid = require('shortid');

var db = require('./libs/mongodb_settings');
var log = require('./libs/logger');
var utils = require('./libs/utils');

var projects = require('./project');

//Rest API
exports.restCommonReport = function(req, res, next) {
    var filterObj = req.body;
    log.debug('-REST call: common report. Company id: %s', filterObj.companyId.toHexString());

    projects.findProjectIdsByCompanyId(filterObj.companyId, function(err, projectIds) {
        if(err) {
            next(err);
            return;
        }
        var projectIdArray = projectIds.map(function(object) {
            return object._id;
        });
        var query = convertFiltersToQuery(filterObj.filters);
        var sortObj = makeSortObject(filterObj.sort);
        var page = filterObj.page;

        if(page == 1) {
            var timelogCollection = db.timelogCollection();
            timelogCollection.find(query)
                .count(function(err, count) {
                    res.append('X-Total-Count', count);
                    filterTimelog(query, sortObj, page, filterObj.pageSize, res,
                        function() {
                            log.debug('-REST result: common report. Company id: %s',
                                filterObj.companyId.toHexString());
                        });
                });
        } else {
            filterTimelog(query, sortObj, page, filterObj.pageSize, res,
                function() {
                    log.debug('-REST result: common report. Company id: %s',
                        filterObj.companyId.toHexString());
                });
        }

    });
};

var columns = {
    date: 'Date',
    userName: 'User',
    projectName: 'Project',
    role: 'Role',
    time: 'Time'
};
//need to extract common parts to separate method!!!!
exports.restConstructCSV = function(req, res, next) {
    var filterObj = req.body;
    log.debug('-REST call: Download common report. Company id: %s',
        filterObj.companyId.toHexString());

    var timelogCollection = db.timelogCollection();
    projects.findProjectIdsByCompanyId(filterObj.companyId, function(err, projectIds) {
        if(err) {
            next(err);
            return;
        }
        var projectIdArray = projectIds.map(function(object) {
            return object._id;
        });
        var query = convertFiltersToQuery(filterObj.filters);
        var sortObj = makeSortObject(filterObj.sort);

        var cursorStream = timelogCollection.find(query)
            .sort(sortObj)
            .stream({
                transform: function(doc) {
                    if(doc.date) {
                        doc.date = utils.formatDate(doc.date);
                    }
                    return doc;
                }
            });
        var csvStringifier = csvStringify({ header: true, columns: columns });
        var fileName = 'report_' + shortid.generate() + '.csv';
        var writeStream = fs.createWriteStream('./report_files/' + fileName,
            {defaultEncoding: 'utf8'});

        cursorStream.pipe(csvStringifier).pipe(writeStream);

        cursorStream.on('end', function() {
            log.debug('-REST Result: Download common report. CSV file is generated. Company id: %s',
                filterObj.companyId.toHexString());
            res.json({url: '/report/download/' + fileName});
        });

        writeStream.on('error', function (err) {
            log.error(err);
        });
    });
};

exports.restDownloadFile = function(req, res, next) {
    var fileName = utils.getFileName(req);
    log.debug('-REST Call: Download file. File is downloaded. %s', fileName);

    res.download('./report_files/' + fileName, 'report.csv', function(err) {
        if(err) {
            next(err);
            return;
        } else {
            if(res.headersSent) {
                fs.unlink('./report_files/' + fileName, function(err) {
                    if (err) {
                        log.warn('Cannot delete %s', fileName);
                    } else {
                        log.info('Successfully deleted %s', fileName);
                    }
                });
            }
        }
        log.debug('-REST Result: Download file. File is downloaded. %s', fileName);
    })
};

exports.restGetFilterValues = function(req, res, next) {
    var companyId = utils.getCompanyId(req);
    log.debug('-REST call: Get filter values. Company id: %s', companyId.toHexString());

    var timelogCollection = db.timelogCollection();
    var filterValues = [];

    projects.findProjectIdsByCompanyId(companyId, function(err, projectIds) {
        if(err) {
            next(err);
            return;
        }

        var projectIdArray = projectIds.map(function(object) {
            return object._id;
        });
        timelogCollection.distinct('userName', {projectId : {$in: projectIdArray}},
            function(err, userNames){
                if(err) {
                    next(err);
                    return;
                }
                filterValues.push({field:'userName', value: userNames});

                timelogCollection.distinct('projectName', {projectId : {$in: projectIdArray}},
                    function(err, projectNames){
                        if(err) {
                            next(err);
                            return;
                        }
                        filterValues.push({field:'projectName', value: projectNames});

                        timelogCollection.distinct('role', {projectId : {$in: projectIdArray}},
                            function(err, roles){
                                if(err) {
                                    next(err);
                                    return;
                                }
                                filterValues.push({field:'role', value: roles});
                                res.json(filterValues);
                                log.debug('-REST result: Report filters returned. Company id: %s',
                                    companyId.toHexString());
                            });
                    });
            });
    });

};

//Private
function convertFiltersToQuery(filters){
    var query = {};
    if(filters) {
        filters.forEach(function(filter) {
            switch(filter.field) {
                case 'date':
                    query.date = {$gte: filter.start,
                                  $lte: filter.end};
                    break;
                default:
                    query[filter.field] = {$in: filter.value};

            }
        });
    }

    return query;
}

function makeSortObject(sort) {
    var sortObj = {};
    if(sort) {
        sortObj[sort.field] = (sort.asc ? 1 : -1);
    }

    return sortObj;
}

function filterTimelog(query, sortObj, page, pageSize, res, callback) {
    var timelogCollection = db.timelogCollection();
    timelogCollection.find(query)
        .sort(sortObj)
        .skip((page-1)*pageSize) // not efficient way but It's just for the first implementation
        .limit(pageSize)
        .toArray(function(err, timelogs) {
            res.json(timelogs);
            callback();
        });
}
<|endoftext|>


<commit_before>/******************************************************
* #### jQuery My Instagram Gallery v01 ####
* Coded by Ican Bachors 2014.
* http://ibacor.com/labs/jquery-my-instagram-gallery/
* Updates will be posted to this site.
******************************************************/

/* Put your instagram user_id */
var ins_id = 503807090;

eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('k=\'/l/O/?m=n.o.q\',r(s);6(s,k);2 6(e,f){$.t({4:\'u://v.7.8/w/x/\'+e+f,y:z,A:\'B\'}).C(2(c){9 d=\'\';$.P(c.0,2(i,a){9 b=\'\';Q(c.0[i].D==R){b=S(c.0[i].T)}U{b=c.0[i].D.V}d+=\'<5 1="W"><G H="\'+c.0[i].E.11.4.h(/\\\\/,"")+\'" F="\'+b+\'"></5>\'});d+=\'
<12 13="14" 1="15 J" 16="17">
\';$(\'.18\').19(d);$(\'.J\').1a(2(){6(e,f+\'&1b=\'+c.1c.1d);$(".I").1e("1f","1g");1h 1i})})}2 r(c){$.t({4:\'u://v.7.8/w/x/\'+c+\'/?m=n.o.q\',y:z,A:\'B\'}).C(2(a){9 b=\'\';b+=\'<5 1="1j"><G H="\'+a.0.1k.h(/\\\\/,"")+\'" 1="1l"></5>\';b+=\'
\'+a.0.K+\'
\';b+=\'
1o: \'+a.0.1p+\'
\';b+=\'
1q: \'+a.0.1r+\'
\';b+=\'
1s: \'+a.0.N+\'
\';b+=\'
<3>\'+a.0.j.l+\'</3> 1t | <3>\'+a.0.j.1u+\'</3> 1v | <3>\'+a.0.j.1w+\'</3> 1x
\';$(\'.1y\').1z(b)})}',62,98,'data|class|function|strong|url|div|album|instagram|com|var|||||||href|replace||counts|sub|media|access_token|141970|467ede5||edbc9c37472d41b790e1db8948793f11|profile|ins_id|ajax|https|api|v1|users|crossDomain|true|dataType|jsonp|done|caption|images|title|img|src|load_more|ins_more|username|target|_BLANK|website|recent|each|if|null|Date|created_time|else|text|ins_img|standard_resolution|ins_popup|rel|ins_gallery|thumbnail|input|type|submit|btn|value|More|bcr_ins_gallery|append|click|max_id|pagination|next_max_id|css|display|none|return|false|ins_pr_user|profile_picture|ins_pr_img|ins_username|http|Name|full_name|Bio|bio|Website|posts|followed_by|followers|follows|following|bcr_ins_profile|html'.split('|'),0,{}))
<commit_msg>add alt<commit_after>/******************************************************
* #### jQuery My Instagram Gallery v01 ####
* Coded by Ican Bachors 2014.
* http://ibacor.com/labs/jquery-my-instagram-gallery/
* Updates will be posted to this site.
******************************************************/

/* Put your instagram user_id */
var ins_id = 503807090;

eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('k=\'/l/O/?m=n.o.q\',r(s);6(s,k);2 6(e,f){$.t({4:\'u://v.7.8/w/x/\'+e+f,y:z,A:\'B\'}).C(2(c){9 d=\'\';$.P(c.0,2(i,a){9 b=\'\';Q(c.0[i].D==R){b=S(c.0[i].T)}U{b=c.0[i].D.V}d+=\'<5 1="W"><G H="\'+c.0[i].E.11.4.h(/\\\\/,"")+\'" 12="" F="\'+b+\'"></5>\'});d+=\'
<13 14="15" 1="16 J" 17="18">
\';$(\'.19\').1a(d);$(\'.J\').1b(2(){6(e,f+\'&1c=\'+c.1d.1e);$(".I").1f("1g","1h");1i 1j})})}2 r(c){$.t({4:\'u://v.7.8/w/x/\'+c+\'/?m=n.o.q\',y:z,A:\'B\'}).C(2(a){9 b=\'\';b+=\'<5 1="1k"><G H="\'+a.0.1l.h(/\\\\/,"")+\'" 1="1m"></5>\';b+=\'
\'+a.0.K+\'
\';b+=\'
1p: \'+a.0.1q+\'
\';b+=\'
1r: \'+a.0.1s+\'
\';b+=\'
1t: \'+a.0.N+\'
\';b+=\'
<3>\'+a.0.j.l+\'</3> 1u | <3>\'+a.0.j.1v+\'</3> 1w | <3>\'+a.0.j.1x+\'</3> 1y
\';$(\'.1z\').1A(b)})}',62,99,'data|class|function|strong|url|div|album|instagram|com|var|||||||href|replace||counts|sub|media|access_token|141970|467ede5||edbc9c37472d41b790e1db8948793f11|profile|ins_id|ajax|https|api|v1|users|crossDomain|true|dataType|jsonp|done|caption|images|title|img|src|load_more|ins_more|username|target|_BLANK|website|recent|each|if|null|Date|created_time|else|text|ins_img|standard_resolution|ins_popup|rel|ins_gallery|thumbnail|alt|input|type|submit|btn|value|More|bcr_ins_gallery|append|click|max_id|pagination|next_max_id|css|display|none|return|false|ins_pr_user|profile_picture|ins_pr_img|ins_username|http|Name|full_name|Bio|bio|Website|posts|followed_by|followers|follows|following|bcr_ins_profile|html'.split('|'),0,{}))
<|endoftext|>