<commit_before>'use strict'

// ----------------------------------------------------------------------------

const log       = require ('ololog')
    , ansi      = require ('ansicolor').nice
    , chai      = require ('chai')
    , expect    = chai.expect
    , assert    = chai.assert

//-----------------------------------------------------------------------------

const printOrderBookOneLiner = (orderbook, method, symbol) => {

    const bids = orderbook.bids
    const asks = orderbook.asks

    log (symbol.toString ().green,
        method,
        orderbook['datetime'],
        'bid: '       + ((bids.length > 0) ? bids[0][0] : 'N/A'),
        'bidVolume: ' + ((bids.length > 0) ? bids[0][1] : 'N/A'),
        'ask: '       + ((asks.length > 0) ? asks[0][0] : 'N/A'),
        'askVolume: ' + ((asks.length > 0) ? asks[0][1] : 'N/A'))
}

/*  ------------------------------------------------------------------------ */

module.exports = (exchange, orderbook, method, symbol) => {

    const format = {
        'bids': [],
        'asks': [],
        'timestamp': 1234567890,
        'datetime': '2017-09-01T00:00:00',
        'nonce': 134234234,
        // 'info': {},
    }

    expect (orderbook).to.have.all.keys (format)

    const bids = orderbook.bids
    const asks = orderbook.asks

    for (let i = 1; i < bids.length; i++) {
        // debugger;
        assert (bids[i][0] <= bids[i - 1][0])
        assert (typeof bids[i][0] === 'number')
        assert (typeof bids[i][1] === 'number')
    }

    for (let i = 1; i < asks.length; i++) {
        assert (asks[i][0] >= asks[i - 1][0])
        assert (typeof asks[i][0] === 'number')
        assert (typeof asks[i][1] === 'number')
    }

    if (![

        'coinmarketcap',
        'xbtce',
        'coinsecure',

    ].includes (exchange.id)) {

        if (bids.length && asks.length)
            assert (bids[0][0] <= asks[0][0],
                `bids[0][0]: ${bids[0][0]} (of ${bids.length}); asks[0][0]:${asks[0][0]} (of ${asks.length})`)

    }

    printOrderBookOneLiner (orderbook, method, symbol)
}<commit_msg>minor edits in test.orderbook.js<commit_after>'use strict'

// ----------------------------------------------------------------------------

const log       = require ('ololog')
    , ansi      = require ('ansicolor').nice
    , chai      = require ('chai')
    , expect    = chai.expect
    , assert    = chai.assert

// ----------------------------------------------------------------------------

const printOrderBookOneLiner = (orderbook, method, symbol) => {

    const bids = orderbook.bids
    const asks = orderbook.asks

    log (symbol.toString ().green,
        method,
        orderbook['datetime'],
        'bid: '       + ((bids.length > 0) ? bids[0][0] : 'N/A'),
        'bidVolume: ' + ((bids.length > 0) ? bids[0][1] : 'N/A'),
        'ask: '       + ((asks.length > 0) ? asks[0][0] : 'N/A'),
        'askVolume: ' + ((asks.length > 0) ? asks[0][1] : 'N/A'))
}

/*  ------------------------------------------------------------------------ */

module.exports = (exchange, orderbook, method, symbol) => {

    const format = {
        'bids': [],
        'asks': [],
        'timestamp': 1234567890,
        'datetime': '2017-09-01T00:00:00',
        'nonce': 134234234,
        // 'info': {},
    }

    expect (orderbook).to.have.all.keys (format)

    const bids = orderbook.bids
    const asks = orderbook.asks

    for (let i = 1; i < bids.length; i++) {
        // debugger;
        assert (bids[i][0] <= bids[i - 1][0])
        assert (typeof bids[i][0] === 'number')
        assert (typeof bids[i][1] === 'number')
    }

    for (let i = 1; i < asks.length; i++) {
        assert (asks[i][0] >= asks[i - 1][0])
        assert (typeof asks[i][0] === 'number')
        assert (typeof asks[i][1] === 'number')
    }

    if (![

        'coinmarketcap',
        'xbtce',
        'coinsecure',

    ].includes (exchange.id)) {

        if (bids.length && asks.length)
            assert (bids[0][0] <= asks[0][0],
                `bids[0][0]: ${bids[0][0]} (of ${bids.length}); asks[0][0]:${asks[0][0]} (of ${asks.length})`)

    }

    printOrderBookOneLiner (orderbook, method, symbol)
}<|endoftext|>


<commit_before>/**
 * FocusManager.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class manages the focus/blur state of the editor. This class is needed since some
 * browsers fire false focus/blur states when the selection is moved to a UI dialog or similar.
 *
 * This class will fire two events focus and blur on the editor instances that got affected.
 * It will also handle the restore of selection when the focus is lost and returned.
 *
 * @class tinymce.FocusManager
 */
define("tinymce/FocusManager", [
	"tinymce/dom/DOMUtils",
	"tinymce/Env"
], function(DOMUtils, Env) {
	/**
	 * Constructs a new focus manager instance.
	 *
	 * @constructor FocusManager
	 * @param {tinymce.EditorManager} editorManager Editor manager instance to handle focus for.
	 */
	function FocusManager(editorManager) {
		function getActiveElement() {
			try {
				return document.activeElement;
			} catch (ex) {
				// IE sometimes fails to get the activeElement when resizing table
				// TODO: Investigate this
				return document.body;
			}
		}

		// We can't store a real range on IE 11 since it gets mutated so we need to use a bookmark object
		// TODO: Move this to a separate range utils class since it's it's logic is present in Selection as well.
		function createBookmark(rng) {
			if (rng && rng.startContainer) {
				return {
					startContainer: rng.startContainer,
					startOffset: rng.startOffset,
					endContainer: rng.endContainer,
					endOffset: rng.endOffset
				};
			}

			return rng;
		}

		function bookmarkToRng(editor, bookmark) {
			var rng;

			if (bookmark.startContainer) {
				rng = editor.getDoc().createRange();
				rng.setStart(bookmark.startContainer, bookmark.startOffset);
				rng.setEnd(bookmark.endContainer, bookmark.endOffset);
			} else {
				rng = bookmark;
			}

			return rng;
		}

		function isUIElement(elm) {
			return !!DOMUtils.DOM.getParent(elm, FocusManager.isEditorUIElement);
		}

		function isNodeInBodyOfEditor(node, editor) {
			var body = editor.getBody();

			while (node) {
				if (node == body) {
					return true;
				}

				node = node.parentNode;
			}
		}

		function registerEvents(e) {
			var editor = e.editor, selectionChangeHandler;

			editor.on('init', function() {
				// On IE take selection snapshot onbeforedeactivate
				if ("onbeforedeactivate" in document && Env.ie < 11) {
					editor.dom.bind(editor.getBody(), 'beforedeactivate', function() {
						try {
							editor.lastRng = editor.selection.getRng();
						} catch (ex) {
							// IE throws "Unexcpected call to method or property access" some times so lets ignore it
						}

						editor.selection.lastFocusBookmark = createBookmark(editor.lastRng);
					});
				} else if (editor.inline || Env.ie > 10) {
					// On other browsers take snapshot on nodechange in inline mode since they have Ghost selections for iframes
					editor.on('nodechange keyup', function() {
						var node = document.activeElement;

						// IE 11 reports active element as iframe not body of iframe
						if (node && node.id == editor.id + '_ifr') {
							node = editor.getBody();
						}

						if (isNodeInBodyOfEditor(node, editor)) {
							editor.lastRng = editor.selection.getRng();
						}
					});

					// Handles the issue with WebKit not retaining selection within inline document
					// If the user releases the mouse out side the body while selecting a nodeChange won't
					// fire and there for the selection snapshot won't be stored
					// TODO: Optimize this since we only need to bind these on the active editor
					if (Env.webkit) {
						selectionChangeHandler = function() {
							var rng = editor.selection.getRng();

							// Store when it's non collapsed
							if (!rng.collapsed) {
								editor.lastRng = rng;
							}
						};

						// Bind selection handler
						DOMUtils.DOM.bind(document, 'selectionchange', selectionChangeHandler);

						editor.on('remove', function() {
							DOMUtils.DOM.unbind(document, 'selectionchange', selectionChangeHandler);
						});
					}
				}
			});

			editor.on('setcontent', function() {
				editor.lastRng = null;
			});

			// Remove last selection bookmark on mousedown see #6305
			editor.on('mousedown', function() {
				editor.selection.lastFocusBookmark = null;
			});

			editor.on('focusin', function() {
				var focusedEditor = editorManager.focusedEditor;

				if (editor.selection.lastFocusBookmark) {
					editor.selection.setRng(bookmarkToRng(editor, editor.selection.lastFocusBookmark));
					editor.selection.lastFocusBookmark = null;
				}

				if (focusedEditor != editor) {
					if (focusedEditor) {
						focusedEditor.fire('blur', {focusedEditor: editor});
					}

					editorManager.activeEditor = editor;
					editorManager.focusedEditor = editor;
					editor.fire('focus', {blurredEditor: focusedEditor});
					editor.focus(false);
				}

				editor.lastRng = null;
			});

			editor.on('focusout', function() {
				window.setTimeout(function() {
					var focusedEditor = editorManager.focusedEditor;

					// Still the same editor the the blur was outside any editor UI
					if (!isUIElement(getActiveElement()) && focusedEditor == editor) {
						editor.fire('blur', {focusedEditor: null});
						editorManager.focusedEditor = null;
						editor.selection.lastFocusBookmark = null;
					}
				}, 0);
			});
		}

		// Check if focus is moved to an element outside the active editor by checking if the target node
		// isn't within the body of the activeEditor nor a UI element such as a dialog child control
		DOMUtils.DOM.bind(document, 'focusin', function(e) {
			var activeEditor = editorManager.activeEditor;

			if (activeEditor && e.target.ownerDocument == document) {
				activeEditor.selection.lastFocusBookmark = createBookmark(activeEditor.lastRng);

				// Fire a blur event if the element isn't a UI element
				if (!isUIElement(e.target) && editorManager.focusedEditor == activeEditor) {
					activeEditor.fire('blur', {focusedEditor: null});
					editorManager.focusedEditor = null;
				}
			}
		});

		editorManager.on('AddEditor', registerEvents);
	}

	/**
	 * Returns true if the specified element is part of the UI for example an button or text input.
	 *
	 * @method isEditorUIElement
	 * @param  {Element} elm Element to check if it's part of the UI or not.
	 * @return {Boolean} True/false state if the element is part of the UI or not.
	 */
	FocusManager.isEditorUIElement = function(elm) {
		return elm.className.indexOf('mce-') !== -1;
	};

	return FocusManager;
});<commit_msg>Fix crash when accessing lastFocusBookmark if editor is not visible<commit_after>/**
 * FocusManager.js
 *
 * Copyright, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * This class manages the focus/blur state of the editor. This class is needed since some
 * browsers fire false focus/blur states when the selection is moved to a UI dialog or similar.
 *
 * This class will fire two events focus and blur on the editor instances that got affected.
 * It will also handle the restore of selection when the focus is lost and returned.
 *
 * @class tinymce.FocusManager
 */
