<commit_before>var TreeModel = function(context, source, startTree){
    this.context = context;
    this.source = source;
    this.dataTree = startTree || {};

    this.handlersTree = {};

    this.mirroringFrom = null;
    this.mirroringTo = null;
};

_.extend(TreeModel.prototype, {

    counter: 1,

    getProperty: function(propertyName){
        if(this.mirroringFrom){
            propertyName = propertyName.replace(this.mirroringFrom, this.mirroringTo);
        }
        return InfinniUI.ObjectUtils.getPropertyValue(this.dataTree, propertyName)
    },

    setProperty: function(propertyName, value){
        var oldValue = this.getProperty(propertyName);
        if(value == oldValue){
            return false;
        }

        InfinniUI.ObjectUtils.setPropertyValue(this.dataTree, propertyName, value);

        this._notifyAboutPropertyChanged(propertyName, oldValue);

        return true;
    },

    simulateSetProperty: function(propertyName, oldValue){
        this._notifyAboutPropertyChanged(propertyName, oldValue);
    },

    onPropertyChanged: function(propertyName, handler, params){
        var handlersNode;
        var bindId = this.counter;
        this.counter ++;

        if(_.isFunction(propertyName)){
            params = handler;
            handler = propertyName;

            handlersNode = this._getHandlersSubTree('*', true);
        }else{
            handlersNode = this._getHandlersSubTree(propertyName, true);
        }

        handler._bindId = bindId;
        if(params && 'owner' in params){
            handler._owner = params.owner;
        }

        handlersNode[bindId] = handler;
    },

    _getHandlersSubTree: function(propertyName, restoreIfNoProperty){
        if(propertyName == ''){
            return this.handlersTree;
        }

        var propertyPaths = propertyName.split('.');
        var tmpResult = this.handlersTree;
        for(var i = 0, ii = propertyPaths.length; i<ii; i++){
            if(tmpResult[propertyPaths[i]]){
                tmpResult = tmpResult[propertyPaths[i]];
            }else{
                if(restoreIfNoProperty){
                    tmpResult[propertyPaths[i]] = {};
                    tmpResult = tmpResult[propertyPaths[i]];
                }else{
                    return {};
                }
            }
        }

        return tmpResult;
    },

    _notifyAboutPropertyChanged: function(propertyName, oldValue){
        var handlers = this._getHandlersSubTree(propertyName);

        var needMirroring = this.mirroringTo != null && this.mirroringFrom != null && propertyName.indexOf(this.mirroringTo) == 0;
        var mirroringPath = propertyName.replace(this.mirroringTo, this.mirroringFrom);

        this._notifyAboutPropertyChanged_bubblingAction(propertyName, oldValue, handlers);

        this._notifyAboutPropertyChanged_capturingAction(propertyName, oldValue, handlers);
        if(needMirroring){
            handlers = this._getHandlersSubTree(mirroringPath);
            this._notifyAboutPropertyChanged_capturingAction(mirroringPath, oldValue, handlers);
        }
    },

    _notifyAboutPropertyChanged_capturingAction: function(propertyName, oldValue, handlersSubTree){
        var tmpValue;
        var tmpProperty;
        var handler;

        for( var k in handlersSubTree ){
            if($.isFunction(handlersSubTree[k])){

                handler = handlersSubTree[k];
                if(this._isOwnerAlive(handler)){
                    this._callHandlerAboutPropertyChanged(handler, propertyName, oldValue);
                }else{
                    delete handlersSubTree[k];
                }

            } else if($.isPlainObject(handlersSubTree[k]) && k != '*'){

                tmpValue = $.isPlainObject(oldValue) ? oldValue[k] : undefined;
                tmpProperty = propertyName == '' ? k :propertyName + '.' + k;
                this._notifyAboutPropertyChanged_capturingAction(tmpProperty, tmpValue, handlersSubTree[k]);

            }
        }
    },

    _notifyAboutPropertyChanged_bubblingAction: function(propertyName, oldValue, handlersSubTree){
        var propertyNamePaths = propertyName.split('.');
        var tmpPropertyName;

        var handlersNode = this.handlersTree;
        var that = this;

        checkAndCallAnyHandlers(handlersNode);

        if(propertyName != ''){
            for(var i = 0, ii = propertyNamePaths.length; i < ii; i++){

                tmpPropertyName = propertyNamePaths[i];
                if(handlersNode[tmpPropertyName]){
                    handlersNode = handlersNode[tmpPropertyName];
                    checkAndCallAnyHandlers(handlersNode);

                }else{
                    break;
                }
            }
        }

        function checkAndCallAnyHandlers(_handlersNode){
            var handler;

            if('*', _handlersNode){
                for( var k in _handlersNode['*'] ){
                    handler = _handlersNode['*'][k];
                    if(that._isOwnerAlive(handler)){
                        that._callHandlerAboutPropertyChanged(handler, propertyName, oldValue);
                    }else{
                        delete _handlersNode['*'][k];
                    }
                }
            }
        }
    },

    _isOwnerAlive: function(handler){
        if(handler._owner && 'isRemoved' in handler._owner){

            if(typeof handler._owner.isRemoved == 'function'){
                return handler._owner.isRemoved();
            }else{
                return !handler._owner.isRemoved;
            }

        }else{
            return true;
        }
    },

    _callHandlerAboutPropertyChanged: function(handler, propertyName, oldValue){
        var args = {
            property: propertyName,
            newValue: this.getProperty(propertyName),
            oldValue: oldValue,
            source: this.source
        };

        handler(this.context, args);
    },

    setMirroring: function(mirroringFrom, mirroringTo){
        this.mirroringFrom = mirroringFrom;
        this.mirroringTo = mirroringTo;
    }

});<commit_msg>~typo fix<commit_after>var TreeModel = function(context, source, startTree){
    this.context = context;
    this.source = source;
    this.dataTree = startTree || {};

    this.handlersTree = {};

    this.mirroringFrom = null;
    this.mirroringTo = null;
};

_.extend(TreeModel.prototype, {

    counter: 1,

    getProperty: function(propertyName){
        if(this.mirroringFrom){
            propertyName = propertyName.replace(this.mirroringFrom, this.mirroringTo);
        }
        return InfinniUI.ObjectUtils.getPropertyValue(this.dataTree, propertyName)
    },

    setProperty: function(propertyName, value){
        var oldValue = this.getProperty(propertyName);
        if(value == oldValue){
            return false;
        }

        InfinniUI.ObjectUtils.setPropertyValue(this.dataTree, propertyName, value);

        this._notifyAboutPropertyChanged(propertyName, oldValue);

        return true;
    },

    simulateSetProperty: function(propertyName, oldValue){
        this._notifyAboutPropertyChanged(propertyName, oldValue);
    },

    onPropertyChanged: function(propertyName, handler, params){
        var handlersNode;
        var bindId = this.counter;
        this.counter ++;

        if(_.isFunction(propertyName)){
            params = handler;
            handler = propertyName;

            handlersNode = this._getHandlersSubTree('*', true);
        }else{
            handlersNode = this._getHandlersSubTree(propertyName, true);
        }

        handler._bindId = bindId;
        if(params && 'owner' in params){
            handler._owner = params.owner;
        }

        handlersNode[bindId] = handler;
    },

    _getHandlersSubTree: function(propertyName, restoreIfNoProperty){
        if(propertyName == ''){
            return this.handlersTree;
        }

        var propertyPaths = propertyName.split('.');
        var tmpResult = this.handlersTree;
        for(var i = 0, ii = propertyPaths.length; i<ii; i++){
            if(tmpResult[propertyPaths[i]]){
                tmpResult = tmpResult[propertyPaths[i]];
            }else{
                if(restoreIfNoProperty){
                    tmpResult[propertyPaths[i]] = {};
                    tmpResult = tmpResult[propertyPaths[i]];
                }else{
                    return {};
                }
            }
        }

        return tmpResult;
    },

    _notifyAboutPropertyChanged: function(propertyName, oldValue){
        var handlers = this._getHandlersSubTree(propertyName);

        var needMirroring = this.mirroringTo != null && this.mirroringFrom != null && propertyName.indexOf(this.mirroringTo) == 0;
        var mirroringPath = propertyName.replace(this.mirroringTo, this.mirroringFrom);

        this._notifyAboutPropertyChanged_bubblingAction(propertyName, oldValue, handlers);

        this._notifyAboutPropertyChanged_capturingAction(propertyName, oldValue, handlers);
        if(needMirroring){
            handlers = this._getHandlersSubTree(mirroringPath);
            this._notifyAboutPropertyChanged_capturingAction(mirroringPath, oldValue, handlers);
        }
    },

    _notifyAboutPropertyChanged_capturingAction: function(propertyName, oldValue, handlersSubTree){
        var tmpValue;
        var tmpProperty;
        var handler;

        for( var k in handlersSubTree ){
            if($.isFunction(handlersSubTree[k])){

                handler = handlersSubTree[k];
                if(this._isOwnerAlive(handler)){
                    this._callHandlerAboutPropertyChanged(handler, propertyName, oldValue);
                }else{
                    delete handlersSubTree[k];
                }

            } else if($.isPlainObject(handlersSubTree[k]) && k != '*'){

                tmpValue = $.isPlainObject(oldValue) ? oldValue[k] : undefined;
                tmpProperty = propertyName == '' ? k :propertyName + '.' + k;
                this._notifyAboutPropertyChanged_capturingAction(tmpProperty, tmpValue, handlersSubTree[k]);

            }
        }
    },

    _notifyAboutPropertyChanged_bubblingAction: function(propertyName, oldValue, handlersSubTree){
        var propertyNamePaths = propertyName.split('.');
        var tmpPropertyName;

        var handlersNode = this.handlersTree;
        var that = this;

        checkAndCallAnyHandlers(handlersNode);

        if(propertyName != ''){
            for(var i = 0, ii = propertyNamePaths.length; i < ii; i++){

                tmpPropertyName = propertyNamePaths[i];
                if(handlersNode[tmpPropertyName]){
                    handlersNode = handlersNode[tmpPropertyName];
                    checkAndCallAnyHandlers(handlersNode);

                }else{
                    break;
                }
            }
        }

        function checkAndCallAnyHandlers(_handlersNode){
            var handler;

            if('*' in _handlersNode){
                for( var k in _handlersNode['*'] ){
                    handler = _handlersNode['*'][k];
                    if(that._isOwnerAlive(handler)){
                        that._callHandlerAboutPropertyChanged(handler, propertyName, oldValue);
                    }else{
                        delete _handlersNode['*'][k];
                    }
                }
            }
        }
    },

    _isOwnerAlive: function(handler){
        if(handler._owner && 'isRemoved' in handler._owner){

            if(typeof handler._owner.isRemoved == 'function'){
                return handler._owner.isRemoved();
            }else{
                return !handler._owner.isRemoved;
            }

        }else{
            return true;
        }
    },

    _callHandlerAboutPropertyChanged: function(handler, propertyName, oldValue){
        var args = {
            property: propertyName,
            newValue: this.getProperty(propertyName),
            oldValue: oldValue,
            source: this.source
        };

        handler(this.context, args);
    },

    setMirroring: function(mirroringFrom, mirroringTo){
        this.mirroringFrom = mirroringFrom;
        this.mirroringTo = mirroringTo;
    }

});<|endoftext|>