define("tinymce/FocusManager", [
	"tinymce/dom/DOMUtils",
	"tinymce/Env"
], function(DOMUtils, Env) {
	/**
	 * Constructs a new focus manager instance.
	 *
	 * @constructor FocusManager
	 * @param {tinymce.EditorManager} editorManager Editor manager instance to handle focus for.
	 */
	function FocusManager(editorManager) {
		function getActiveElement() {
			try {
				return document.activeElement;
			} catch (ex) {
				// IE sometimes fails to get the activeElement when resizing table
				// TODO: Investigate this
				return document.body;
			}
		}

		// We can't store a real range on IE 11 since it gets mutated so we need to use a bookmark object
		// TODO: Move this to a separate range utils class since it's it's logic is present in Selection as well.
		function createBookmark(rng) {
			if (rng && rng.startContainer) {
				return {
					startContainer: rng.startContainer,
					startOffset: rng.startOffset,
					endContainer: rng.endContainer,
					endOffset: rng.endOffset
				};
			}

			return rng;
		}

		function bookmarkToRng(editor, bookmark) {
			var rng;

			if (bookmark.startContainer) {
				rng = editor.getDoc().createRange();
				rng.setStart(bookmark.startContainer, bookmark.startOffset);
				rng.setEnd(bookmark.endContainer, bookmark.endOffset);
			} else {
				rng = bookmark;
			}

			return rng;
		}

		function isUIElement(elm) {
			return !!DOMUtils.DOM.getParent(elm, FocusManager.isEditorUIElement);
		}

		function isNodeInBodyOfEditor(node, editor) {
			var body = editor.getBody();

			while (node) {
				if (node == body) {
					return true;
				}

				node = node.parentNode;
			}
		}

		function registerEvents(e) {
			var editor = e.editor, selectionChangeHandler;

			editor.on('init', function() {
				// On IE take selection snapshot onbeforedeactivate
				if ("onbeforedeactivate" in document && Env.ie < 11) {
					editor.dom.bind(editor.getBody(), 'beforedeactivate', function() {
						try {
							editor.lastRng = editor.selection.getRng();
						} catch (ex) {
							// IE throws "Unexcpected call to method or property access" some times so lets ignore it
						}

						editor.selection.lastFocusBookmark = createBookmark(editor.lastRng);
					});
				} else if (editor.inline || Env.ie > 10) {
					// On other browsers take snapshot on nodechange in inline mode since they have Ghost selections for iframes
					editor.on('nodechange keyup', function() {
						var node = document.activeElement;

						// IE 11 reports active element as iframe not body of iframe
						if (node && node.id == editor.id + '_ifr') {
							node = editor.getBody();
						}

						if (isNodeInBodyOfEditor(node, editor)) {
							editor.lastRng = editor.selection.getRng();
						}
					});

					// Handles the issue with WebKit not retaining selection within inline document
					// If the user releases the mouse out side the body while selecting a nodeChange won't
					// fire and there for the selection snapshot won't be stored
					// TODO: Optimize this since we only need to bind these on the active editor
					if (Env.webkit) {
						selectionChangeHandler = function() {
							var rng = editor.selection.getRng();

							// Store when it's non collapsed
							if (!rng.collapsed) {
								editor.lastRng = rng;
							}
						};

						// Bind selection handler
						DOMUtils.DOM.bind(document, 'selectionchange', selectionChangeHandler);

						editor.on('remove', function() {
							DOMUtils.DOM.unbind(document, 'selectionchange', selectionChangeHandler);
						});
					}
				}
			});

			editor.on('setcontent', function() {
				editor.lastRng = null;
			});

			// Remove last selection bookmark on mousedown see #6305
			editor.on('mousedown', function() {
				editor.selection.lastFocusBookmark = null;
			});

			editor.on('focusin', function() {
				var focusedEditor = editorManager.focusedEditor;

				if (editor.selection.lastFocusBookmark) {
					editor.selection.setRng(bookmarkToRng(editor, editor.selection.lastFocusBookmark));
					editor.selection.lastFocusBookmark = null;
				}

				if (focusedEditor != editor) {
					if (focusedEditor) {
						focusedEditor.fire('blur', {focusedEditor: editor});
					}

					editorManager.activeEditor = editor;
					editorManager.focusedEditor = editor;
					editor.fire('focus', {blurredEditor: focusedEditor});
					editor.focus(false);
				}

				editor.lastRng = null;
			});

			editor.on('focusout', function() {
				window.setTimeout(function() {
					var focusedEditor = editorManager.focusedEditor;

					// Still the same editor the the blur was outside any editor UI
					if (!isUIElement(getActiveElement()) && focusedEditor == editor) {
						editor.fire('blur', {focusedEditor: null});
						editorManager.focusedEditor = null;

						// Make sure selection is valid
						if (editor.selection) {
							editor.selection.lastFocusBookmark = null;
						}
					}
				}, 0);
			});
		}

		// Check if focus is moved to an element outside the active editor by checking if the target node
		// isn't within the body of the activeEditor nor a UI element such as a dialog child control
		DOMUtils.DOM.bind(document, 'focusin', function(e) {
			var activeEditor = editorManager.activeEditor;

			if (activeEditor && e.target.ownerDocument == document) {
				activeEditor.selection.lastFocusBookmark = createBookmark(activeEditor.lastRng);

				// Fire a blur event if the element isn't a UI element
				if (!isUIElement(e.target) && editorManager.focusedEditor == activeEditor) {
					activeEditor.fire('blur', {focusedEditor: null});
					editorManager.focusedEditor = null;
				}
			}
		});

		editorManager.on('AddEditor', registerEvents);
	}

	/**
	 * Returns true if the specified element is part of the UI for example an button or text input.
	 *
	 * @method isEditorUIElement
	 * @param  {Element} elm Element to check if it's part of the UI or not.
	 * @return {Boolean} True/false state if the element is part of the UI or not.
	 */
	FocusManager.isEditorUIElement = function(elm) {
		return elm.className.indexOf('mce-') !== -1;
	};

	return FocusManager;
});<|endoftext|>


<commit_before>export { PassThrough_FiltersArray_BiasesArray };
export { PassThrough_FiltersArray_BiasesArray_Root };
export { PassThrough_FiltersArray_BiasesArray_Bag };
export { PassThrough };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as TwoTensors from "../../util/TwoTensors.js";
import * as MultiLayerMap from "../../util/MultiLayerMap.js";
import { PadInfoCalculator } from "./Depthwise_PadInfoCalculator.js";

/**
 * A depthwise convolution and bias which just pass the input to output.
 *
 * It is usually used in passing the higher half channels of the input to output (for achieving ShuffleNetV2_ByMopbileNetV1's body/tail).
 *
 * Note1: Although depthwise (and pointwise) convolution could be past-through, the activation function will destroy the past-through
 * result. Using Pointwise_FiltersArray_BiasesArray may be better to handle this issue.
 *
 * Note2: If both effectFilterValue and surroundingFilterValue are the same as ( 1 / ( filterHeight * filter Width ) ), the result filter
 * will have the same effect as average pooling.
 *
 *
 *
 * @member {number} effectFilterValue
 *   The value used as the effect value of the pass-through depthwise convolution filter. Default is 1. If there will be no activation
 * function after this pass-through operation, value 1 is enough. However, if there wiil be an activation function, this past-through
 * result might be destroyed by the activation function. In order to alleviate this issue, a non-one filter value should be used. For
 * example, if every input value's range is [ 0,255 ] and RELU6 will be used as activation function, using 0.015625 (= 1 / 64 ) as
 * filterValue is appropriate because input values will be shrinked from [ 0, 255 ] into [ 0, 3.984375 ] which will still be kept
 * linear by RELU6.
 *
 * @member {number} surroundingFilterValue
 *   The value used as the surrounding value of the pass-through depthwise convolution filter. Default is 0.
 *
 * @member {number} biasValue
 *   The value used as the pass-through bias (used only if ( bBias == true ) ). Default is 0. If there will be no activation function
 * after this pass-through operation, value 0 is enough. However, if there wiil be an activation function, this past-through result
 * might be destroyed by the activation function. In order to alleviate this issue, a non-zero bias value should be used. For example,
 * if every input value's range is [ -2, +2 ] and RELU6 will be used as activation function, using +2 as biasValue is appropriate
 * because input values will be shifted from [ -2, +2 ] into [ 0, 4 ] which will still be kept linear by RELU6.
 *
 * @member {number[]} filtersShape
 *   The shape of the pass-through filters array.
 *
 * @member {number[]} biasesShape
 *   The shape of the pass-through biases array.
 *
 * @member {number[]} filtersArray
 *   The pass-through filters array.
 *
 * @member {number[]} biasesArray
 *   The pass-through biases array.
 *
 * @see PadInfoCalculator
 */
let PassThrough_FiltersArray_BiasesArray
  = ( ParentClass = Object ) => class PassThrough_FiltersArray_BiasesArray extends PadInfoCalculator( ParentClass ) {

  /**
   * Used as default Depthwise.PassThrough_FiltersArray_BiasesArray provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.PassThrough_FiltersArray_BiasesArray.Pool",
    PassThrough_FiltersArray_BiasesArray, PassThrough_FiltersArray_BiasesArray.setAsConstructor );

  /**
   */
  constructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad );
    PassThrough_FiltersArray_BiasesArray.setAsConstructor_self.call( this,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
  }

  /** @override */
  static setAsConstructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super.setAsConstructor( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad );
    PassThrough_FiltersArray_BiasesArray.setAsConstructor_self.call( this,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
    return this;
  }

  /** @override */
  static setAsConstructor_self( bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {
    this.bBias = bBias;
    this.effectFilterValue = effectFilterValue;
    this.surroundingFilterValue = surroundingFilterValue;
    this.biasValue = biasValue;

    this.filtersShape = Recyclable.Array.Pool.get_or_create_by( 4 );
    this.filtersShape[ 0 ] = this.filterHeight;
    this.filtersShape[ 1 ] = this.filterWidth;
    this.filtersShape[ 2 ] = this.inputChannelCount;
    this.filtersShape[ 3 ] = this.channelMultiplier;

    PassThrough_FiltersArray_BiasesArray.generate_PassThrough_FiltersArray.call( this, effectFilterValue, surroundingFilterValue );

    if ( this.bBias ) {
      this.biasesShape = Recyclable.Array.Pool.get_or_create_by( 3 );
      this.biasesShape[ 0 ] = 1;
      this.biasesShape[ 1 ] = 1;
      this.biasesShape[ 2 ] = this.outputChannelCount;

      this.biasesArray = Recyclable.Array.Pool.get_or_create_by( this.outputChannelCount );
      this.biasesArray.fill( biasValue );
    }
  }

  /** @override */
  disposeResources() {
    if ( this.biasesArray ) {
      this.biasesArray.disposeResources_and_recycleToPool();
      this.biasesArray = null;
    }

    if ( this.biasesShape ) {
      this.biasesShape.disposeResources_and_recycleToPool();
      this.biasesShape = null;
    }

    if ( this.filtersArray ) {
      this.filtersArray.disposeResources_and_recycleToPool();
      this.filtersArray = null;
    }

    if ( this.filtersShape ) {
      this.filtersShape.disposeResources_and_recycleToPool();
      this.filtersShape = null;
    }

    super.disposeResources();
  }

  /**
   * Determine the following properties:
   *   - this.filtersArray
   *
   * It is an number array representing the depthwise convolution filters which could pass the input to output unchangely.
   *
   * If both effectFilterValue and otherFilterValue are the same as ( 1 / ( filterHeight * filter Width ) ), the result filter
   * will have the same effect as average pooling.
   *
   *
   * @param {number} effectFilterValue
   *   The filter value used for the effect input pixel of the depthwise convolution. For pass-through, it is usually 1.
   * Note: It is not always just at center of filter according to the filter shape and paddding.
   *
   * @param {number} surroundingFilterValue
   *   The filter value used for the surrounding input pixel of the depthwise convolution. For pass-through, it is usually 0.
   *
   */
  static generate_PassThrough_FiltersArray( effectFilterValue, surroundingFilterValue ) {

    if (   ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG === this.AvgMax_Or_ChannelMultiplier )
        || ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX === this.AvgMax_Or_ChannelMultiplier ) ) {

      if ( this.filtersArray ) {
        this.filtersArray.disposeResources_and_recycleToPool();
        this.filtersArray = null;
      }

      return; // The depthwise filter of AVG pooling and MAX pooling can not be manipulated.
    }

    // Make up a depthwise convolution filter.
    this.filtersArray = Recyclable.Array.Pool.get_or_create_by(
      this.filterHeight * this.filterWidth * this.inputChannelCount * this.channelMultiplier );

    // There is only one position (inside the effect depthwise filter) uses effectFilterValue.
    // All other positions of the filter should be surroundingFilterValue.
    //
    let oneEffectFilterY = this.padHeightTop;
    let oneEffectFilterX = this.padWidthLeft;

    // Note: Unfortunately, this may not work for ( dilation > 1 ) because the non-zero-filter-value might be just at the dilation
    //       position which does not exist in a filter. So, only ( dilation == 1 ) is supported.

    let filterIndex = 0; // The index in the filter weights array.

    for ( let filterY = 0, effectFilterY = 0; filterY < this.filterHeight; ++filterY ) {
      for ( let dilationFilterY = 0; dilationFilterY < this.dilationHeight; ++dilationFilterY, ++effectFilterY ) {

        for ( let filterX = 0, effectFilterX = 0; filterX < this.filterWidth; ++filterX ) {
          for ( let dilationFilterX = 0; dilationFilterX < this.dilationWidth; ++dilationFilterX, ++effectFilterX ) {

            // The filter's dilation part can not be manipulated. (They are always zero.)
            if ( ( 0 != dilationFilterY ) || ( 0 != dilationFilterX ) )
              continue;

            for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) {

              for ( let outChannelSub = 0; outChannelSub < this.channelMultiplier; ++outChannelSub ) {

                if ( ( effectFilterY == oneEffectFilterY ) && ( effectFilterX == oneEffectFilterX ) ) {
                  this.filtersArray[ filterIndex ] = effectFilterValue;
                } else {
                  this.filtersArray[ filterIndex ] = surroundingFilterValue;
                }

                ++filterIndex;
              }
            }
          }
        }
      }
    }
  }

}

/**
 * Almost the same as Depthwise.PassThrough_FiltersArray_BiasesArray class except its parent class is fixed to Object. In other words,
 * caller can not specify the parent class of Depthwise.PassThrough_FiltersArray_BiasesArray_Root (so it is named "Root" which can not
 * have parent class).
 */
class PassThrough_FiltersArray_BiasesArray_Root extends PassThrough_FiltersArray_BiasesArray() {
}

/**
 * A pool for PassThrough_FiltersArray_BiasesArray with various parameters. It could reduce re-creating them of same parameters again
 * and again to improve performance.
 *
 */
class PassThrough_FiltersArray_BiasesArray_Bag extends Recyclable.Base( MultiLayerMap.Base ) {

  /**
   * Used as default Depthwise.PassThrough_FiltersArray_BiasesArray_Bag provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.PassThrough_FiltersArray_BiasesArray_Bag.Pool",
    PassThrough_FiltersArray_BiasesArray_Bag, PassThrough_FiltersArray_BiasesArray_Bag.setAsConstructor );

  /**
   */
  constructor() {
    super();
    PassThrough_FiltersArray_BiasesArray_Bag.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor() {
    super.setAsConstructor();
    PassThrough_FiltersArray_BiasesArray_Bag.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
  }

  /** Release all channel shufflers and their tf.tensor.
   * @override
   */
  disposeResources() {
    this.clear();
    super.disposeResources();
  }

  /** @override */
  clear() {
    for ( let aPassThrough_FiltersArray_BiasesArray of this.values() ) {
      aPassThrough_FiltersArray_BiasesArray.disposeResources_and_recycleToPool();
    }
    super.clear();
  }

  /**
   *
   */
  get_by_PassThroughStyleId(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, nPassThroughStyleId ) {

    const thePassThroughStyleInfo = ValueDesc.PassThroughStyle.Singleton.getInfoById( nPassThroughStyleId );
    return this.get_by_effectFilterValue_surroundingFilterValue_biasValue(
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, thePassThroughStyleInfo.filterValue, 0, thePassThroughStyleInfo.biasValue );
  }

  /**
   *
   */
  get_by_effectFilterValue_surroundingFilterValue_biasValue(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    return this.get_or_create_by_arguments1_etc( PassThrough_FiltersArray_BiasesArray_Bag.create_by,
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
  }

  /** */
  static create_by(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue, surroundingFilterValue, biasValue ) {

    return new PassThrough_FiltersArray_BiasesArray_Root(
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
  }

}

/**
 * A depthwise convolution and bias which just pass the input to output.
 *
 * It is usually used in passing the higher half channels of the input to output (for achieving ShuffleNetV2_ByMopbileNetV1's body/tail).
 *
 *
 * @see PassThrough_FiltersArray_BiasesArray
 * @see PadInfoCalculator
 * @see TwoTensors.filtersTensor4d_biasesTensor3d
 */
class PassThrough extends PassThrough_FiltersArray_BiasesArray( TwoTensors.filtersTensor4d_biasesTensor3d() ) {

  /**
   * Used as default Depthwise.PassThrough provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.PassThrough.Pool", PassThrough, PassThrough.setAsConstructor );

  /**
   */
  constructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );

    PassThrough.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super.setAsConstructor( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );

    PassThrough.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
    this.filtersTensor4d = tf.tensor4d( this.filtersArray, this.filtersShape );
    if ( this.bBias ) {
      this.biasesTensor3d = tf.tensor3d( this.biasesArray, this.biasesShape );
    }
    this.bInitOk = true;
  }

  /** @override */
  disposeResources() {
    this.bInitOk = false;
    super.disposeResources(); // Release .filtersTensor4d and biasesTensor3d.
  }

}

<commit_msg>Update Depthwise_PassThrough.js<commit_after>export { PassThrough_FiltersArray_BiasesArray };
export { PassThrough_FiltersArray_BiasesArray_Root };
export { PassThrough_FiltersArray_BiasesArray_Bag };
export { PassThrough };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as TwoTensors from "../../util/TwoTensors.js";
import * as MultiLayerMap from "../../util/MultiLayerMap.js";
import { PadInfoCalculator } from "./Depthwise_PadInfoCalculator.js";

/**
 * A depthwise convolution and bias which just pass the input to output.
 *
 * It is usually used in passing the higher half channels of the input to output (for achieving ShuffleNetV2_ByMopbileNetV1's body/tail).
 *
 * Note1: Although depthwise (and pointwise) convolution could be past-through, the activation function will destroy the past-through
 * result. Using Pointwise_FiltersArray_BiasesArray may be better to handle this issue.
 *
 * Note2: If both effectFilterValue and surroundingFilterValue are the same as ( 1 / ( filterHeight * filter Width ) ), the result filter
 * will have the same effect as average pooling.
 *
 *
 *
 * @member {number} effectFilterValue
 *   The value used as the effect value of the pass-through depthwise convolution filter. Default is 1. If there will be no activation
 * function after this pass-through operation, value 1 is enough. However, if there wiil be an activation function, this past-through
 * result might be destroyed by the activation function. In order to alleviate this issue, a non-one filter value should be used. For
 * example, if every input value's range is [ 0,255 ] and RELU6 will be used as activation function, using 0.015625 (= 1 / 64 ) as
 * filterValue is appropriate because input values will be shrinked from [ 0, 255 ] into [ 0, 3.984375 ] which will still be kept
 * linear by RELU6.
 *
 * @member {number} surroundingFilterValue
 *   The value used as the surrounding value of the pass-through depthwise convolution filter. Default is 0.
 *
 * @member {number} biasValue
 *   The value used as the pass-through bias (used only if ( bBias == true ) ). Default is 0. If there will be no activation function
 * after this pass-through operation, value 0 is enough. However, if there wiil be an activation function, this past-through result
 * might be destroyed by the activation function. In order to alleviate this issue, a non-zero bias value should be used. For example,
 * if every input value's range is [ -2, +2 ] and RELU6 will be used as activation function, using +2 as biasValue is appropriate
 * because input values will be shifted from [ -2, +2 ] into [ 0, 4 ] which will still be kept linear by RELU6.
 *
 * @member {number[]} filtersShape
 *   The shape of the pass-through filters array.
 *
 * @member {number[]} biasesShape
 *   The shape of the pass-through biases array.
 *
 * @member {number[]} filtersArray
 *   The pass-through filters array.
 *
 * @member {number[]} biasesArray
 *   The pass-through biases array.
 *
 * @see PadInfoCalculator
 */
let PassThrough_FiltersArray_BiasesArray
  = ( ParentClass = Object ) => class PassThrough_FiltersArray_BiasesArray extends PadInfoCalculator( ParentClass ) {

  /**
   * Used as default Depthwise.PassThrough_FiltersArray_BiasesArray provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.PassThrough_FiltersArray_BiasesArray.Pool",
    PassThrough_FiltersArray_BiasesArray, PassThrough_FiltersArray_BiasesArray.setAsConstructor );

  /**
   */
  constructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad );
    PassThrough_FiltersArray_BiasesArray.setAsConstructor_self.call( this,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
  }