<commit_before>window.onload = () => { start(); };

const objects = {};
let gesture = {};

function start() {
  createGrid(document.getElementById('grid'), 30);
}

function createGrid(parent, n) {
  for (let i = 0; i < n; i++) {
    createDividerRow(parent, n, i - 1, i);
    createCellRow(parent, n, i);
  }
  createDividerRow(parent, n, n - 1, n);
}

function createDividerRow(parent, n, previousRow, nextRow) {
  const rowContainer = createRowContainer(parent);
  for (let i = 0; i < n; i++) {
    createCornerCell(rowContainer, previousRow, nextRow, i - 1, i);
    createHorizontalCell(rowContainer, previousRow, nextRow, i);
  }
  createCornerCell(rowContainer, previousRow, nextRow, n - 1, n);
}

function createCellRow(parent, n, row) {
  const rowContainer = createRowContainer(parent);
  for (let i = 0; i < n; i++) {
    createVerticalCell(rowContainer, row, i - 1, i);
    createPrimaryCell(rowContainer, row, i);
  }
  createVerticalCell(rowContainer, row, n - 1, n);
}

function createRowContainer(parent) {
  return createAndAppendDivWithClass(parent, 'row-container');
}

function createAndAppendDivWithClass(parent, className) {
  const result = document.createElement('div');
  result.className = className;
  parent.appendChild(result);
  return result;
}

function dividerCellKey(previousRow, previousColumn, nextRow, nextColumn) {
  return `cell ${previousRow},${previousColumn}:${nextRow},${nextColumn}`;
}

function primaryCellKey(row, column) {
  return `cell ${row},${column}`;
}

function createCornerCell(parent, previousRow, nextRow, previousColumn, nextColumn) {
  createCell(parent, 'cell corner-cell',
      dividerCellKey(previousRow, previousColumn, nextRow, nextColumn));
}

function createHorizontalCell(parent, previousRow, nextRow, column) {
  createCell(parent, 'cell horizontal-cell',
      dividerCellKey(previousRow, column, nextRow, column));
}

function createVerticalCell(parent, row, previousColumn, nextColumn) {
  createCell(parent, 'cell vertical-cell',
      dividerCellKey(row, previousColumn, row, nextColumn));
}

function createPrimaryCell(parent, row, column) {
  const cell = createCell(parent, 'cell primary-cell', primaryCellKey(row, column));
  cell.setAttribute('data-row', row);
  cell.setAttribute('data-column', column);
}

function createCell(parent, className, key) {
  const cell = createAndAppendDivWithClass(parent, className + ' solid');
  objects[key] = cell;
  cell.onmousedown = () => { startGesture(cell); };
  cell.onmouseover = (e) => {
    if (e.buttons == 1) {
      continueGesture(cell);
    }
  };
  cell.ondragenter = () => { cellClicked(cell); };
  return cell;
}

function startGesture(cell) {
  if (cell.classList.contains('solid')) {
    gesture.callback = setClear;
  } else if (cell.classList.contains('clear')) {
    gesture.callback = setSolid;
  }
  continueGesture(cell);
}

function continueGesture(cell) {
  gesture.callback(cell);
  if (cell.classList.contains('primary-cell')) {
    updatePrimaryCellNeighbors(cell);
  }
}

function setSolid(cell) {
  cell.classList.remove('clear');
  cell.classList.add('solid');
}

function setClear(cell) {
  cell.classList.remove('solid');
  cell.classList.add('clear');
}

function updatePrimaryCellNeighbors(cell) {
  for (const neighbor of getNeighbors(cell)) {
    const anyPrimaryCellIsSolid =
        ([cell].concat(neighbor.primaryCellKeys.map(key => { return objects[key]; })))
        .some(primaryCell => {
          return primaryCell && primaryCell.classList.contains('solid');
        });
    if (anyPrimaryCellIsSolid) {
      setSolid(objects[neighbor.dividerCellKey]);
    } else {
      setClear(objects[neighbor.dividerCellKey]);
    }
  }
}

function getNeighbors(cell) {
  const row = parseInt(cell.getAttribute('data-row'), 10);
  const column = parseInt(cell.getAttribute('data-column'), 10);
  return [
    // Cardinal directions:
    {  // top
      primaryCellKeys: [
        primaryCellKey(row - 1, column)
      ],
      dividerCellKey: dividerCellKey(row - 1, column, row, column)
    },
    {  // right
      primaryCellKeys: [
        primaryCellKey(row, column + 1)
      ],
      dividerCellKey: dividerCellKey(row, column, row, column + 1)
    },
    {  // bottom
      primaryCellKeys: [
        primaryCellKey(row + 1, column)
      ],
      dividerCellKey: dividerCellKey(row, column, row + 1, column)
    },
    {  // left
      primaryCellKeys: [
        primaryCellKey(row, column - 1)
      ],
      dividerCellKey: dividerCellKey(row, column - 1, row, column )
    },
    // Diagonal directions:
    {  // top-right
      primaryCellKeys: [
        primaryCellKey(row - 1, column),
        primaryCellKey(row, column + 1),
        primaryCellKey(row - 1, column + 1)
      ],
      dividerCellKey: dividerCellKey(row - 1, column, row, column + 1)
    },
    {  // bottom-right
      primaryCellKeys: [
        primaryCellKey(row + 1, column),
        primaryCellKey(row, column + 1),
        primaryCellKey(row + 1, column + 1)
      ],
      dividerCellKey: dividerCellKey(row, column, row + 1, column + 1)
    },
    {  // bottom-left
      primaryCellKeys: [
        primaryCellKey(row + 1, column),
        primaryCellKey(row, column - 1),
        primaryCellKey(row + 1, column - 1)
      ],
      dividerCellKey: dividerCellKey(row, column - 1, row + 1, column)
    },
    {  // top-left
      primaryCellKeys: [
        primaryCellKey(row - 1, column),
        primaryCellKey(row, column - 1),
        primaryCellKey(row - 1, column - 1)
      ],
      dividerCellKey: dividerCellKey(row - 1, column - 1, row, column)
    }
  ];
}
<commit_msg>Non-primary cell gestures do not update neighbors.<commit_after>window.onload = () => { start(); };

const objects = {};
let gesture = {};

function start() {
  createGrid(document.getElementById('grid'), 30);
}

function createGrid(parent, n) {
  for (let i = 0; i < n; i++) {
    createDividerRow(parent, n, i - 1, i);
    createCellRow(parent, n, i);
  }
  createDividerRow(parent, n, n - 1, n);
}

function createDividerRow(parent, n, previousRow, nextRow) {
  const rowContainer = createRowContainer(parent);
  for (let i = 0; i < n; i++) {
    createCornerCell(rowContainer, previousRow, nextRow, i - 1, i);
    createHorizontalCell(rowContainer, previousRow, nextRow, i);
  }
  createCornerCell(rowContainer, previousRow, nextRow, n - 1, n);
}

function createCellRow(parent, n, row) {
  const rowContainer = createRowContainer(parent);
  for (let i = 0; i < n; i++) {
    createVerticalCell(rowContainer, row, i - 1, i);
    createPrimaryCell(rowContainer, row, i);
  }
  createVerticalCell(rowContainer, row, n - 1, n);
}

function createRowContainer(parent) {
  return createAndAppendDivWithClass(parent, 'row-container');
}

function createAndAppendDivWithClass(parent, className) {
  const result = document.createElement('div');
  result.className = className;
  parent.appendChild(result);
  return result;
}

function dividerCellKey(previousRow, previousColumn, nextRow, nextColumn) {
  return `cell ${previousRow},${previousColumn}:${nextRow},${nextColumn}`;
}

function primaryCellKey(row, column) {
  return `cell ${row},${column}`;
}

function createCornerCell(parent, previousRow, nextRow, previousColumn, nextColumn) {
  createCell(parent, 'cell corner-cell',
      dividerCellKey(previousRow, previousColumn, nextRow, nextColumn));
}

function createHorizontalCell(parent, previousRow, nextRow, column) {
  createCell(parent, 'cell horizontal-cell',
      dividerCellKey(previousRow, column, nextRow, column));
}

function createVerticalCell(parent, row, previousColumn, nextColumn) {
  createCell(parent, 'cell vertical-cell',
      dividerCellKey(row, previousColumn, row, nextColumn));
}