  /** @override */
  static setAsConstructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super.setAsConstructor( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad );
    PassThrough_FiltersArray_BiasesArray.setAsConstructor_self.call( this,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
    return this;
  }

  /** @override */
  static setAsConstructor_self( bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {
    this.bBias = bBias;
    this.effectFilterValue = effectFilterValue;
    this.surroundingFilterValue = surroundingFilterValue;
    this.biasValue = biasValue;

    this.filtersShape = Recyclable.Array.Pool.get_or_create_by( 4 );
    this.filtersShape[ 0 ] = this.filterHeight;
    this.filtersShape[ 1 ] = this.filterWidth;
    this.filtersShape[ 2 ] = this.inputChannelCount;
    this.filtersShape[ 3 ] = this.channelMultiplier;

    PassThrough_FiltersArray_BiasesArray.generate_PassThrough_FiltersArray.call( this, effectFilterValue, surroundingFilterValue );

    if ( this.bBias ) {
      this.biasesShape = Recyclable.Array.Pool.get_or_create_by( 3 );
      this.biasesShape[ 0 ] = 1;
      this.biasesShape[ 1 ] = 1;
      this.biasesShape[ 2 ] = this.outputChannelCount;

      this.biasesArray = Recyclable.Array.Pool.get_or_create_by( this.outputChannelCount );
      this.biasesArray.fill( biasValue );
    }
  }

  /** @override */
  disposeResources() {
    if ( this.biasesArray ) {
      this.biasesArray.disposeResources_and_recycleToPool();
      this.biasesArray = null;
    }

    if ( this.biasesShape ) {
      this.biasesShape.disposeResources_and_recycleToPool();
      this.biasesShape = null;
    }

    if ( this.filtersArray ) {
      this.filtersArray.disposeResources_and_recycleToPool();
      this.filtersArray = null;
    }

    if ( this.filtersShape ) {
      this.filtersShape.disposeResources_and_recycleToPool();
      this.filtersShape = null;
    }

    super.disposeResources();
  }

  /**
   * Determine the following properties:
   *   - this.filtersArray
   *
   * It is an number array representing the depthwise convolution filters which could pass the input to output unchangely.
   *
   * If both effectFilterValue and otherFilterValue are the same as ( 1 / ( filterHeight * filter Width ) ), the result filter
   * will have the same effect as average pooling.
   *
   *
   * @param {number} effectFilterValue
   *   The filter value used for the effect input pixel of the depthwise convolution. For pass-through, it is usually 1.
   * Note: It is not always just at center of filter according to the filter shape and paddding.
   *
   * @param {number} surroundingFilterValue
   *   The filter value used for the surrounding input pixel of the depthwise convolution. For pass-through, it is usually 0.
   *
   */
  static generate_PassThrough_FiltersArray( effectFilterValue, surroundingFilterValue ) {

    if (   ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.AVG === this.AvgMax_Or_ChannelMultiplier )
        || ( ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX === this.AvgMax_Or_ChannelMultiplier ) ) {

      if ( this.filtersArray ) {
        this.filtersArray.disposeResources_and_recycleToPool();
        this.filtersArray = null;
      }

      return; // The depthwise filter of AVG pooling and MAX pooling can not be manipulated.
    }

    // Make up a depthwise convolution filter.
    this.filtersArray = Recyclable.Array.Pool.get_or_create_by(
      this.filterHeight * this.filterWidth * this.inputChannelCount * this.channelMultiplier );

    // There is only one position (inside the effect depthwise filter) uses effectFilterValue.
    // All other positions of the filter should be surroundingFilterValue.
    //
    let oneEffectFilterY = this.padHeightTop;
    let oneEffectFilterX = this.padWidthLeft;

    // Note: Unfortunately, this may not work for ( dilation > 1 ) because the non-zero-filter-value might be just at the dilation
    //       position which does not exist in a filter. So, only ( dilation == 1 ) is supported.

    let filterIndex = 0; // The index in the filter weights array.

    for ( let filterY = 0, effectFilterY = 0; filterY < this.filterHeight; ++filterY ) {
      for ( let dilationFilterY = 0; dilationFilterY < this.dilationHeight; ++dilationFilterY, ++effectFilterY ) {

        for ( let filterX = 0, effectFilterX = 0; filterX < this.filterWidth; ++filterX ) {
          for ( let dilationFilterX = 0; dilationFilterX < this.dilationWidth; ++dilationFilterX, ++effectFilterX ) {

            // The filter's dilation part can not be manipulated. (They are always zero.)
            if ( ( 0 != dilationFilterY ) || ( 0 != dilationFilterX ) )
              continue;

            for ( let inChannel = 0; inChannel < this.inputChannelCount; ++inChannel ) {

              for ( let outChannelSub = 0; outChannelSub < this.channelMultiplier; ++outChannelSub ) {

                if ( ( effectFilterY == oneEffectFilterY ) && ( effectFilterX == oneEffectFilterX ) ) {
                  this.filtersArray[ filterIndex ] = effectFilterValue;
                } else {
                  this.filtersArray[ filterIndex ] = surroundingFilterValue;
                }

                ++filterIndex;
              }
            }
          }
        }
      }
    }
  }

}

/**
 * Almost the same as Depthwise.PassThrough_FiltersArray_BiasesArray class except its parent class is fixed to Object. In other words,
 * caller can not specify the parent class of Depthwise.PassThrough_FiltersArray_BiasesArray_Root (so it is named "Root" which can not
 * have parent class).
 */
class PassThrough_FiltersArray_BiasesArray_Root extends PassThrough_FiltersArray_BiasesArray() {
}

/**
 * A pool for PassThrough_FiltersArray_BiasesArray with various parameters. It could reduce re-creating them of same parameters again
 * and again to improve performance.
 *
 */
class PassThrough_FiltersArray_BiasesArray_Bag extends Recyclable.Base( MultiLayerMap.Base ) {

  /**
   * Used as default Depthwise.PassThrough_FiltersArray_BiasesArray_Bag provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.PassThrough_FiltersArray_BiasesArray_Bag.Pool",
    PassThrough_FiltersArray_BiasesArray_Bag, PassThrough_FiltersArray_BiasesArray_Bag.setAsConstructor );

  /**
   */
  constructor() {
    super();
    PassThrough_FiltersArray_BiasesArray_Bag.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor() {
    super.setAsConstructor();
    PassThrough_FiltersArray_BiasesArray_Bag.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
  }

  /** @override */
  disposeResources() {
    this.clear();
    super.disposeResources();
  }

  /** @override */
  clear() {
    for ( let aPassThrough_FiltersArray_BiasesArray of this.values() ) {
      aPassThrough_FiltersArray_BiasesArray.disposeResources_and_recycleToPool();
    }
    super.clear();
  }

  /**
   *
   */
  get_by_PassThroughStyleId(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, nPassThroughStyleId ) {

    const thePassThroughStyleInfo = ValueDesc.PassThroughStyle.Singleton.getInfoById( nPassThroughStyleId );
    return this.get_by_effectFilterValue_surroundingFilterValue_biasValue(
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, thePassThroughStyleInfo.filterValue, 0, thePassThroughStyleInfo.biasValue );
  }

  /**
   *
   */
  get_by_effectFilterValue_surroundingFilterValue_biasValue(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    return this.get_or_create_by_arguments1_etc( PassThrough_FiltersArray_BiasesArray_Bag.create_by,
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
  }

  /** */
  static create_by(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue, surroundingFilterValue, biasValue ) {

    return new PassThrough_FiltersArray_BiasesArray_Root(
      inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );
  }

}

/**
 * A depthwise convolution and bias which just pass the input to output.
 *
 * It is usually used in passing the higher half channels of the input to output (for achieving ShuffleNetV2_ByMopbileNetV1's body/tail).
 *
 *
 * @see PassThrough_FiltersArray_BiasesArray
 * @see PadInfoCalculator
 * @see TwoTensors.filtersTensor4d_biasesTensor3d
 */
class PassThrough extends PassThrough_FiltersArray_BiasesArray( TwoTensors.filtersTensor4d_biasesTensor3d() ) {

  /**
   * Used as default Depthwise.PassThrough provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Depthwise.PassThrough.Pool", PassThrough, PassThrough.setAsConstructor );

  /**
   */
  constructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );

    PassThrough.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor(
    inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
    bBias, effectFilterValue = 1, surroundingFilterValue = 0, biasValue = 0 ) {

    super.setAsConstructor( inputHeight, inputWidth, inputChannelCount, AvgMax_Or_ChannelMultiplier, filterHeight, filterWidth, stridesPad,
      bBias, effectFilterValue, surroundingFilterValue, biasValue );

    PassThrough.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
    this.filtersTensor4d = tf.tensor4d( this.filtersArray, this.filtersShape );
    if ( this.bBias ) {
      this.biasesTensor3d = tf.tensor3d( this.biasesArray, this.biasesShape );
    }
    this.bInitOk = true;
  }

  /** @override */
  disposeResources() {
    this.bInitOk = false;
    super.disposeResources(); // Release .filtersTensor4d and biasesTensor3d.
  }

}

<|endoftext|>


<commit_before>import Lokka from 'lokka';
import Transport from 'lokka-transport-http';

var url = process.env.NODE_ENV === 'production' ? 'http://gma-village-graphql.appspot.com/graphql' : 'http://localhost:8080/graphql'
const client = new Lokka({
  transport: new Transport(url, {credentials: false}),

});

export default client
<commit_msg>hard coded correct graphql server location for prod<commit_after>import Lokka from 'lokka';
import Transport from 'lokka-transport-http';

const prod = process.env.NODE_ENV === 'production'
var url = prod ? 'https://gma-village-graphql-dev-dot-gma-village.appspot.com/graphql' : 'http://localhost:8080/graphql'

const client = new Lokka({
  transport: new Transport(url, {credentials: false})
});

export default client
<|endoftext|>


<commit_before>'use strict';

// #####################################################################################################################
// #IMPORTS#
var autoprefixer = require('gulp-autoprefixer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var minifyCss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');

var argv = require('minimist')(process.argv.slice(2));

// #####################################################################################################################
// #SETTINGS#
var options = {
    debug: argv.debug
};
var PROJECT_ROOT = __dirname;
var PROJECT_PATH = {
    js: PROJECT_ROOT + '/js',
    sass: PROJECT_ROOT + '/sass',
    css: PROJECT_ROOT + '/css',
    icons: PROJECT_ROOT + '/fonts'
};

var PROJECT_PATTERNS = {
    js: [
        PROJECT_PATH.js + '/modules/*.js',
        '!' + PROJECT_PATH.js + '/modules/jquery.ui.*.js',
        '/gulpfile.js',
    ],
    sass: [
        PROJECT_PATH.sass + '/**/*.{scss,sass}'
    ],
    icons: [
        PROJECT_PATH.icons + '/src/*.svg'
    ]
};

// #####################################################################################################################
// #TASKS#
gulp.task('sass', function () {
    gulp.src(PROJECT_PATTERNS.sass)
        .pipe(gulpif(options.debug, sourcemaps.init()))
        .pipe(sass())
        .on('error', function (error) {
            gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.messageFormatted));
        })
        .pipe(autoprefixer({
            browsers: ['last 3 versions'],
            cascade: false
        }))
        .pipe(minifyCss())
        .pipe(gulpif(options.debug, sourcemaps.write()))
        .pipe(gulp.dest(PROJECT_PATH.css));
});

gulp.task('icons', function () {
    gulp.src(PROJECT_PATTERNS.icons)
    .pipe(iconfontCss({
        fontName: 'django-cms-iconfont',
        fontPath: '../fonts/',
        path: PROJECT_PATH.sass + '/libs/_iconfont.scss',
        targetPath: '../sass/components/_iconography.scss'
    }))
    .pipe(iconfont({
        fontName: 'django-cms-iconfont',
        normalize: true
    }))
    .on('glyphs', function(glyphs, options) {
        gutil.log.bind(glyphs, options);
    })
    .pipe(gulp.dest(PROJECT_PATH.icons));
});

gulp.task('lint', ['lint:javascript']);
gulp.task('lint:javascript', function () {
    // DOCS: http://jshint.com/docs/
    return gulp.src(PROJECT_PATTERNS.js)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
            if (process.env.CI) {
                // Force the process to exit with error code
                process.exit(1);
            }
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('watch', function () {
    gulp.watch(PROJECT_PATTERNS.sass, ['sass']);
    gulp.watch(PROJECT_PATTERNS.js, ['lint']);
});

gulp.task('default', ['sass', 'lint', 'watch']);
<commit_msg>gulpfile 755 -> 644<commit_after>'use strict';

// #####################################################################################################################
// #IMPORTS#
var autoprefixer = require('gulp-autoprefixer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var minifyCss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');

var argv = require('minimist')(process.argv.slice(2));

// #####################################################################################################################
// #SETTINGS#
var options = {
    debug: argv.debug
};
var PROJECT_ROOT = __dirname;
var PROJECT_PATH = {
    js: PROJECT_ROOT + '/js',
    sass: PROJECT_ROOT + '/sass',
    css: PROJECT_ROOT + '/css',
    icons: PROJECT_ROOT + '/fonts'
};

var PROJECT_PATTERNS = {
    js: [
        PROJECT_PATH.js + '/modules/*.js',
        '!' + PROJECT_PATH.js + '/modules/jquery.ui.*.js',
        '/gulpfile.js',
    ],
    sass: [
        PROJECT_PATH.sass + '/**/*.{scss,sass}'
    ],
    icons: [
        PROJECT_PATH.icons + '/src/*.svg'
    ]
};

// #####################################################################################################################
// #TASKS#
gulp.task('sass', function () {
    gulp.src(PROJECT_PATTERNS.sass)
        .pipe(gulpif(options.debug, sourcemaps.init()))
        .pipe(sass())
        .on('error', function (error) {
            gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.messageFormatted));
        })
        .pipe(autoprefixer({
            browsers: ['last 3 versions'],
            cascade: false
        }))
        .pipe(minifyCss())
        .pipe(gulpif(options.debug, sourcemaps.write()))
        .pipe(gulp.dest(PROJECT_PATH.css));
});

gulp.task('icons', function () {
    gulp.src(PROJECT_PATTERNS.icons)
    .pipe(iconfontCss({
        fontName: 'django-cms-iconfont',
        fontPath: '../fonts/',
        path: PROJECT_PATH.sass + '/libs/_iconfont.scss',
        targetPath: '../sass/components/_iconography.scss'
    }))
    .pipe(iconfont({
        fontName: 'django-cms-iconfont',
        normalize: true
    }))
    .on('glyphs', function(glyphs, options) {
        gutil.log.bind(glyphs, options);
    })
    .pipe(gulp.dest(PROJECT_PATH.icons));
});

gulp.task('lint', ['lint:javascript']);
gulp.task('lint:javascript', function () {
    // DOCS: http://jshint.com/docs/
    return gulp.src(PROJECT_PATTERNS.js)
        .pipe(jshint())
        .pipe(jscs())
        .on('error', function (error) {
            gutil.log('\n' + error.message);
            if (process.env.CI) {
                // Force the process to exit with error code
                process.exit(1);
            }
        })
        .pipe(jshint.reporter('jshint-stylish'));
});

gulp.task('watch', function () {
    gulp.watch(PROJECT_PATTERNS.sass, ['sass']);
    gulp.watch(PROJECT_PATTERNS.js, ['lint']);
});

gulp.task('default', ['sass', 'lint', 'watch']);
<|endoftext|>


<commit_before>'use strict'

function WorldManager() {
    this.__init__()
}

WorldManager.prototype = {

    player         : null,

    previous_world : null,
    current_world  : null,
    current_scene  : null,

    // Pre-defined worlds.
    world_login    : null,
    world_home     : null,
    world_settings : null,

    // Skybox
    SKY_BOX_TEXTURE_FRONT  : null,
    SKY_BOX_TEXTURE_BACK   : null,
    SKY_BOX_TEXTURE_LEFT   : null,
    SKY_BOX_TEXTURE_RIGHT  : null,
    SKY_BOX_TEXTURE_BOTTOM : null,
    SKY_BOX_TEXTURE_TOP    : null,
    number_of_sky_box_textures_loaded: null,

    __init__: function() {
        this.world_login = new LoginWorld()
        this.world_home = new HomeWorld()

        this.number_of_sky_box_textures_loaded = 0
        this.load_sky_box()
    },

    set_player: function(player) {
        this.player = player
        this.world_login.set_player(player)
        this.world_home.set_player(player)
    },

    update_current_scene: function() {
        this.current_world.update()
    },

    set_current_world: function(world) {
        if (this.current_world !== null) {

            // Before exiting the world make sure to remove the camera reference.
            this.current_world.remove_from_scene(this.player.fps_controls.yaw)

            this.current_world.exit_world()
            this.current_world.current_world = false
            this.previous_world = this.current_world
        }
        this.current_world = world
        this.current_world.current_world = true
        this.current_scene = this.current_world.scene

        // Before adding the world make sure to add the camera reference.
        this.current_world.add_to_scene(this.player.fps_controls.yaw)
        this.current_world.enter_world()
    },

    key_down_event: function(event) {
        this.current_world.key_down_event(event)
    },

    add_to_current_scene: function(object) {
        this.current_world.add(object)
    },

    add_to_all_scenes: function(object) {
        this.world_login.add_to_scene(object)
        this.world_home.add_to_scene(object)
    },

    // Skybox
    create_sky_boxes: function() {
        var skybox_materials = [this.SKY_BOX_TEXTURE_FRONT, this.SKY_BOX_TEXTURE_BACK, this.SKY_BOX_TEXTURE_TOP, this.SKY_BOX_TEXTURE_BOTTOM, this.SKY_BOX_TEXTURE_RIGHT, this.SKY_BOX_TEXTURE_LEFT]
        this.world_login.add_sky_box(skybox_materials)
    },

    load_sky_box: function() {
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_front.jp2', this.SKY_BOX_TEXTURE_FRONT).bind(this)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_back.jp2', this.SKY_BOX_TEXTURE_BACK).bind(this)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_top.jp2', this.SKY_BOX_TEXTURE_TOP).bind(this)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_bottom.jp2', this.SKY_BOX_TEXTURE_BOTTOM).bind(this)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_right.jp2', this.SKY_BOX_TEXTURE_RIGHT).bind(this)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_left.jp2', this.SKY_BOX_TEXTURE_LEFT).bind(this)
    },

    // TODO : Add error checking.
    load_specific_texture: function(texture_url, variable_to_map_to) {
        var ta = new THREE.TextureLoader().load(texture_url,
        //function when resource is loaded
            function(texture) {
                variable_to_map_to = new THREE.MeshBasicMaterial({map: texture})
                this.number_of_sky_box_textures_loaded += 1
                if (this.number_of_sky_box_textures_loaded == 6) {
                    this.create_sky_boxes()
                }
            }
        )
    },

}<commit_msg>general updating 12<commit_after>'use strict'

function WorldManager() {
    this.__init__()
}