function createPrimaryCell(parent, row, column) {
  const cell = createCell(parent, 'cell primary-cell', primaryCellKey(row, column));
  cell.setAttribute('data-row', row);
  cell.setAttribute('data-column', column);
}

function createCell(parent, className, key) {
  const cell = createAndAppendDivWithClass(parent, className + ' solid');
  objects[key] = cell;
  cell.onmousedown = () => { startGesture(cell); };
  cell.onmouseover = (e) => {
    if (e.buttons == 1) {
      continueGesture(cell);
    }
  };
  cell.ondragenter = () => { cellClicked(cell); };
  return cell;
}

function startGesture(cell) {
  if (cell.classList.contains('solid')) {
    gesture.callback = setClear;
  } else if (cell.classList.contains('clear')) {
    gesture.callback = setSolid;
  }
  gesture.primaryCellsOnly = cell.classList.contains('primary-cell');
  continueGesture(cell);
}

function continueGesture(cell) {
  const primaryCell = cell.classList.contains('primary-cell');
  if (!gesture.primaryCellsOnly || primaryCell) {
    gesture.callback(cell);
  }
  if (gesture.primaryCellsOnly && primaryCell) {
    // Primary cell gestures update neighbors.
    updatePrimaryCellNeighbors(cell);
  }
}

function setSolid(cell) {
  cell.classList.remove('clear');
  cell.classList.add('solid');
}

function setClear(cell) {
  cell.classList.remove('solid');
  cell.classList.add('clear');
}

function updatePrimaryCellNeighbors(cell) {
  for (const neighbor of getNeighbors(cell)) {
    const anyPrimaryCellIsSolid =
        ([cell].concat(neighbor.primaryCellKeys.map(key => { return objects[key]; })))
        .some(primaryCell => {
          return primaryCell && primaryCell.classList.contains('solid');
        });
    if (anyPrimaryCellIsSolid) {
      setSolid(objects[neighbor.dividerCellKey]);
    } else {
      setClear(objects[neighbor.dividerCellKey]);
    }
  }
}

function getNeighbors(cell) {
  const row = parseInt(cell.getAttribute('data-row'), 10);
  const column = parseInt(cell.getAttribute('data-column'), 10);
  return [
    // Cardinal directions:
    {  // top
      primaryCellKeys: [
        primaryCellKey(row - 1, column)
      ],
      dividerCellKey: dividerCellKey(row - 1, column, row, column)
    },
    {  // right
      primaryCellKeys: [
        primaryCellKey(row, column + 1)
      ],
      dividerCellKey: dividerCellKey(row, column, row, column + 1)
    },
    {  // bottom
      primaryCellKeys: [
        primaryCellKey(row + 1, column)
      ],
      dividerCellKey: dividerCellKey(row, column, row + 1, column)
    },
    {  // left
      primaryCellKeys: [
        primaryCellKey(row, column - 1)
      ],
      dividerCellKey: dividerCellKey(row, column - 1, row, column )
    },
    // Diagonal directions:
    {  // top-right
      primaryCellKeys: [
        primaryCellKey(row - 1, column),
        primaryCellKey(row, column + 1),
        primaryCellKey(row - 1, column + 1)
      ],
      dividerCellKey: dividerCellKey(row - 1, column, row, column + 1)
    },
    {  // bottom-right
      primaryCellKeys: [
        primaryCellKey(row + 1, column),
        primaryCellKey(row, column + 1),
        primaryCellKey(row + 1, column + 1)
      ],
      dividerCellKey: dividerCellKey(row, column, row + 1, column + 1)
    },
    {  // bottom-left
      primaryCellKeys: [
        primaryCellKey(row + 1, column),
        primaryCellKey(row, column - 1),
        primaryCellKey(row + 1, column - 1)
      ],
      dividerCellKey: dividerCellKey(row, column - 1, row + 1, column)
    },
    {  // top-left
      primaryCellKeys: [
        primaryCellKey(row - 1, column),
        primaryCellKey(row, column - 1),
        primaryCellKey(row - 1, column - 1)
      ],
      dividerCellKey: dividerCellKey(row - 1, column - 1, row, column)
    }
  ];
}
<|endoftext|>