WorldManager.prototype = {

    player         : null,

    previous_world : null,
    current_world  : null,
    current_scene  : null,

    // Pre-defined worlds.
    world_login    : null,
    world_home     : null,
    world_settings : null,

    // Skybox
    SKY_BOX_TEXTURE_FRONT  : null,
    SKY_BOX_TEXTURE_BACK   : null,
    SKY_BOX_TEXTURE_LEFT   : null,
    SKY_BOX_TEXTURE_RIGHT  : null,
    SKY_BOX_TEXTURE_BOTTOM : null,
    SKY_BOX_TEXTURE_TOP    : null,
    number_of_sky_box_textures_loaded: null,

    __init__: function() {
        this.world_login = new LoginWorld()
        this.world_home = new HomeWorld()

        this.number_of_sky_box_textures_loaded = 0
        this.load_sky_box()
    },

    set_player: function(player) {
        this.player = player
        this.world_login.set_player(player)
        this.world_home.set_player(player)
    },

    update_current_scene: function() {
        this.current_world.update()
    },

    set_current_world: function(world) {
        if (this.current_world !== null) {

            // Before exiting the world make sure to remove the camera reference.
            this.current_world.remove_from_scene(this.player.fps_controls.yaw)

            this.current_world.exit_world()
            this.current_world.current_world = false
            this.previous_world = this.current_world
        }
        this.current_world = world
        this.current_world.current_world = true
        this.current_scene = this.current_world.scene

        // Before adding the world make sure to add the camera reference.
        this.current_world.add_to_scene(this.player.fps_controls.yaw)
        this.current_world.enter_world()
    },

    key_down_event: function(event) {
        this.current_world.key_down_event(event)
    },

    add_to_current_scene: function(object) {
        this.current_world.add(object)
    },

    add_to_all_scenes: function(object) {
        this.world_login.add_to_scene(object)
        this.world_home.add_to_scene(object)
    },

    // Skybox
    create_sky_boxes: function() {
        var skybox_materials = [this.SKY_BOX_TEXTURE_FRONT, this.SKY_BOX_TEXTURE_BACK, this.SKY_BOX_TEXTURE_TOP, this.SKY_BOX_TEXTURE_BOTTOM, this.SKY_BOX_TEXTURE_RIGHT, this.SKY_BOX_TEXTURE_LEFT]
        this.world_login.add_sky_box(skybox_materials)
    },

    load_sky_box: function() {
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_front.jp2', this.SKY_BOX_TEXTURE_FRONT)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_back.jp2', this.SKY_BOX_TEXTURE_BACK)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_top.jp2', this.SKY_BOX_TEXTURE_TOP)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_bottom.jp2', this.SKY_BOX_TEXTURE_BOTTOM)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_right.jp2', this.SKY_BOX_TEXTURE_RIGHT)
        this.load_specific_texture('/home/git_repos/quasar_source/quasar_source_code/quasar_site_django/static/assets/skybox/skybox_texture_left.jp2', this.SKY_BOX_TEXTURE_LEFT)
    },

    // TODO : Add error checking.
    load_specific_texture: function(texture_url, variable_to_map_to) {
        var ta = new THREE.TextureLoader().load(texture_url,
        //function when resource is loaded
            function(texture) {
                variable_to_map_to = new THREE.MeshBasicMaterial({map: texture})
                this.number_of_sky_box_textures_loaded += 1
                if (this.number_of_sky_box_textures_loaded == 6) {
                    this.create_sky_boxes()
                }
            }
        )
    },

}<|endoftext|>


<commit_before>"use strict";

/**
 * Contains a set of methods for inflection rules sorting.
 *
 * @type {Object}
 */
const sort = {};

sort.rulesByApplicationDesc = (firstRule, secondRule, application) => {
    return !firstRule.applications.length && secondRule.applications.length && secondRule.applications.indexOf(application) !== -1;
};

module.exports = sort;
<commit_msg>Added doc block to the sort rulesByApplicationDesc method<commit_after>"use strict";

/**
 * Contains a set of methods for inflection rules sorting.
 *
 * @type {Object}
 */
const sort = {};

/**
 * Sort by the rule applications ("noun", "adjective" etc.) descending.
 *
 * @param {Object} firstRule
 * @param {Object} secondRule
 * @param {string} value
 * @return {boolean}
 */
sort.rulesByApplicationDesc = (firstRule, secondRule, value) => {
    return !firstRule.applications.length && secondRule.applications.length && secondRule.applications.indexOf(value) !== -1;
};

module.exports = sort;
<|endoftext|>


<commit_before>/**
* Generates HTML that can function as standalone chapters or as chapters loaded by the main app
* This attemps to load folders in the ./input/ directory, read the ./input/version/info.json and
* then use a renderer found in ./node_modules/generate_renderername.js
*
* See options for details on running
*/

// MODULES
var fs = require('fs'),
	path = require('path'),
	rmrf = require('rimraf').sync,
	mkdirp = require('mkdirp').sync,
	bibleData = require('./data/bible_data.js'),
	bibleFormatter = require('./bible_formatter.js'),
	verseIndexer = require('./verse_indexer.js'),
	ProgressBar = require('progress'),
	argv = require('minimist')(process.argv.slice(2));

// VARS
var
	baseOutput = './app/content/texts/',
	baseInput = './input',
	createIndex = !!argv['i'],
	progressBar = null;

function startProgress(total, label) {
	label = label || 'Progress';

	if (progressBar != null) {
		progressBar.terminate();
	}
	progressBar = new ProgressBar('[:bar] [:current/:total] :elapseds', {total: total, width: 50});
}

function updateProgress() {
	progressBar.tick();
}

function cleanFolder(folderPath) {
	mkdirp(folderPath);
	rmrf(path.join(folderPath, '*'));
}