<commit_before>/**
 * Copyright 2017 IBM All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
var path = require('path');
var fs = require('fs');
var util = require('util');
var hfc = require('fabric-client');
var Peer = require('fabric-client/lib/Peer.js');
var EventHub = require('fabric-client/lib/EventHub.js');
var config = require('../config.json');
var helper = require('./helper.js');
var logger = helper.getLogger('Query');

var getBlockByNumber = function(peer,channelName, blockNumber, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryBlock(parseInt(blockNumber), target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response_payloads) => {
		if (response_payloads) {
			//logger.debug(response_payloads);
			// logger.debug(response_payloads);
			return response_payloads; //response_payloads.data.data[0].buffer;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};

var getTransactionByID = function(peer,channelName, trxnID, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryTransaction(trxnID, target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response_payloads) => {
		if (response_payloads) {
			 logger.debug(response_payloads);
			return response_payloads;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};
var getBlockByHash = function(peer, hash, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryBlockByHash(new Buffer(hash,"hex"), target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response_payloads) => {
		if (response_payloads) {
			// logger.debug(response_payloads);
			return response_payloads;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};
var getChainInfo = function(peer,channelName, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryInfo(target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((blockchainInfo) => {
		if (blockchainInfo) {
			// FIXME: Save this for testing 'getBlockByHash'  ?
			logger.debug('===========================================');
			logger.debug(blockchainInfo.currentBlockHash);
			logger.debug('===========================================');
			//logger.debug(blockchainInfo);
			return blockchainInfo;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};

var getChannelConfig=function(org,channelName){
    var channel = helper.getChannelForOrg(org,channelName);

    return helper.getOrgAdmin(org).then((member) => {
        return channel.getChannelConfig()
    }).then((response) => {
        return response
    }).catch((err) => {
        logger.error(err)
    });

}
//getInstalledChaincodes
var getInstalledChaincodes = function(peer,channelName, type, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);
	var client = helper.getClientForOrg(org);

	return helper.getOrgAdmin(org).then((member) => {
		if (type === 'installed') {
			return client.queryInstalledChaincodes(target);
		} else {
			return channel.queryInstantiatedChaincodes(target);
		}
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response) => {
		if (response) {
			if (type === 'installed') {
				logger.debug('<<< Installed Chaincodes >>>');
			} else {
				logger.debug('<<< Instantiated Chaincodes >>>');
			}
			var details = [];
			for (let i = 0; i < response.chaincodes.length; i++) {
				let detail={}
				logger.debug('name: ' + response.chaincodes[i].name + ', version: ' +
					response.chaincodes[i].version + ', path: ' + response.chaincodes[i].path
				);
                detail.name=response.chaincodes[i].name
				detail.version=response.chaincodes[i].version
				detail.path=response.chaincodes[i].path
                details.push(detail);
			}
			return details;
		} else {
			logger.error('response is null');
			return 'response is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};
var getChannels = function(peer, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org);
	var client = helper.getClientForOrg(org);

	return helper.getRegisteredUsers(username, org).then((member) => {
		//channel.setPrimaryPeer(targets[0]);
		return client.queryChannels(target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response) => {
		if (response) {
			logger.debug('<<< channels >>>');
			var channelNames = [];
			for (let i = 0; i < response.channels.length; i++) {
				channelNames.push('channel id: ' + response.channels[i].channel_id);
			}
			logger.debug(channelNames);
			return response;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};

var getChannelHeight=function(peer,channelName,username,org){
	return getChainInfo(peer,channelName,username,org).then(response=>{
		if(response){
			logger.debug('<<<<<<<<<< channel height >>>>>>>>>')
			logger.debug(response.height.low)
			return response.height.low.toString()
		}
	})
}

function buildTarget(peer, org) {
	var target = null;
	if (typeof peer !== 'undefined') {
		let targets = helper.newPeers([helper.getPeerAddressByName(org, peer)]);
		if (targets && targets.length > 0) target = targets[0];
	}

	return target;
}

exports.getBlockByNumber = getBlockByNumber;
exports.getTransactionByID = getTransactionByID;
exports.getBlockByHash = getBlockByHash;
exports.getChainInfo = getChainInfo;
exports.getInstalledChaincodes = getInstalledChaincodes;
exports.getChannels = getChannels;
exports.getChannelHeight=getChannelHeight;
exports.getChannelConfig=getChannelConfig;<commit_msg>modify license headers<commit_after>/**
 * Copyright 2017 ONECHAIN All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
var path = require('path');
var fs = require('fs');
var util = require('util');
var hfc = require('fabric-client');
var Peer = require('fabric-client/lib/Peer.js');
var EventHub = require('fabric-client/lib/EventHub.js');
var config = require('../config.json');
var helper = require('./helper.js');
var logger = helper.getLogger('Query');

var getBlockByNumber = function(peer,channelName, blockNumber, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryBlock(parseInt(blockNumber), target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response_payloads) => {
		if (response_payloads) {
			//logger.debug(response_payloads);
			// logger.debug(response_payloads);
			return response_payloads; //response_payloads.data.data[0].buffer;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};

var getTransactionByID = function(peer,channelName, trxnID, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryTransaction(trxnID, target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response_payloads) => {
		if (response_payloads) {
			 logger.debug(response_payloads);
			return response_payloads;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};
var getBlockByHash = function(peer, hash, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryBlockByHash(new Buffer(hash,"hex"), target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response_payloads) => {
		if (response_payloads) {
			// logger.debug(response_payloads);
			return response_payloads;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};
var getChainInfo = function(peer,channelName, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);

	return helper.getRegisteredUsers(username, org).then((member) => {
		return channel.queryInfo(target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((blockchainInfo) => {
		if (blockchainInfo) {
			// FIXME: Save this for testing 'getBlockByHash'  ?
			logger.debug('===========================================');
			logger.debug(blockchainInfo.currentBlockHash);
			logger.debug('===========================================');
			//logger.debug(blockchainInfo);
			return blockchainInfo;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};

var getChannelConfig=function(org,channelName){
    var channel = helper.getChannelForOrg(org,channelName);

    return helper.getOrgAdmin(org).then((member) => {
        return channel.getChannelConfig()
    }).then((response) => {
        return response
    }).catch((err) => {
        logger.error(err)
    });

}
//getInstalledChaincodes
var getInstalledChaincodes = function(peer,channelName, type, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org,channelName);
	var client = helper.getClientForOrg(org);

	return helper.getOrgAdmin(org).then((member) => {
		if (type === 'installed') {
			return client.queryInstalledChaincodes(target);
		} else {
			return channel.queryInstantiatedChaincodes(target);
		}
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response) => {
		if (response) {
			if (type === 'installed') {
				logger.debug('<<< Installed Chaincodes >>>');
			} else {
				logger.debug('<<< Instantiated Chaincodes >>>');
			}
			var details = [];
			for (let i = 0; i < response.chaincodes.length; i++) {
				let detail={}
				logger.debug('name: ' + response.chaincodes[i].name + ', version: ' +
					response.chaincodes[i].version + ', path: ' + response.chaincodes[i].path
				);
                detail.name=response.chaincodes[i].name
				detail.version=response.chaincodes[i].version
				detail.path=response.chaincodes[i].path
                details.push(detail);
			}
			return details;
		} else {
			logger.error('response is null');
			return 'response is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};
var getChannels = function(peer, username, org) {
	var target = buildTarget(peer, org);
	var channel = helper.getChannelForOrg(org);
	var client = helper.getClientForOrg(org);

	return helper.getRegisteredUsers(username, org).then((member) => {
		//channel.setPrimaryPeer(targets[0]);
		return client.queryChannels(target);
	}, (err) => {
		logger.info('Failed to get submitter "' + username + '"');
		return 'Failed to get submitter "' + username + '". Error: ' + err.stack ?
			err.stack : err;
	}).then((response) => {
		if (response) {
			logger.debug('<<< channels >>>');
			var channelNames = [];
			for (let i = 0; i < response.channels.length; i++) {
				channelNames.push('channel id: ' + response.channels[i].channel_id);
			}
			logger.debug(channelNames);
			return response;
		} else {
			logger.error('response_payloads is null');
			return 'response_payloads is null';
		}
	}, (err) => {
		logger.error('Failed to send query due to error: ' + err.stack ? err.stack :
			err);
		return 'Failed to send query due to error: ' + err.stack ? err.stack : err;
	}).catch((err) => {
		logger.error('Failed to query with error:' + err.stack ? err.stack : err);
		return 'Failed to query with error:' + err.stack ? err.stack : err;
	});
};

var getChannelHeight=function(peer,channelName,username,org){
	return getChainInfo(peer,channelName,username,org).then(response=>{
		if(response){
			logger.debug('<<<<<<<<<< channel height >>>>>>>>>')
			logger.debug(response.height.low)
			return response.height.low.toString()
		}
	})
}

function buildTarget(peer, org) {
	var target = null;
	if (typeof peer !== 'undefined') {
		let targets = helper.newPeers([helper.getPeerAddressByName(org, peer)]);
		if (targets && targets.length > 0) target = targets[0];
	}

	return target;
}

exports.getBlockByNumber = getBlockByNumber;
exports.getTransactionByID = getTransactionByID;
exports.getBlockByHash = getBlockByHash;
exports.getChainInfo = getChainInfo;
exports.getInstalledChaincodes = getInstalledChaincodes;
exports.getChannels = getChannels;
exports.getChannelHeight=getChannelHeight;
exports.getChannelConfig=getChannelConfig;<|endoftext|>


<commit_before>var path       = require('path');
var less       = require('less');
var fs         = require('fs');
var crypto     = require('crypto');
var chokidar   = require('chokidar');
var browserify = require('browserify');
var UglifyJS   = require('uglify-js');
var debug      = require('debug')('Noumena:setup');
var app;

function buildCss(next, ensureDirectory) {
    var code = fs.readFileSync(process.cwd() + '/all.less', {encoding: 'utf8'});
    var options = {
        paths        : [process.cwd()],
        optimization : 2,
        filename     : "all.less",
        compress     : true,
        cleancss     : true,
        ieCompat     : false
    };
    var parser = new less.Parser(options);
    parser.parse(code, function(error, cssTree) {
        ensureDirectory();

        if (error) { return less.writeError(error, options); }

        var css = cssTree.toCSS(options);

        app.set('css', {
            md5:  crypto.createHash('md5').update(css).digest('hex'),
            code: css
        });

        next();
    });
}

function buildJs(next, ensureDirectory) {
    var b = browserify();
    b.add('./main.js');
    b.bundle(function(err, buf) {
        ensureDirectory();

        if (err) {
            var js = 'alert("JS build error!\n\n"+' + JSON.stringify(String(err)) + ');';
        } else {
            var js = buf.toString();
        }

        var options = {
            fromString : true,
            mangle     : {screw_ie8: true},
            compress   : {
                booleans      : true,
                cascade       : true,
                comparisons   : true,
                conditionals  : true,
                dead_code     : true,
                drop_console  : true,
                drop_debugger : true,
                evaluate      : true,
                hoist_funs    : true,
                if_return     : true,
                join_vars     : true,
                loops         : true,
                negate_iife   : true,
                properties    : true,
                screw_ie8     : true,
                sequences     : true,
                unused        : true
            }
        };

        var minified = UglifyJS.minify(js, options).code;

        app.set('js', {
            md5:  crypto.createHash('md5').update(minified).digest('hex'),
            code: minified
        });

        next();
    });
}

// Auto-compilation abstraction. You give it a directory path, and a compilation routine.
// The routine will be executed in the directory specified, and this directory will be
// watched for changes, running this compile step again when changes are detected.
// If the routine needs to be async, we'll pass it a "next" argument.
function autoCompile(directory, routine) {
    var absolute = path.resolve(__dirname, directory);
    function compile() {
        var originalDirectory = process.cwd();
        var ensureDirectory = process.chdir.bind(process, absolute);
        var next = process.chdir.bind(process, originalDirectory);
        try {
            ensureDirectory();
            routine(next, ensureDirectory);
        } catch (e) {
            debug('Compile routine error for ' + directory + ': \n' + e);
            next();
        }
        next();
    }
    compile();
    var watcher = chokidar.watch(absolute);
    var timeout = null;
    watcher.on('all', function change() {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        timeout = setTimeout(function() {
            compile();
            timeout = null;
        }, 150);
    });
    // It's not like Chokidar is particularly helpful when it flops over and dies, but...
    watcher.on('error', function(error){ debug('Chokidar error: ' + error); });
}

// This setup mechanism is invoked before starting the server.
function setup(instance) {
    app = instance;
    autoCompile('../stylesheets', buildCss);
    autoCompile('../scripting', buildJs);
}

module.exports = setup;
<commit_msg>Fix for changes in less API.<commit_after>var path       = require('path');
var less       = require('less');
var fs         = require('fs');
var crypto     = require('crypto');
var chokidar   = require('chokidar');
var browserify = require('browserify');
var UglifyJS   = require('uglify-js');
var debug      = require('debug')('Noumena:setup');
var app;

function buildCss(next, ensureDirectory) {
    var code = fs.readFileSync(process.cwd() + '/all.less', {encoding: 'utf8'});
    var options = {
        paths        : [process.cwd()],
        filename     : "all.less",
        compress     : true,
        ieCompat     : false
    };
    less.render(code, options, function(error, output) {
        ensureDirectory();

        if (error) { return less.writeError(error, options); }

        app.set('css', {
            md5:  crypto.createHash('md5').update(output.css).digest('hex'),
            code: output.css
        });

        next();
    });
}

function buildJs(next, ensureDirectory) {
    var b = browserify();
    b.add('./main.js');
    b.bundle(function(err, buf) {
        ensureDirectory();

        if (err) {
            var js = 'alert("JS build error!\n\n"+' + JSON.stringify(String(err)) + ');';
        } else {
            var js = buf.toString();
        }

        var options = {
            fromString : true,
            mangle     : {screw_ie8: true},
            compress   : {
                booleans      : true,
                cascade       : true,
                comparisons   : true,
                conditionals  : true,
                dead_code     : true,
                drop_console  : true,
                drop_debugger : true,
                evaluate      : true,
                hoist_funs    : true,
                if_return     : true,
                join_vars     : true,
                loops         : true,
                negate_iife   : true,
                properties    : true,
                screw_ie8     : true,
                sequences     : true,
                unused        : true
            }
        };

        var minified = UglifyJS.minify(js, options).code;

        app.set('js', {
            md5:  crypto.createHash('md5').update(minified).digest('hex'),
            code: minified
        });

        next();
    });
}

// Auto-compilation abstraction. You give it a directory path, and a compilation routine.
// The routine will be executed in the directory specified, and this directory will be
// watched for changes, running this compile step again when changes are detected.
// If the routine needs to be async, we'll pass it a "next" argument.
function autoCompile(directory, routine) {
    var absolute = path.resolve(__dirname, directory);
    function compile() {
        var originalDirectory = process.cwd();
        var ensureDirectory = process.chdir.bind(process, absolute);
        var next = process.chdir.bind(process, originalDirectory);
        try {
            ensureDirectory();
            routine(next, ensureDirectory);
        } catch (e) {
            debug('Compile routine error for ' + directory + ': \n' + e);
            next();
        }
        next();
    }
    compile();
    var watcher = chokidar.watch(absolute);
    var timeout = null;
    watcher.on('all', function change() {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        timeout = setTimeout(function() {
            compile();
            timeout = null;
        }, 150);
    });
    // It's not like Chokidar is particularly helpful when it flops over and dies, but...
    watcher.on('error', function(error){ debug('Chokidar error: ' + error); });
}

// This setup mechanism is invoked before starting the server.
function setup(instance) {
    app = instance;
    autoCompile('../stylesheets', buildCss);
    autoCompile('../scripting', buildJs);
}

module.exports = setup;
<|endoftext|>


<commit_before>/**
 * Create the store with asynchronously loaded reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
import { persistStore, autoRehydrate } from 'redux-persist-immutable'

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history),
  ];

  const enhancers = [
    applyMiddleware(...middlewares),
    autoRehydrate()
  ];

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
      window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );

  // begin periodically persisting the store
  // persistStore(store, {blacklist: ['route']});

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.asyncReducers = {}; // Async reducer registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      import('./reducers').then((reducerModule) => {
        const createReducers = reducerModule.default;
        const nextReducers = createReducers(store.asyncReducers);

        store.replaceReducer(nextReducers);
      });
    });
  }

  return store;
}
<commit_msg>Good to go<commit_after>/**
 * Create the store with asynchronously loaded reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
import { persistStore, autoRehydrate } from 'redux-persist-immutable'

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history),
  ];

  const enhancers = [
    applyMiddleware(...middlewares),
    autoRehydrate()
  ];

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
      window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );

  // begin periodically persisting the store
  persistStore(store, {blacklist: ['route']});

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.asyncReducers = {}; // Async reducer registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      import('./reducers').then((reducerModule) => {
        const createReducers = reducerModule.default;
        const nextReducers = createReducers(store.asyncReducers);

        store.replaceReducer(nextReducers);
      });
    });
  }

  return store;
}
<|endoftext|>


<commit_before>/**
 * Create the store with asynchronously loaded reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
import logger from './logger';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
    sagaMiddleware,
    logger,
    routerMiddleware(history),
  ];

  const enhancers = [
    applyMiddleware(...middlewares),
  ];

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
      window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.asyncReducers = {}; // Async reducer registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      import('./reducers').then((reducerModule) => {
        const createReducers = reducerModule.default;
        const nextReducers = createReducers(store.asyncReducers);

        store.replaceReducer(nextReducers);
      });
    });
  }

  return store;
}
<commit_msg>. when production env should remove logger<commit_after>/**
 * Create the store with asynchronously loaded reducers
 */

import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
import logger from './logger';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
  // Create the store with two middlewares
  // 1. sagaMiddleware: Makes redux-sagas work
  // 2. routerMiddleware: Syncs the location/URL path to the state
  const middlewares = [
    sagaMiddleware,
    routerMiddleware(history),
  ];

  if (process.env.NODE_ENV !== 'production') {
    middlewares.push(logger);
  }

  const enhancers = [
    applyMiddleware(...middlewares),
  ];

  // If Redux DevTools Extension is installed use it, otherwise use Redux compose
  /* eslint-disable no-underscore-dangle */
  const composeEnhancers =
    process.env.NODE_ENV !== 'production' &&
    typeof window === 'object' &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
      window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
  /* eslint-enable */

  const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers)
  );

  // Extensions
  store.runSaga = sagaMiddleware.run;
  store.asyncReducers = {}; // Async reducer registry

  // Make reducers hot reloadable, see http://mxs.is/googmo
  /* istanbul ignore next */
  if (module.hot) {
    module.hot.accept('./reducers', () => {
      import('./reducers').then((reducerModule) => {
        const createReducers = reducerModule.default;
        const nextReducers = createReducers(store.asyncReducers);

        store.replaceReducer(nextReducers);
      });
    });
  }

  return store;
}
<|endoftext|>


<commit_before>import React from "react";
import DevTools from "mobx-react-devtools";
import {computed} from "mobx";
import {InternalError, NotFound} from "./errors";
import {Wrapper} from "tide/base/context";
import {MobxObserver} from "tide/base/base";

/**
 * @class
 */
export class TidePage extends MobxObserver {
    static displayName = "Tide.Page";

    get page_state() {
        return this.props.tide.page_state;
    }

    get tide() {
        return this.props.tide;
    }

    /**
     * Compile the data into the current view.
     * It is safe to call at all stages of the render, because it will always return some kind of React.Component
     * even if its just a div to tell us that the page is loading.
     * @returns {ReactElement|XML}
     */
    @computed get current_view() {
        const page_state = this.page_state;

        let view       = page_state.view;
        let data       = page_state.data;
        let status     = page_state.status;
        let route_name = page_state.route_name;
        let last_update = page_state.last_update;

        console.log(`[Tide] Current View: ${route_name} - ${status}. Updated @ ${last_update}`);

        if ( !status ) {
            return
[Tide] Waiting to initialize data store.

        }
        if ( !route_name ) {
            return
[Tide] No route set.

        }

        if ( status === 'pending' ) {
            return
[Tide] Loading page ... status: {status}

        }

        if(status === 'failed'){
            return
[Tide] Attempting to load this page failed.

        }

        // Status at this point should be processing / ok / failed
        return this._create_view(view, data, []);
    }

    /**
     * Ensure that we create a view with a React Element.
     * @private
     * @param {XML|React.Component|React.Element|ReactElement} view
     * @param {*} props
     * @param {Array.<ReactElement>} children
     * @returns {ReactElement}
     */
    _create_view(view, props, children) {
        if ( React.isValidElement(view) ) {
            return React.cloneElement(view, props, children);
        }

        return React.createElement(view, props, children);
    }

    render() {
        // Page State, includes current view
        const page_state = this.page_state;

        let route_name = page_state.route_name;
        let app_label  = page_state.app_label;
        let status     = page_state.status;
        let view       = this.current_view;

        if(!route_name || !this.tide.has_app(app_label)){
            return <InternalError />
        }

        // Get Application Configuration for current view
        // We'll put store/app in a wrapper at the end so the context
        // is populated down to the View/Presenters that our render has returned
        let app_conf = this.tide.get_app(app_label);

        let app    = app_conf.app;
        let store  = app_conf.store;
        let layout = app_conf.layout;

        console.log(`[Tide] Rendering... ${route_name} in app: ${app_label}. Status: ${status}`);

        let children =

            {view || <InternalError />}
            {this.tide.dev_mode ? <DevTools /> : ""}

;

        let layout_component = this._create_view(layout, {}, children);

        return <Wrapper app={app} store={store}>{layout_component}</Wrapper>;
    }
}<commit_msg>Remove dev tools<commit_after>import React from "react";
//import DevTools from "mobx-react-devtools";
import {computed} from "mobx";
import {InternalError, NotFound} from "./errors";
import {Wrapper} from "tide/base/context";
import {MobxObserver} from "tide/base/base";

/**
 * @class
 */
export class TidePage extends MobxObserver {
    static displayName = "Tide.Page";

    get page_state() {
        return this.props.tide.page_state;
    }

    get tide() {
        return this.props.tide;
    }

    /**
     * Compile the data into the current view.
     * It is safe to call at all stages of the render, because it will always return some kind of React.Component
     * even if its just a div to tell us that the page is loading.
     * @returns {ReactElement|XML}
     */
    @computed get current_view() {
        const page_state = this.page_state;

        let view       = page_state.view;
        let data       = page_state.data;
        let status     = page_state.status;
        let route_name = page_state.route_name;
        let last_update = page_state.last_update;

        console.log(`[Tide] Current View: ${route_name} - ${status}. Updated @ ${last_update}`);

        if ( !status ) {
            return
[Tide] Waiting to initialize data store.

        }
        if ( !route_name ) {
            return
[Tide] No route set.

        }

        if ( status === 'pending' ) {
            return
[Tide] Loading page ... status: {status}

        }

        if(status === 'failed'){
            return
[Tide] Attempting to load this page failed.

        }

        // Status at this point should be processing / ok / failed
        return this._create_view(view, data, []);
    }

    /**
     * Ensure that we create a view with a React Element.
     * @private
     * @param {XML|React.Component|React.Element|ReactElement} view
     * @param {*} props
     * @param {Array.<ReactElement>} children
     * @returns {ReactElement}
     */
    _create_view(view, props, children) {
        if ( React.isValidElement(view) ) {
            return React.cloneElement(view, props, children);
        }

        return React.createElement(view, props, children);
    }

    render() {
        // Page State, includes current view
        const page_state = this.page_state;

        let route_name = page_state.route_name;
        let app_label  = page_state.app_label;
        let status     = page_state.status;
        let view       = this.current_view;

        if(!route_name || !this.tide.has_app(app_label)){
            return <InternalError />
        }

        // Get Application Configuration for current view
        // We'll put store/app in a wrapper at the end so the context
        // is populated down to the View/Presenters that our render has returned
        let app_conf = this.tide.get_app(app_label);

        let app    = app_conf.app;
        let store  = app_conf.store;
        let layout = app_conf.layout;

        console.log(`[Tide] Rendering... ${route_name} in app: ${app_label}. Status: ${status}`);

        let children =

            {view || <InternalError />}
            {/*{this.tide.dev_mode ? <DevTools /> : ""}*/}

;

        let layout_component = this._create_view(layout, {}, children);

        return <Wrapper app={app} store={store}>{layout_component}</Wrapper>;
    }
}<|endoftext|>


<commit_before>// Your init script
//
// Atom will evaluate this file each time a new window is opened. It is run
// after packages are loaded/activated and after the previous editor state
// has been restored.
'use strict';

const {exec} = require('child_process');