function convertFolder(inputPath) {

	var infoFilePath = path.join(inputPath, 'info.json'),
		startDate = new Date();

	if (fs.existsSync(infoFilePath)) {

		var info = JSON.parse( fs.readFileSync(infoFilePath, 'utf8') ),
			generatorName = info.generator,
			outputPath = path.join(baseOutput, info['id']),
			indexOutputPath = path.join(outputPath, 'index'),
			indexLemmaOutputPath = path.join(outputPath, 'indexlemma'),
			generator = null;

		try {
			generator = require(path.join(
				__dirname,
				'generators',
				'generate_' + generatorName + '.js'
			));
		} catch (ex) {
				console.error('Error processing generator "' + generatorName + '":', ex.message)
			return;
		}

		console.log('-----');
		console.log(info['name'],  outputPath);

		// DELETE: existing data
		cleanFolder(outputPath);

		// RUN GENERATOR
		console.time('processText');
		var data = generator.generate(inputPath, info, createIndex, startProgress, updateProgress);
		console.timeEnd('processText');

		// create chapters
		console.time('outputFiles');
		for (var i=0, il=data.chapterData.length; i<il; i++) {

			var thisChapter = data.chapterData[i],
				chapterHtml = bibleFormatter.openChapterDocument(info, thisChapter) +
								thisChapter.html +
								(typeof (thisChapter.notes) != 'undefined' ? bibleFormatter.breakChar + '
' + bibleFormatter.breakChar + thisChapter.notes + bibleFormatter.breakChar + '
' + bibleFormatter.breakChar: '') +
								bibleFormatter.closeChapterDocument(info, thisChapter),

				filePath = path.join(outputPath, thisChapter.id + '.html');

			fs.writeFileSync(filePath, chapterHtml);
		}
		console.timeEnd('outputFiles');

		// create books index
		var booksIndexHtml = bibleFormatter.openVersionIndex(info),
			hasPrintedOt = false,
			hasPrintedNt = false,
			hasPrintedAp = false;

		// all books
		for (var i=0, il=info.divisions.length; i<il; i++) {
			var dbsCode = info.divisions[i],
				bookName = info.divisionNames[i];

			if (bibleData.OT_BOOKS.indexOf(dbsCode) > -1 && !hasPrintedOt) {
				booksIndexHtml += '
Old Testament
';
				hasPrintedOt = true;
			}
			if (bibleData.NT_BOOKS.indexOf(dbsCode) > -1 && !hasPrintedNt) {
				booksIndexHtml += '
New Testament
';
				hasPrintedNt = true;
			}
			if (bibleData.AP_BOOKS.indexOf(dbsCode) > -1 && !hasPrintedAp) {
				booksIndexHtml += '
Deuterocanonical Books
';
				hasPrintedAp = true;
			}

			booksIndexHtml += '
' + bookName + '
' + bibleFormatter.breakChar;

			// do all chapters?
			var singleBookIndexHtml = bibleFormatter.openBookIndex(info, bookName);

			for (var j=0, jl=info.sections.length; j<jl; j++) {
				var sectionid = info.sections[j],
					sectionDbsCode = sectionid.substr(0,2),
					sectionChapterNumber = sectionid.substr(2);

				if (sectionDbsCode == dbsCode) {
					singleBookIndexHtml +=  '
' + bookName + ' ' + sectionChapterNumber + '
' + bibleFormatter.breakChar;
				}
			}
			singleBookIndexHtml += bibleFormatter.closeBookIndex();
			fs.writeFileSync( path.join(outputPath, dbsCode + '.html') , singleBookIndexHtml);

		}
		booksIndexHtml += bibleFormatter.closeVersionIndex(info);

		fs.writeFileSync( path.join(outputPath, 'index.html') , booksIndexHtml);

		// DO chapters index

		// do index
		if (createIndex && data.indexData) {
			cleanFolder(indexOutputPath);
			console.time('createIndex');
			verseIndexer.createIndexFiles(indexOutputPath, data.indexData, 'words');
			console.timeEnd('createIndex');

			cleanFolder(indexLemmaOutputPath);
			console.time('createLemma');
			verseIndexer.createIndexFiles(indexLemmaOutputPath, data.indexLemmaData, 'strongs');
			console.timeEnd('createLemma');
		}

		// save info
		var infoPath = path.join(outputPath, 'info.json');
		fs.writeFileSync(infoPath, JSON.stringify(info));

		// save about
		var aboutPage = bibleFormatter.openAboutPage(info) +
						(typeof data.aboutHtml != 'undefined' ? data.aboutHtml : '') +
						bibleFormatter.closeAboutPage(info),

			aboutPath = path.join(outputPath, 'about.html');

		fs.writeFileSync(aboutPath, aboutPage);

		if (typeof info.stylesheet != 'undefined') {
			var inStylePath = path.join(inputPath, info.stylesheet),
				inStyleText = fs.readFileSync(inStylePath, 'utf8' ),
				outStylePath = path.join(outputPath, info.stylesheet);

			fs.writeFileSync(outStylePath, inStyleText);

			console.log('Copying stylesheet', inStylePath, outStylePath);
		}

		var endDate = new Date();
		console.log('-time: ' + MillisecondsToDuration(endDate - startDate));

	}

	return;
}

function convertTexts(baseInput, texts) {
	texts = texts === undefined ? fs.readdirSync(baseInput) : texts;

	texts.forEach(function(textFoldername) {
		convertFolder(path.join(baseInput, textFoldername));
	});
}

function MillisecondsToDuration(n) {
	var hms = "";
	var dtm = new Date();
	dtm.setTime(n);

	var h = "000" + Math.floor(n / 3600000);
	var m = "0" + dtm.getMinutes();
	var s = "0" + dtm.getSeconds();
	var cs = "0" + Math.round(dtm.getMilliseconds() / 10);

	hms = h.substr(h.length-4) + ":" + m.substr(m.length-2) + ":";
	hms += s.substr(s.length-2) + "." + cs.substr(cs.length-2);

	return hms;
}

// START

// make /texts/ folder
if (!fs.existsSync(baseInput)) {
	fs.mkdirSync(baseInput);
}

// parse arguments
if (argv['h']) {
	console.log('----------------\n' +
				'Generator Help\n' +
				'-v VERSION,VERSION = only some versions\n' +
				'-e VERSION,VERSION = exclude some versions\n' +
				'-i = create index\n');
	return;
}

// Generate listed texts
if (argv['v'] !== undefined) {
	convertTexts(baseInput, argv['v'].split(','));

// Generate all but listed texts
} else if (typeof argv['e'] != 'undefined') {
	var foldersToExclude = argv['e'].split(',');

	var folders = fs.readdirSync(baseInput);

	convertTexts(
		baseInput,
		folders.filter(function(name) { return foldersToExclude.indexOf(name) === -1; })
	);

// Generate all texts
} else {
	convertTexts(baseInput);
}
<commit_msg>Because of hoisting, we can put the stuff that runs first.<commit_after>/**
* Generates HTML that can function as standalone chapters or as chapters loaded by the main app
* This attemps to load folders in the ./input/ directory, read the ./input/version/info.json and
* then use a renderer found in ./node_modules/generate_renderername.js
*
* See options for details on running
*/

// MODULES
var fs = require('fs'),
	path = require('path'),
	rmrf = require('rimraf').sync,
	mkdirp = require('mkdirp').sync,
	bibleData = require('./data/bible_data.js'),
	bibleFormatter = require('./bible_formatter.js'),
	verseIndexer = require('./verse_indexer.js'),
	ProgressBar = require('progress'),
	argv = require('minimist')(process.argv.slice(2));

// VARS
var
	baseOutput = path.join('app', 'content', 'texts'),
	baseInput = 'input',
	createIndex = !!argv['i'],
	progressBar = null;

// parse arguments
if (argv['h']) {
	console.log('----------------\n' +
				'Generator Help\n' +
				'-v VERSION,VERSION = only some versions\n' +
				'-e VERSION,VERSION = exclude some versions\n' +
				'-i = create index\n');
	return;
}

// Generate listed texts
if (argv['v'] !== undefined) {
	convertTexts(baseInput, argv['v'].split(','));

// Generate all but listed texts
} else if (typeof argv['e'] != 'undefined') {
	var foldersToExclude = argv['e'].split(',');

	var folders = fs.readdirSync(baseInput);

	convertTexts(
		baseInput,
		folders.filter(function(name) { return foldersToExclude.indexOf(name) === -1; })
	);

// Generate all texts
} else {
	convertTexts(baseInput);
}

// Functions
function startProgress(total, label) {
	label = label || 'Progress';

	if (progressBar != null) {
		progressBar.terminate();
	}
	progressBar = new ProgressBar('[:bar] [:current/:total] :elapseds', {total: total, width: 50});
}

function updateProgress() {
	progressBar.tick();
}

function cleanFolder(folderPath) {
	mkdirp(folderPath);
	rmrf(path.join(folderPath, '*'));
}

function convertFolder(inputPath) {

	var infoFilePath = path.join(inputPath, 'info.json'),
		startDate = new Date();

	if (fs.existsSync(infoFilePath)) {

		var info = JSON.parse( fs.readFileSync(infoFilePath, 'utf8') ),
			generatorName = info.generator,
			outputPath = path.join(baseOutput, info['id']),
			indexOutputPath = path.join(outputPath, 'index'),
			indexLemmaOutputPath = path.join(outputPath, 'indexlemma'),
			generator = null;

		try {
			generator = require(path.join(
				__dirname,
				'generators',
				'generate_' + generatorName + '.js'
			));
		} catch (ex) {
			console.error('Error processing generator "' + generatorName + '":', ex.message)
			return;
		}

		console.log('-----');
		console.log(info['name'],  outputPath);

		// DELETE: existing data
		cleanFolder(outputPath);

		// RUN GENERATOR
		console.time('processText');
		var data = generator.generate(inputPath, info, createIndex, startProgress, updateProgress);
		console.timeEnd('processText');

		// create chapters
		console.time('outputFiles');
		for (var i=0, il=data.chapterData.length; i<il; i++) {

			var thisChapter = data.chapterData[i],
				chapterHtml = bibleFormatter.openChapterDocument(info, thisChapter) +
								thisChapter.html +
								(typeof (thisChapter.notes) != 'undefined' ? bibleFormatter.breakChar + '
' + bibleFormatter.breakChar + thisChapter.notes + bibleFormatter.breakChar + '
' + bibleFormatter.breakChar: '') +
								bibleFormatter.closeChapterDocument(info, thisChapter),

				filePath = path.join(outputPath, thisChapter.id + '.html');

			fs.writeFileSync(filePath, chapterHtml);
		}
		console.timeEnd('outputFiles');

		// create books index
		var booksIndexHtml = bibleFormatter.openVersionIndex(info),
			hasPrintedOt = false,
			hasPrintedNt = false,
			hasPrintedAp = false;

		// all books
		for (var i=0, il=info.divisions.length; i<il; i++) {
			var dbsCode = info.divisions[i],
				bookName = info.divisionNames[i];

			if (bibleData.OT_BOOKS.indexOf(dbsCode) > -1 && !hasPrintedOt) {
				booksIndexHtml += '
Old Testament
';
				hasPrintedOt = true;
			}
			if (bibleData.NT_BOOKS.indexOf(dbsCode) > -1 && !hasPrintedNt) {
				booksIndexHtml += '
New Testament
';
				hasPrintedNt = true;
			}
			if (bibleData.AP_BOOKS.indexOf(dbsCode) > -1 && !hasPrintedAp) {
				booksIndexHtml += '
Deuterocanonical Books
';
				hasPrintedAp = true;
			}

			booksIndexHtml += '
' + bookName + '
' + bibleFormatter.breakChar;

			// do all chapters?
			var singleBookIndexHtml = bibleFormatter.openBookIndex(info, bookName);

			for (var j=0, jl=info.sections.length; j<jl; j++) {
				var sectionid = info.sections[j],
					sectionDbsCode = sectionid.substr(0,2),
					sectionChapterNumber = sectionid.substr(2);

				if (sectionDbsCode == dbsCode) {
					singleBookIndexHtml +=  '
' + bookName + ' ' + sectionChapterNumber + '
' + bibleFormatter.breakChar;
				}
			}
			singleBookIndexHtml += bibleFormatter.closeBookIndex();
			fs.writeFileSync( path.join(outputPath, dbsCode + '.html') , singleBookIndexHtml);
		}
		booksIndexHtml += bibleFormatter.closeVersionIndex(info);

		fs.writeFileSync( path.join(outputPath, 'index.html') , booksIndexHtml);

		// DO chapters index

		// do index
		if (createIndex && data.indexData) {
			cleanFolder(indexOutputPath);
			console.time('createIndex');
			verseIndexer.createIndexFiles(indexOutputPath, data.indexData, 'words');
			console.timeEnd('createIndex');

			cleanFolder(indexLemmaOutputPath);
			console.time('createLemma');
			verseIndexer.createIndexFiles(indexLemmaOutputPath, data.indexLemmaData, 'strongs');
			console.timeEnd('createLemma');
		}

		// save info
		var infoPath = path.join(outputPath, 'info.json');
		fs.writeFileSync(infoPath, JSON.stringify(info));

		// save about
		var aboutPage = bibleFormatter.openAboutPage(info) +
						(typeof data.aboutHtml != 'undefined' ? data.aboutHtml : '') +
						bibleFormatter.closeAboutPage(info),

			aboutPath = path.join(outputPath, 'about.html');

		fs.writeFileSync(aboutPath, aboutPage);

		if (typeof info.stylesheet != 'undefined') {
			var inStylePath = path.join(inputPath, info.stylesheet),
				inStyleText = fs.readFileSync(inStylePath, 'utf8' ),
				outStylePath = path.join(outputPath, info.stylesheet);

			fs.writeFileSync(outStylePath, inStyleText);

			console.log('Copying stylesheet', inStylePath, outStylePath);
		}

		console.log('-time: ' + MillisecondsToDuration((new Date()) - startDate));
	}

	return;
}

function convertTexts(baseInput, texts) {
	mkdirp(baseOutput);

	texts = texts === undefined ? fs.readdirSync(baseInput) : texts;

	texts.forEach(function(textFoldername) {
		convertFolder(path.join(baseInput, textFoldername));
	});
}

function MillisecondsToDuration(n) {
	var hms = "";
	var dtm = new Date();
	dtm.setTime(n);

	var h = "000" + Math.floor(n / 3600000);
	var m = "0" + dtm.getMinutes();
	var s = "0" + dtm.getSeconds();
	var cs = "0" + Math.round(dtm.getMilliseconds() / 10);

	hms = h.substr(h.length-4) + ":" + m.substr(m.length-2) + ":";
	hms += s.substr(s.length-2) + "." + cs.substr(cs.length-2);

	return hms;
}
<|endoftext|>


<commit_before>'use strict';

angular.module('digApp.directives')
.directive('checkboxFilterList', function() {
    return {
        restrict: 'E',
        scope: {
            aggregationName: '@',
            aggregationKey: '@',
            aggregationTermsType: '@',
            userDisplayCount: '=searchCount',
            buckets: '=',
            indexVM: '=indexvm',
            ejs: '=',
            filters: '=',
            filterStates: '='
        },
        templateUrl: 'components/checkbox-filter/checkbox-filter-list/checkbox-filter-list.partial.html',
        link: function($scope, $element) {
            $scope.facetCount = 0;
            $scope.showAll = false;
            $scope.displayBuckets = [];

            $scope.buttonStatus = {
                more: false,
                less: false,
                all: false
            };

            $element.addClass('checkbox-filter-list');

            $scope.more = function() {
                if($scope.userDisplayCount <= $scope.facetCount) {
                    $scope.userDisplayCount += 10;
                    $scope.resetDisplayBuckets();
                }
            };

            $scope.less = function() {
                if($scope.userDisplayCount > 10) {
                    $scope.userDisplayCount -= 10;
                    if ($scope.userDisplayCount < 10) {
                        $scope.userDisplayCount = 10;
                    }
                    $scope.resetDisplayBuckets();
                }
            };

            $scope.all = function() {
                if($scope.facetCount > 10) {
                    if ($scope.showAll) {
                        $scope.userDisplayCount = $scope.lastDisplayCount;
                    } else {
                        $scope.lastDisplayCount = $scope.userDisplayCount;
                        $scope.userDisplayCount = (Math.floor($scope.facetCount / 10) * 10) + 10;
                    }
                    $scope.showAll = !$scope.showAll;

                    $scope.resetDisplayBuckets();
                }
            };

            var disableButtons = function() {
                $scope.buttonStatus.moreButton = ($scope.userDisplayCount > $scope.facetCount);
                $scope.buttonStatus.lessButton = ($scope.userDisplayCount <= 10);
                $scope.buttonStatus.allButton = ($scope.facetCount <= 10);
            };

            $scope.getAggregationTermBucket = function(term) {
                var aggObj = null;

                // Return false if we have no aggregations or none on that field.
                if (!$scope.buckets) {
                    return false;
                }

                aggObj = (_.filter($scope.buckets, function(bucket) {
                    return (bucket.key && bucket.key == term);
                }));

                return (aggObj.length !== 0) ? aggObj[0] : false;
            };

            $scope.resetDisplayBuckets = function() {
                disableButtons();

                $scope.displayBuckets = [];
                var checkedItems = [];
                var bucket;

                // Get checked items and add to display buckets if they dropped out of our aggregations.
                for (var term in $scope.filterStates[$scope.aggregationName]) {
                    if ($scope.filterStates[$scope.aggregationName].hasOwnProperty(term) &&
                        $scope.filterStates[$scope.aggregationName][term]) {
                        checkedItems.push(term);
                    }
                }

                // fill the rest of display buckets with the aggregation buckets.
                var numBuckets = ($scope.buckets) ? $scope.buckets.length : 0;
                var remainingBucketSlots = Math.min($scope.userDisplayCount, numBuckets);

                for (var i = 0; i < remainingBucketSlots; i++) {
                    $scope.displayBuckets.push($scope.buckets[i]);
                }

                // Add hidden fields for any checked items that didn't come
                // back in our current aggregation set.  This is necessary to
                // keep the eui directives in sync with the user state.  If no
                // controll for this these are in the page, it will result in
                // extraneous filters being applied to elastic query searches.
                for (i = 0; i < checkedItems.length; i++) {
                    if (!_.find($scope.displayBuckets, function(item) {
                        // Converting the key to a string since checkedItems is populated by string keys.
                        return ((item.key) ? item.key.toString() : '') === checkedItems[i];
                    })) {
                        var key;
                        if($scope.aggregationTermsType === 'number') {
                            key = Number(checkedItems[i]);
                        } else {
                            key = checkedItems[i];
                        }

                        /* jshint camelcase:false */
                        $scope.displayBuckets.push({
                            // TODO: Configure better type checking in euiConfigs mapping
                            key: key,
                            doc_count: 0,
                            hidden: true
                        });
                        /* jshint camelcase:true */
                    }
                }
            };

            $scope.$watch('buckets', function() {
                $scope.facetCount = ($scope.buckets ? $scope.buckets.length : 0);

                $scope.resetDisplayBuckets();
            }, true);
        }
    };
});<commit_msg>Cleanup<commit_after>'use strict';

angular.module('digApp.directives')
.directive('checkboxFilterList', function() {
    return {
        restrict: 'E',
        scope: {
            aggregationName: '@',
            aggregationKey: '@',
            aggregationTermsType: '@',
            userDisplayCount: '=searchCount',
            buckets: '=',
            indexVM: '=indexvm',
            ejs: '=',
            filters: '=',
            filterStates: '='
        },
        templateUrl: 'components/checkbox-filter/checkbox-filter-list/checkbox-filter-list.partial.html',
        link: function($scope, $element) {
            $scope.facetCount = 0;
            $scope.showAll = false;
            $scope.displayBuckets = [];

            $scope.buttonStatus = {
                more: false,
                less: false,
                all: false
            };

            $element.addClass('checkbox-filter-list');

            $scope.more = function() {
                if($scope.userDisplayCount <= $scope.facetCount) {
                    $scope.userDisplayCount += 10;
                    $scope.resetDisplayBuckets();
                }
            };

            $scope.less = function() {
                if($scope.userDisplayCount > 10) {
                    $scope.userDisplayCount -= 10;
                    if($scope.userDisplayCount < 10) {
                        $scope.userDisplayCount = 10;
                    }
                    $scope.resetDisplayBuckets();
                }
            };

            $scope.all = function() {
                if($scope.facetCount > 10) {
                    if($scope.showAll) {
                        $scope.userDisplayCount = $scope.lastDisplayCount;
                    } else {
                        $scope.lastDisplayCount = $scope.userDisplayCount;
                        $scope.userDisplayCount = (Math.floor($scope.facetCount / 10) * 10) + 10;
                    }
                    $scope.showAll = !$scope.showAll;

                    $scope.resetDisplayBuckets();
                }
            };

            var disableButtons = function() {
                $scope.buttonStatus.moreButton = ($scope.userDisplayCount > $scope.facetCount);
                $scope.buttonStatus.lessButton = ($scope.userDisplayCount <= 10);
                $scope.buttonStatus.allButton = ($scope.facetCount <= 10);
            };

            $scope.getAggregationTermBucket = function(term) {
                var aggObj = null;

                // Return false if we have no aggregations or none on that field.
                if(!$scope.buckets) {
                    return false;
                }

                aggObj = (_.filter($scope.buckets, function(bucket) {
                    return (bucket.key && bucket.key == term);
                }));

                return (aggObj.length !== 0) ? aggObj[0] : false;
            };

            $scope.resetDisplayBuckets = function() {
                disableButtons();

                $scope.displayBuckets = [];
                var checkedItems = [];

                // Get checked items and add to display buckets if they dropped out of our aggregations.
                for(var term in $scope.filterStates[$scope.aggregationName]) {
                    if($scope.filterStates[$scope.aggregationName].hasOwnProperty(term) &&
                        $scope.filterStates[$scope.aggregationName][term]) {
                        checkedItems.push(term);
                    }
                }

                // fill the rest of display buckets with the aggregation buckets.
                var numBuckets = ($scope.buckets) ? $scope.buckets.length : 0;
                var remainingBucketSlots = Math.min($scope.userDisplayCount, numBuckets);

                for(var i = 0; i < remainingBucketSlots; i++) {
                    $scope.displayBuckets.push($scope.buckets[i]);
                }

                // Add hidden fields for any checked items that didn't come
                // back in our current aggregation set.  This is necessary to
                // keep the eui directives in sync with the user state.  If no
                // controll for this these are in the page, it will result in
                // extraneous filters being applied to elastic query searches.
                for(i = 0; i < checkedItems.length; i++) {
                    if(!_.find($scope.displayBuckets, function(item) {
                        // Converting the key to a string since checkedItems is populated by string keys.
                        return ((item.key) ? item.key.toString() : '') === checkedItems[i];
                    })) {
                        var key;
                        if($scope.aggregationTermsType === 'number') {
                            key = Number(checkedItems[i]);
                        } else {
                            key = checkedItems[i];
                        }

                        /* jshint camelcase:false */
                        $scope.displayBuckets.push({
                            // TODO: Configure better type checking in euiConfigs mapping
                            key: key,
                            doc_count: 0,
                            hidden: true
                        });
                        /* jshint camelcase:true */
                    }
                }
            };

            $scope.$watch('buckets', function() {
                $scope.facetCount = ($scope.buckets ? $scope.buckets.length : 0);

                $scope.resetDisplayBuckets();
            }, true);
        }
    };
});<|endoftext|>


<commit_before>$(function() {
	console.log("ready");
	$('#plan').click(function(){
	    $('#action').val("plan");
    });
	$('#apply').click(function(){
	    $('#action').val("apply");
    });
});<commit_msg>Removed line for debugging<commit_after>$(function() {
	$('#plan').click(function(){
	    $('#action').val("plan");
    });
	$('#apply').click(function(){
	    $('#action').val("apply");
    });
});<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Form } from 'semantic-ui-react'

type Props = {
  match: any,
  sessionId: string,
  operations: Array<string>,
  defaultPayloads: { [string]: Object },
  execute: ({ entitiName: string, operation: string, payload: any }) => any,
}

type State = {
  operation: string, // FIXME: enum
  payload: Object,
}

class OperationEditor extends Component<Props, State> {
  state: State = {
    operation: null,
    payload: null,
  }

  handleChangeOperation = (event, { value }) => {
    if (!this.props.defaultPayloads[value]) {
      throw new Error(`Unknown operation: ${value}`)
    }

    const payload = this.props.defaultPayloads[value]

    this.setState({
      operation: value,
      payload: JSON.stringify(payload, null, 2),
    })
  }

  handleChangePayload = (event, { value }) => {
    this.setState({ payload: value })
  }

  handleRun = () => {
    const { match, execute } = this.props

    const payload = JSON.parse(this.state.payload)
    execute({
      sessionId: this.props.sessionId,
      entityName: match.params.functional,
      operation: this.state.operation,
      payload,
    })
  }

  componentDidMount() {
    const { operations } = this.props

    this.handleChangeOperation(null, { value: operations[0] })
  }

  render () {
    const { operations } = this.props
    return (

        <Form>
          <Form.Group>
            <Form.Select
              label='Operation'
              options={operations.map(op => ({
                key: op,
                text: op,
                value: op,
              }))}
              defaultValue={operations[0]}
              onChange={this.handleChangeOperation}
            />
          </Form.Group>
          <Form.TextArea
            rows={4}
            label='Payload'
            value={this.state.payload}
            onChange={this.handleChangePayload}
          />
          <Form.Button
            positive
            onClick={this.handleRun}
          >
            Run
          </Form.Button>
        </Form>

    )
  }
}

export default OperationEditor
<commit_msg>Fix typo<commit_after>import React, { Component } from 'react'
import { Form } from 'semantic-ui-react'

type Props = {
  match: any,
  sessionId: string,
  operations: Array<string>,
  defaultPayloads: { [string]: Object },
  execute: ({ entityName: string, operation: string, payload: any }) => any,
}

type State = {
  operation: string, // FIXME: enum
  payload: Object,
}

class OperationEditor extends Component<Props, State> {
  state: State = {
    operation: null,
    payload: null,
  }

  handleChangeOperation = (event, { value }) => {
    if (!this.props.defaultPayloads[value]) {
      throw new Error(`Unknown operation: ${value}`)
    }

    const payload = this.props.defaultPayloads[value]

    this.setState({
      operation: value,
      payload: JSON.stringify(payload, null, 2),
    })
  }

  handleChangePayload = (event, { value }) => {
    this.setState({ payload: value })
  }

  handleRun = () => {
    const { match, execute } = this.props

    const payload = JSON.parse(this.state.payload)
    execute({
      sessionId: this.props.sessionId,
      entityName: match.params.functional,
      operation: this.state.operation,
      payload,
    })
  }

  componentDidMount() {
    const { operations } = this.props

    this.handleChangeOperation(null, { value: operations[0] })
  }

  render () {
    const { operations } = this.props
    return (

        <Form>
          <Form.Group>
            <Form.Select
              label='Operation'
              options={operations.map(op => ({
                key: op,
                text: op,
                value: op,
              }))}
              defaultValue={operations[0]}
              onChange={this.handleChangeOperation}
            />
          </Form.Group>
          <Form.TextArea
            rows={4}
            label='Payload'
            value={this.state.payload}
            onChange={this.handleChangePayload}
          />
          <Form.Button
            positive
            onClick={this.handleRun}
          >
            Run
          </Form.Button>
        </Form>

    )
  }
}

export default OperationEditor
<|endoftext|>