// Set preferred size of current Atom window while preserving window position;
// assumes Tree View is open
function setPreferredWindowDimensions() {
  const originalWindowDimensions = atom.getWindowDimensions();
  atom.setWindowDimensions({
    width: 1080,
    height: 710,
    x: originalWindowDimensions.x,
    y: originalWindowDimensions.y
  });
}
setPreferredWindowDimensions();

// Sync Atom packages via package-sync package
function syncPackages() {
  const workspaceView = atom.views.getView(atom.workspace);
  return atom.commands.dispatch(workspaceView, 'package-sync:sync');
}
syncPackages();

// Extend the JavaScript tree-sitter grammar with additional highlighting
function extendJavaScriptTreeSitterGrammar() {
  const jsGrammar = atom.grammars.treeSitterGrammarsById['source.js'];
  if (jsGrammar && jsGrammar.scopeMap) {
    // Colorize `this` and `arguments` in red like other language keywords
    jsGrammar.scopeMap.addSelector('this', 'variable.language.js');
    jsGrammar.scopeMap.addSelector('identifier', [
      {
        match: /^arguments$/,
        scopes: 'variable.language.js'
      },
      // Colorize JSON built-in object like other class names (instead of like an
      // object)
      {
        match: /^JSON$/,
        scopes: 'meta.class'
      },
      // Preserve existing identifier grammar rules
      ...jsGrammar.scopeMap.namedScopeTable.identifier.result
    ]);
  }
}
// All Atom grammars are loaded asynchronously, so use nested setImmediate()
// calls to wait for the first-mate JavaScript grammar to load before modifying
// the tree-sitter grammar
setImmediate(() => {
  setImmediate(() => {
    extendJavaScriptTreeSitterGrammar();
  });
});

// Extend the Python tree-sitter grammar with additional highlighting
function extendPythonTreeSitterGrammar() {
  // Force tree-sitter grammar to override first-mate grammar
  const pyGrammar = atom.grammars.treeSitterGrammarsById['source.python'];
  if (pyGrammar && pyGrammar.firstLineRegex) {
    pyGrammar.firstLineRegex = atom.grammars.textmateRegistry.grammarsByScopeName['source.python'].firstLineRegex;
  }
  if (pyGrammar && pyGrammar.scopeMap) {
    // Colorize function parameter names
    pyGrammar.scopeMap.addSelector(
      'parameters > identifier',
      'variable.parameter.function'
    );
    pyGrammar.scopeMap.addSelector(
      'default_parameter > identifier:nth-child(0)',
      'variable.parameter.function'
    );
    // Colorize variable and class names within class argument lists
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > attribute',
      'entity.other.inherited-class.python'
    );
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > identifier',
      'entity.other.inherited-class.python'
    );
    // Colorize variable and class names as values of keyword arguments within
    // class argument lists
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > keyword_argument > attribute',
      'entity.other.inherited-class.python'
    );
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > keyword_argument > identifier:nth-child(2)',
      'entity.other.inherited-class.python'
    );
    // Colorize `self` and `cls`
    pyGrammar.scopeMap.addSelector('identifier, identifier:nth-child(0)', [
      {
        match: /^self$/,
        scopes: 'variable.language.self.python'
      },
      {
        match: /^cls$/,
        scopes: 'variable.language.cls.python'
      }
    ]);
  }
  // Re-apply Python tree-sitter grammar to all open Python files
  atom.grammars.grammarScoresByBuffer.forEach((score, buffer) => {
    if (buffer.getLanguageMode().grammar.scopeName === 'source.python' && !atom.grammars.languageOverridesByBufferId.has(buffer.id)) {
      atom.grammars.autoAssignLanguageMode(buffer);
    }
  });
}
// Wait for the Python first-mate grammar to load before modifying the
// tree-sitter grammar
setImmediate(() => {
  setImmediate(() => {
    extendPythonTreeSitterGrammar();
  });
});

// Override getGrammars to work around bug with tree-sitter grammars never
// applying; see
// <https://github.com/atom/atom/issues/17029#issuecomment-457084440>
atom.grammars.getGrammars = () => {
  const allGrammars = atom.grammars.textmateRegistry.getGrammars();
  const tsGrammars = Object.values(atom.grammars.treeSitterGrammarsById);
  const combinedGrammars = tsGrammars.concat(allGrammars);
  const combinedGrammarNames = combinedGrammars.map((grammar) => grammar.name);
  return combinedGrammars.filter((grammar, g) => {
    return (
      // Prefer tree-sitter grammars whenever possible
      grammar.constructor.name === 'TreeSitterGrammar'
      // OR, if this is a first-mate grammar without a corresponding tree-sitter
      // grammar, add it to the list
      || combinedGrammarNames.indexOf(grammar.name) === g
    );
  });
};

// Add command to copy to clipboard an array of the editor's current cursor
// scopes
atom.commands.add('atom-text-editor:not([mini])', 'editor:copy-cursor-scope', () => {
  const editor = atom.workspace.getActiveTextEditor();
  const scopes = editor.getCursorScope().scopes;
  if (scopes) {
    const scopeString = JSON.stringify(scopes)
      .replace(/,/g, ', ')
      .replace(/"/g, '\'');
    atom.clipboard.write(scopeString);
    const list = scopes.map((item) => `* ${item}`);
    const content = `Copied Scopes at Cursor\n${list.join('\n')}`;
    atom.notifications.addInfo(content, {
      dismissable: true
    });
  } else {
    atom.notifications.addError('Scopes at Cursor', {
      detail: 'Could not write scopes to clipboard'
    });
  }
});

// Add command for revealing the project folder at the workspace level
atom.commands.add('atom-workspace', 'application:show-project-folder-in-file-manager', () => {
  const projectPaths = atom.project.getPaths();
  if (projectPaths.length > 0) {
    exec(`open ${projectPaths[0]}`);
  }
});
<commit_msg>Make cmd-0 in Atom reset font size to 16<commit_after>// Your init script
//
// Atom will evaluate this file each time a new window is opened. It is run
// after packages are loaded/activated and after the previous editor state
// has been restored.
'use strict';

const {exec} = require('child_process');

// Set preferred size of current Atom window while preserving window position;
// assumes Tree View is open
function setPreferredWindowDimensions() {
  const originalWindowDimensions = atom.getWindowDimensions();
  atom.setWindowDimensions({
    width: 1080,
    height: 710,
    x: originalWindowDimensions.x,
    y: originalWindowDimensions.y
  });
}
setPreferredWindowDimensions();

// Sync Atom packages via package-sync package
function syncPackages() {
  const workspaceView = atom.views.getView(atom.workspace);
  return atom.commands.dispatch(workspaceView, 'package-sync:sync');
}
syncPackages();

// Extend the JavaScript tree-sitter grammar with additional highlighting
function extendJavaScriptTreeSitterGrammar() {
  const jsGrammar = atom.grammars.treeSitterGrammarsById['source.js'];
  if (jsGrammar && jsGrammar.scopeMap) {
    // Colorize `this` and `arguments` in red like other language keywords
    jsGrammar.scopeMap.addSelector('this', 'variable.language.js');
    jsGrammar.scopeMap.addSelector('identifier', [
      {
        match: /^arguments$/,
        scopes: 'variable.language.js'
      },
      // Colorize JSON built-in object like other class names (instead of like an
      // object)
      {
        match: /^JSON$/,
        scopes: 'meta.class'
      },
      // Preserve existing identifier grammar rules
      ...jsGrammar.scopeMap.namedScopeTable.identifier.result
    ]);
  }
}
// All Atom grammars are loaded asynchronously, so use nested setImmediate()
// calls to wait for the first-mate JavaScript grammar to load before modifying
// the tree-sitter grammar
setImmediate(() => {
  setImmediate(() => {
    extendJavaScriptTreeSitterGrammar();
  });
});

// Extend the Python tree-sitter grammar with additional highlighting
function extendPythonTreeSitterGrammar() {
  // Force tree-sitter grammar to override first-mate grammar
  const pyGrammar = atom.grammars.treeSitterGrammarsById['source.python'];
  if (pyGrammar && pyGrammar.firstLineRegex) {
    pyGrammar.firstLineRegex = atom.grammars.textmateRegistry.grammarsByScopeName['source.python'].firstLineRegex;
  }
  if (pyGrammar && pyGrammar.scopeMap) {
    // Colorize function parameter names
    pyGrammar.scopeMap.addSelector(
      'parameters > identifier',
      'variable.parameter.function'
    );
    pyGrammar.scopeMap.addSelector(
      'default_parameter > identifier:nth-child(0)',
      'variable.parameter.function'
    );
    // Colorize variable and class names within class argument lists
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > attribute',
      'entity.other.inherited-class.python'
    );
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > identifier',
      'entity.other.inherited-class.python'
    );
    // Colorize variable and class names as values of keyword arguments within
    // class argument lists
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > keyword_argument > attribute',
      'entity.other.inherited-class.python'
    );
    pyGrammar.scopeMap.addSelector(
      'class_definition > argument_list > keyword_argument > identifier:nth-child(2)',
      'entity.other.inherited-class.python'
    );
    // Colorize `self` and `cls`
    pyGrammar.scopeMap.addSelector('identifier, identifier:nth-child(0)', [
      {
        match: /^self$/,
        scopes: 'variable.language.self.python'
      },
      {
        match: /^cls$/,
        scopes: 'variable.language.cls.python'
      }
    ]);
  }
  // Re-apply Python tree-sitter grammar to all open Python files
  atom.grammars.grammarScoresByBuffer.forEach((score, buffer) => {
    if (buffer.getLanguageMode().grammar.scopeName === 'source.python' && !atom.grammars.languageOverridesByBufferId.has(buffer.id)) {
      atom.grammars.autoAssignLanguageMode(buffer);
    }
  });
}
// Wait for the Python first-mate grammar to load before modifying the
// tree-sitter grammar
setImmediate(() => {
  setImmediate(() => {
    extendPythonTreeSitterGrammar();
  });
});

// Override getGrammars to work around bug with tree-sitter grammars never
// applying; see
// <https://github.com/atom/atom/issues/17029#issuecomment-457084440>
atom.grammars.getGrammars = () => {
  const allGrammars = atom.grammars.textmateRegistry.getGrammars();
  const tsGrammars = Object.values(atom.grammars.treeSitterGrammarsById);
  const combinedGrammars = tsGrammars.concat(allGrammars);
  const combinedGrammarNames = combinedGrammars.map((grammar) => grammar.name);
  return combinedGrammars.filter((grammar, g) => {
    return (
      // Prefer tree-sitter grammars whenever possible
      grammar.constructor.name === 'TreeSitterGrammar'
      // OR, if this is a first-mate grammar without a corresponding tree-sitter
      // grammar, add it to the list
      || combinedGrammarNames.indexOf(grammar.name) === g
    );
  });
};

// Add command to copy to clipboard an array of the editor's current cursor
// scopes
atom.commands.add('atom-text-editor:not([mini])', 'editor:copy-cursor-scope', () => {
  const editor = atom.workspace.getActiveTextEditor();
  const scopes = editor.getCursorScope().scopes;
  if (scopes) {
    const scopeString = JSON.stringify(scopes)
      .replace(/,/g, ', ')
      .replace(/"/g, '\'');
    atom.clipboard.write(scopeString);
    const list = scopes.map((item) => `* ${item}`);
    const content = `Copied Scopes at Cursor\n${list.join('\n')}`;
    atom.notifications.addInfo(content, {
      dismissable: true
    });
  } else {
    atom.notifications.addError('Scopes at Cursor', {
      detail: 'Could not write scopes to clipboard'
    });
  }
});

// Add command for revealing the project folder at the workspace level
atom.commands.add('atom-workspace', 'application:show-project-folder-in-file-manager', () => {
  const projectPaths = atom.project.getPaths();
  if (projectPaths.length > 0) {
    exec(`open ${projectPaths[0]}`);
  }
});

// Change the base font size to 16 so that pressing cmd-0 will reset the font
// size to my preferred
atom.commands.add('body', 'window:reset-font-size', () => {
  atom.config.set('editor.fontSize', 16);
});
<|endoftext|>


<commit_before>var debug       = require('debug')('auth:data');
var base        = require('taskcluster-base');
var assert      = require('assert');
var _           = require('lodash');
var taskcluster = require('taskcluster-client');

var Client = base.Entity.configure({
  version:          1,
  partitionKey:     base.Entity.keys.StringKey('clientId'),
  rowKey:           base.Entity.keys.ConstantKey('client'),
  signEntities:     true,
  properties: {
    clientId:       base.Entity.types.String,
    description:    base.Entity.types.Text,
    accessToken:    base.Entity.types.EncryptedText,
    expires:        base.Entity.types.Date,
    /**
     * Details object with properties:
     * - created          // Time when client was created
     * - lastModified     // Last time client was modified
     * - lastDateUsed     // Only updated if more than 6 hours out of date
     * - lastRotated      // Last time accessToken was reset
     * (more properties may be added in the future)
     */
    details:        base.Entity.types.JSON
  },
  context:          ['resolver']
});

/** Get scopes granted to this client */
Client.prototype.expandedScopes = function() {
  return this.resolver.resolve(['assume:client-id:' + this.clientId]);
};

/** Get JSON representation of client */
Client.prototype.json = function() {
  return {
    clientId:       this.clientId,
    description:    this.description,
    expires:        this.expires.toJSON(),
    created:        this.details.created,
    lastModified:   this.details.lastModified,
    lastDateUsed:   this.details.lastDateUsed,
    lastRotated:    this.details.lastRotated,
    expandedScopes: this.scopes()
  };
};

/**
 * Ensure root client exists and has the given accessToken.
 *
 * Should only be called if the app is configured with a rootAccessToken.
 * Otherwise, app should assume whatever is in the table storage is the
 * root access token, and that appropriate role is attached.
 */
Client.ensureRootClient = function(accessToken) {
  assert(typeof(accessToken) === 'string',
         "Expected accessToken to be a string");
  let Client = this;
  // Create client resolving conflicts by overwriting
  return Client.create({
    clientId:         'root',
    description:      "Automatically created `root` client " +
                      "for bootstrapping API access",
    accessToken:      accessToken,
    expires:          taskcluster.fromNow('24 hours'),
    details: {
      created:        new Date().toJSON(),
      lastModified:   new Date().toJSON(),
      lastDateUsed:   new Date().toJSON(),
      lastRotated:    new Date().toJSON()
    }
  }, true);
};

// Export Client
exports.Client = Client;

var Role = base.Entity.configure({
  version:          1,
  partitionKey:     base.Entity.keys.StringKey('roleId'),
  rowKey:           base.Entity.keys.ConstantKey('role'),
  signEntities:     true,
  properties: {
    roleId:         base.Entity.types.String,
    description:    base.Entity.types.Text,
    scopes:         base.Entity.types.JSON,
    /**
     * Details object with properties:
     * - created
     * - lastModified
     * (more properties may be added in the future)
     */
    details:        base.Entity.types.JSON,
  },
  context:          ['resolver']
});

/** Get JSON representation of a role */
Role.prototype.json = function() {
  return {
    roleId:         this.roleId,
    description:    this.description,
    created:        this.details.created,
    lastModified:   this.details.lastModified,
    scopes:         this.scopes,
    expandedScopes: this.resolver.resolve(['assume:' + this.roleId])
  };
};

/**
 * Ensure the role: client-id:root -> ['*'] exists
 *
 * Should only be called if the app is configured with a rootAccessToken.
 * Otherwise, app should assume whatever is in the table storage is the
 * root access token, and that appropriate role is attached.
 *
 * Basically, this is for bootstrapping only.
 */
Role.ensureRootRole = function() {
  let Role = this;
  return Role.create({
    roleId:       'client-id:root',
    description:  "Automatically created role for bootstrapping the `root` "+
                  "client.",
    scopes:       ['*'],
    details: {
      created:        new Date().toJSON(),
      lastModified:   new Date().toJSON()
    }
  }, true);
};

// Export Role
exports.Role = Role;

<commit_msg>Minor fix<commit_after>var debug       = require('debug')('auth:data');
var base        = require('taskcluster-base');
var assert      = require('assert');
var _           = require('lodash');
var taskcluster = require('taskcluster-client');

var Client = base.Entity.configure({
  version:          1,
  partitionKey:     base.Entity.keys.StringKey('clientId'),
  rowKey:           base.Entity.keys.ConstantKey('client'),
  signEntities:     true,
  properties: {
    clientId:       base.Entity.types.String,
    description:    base.Entity.types.Text,
    accessToken:    base.Entity.types.EncryptedText,
    expires:        base.Entity.types.Date,
    /**
     * Details object with properties:
     * - created          // Time when client was created
     * - lastModified     // Last time client was modified
     * - lastDateUsed     // Only updated if more than 6 hours out of date
     * - lastRotated      // Last time accessToken was reset
     * (more properties may be added in the future)
     */
    details:        base.Entity.types.JSON
  },
  context:          ['resolver']
});

/** Get scopes granted to this client */
Client.prototype.expandedScopes = function() {
  return this.resolver.resolve(['assume:client-id:' + this.clientId]);
};

/** Get JSON representation of client */
Client.prototype.json = function() {
  return {
    clientId:       this.clientId,
    description:    this.description,
    expires:        this.expires.toJSON(),
    created:        this.details.created,
    lastModified:   this.details.lastModified,
    lastDateUsed:   this.details.lastDateUsed,
    lastRotated:    this.details.lastRotated,
    expandedScopes: this.expandedScopes()
  };
};

/**
 * Ensure root client exists and has the given accessToken.
 *
 * Should only be called if the app is configured with a rootAccessToken.
 * Otherwise, app should assume whatever is in the table storage is the
 * root access token, and that appropriate role is attached.
 */
Client.ensureRootClient = function(accessToken) {
  assert(typeof(accessToken) === 'string',
         "Expected accessToken to be a string");
  let Client = this;
  // Create client resolving conflicts by overwriting
  return Client.create({
    clientId:         'root',
    description:      "Automatically created `root` client " +
                      "for bootstrapping API access",
    accessToken:      accessToken,
    expires:          taskcluster.fromNow('24 hours'),
    details: {
      created:        new Date().toJSON(),
      lastModified:   new Date().toJSON(),
      lastDateUsed:   new Date().toJSON(),
      lastRotated:    new Date().toJSON()
    }
  }, true);
};

// Export Client
exports.Client = Client;

var Role = base.Entity.configure({
  version:          1,
  partitionKey:     base.Entity.keys.StringKey('roleId'),
  rowKey:           base.Entity.keys.ConstantKey('role'),
  signEntities:     true,
  properties: {
    roleId:         base.Entity.types.String,
    description:    base.Entity.types.Text,
    scopes:         base.Entity.types.JSON,
    /**
     * Details object with properties:
     * - created
     * - lastModified
     * (more properties may be added in the future)
     */
    details:        base.Entity.types.JSON,
  },
  context:          ['resolver']
});

/** Get JSON representation of a role */
Role.prototype.json = function() {
  return {
    roleId:         this.roleId,
    description:    this.description,
    created:        this.details.created,
    lastModified:   this.details.lastModified,
    scopes:         this.scopes,
    expandedScopes: this.resolver.resolve(['assume:' + this.roleId])
  };
};

/**
 * Ensure the role: client-id:root -> ['*'] exists
 *
 * Should only be called if the app is configured with a rootAccessToken.
 * Otherwise, app should assume whatever is in the table storage is the
 * root access token, and that appropriate role is attached.
 *
 * Basically, this is for bootstrapping only.
 */
Role.ensureRootRole = function() {
  let Role = this;
  return Role.create({
    roleId:       'client-id:root',
    description:  "Automatically created role for bootstrapping the `root` "+
                  "client.",
    scopes:       ['*'],
    details: {
      created:        new Date().toJSON(),
      lastModified:   new Date().toJSON()
    }
  }, true);
};

// Export Role
exports.Role = Role;

<|endoftext|>


<commit_before>"use strict"

define('textanalysis.ui', ['autocomplete', 'rhizicore', 'textanalysis', 'signal', 'consts'],
       function(autocomplete, RZ, textanalysis, signal, consts) {
var text = ""; // Last text of sentence
var element_name = '#textanalyser';
var element = $(element_name);
var suggestionChange;

function analyzeSentence(sentence, finalize)
{
    var ret = textanalysis.textAnalyser(sentence, finalize);

    switch (ret.state) {
    case textanalysis.ANALYSIS_NODE_START:
        $('.typeselection').css({top:window.innerHeight/2-115,left:window.innerWidth/2-325});
        $('.typeselection').html('

Use [TAB] key to pick a type

');
        break;
    case textanalysis.ANALYSIS_LINK:
        $('.typeselection').css('top', -300);
        $('.typeselection').css('left', 0);
        break;
    }

    var backend_commit = finalize;
    ret.applyToGraph(RZ.graph, finalize, backend_commit);

    if (finalize || sentence.length == 0) {
        $('.typeselection').css('top', -300);
        $('.typeselection').css('left', 0);
    }
}

function textSelect(inp, s, e) {
    e = e || s;
    if (inp.createTextRange) {
        var r = inp.createTextRange();
        r.collapse(true);
        r.moveEnd('character', e);
        r.moveStart('character', s);
        r.select();
    }else if(inp.setSelectionRange) {
        inp.focus();
        inp.setSelectionRange(s, e);
    }
}

function changeType(arg, id) {
    var typeindex;
    var lastnode = textanalysis.lastnode();
    var nodetype;

    if(!id) {
        id = "new node";
    }
    typeindex = (arg === 'up'? textanalysis.typeindex_next() : textanalysis.typeindex_prev());
    nodetype = textanalysis.nodetypes()[typeindex];

    if (arg === 'up') {
        RZ.graph.editType(id, null, nodetype);
        $('.typeselection').html('

' + "Chosen Type: " + nodetype + '

');
        RZ.graph.findCoordinates(lastnode, null);
    } else {
        RZ.graph.editType(id, null, nodetype);
        $('.typeselection').html('

' + "Chosen Type: " + nodetype + '

');
        RZ.graph.findCoordinates(lastnode, null);
    }
    RZ.graph.update(true);
}

return {
    analyzeSentence: analyzeSentence,
    main:function () {
        if (element.length != 1) {
            return;
        }

        element.autocompleteTrigger({
            triggerStart: '#',
            triggerEnd: '',
            source: textanalysis.autocompleteCallback,
            open: function() {
                $('.ui-autocomplete').css('width', '10px');
            }
        });

        $(document).keydown(function(e) {
            signal.signal(consts.KEYSTROKES, [{where: consts.KEYSTROKE_WHERE_DOCUMENT, keys: [e.keyCode]}]);
            if (e.keyCode == 9) {//TAB
                e.preventDefault();
                changeType(e.shiftKey ? "up" : "down", textanalysis.lastnode());
                return false;
            }

            if (e.keyCode == 37) {//UP
                  $('html, body').scrollLeft(0);
            }
            if (e.keyCode == 39) {//DOWN
                  $('html, body').scrollLeft(0);
            }

            if (e.keyCode == 38) {//UP
                suggestionChange = true;
            }
            if (e.keyCode == 40) {//DOWN
                suggestionChange = true;
            }

            if (e.keyCode == 9) {//TAB
                return false;
            }
        });

        element.keypress(function(e) {
            signal.signal(consts.KEYSTROKES, [{where: consts.KEYSTROKE_WHERE_TEXTANALYSIS, keys:[e.which]}]);
            if (e.which == 13) {
                if(!suggestionChange) {
                    text = element.val();
                    element.val("");
                    analyzeSentence(text, true);
                } else {
                    suggestionChange = false;
                }
                return false;
            }

            if (e.which == 37) {//RIGHT
                $('body').scrollLeft(0);
                e.stopPropagation();
                return false;
            }
            if (e.which == 39) { //LEFT
                $('body').scrollLeft(0);
                e.stopPropagation();
                return false;
            }
        });

        if ('oninput' in document.documentElement) {
            element.on('input', function(e) {
                text = element.val();
                analyzeSentence(text, false);
            });
        } else {
            console.log('textanalysis.ui: fallback to polling');
            window.setInterval(function() {
                if (element.val() != text) {
                    if (text.length * 8 > 500) {
                        element.css('width', text.length * 8 + 20);
                    }
                    // text changed
                    text = element.val();
                    analyzeSentence(text, false);
                    suggestionChange = false;
                }
            }, 50);
        }
    }
};
}); // define
<commit_msg>default not to commit changes to backend<commit_after>"use strict"

define('textanalysis.ui', ['autocomplete', 'rhizicore', 'textanalysis', 'signal', 'consts'],
       function(autocomplete, RZ, textanalysis, signal, consts) {
var text = ""; // Last text of sentence
var element_name = '#textanalyser';
var element = $(element_name);
var suggestionChange;

function analyzeSentence(sentence, finalize)
{
    var ret = textanalysis.textAnalyser(sentence, finalize);

    switch (ret.state) {
    case textanalysis.ANALYSIS_NODE_START:
        $('.typeselection').css({top:window.innerHeight/2-115,left:window.innerWidth/2-325});
        $('.typeselection').html('

Use [TAB] key to pick a type

');
        break;
    case textanalysis.ANALYSIS_LINK:
        $('.typeselection').css('top', -300);
        $('.typeselection').css('left', 0);
        break;
    }

    var backend_commit = false;
    ret.applyToGraph(RZ.graph, backend_commit);

    if (finalize || sentence.length == 0) {
        $('.typeselection').css('top', -300);
        $('.typeselection').css('left', 0);
    }
}

function textSelect(inp, s, e) {
    e = e || s;
    if (inp.createTextRange) {
        var r = inp.createTextRange();
        r.collapse(true);
        r.moveEnd('character', e);
        r.moveStart('character', s);
        r.select();
    }else if(inp.setSelectionRange) {
        inp.focus();
        inp.setSelectionRange(s, e);
    }
}

function changeType(arg, id) {
    var typeindex;
    var lastnode = textanalysis.lastnode();
    var nodetype;

    if(!id) {
        id = "new node";
    }
    typeindex = (arg === 'up'? textanalysis.typeindex_next() : textanalysis.typeindex_prev());
    nodetype = textanalysis.nodetypes()[typeindex];

    if (arg === 'up') {
        RZ.graph.editType(id, null, nodetype);
        $('.typeselection').html('

' + "Chosen Type: " + nodetype + '

');
        RZ.graph.findCoordinates(lastnode, null);
    } else {
        RZ.graph.editType(id, null, nodetype);
        $('.typeselection').html('

' + "Chosen Type: " + nodetype + '

');
        RZ.graph.findCoordinates(lastnode, null);
    }
    RZ.graph.update(true);
}

return {
    analyzeSentence: analyzeSentence,
    main:function () {
        if (element.length != 1) {
            return;
        }

        element.autocompleteTrigger({
            triggerStart: '#',
            triggerEnd: '',
            source: textanalysis.autocompleteCallback,
            open: function() {
                $('.ui-autocomplete').css('width', '10px');
            }
        });

        $(document).keydown(function(e) {
            signal.signal(consts.KEYSTROKES, [{where: consts.KEYSTROKE_WHERE_DOCUMENT, keys: [e.keyCode]}]);
            if (e.keyCode == 9) {//TAB
                e.preventDefault();
                changeType(e.shiftKey ? "up" : "down", textanalysis.lastnode());
                return false;
            }

            if (e.keyCode == 37) {//UP
                  $('html, body').scrollLeft(0);
            }
            if (e.keyCode == 39) {//DOWN
                  $('html, body').scrollLeft(0);
            }

            if (e.keyCode == 38) {//UP
                suggestionChange = true;
            }
            if (e.keyCode == 40) {//DOWN
                suggestionChange = true;
            }

            if (e.keyCode == 9) {//TAB
                return false;
            }
        });

        element.keypress(function(e) {
            signal.signal(consts.KEYSTROKES, [{where: consts.KEYSTROKE_WHERE_TEXTANALYSIS, keys:[e.which]}]);
            if (e.which == 13) {
                if(!suggestionChange) {
                    text = element.val();
                    element.val("");
                    analyzeSentence(text, true);
                } else {
                    suggestionChange = false;
                }
                return false;
            }

            if (e.which == 37) {//RIGHT
                $('body').scrollLeft(0);
                e.stopPropagation();
                return false;
            }
            if (e.which == 39) { //LEFT
                $('body').scrollLeft(0);
                e.stopPropagation();
                return false;
            }
        });

        if ('oninput' in document.documentElement) {
            element.on('input', function(e) {
                text = element.val();
                analyzeSentence(text, false);
            });
        } else {
            console.log('textanalysis.ui: fallback to polling');
            window.setInterval(function() {
                if (element.val() != text) {
                    if (text.length * 8 > 500) {
                        element.css('width', text.length * 8 + 20);
                    }
                    // text changed
                    text = element.val();
                    analyzeSentence(text, false);
                    suggestionChange = false;
                }
            }, 50);
        }
    }
};
}); // define
<|endoftext|>