<commit_before>'use strict';

angular.module('kkApp')
.controller('AccountsCtrl',
  ['$scope', 'accounts', 'User',
  function ($scope, accounts, User) {
    $scope.accounts = accounts;
    $scope.gridOptions =
    {
      data: 'accounts',
      enableCellSelection: true,
      enableRowSelection: false,
      columnDefs: [ { field: 'username',
                      displayName: 'Username',
                      enableCellEdit: true
                    },
                    { field:'email',
                      displayName:'E-Mail',
                      enableCellEdit: true
                    } ]
    };

    $scope.$watch('accounts', function(newValue, oldValue)
    {
      // Added an account or deleted one should not trigger an update
      // Performance wise this is not ideal, but works so far
      for (var i = newValue.length - 1; i >= 0; i--)
      {
        if(i<oldValue.length)
        {
          if(!angular.equals(oldValue[i],newValue[i]) && oldValue[i].id == newValue[i].id)
          {
            // Update account
            var user = new User($scope.accounts[i]);
            user.$update(function(user) {
            }, function() {
            });
          }
        }
      }
    }, true);

    $scope.addNewUser = function ()
    {
      var user = new User({ username: "user" + $scope.accounts.length,
        email : "user" + $scope.accounts.length + "@localhost",
        passwd_hash : "password",
        admin : false});

      user.$save( function(user) {
        $scope.accounts.unshift(user);
      });
    };
  }]);<commit_msg>Added password row for table<commit_after>'use strict';

angular.module('kkApp')
.controller('AccountsCtrl',
  ['$scope', 'accounts', 'User',
  function ($scope, accounts, User) {
    var passwordCell = '
' +
      '******
';

    var editCell = '<input type="text" ng-cell-input ng-class="\'colt\' + $index" ng-input="COL_FIELD" ng-model="COL_FIELD"></input>';
    var passwordEditCell = '<input type="password" ng-cell-input ng-class="\'colt\' + $index" ng-input="COL_FIELD" ng-model="COL_FIELD"></input>';

    $scope.accounts = accounts;
    $scope.gridOptions =
    {
      data: 'accounts',
      enableCellSelection: true,
      enableRowSelection: false,
      rowHeight:50,
      columnDefs: [ { field: 'username',
                      displayName: 'Username',
                      enableCellEdit: true,
                      editableCellTemplate: editCell,
                    },
                    { field:'email',
                      displayName:'E-Mail',
                      enableCellEdit: true,
                      editableCellTemplate: editCell,
                    },
                    { field:'passwd_hash',
                      displayName:'Password',
                      cellTemplate: passwordCell,
                      editableCellTemplate: passwordEditCell,
                      enableCellEdit: true
                    } ]
    };

    $scope.$watch('accounts', function(newValue, oldValue)
    {
      // Added an account or deleted one should not trigger an update
      // Performance wise this is not ideal, but works so far
      for (var i = newValue.length - 1; i >= 0; i--)
      {
        if(i<oldValue.length)
        {
          if(!angular.equals(oldValue[i],newValue[i]) && oldValue[i].id == newValue[i].id)
          {
            // Update account
            console.log("Updating " + i);
            var user = new User($scope.accounts[i]);
            user.$update(function(user) {
            }, function() {
            });
          }
        }
      }
    }, true);

    $scope.addNewUser = function ()
    {
      var user = new User({ username: "user" + $scope.accounts.length,
        email : "user" + $scope.accounts.length + "@localhost",
        passwd_hash : "password",
        admin : false});

      user.$save( function(user) {
        $scope.accounts.unshift(user);
      });
    };
  }]);<|endoftext|>


<commit_before>var BH1750 = require('../bh1750');
var light = new BH1750();

light.readLight(function(value){
    console.log("light value is: ", value, "lx");
});

<commit_msg>Update index.js<commit_after>var HDC1008 = require('../hdc1008');
var temp = new HDC1008();

temp.readTemperature(function(value){
    console.log("temperature value is: ", value, "°C");
});

<|endoftext|>


<commit_before>
module.exports = function(RED) {
	function averageValues(that, values, keys) {
		console.log("AVV: ", that.topicSuffix, values[0], keys, that.avgCount)
		if(that.avgCount == that.max-1) {
			that.avgCount=0;
			ret = that.lastMsg;
			//Are we storing objects or simple values?
			if(keys) {
				for(k in keys) {
					for(var v=0; v<values.length; v++) {
						//console.log("AV: ", keys[k], that.averages[keys[k]], values[v])
						that.averages[keys[k]] += values[v][keys[k]];
					}
					//console.log("Averaging ", that.averages, keys[k]);
					ret.payload[keys[k]] = (that.averages[keys[k]] / values.length).toFixed(2);
					that.averages[keys[k]] = 0;
				}
				//console.log("SENDING: ", ret)
				that.send([null, ret])
			} else {
				var sum  = values.reduce(function(a, b) {
					return a + b.value}, 0);
				var average  = (sum /  values.length).toFixed(2);
				console.log("SENDING: ", average)
				that.send([null, {payload: average, topic: that.lastMsg.topic}])
			}
		} else {
			that.avgCount++;
		}
	}
    function Journal(config) {
	var Fifo = require('fifo-array');
	var storage = require('node-persist');
        RED.nodes.createNode(this,config);
		this.max = config.max;
		this.name = config.name;
		this.storeName = config.storeName;
		this.persist = config.persist;
		this.persistInterval  = config.persistInterval;
		this.clocked = config.clocked;
		console.log("Clocked: ", this.clocked)
		this.clockInterval = config.clockInterval;
		this.keysToAverage = config.keysToAverage ? config.keysToAverage.split(",") : null;
		this.topicSuffix = config.topicSuffix;
		this.lastMsg = {payload: null};
		this.avgCount = 0;
		if(this.keysToAverage) {
			this.averages = {}
			for(k in this.keysToAverage) {
				this.averages[this.keysToAverage[k]] = 0;
			}
		} else {
			this.averages = 0;
		}
		console.log("AVERAGES: ", this.averages)
        var node = this;
		storage.initSync({
			interval: 1000 * this.persistInterval
		});
		//Set up the clocked journalling if applicable
		if(this.clocked) {
			function journalClock(){
				console.log("Clock!!!: ", new Date())
				if(this.lastMsg) {
					fifo.push(this.lastMsg.payload);
				}
				node.send([{payload: fifo, topic: this.lastMsg.topic + this.topicSuffix}, null]);
				storage.setItem(this.storeName, fifo);
				that = this;
				averageValues(that, fifo, this.keysToAverage);
			}
			setInterval(journalClock.bind(this), this.clockInterval * 1000);
		}
		// Initialise the fifo with values from the persisted one.
        var fifo  = new Fifo(parseInt(node.max));
		//fifo.journalName = this.name;
		var oldFifo = storage.getItem(this.storeName);
		if(oldFifo) {
			oldFifo.map(function(obj){
				fifo.push(obj);
			})
		}
		var cnt = 0;
        this.on('input', function(msg) {
			this.lastMsg = msg;
			// If clocked, just store the last value.
			if(!this.clocked) {
				// Push the value on to the fifo
	            fifo.push(msg.payload);
				//output the fifo as a message.
				node.send([{payload: fifo, topic: msg.topic + this.topicSuffix}, null]);
				storage.setItem(this.storeName, fifo);
				averageValues(this, fifo, this.keysToAverage);
			}

        });
    }
    RED.nodes.registerType("journal",Journal);
}
<commit_msg>FIX: Cancel timer on node closure<commit_after>
module.exports = function(RED) {
	function averageValues(that, values, keys) {
		console.log("AVV: ", that.topicSuffix, values[0], keys, that.avgCount)
		if(that.avgCount == that.max-1) {
			that.avgCount=0;
			ret = that.lastMsg;
			//Are we storing objects or simple values?
			if(keys) {
				for(k in keys) {
					for(var v=0; v<values.length; v++) {
						//console.log("AV: ", keys[k], that.averages[keys[k]], values[v])
						that.averages[keys[k]] += values[v][keys[k]];
					}
					//console.log("Averaging ", that.averages, keys[k]);
					ret.payload[keys[k]] = (that.averages[keys[k]] / values.length).toFixed(2);
					that.averages[keys[k]] = 0;
				}
				//console.log("SENDING: ", ret)
				that.send([null, ret])
			} else {
				var sum  = values.reduce(function(a, b) {
					return a + b.value}, 0);
				var average  = (sum /  values.length).toFixed(2);
				console.log("SENDING: ", average)
				that.send([null, {payload: average, topic: that.lastMsg.topic}])
			}
		} else {
			that.avgCount++;
		}
	}
    function Journal(config) {
	var Fifo = require('fifo-array');
	var storage = require('node-persist');
        RED.nodes.createNode(this,config);
		this.max = config.max;
		this.name = config.name;
		this.storeName = config.storeName;
		this.persist = config.persist;
		this.persistInterval  = config.persistInterval;
		this.clocked = config.clocked;
		console.log("Clocked: ", this.clocked)
		this.clockInterval = config.clockInterval;
		this.keysToAverage = config.keysToAverage ? config.keysToAverage.split(",") : null;
		this.topicSuffix = config.topicSuffix;
		this.lastMsg = {payload: null};
		this.avgCount = 0;
		if(this.keysToAverage) {
			this.averages = {}
			for(k in this.keysToAverage) {
				this.averages[this.keysToAverage[k]] = 0;
			}
		} else {
			this.averages = 0;
		}
		console.log("AVERAGES: ", this.averages)
        var node = this;
		storage.initSync({
			interval: 1000 * this.persistInterval
		});
		//Set up the clocked journalling if applicable
		if(this.clocked) {
			function journalClock(){
				console.log("Clock!!!: ", new Date())
				if(this.lastMsg) {
					fifo.push(this.lastMsg.payload);
					node.send([{payload: fifo, topic: this.lastMsg.topic + this.topicSuffix}, null]);
					storage.setItem(this.storeName, fifo);
					that = this;
					averageValues(that, fifo, this.keysToAverage);
				}
			}
			this.clock = setInterval(journalClock.bind(this), this.clockInterval * 1000);
		}
		// Initialise the fifo with values from the persisted one.
        var fifo  = new Fifo(parseInt(node.max));
		//fifo.journalName = this.name;
		var oldFifo = storage.getItem(this.storeName);
		if(oldFifo) {
			oldFifo.map(function(obj){
				fifo.push(obj);
			})
		}
		var cnt = 0;
		this.on('close', function(){
			node.warn("Shutting down journal: ", this.name);
			clearInterval(this.clock);
		});
        this.on('input', function(msg) {
			this.lastMsg = msg;
			// If clocked, just store the last value.
			if(!this.clocked) {
				// Push the value on to the fifo
	            fifo.push(msg.payload);
				//output the fifo as a message.
				node.send([{payload: fifo, topic: msg.topic + this.topicSuffix}, null]);
				storage.setItem(this.storeName, fifo);
				averageValues(this, fifo, this.keysToAverage);
			}

        });
    }
    RED.nodes.registerType("journal",Journal);
}
<|endoftext|>


<commit_before>angular.module('MKSTream', [
  'ui.router',
  'clientRoutes',
  'home',
  'connecting',
  'utils'
])
.run([function(){

}]);<commit_msg>[fix] removed .run preventing our controllers to load in app_modules.js<commit_after>angular.module('MKSTream', [
  'ui.router',
  'clientRoutes',
  'home',
  'connecting',
  'utils'
])
// .run([function(){

// }]);<|endoftext|>


<commit_before>export { pointwise1 };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import { HigherHalfPassThrough } from "./HigherHalfPassThrough.js";

/**
 * Calculate the channel count of lower half (of input and output) and higher half (of input and output) for pointwise1 of
 * ShuffleNetV2_ByMopbileNetV1's head/body/tail.
 *
 * @member {number} nConvBlockTypeId
 *   The convolution type id of the block (i.e. ValueDesc.ConvBlockType.Singleton.Ids.Xxx).
 *
 * @member {number} inputChannelCount
 *   The total input channel count of pointwise1.
 *
 * @member {number} outputChannelCount
 *   The total output channel count of pointwise1.
 *
 * @member {number} inputChannelCount_lowerHalf
 *   The lower half of the input channel count.
 *
 * @member {number} inputChannelCount_higherHalf
 *   The higher half of the input channel count.
 *
 * @member {number} outputChannelCount_lowerHalf
 *   The lower half of the output channel count.
 *
 * @member {number} outputChannelCount_higherHalf
 *   The higher half of the output channel count.
 *
 * @member {ValueDesc.Pointwise_HigherHalfDifferent} nHigherHalfDifferent
 *   It will be one of the following:
 *   - ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE (0)
 *   - ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH (1)
 *   - ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF (2)
 *
 */
class pointwise1 extends Recyclable.Root {

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

  /**
   *
   */
  constructor( nConvBlockTypeId, inputChannelCount, outputChannelCount ) {
    super();
    pointwise1.setAsConstructor_self.call( this, nConvBlockTypeId, inputChannelCount, outputChannelCount );
  }

  /** @override */
  static setAsConstructor( nConvBlockTypeId, inputChannelCount, outputChannelCount ) {
    super.setAsConstructor();
    pointwise1.setAsConstructor_self.call( this, nConvBlockTypeId, inputChannelCount, outputChannelCount );
    return this;
  }

  /** @override */
  static setAsConstructor_self( nConvBlockTypeId, inputChannelCount, outputChannelCount ) {
    this.nConvBlockTypeId = nConvBlockTypeId;
    this.inputChannelCount = inputChannelCount;
    this.outputChannelCount = outputChannelCount;

    let infoConvBlockType = ValueDesc.ConvBlockType.Singleton.getInfoById( nConvBlockTypeId );

    this.nHigherHalfDifferent = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE;
    this.inputChannelCount_lowerHalf = undefined;
    this.inputChannelCount_higherHalf = undefined;
    this.outputChannelCount_lowerHalf = undefined;

//!!! ...unfinished... (2021/11/15) What if ( depthwise_AvgMax_Or_ChannelMultiplier > 1 )?

    if ( infoConvBlockType.bHigherHalfDifferent == true ) {

      // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD (5) )
      // (i.e. pointwise1 of ShuffleNetV2_ByMobileNetV1's head)
      if ( infoConvBlockType.bHigherHalfDepthwise2 == true ) {

        this.pointwise1_inputChannelCount_lowerHalf = input0_channelCount;

        if ( pointwise1ChannelCount > 0 ) {
          this.pointwise1_nHigherHalfDifferent = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF;
          this.pointwise1_outputChannelCount_lowerHalf = pointwise1ChannelCount; // For depthwise1 (by specified channel count)

//!!! (2022/07/13 Remarked) Does not work.
//             // Enlarge pointwise1 to ( pointwise1_channel_count + input_channel_count ) so that depthwise1 could include depthwise2.
//             this.pointwise1ChannelCount_modified = (
//                 this.pointwise1_outputChannelCount_lowerHalf // For depthwise1.
//               + input0_channelCount                          // For depthwise2 (by depthwise1).
//             );

        } else {

//!!! (2022/07/13 Remarked) Does not work.
//             // When
//             //   - ShuffleNetV2_byMobileNetV1_head and
//             //   - ( pointwise1ChannelCount == 0 )
//             //       i.e. ( pointwise1_nHigherHalfDifferent
//             //                == ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH )
//             //   - ( depthwise1_nHigherHalfDifferent == ValueDesc.Depthwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_DEPTHWISE2 ) and
//             //   - depthwise exists and ( channelMultiplier == 1 )
//             //
//             if (   ( bDepthwiseRequestedAndNeeded )
//                 && ( depthwise_AvgMax_Or_ChannelMultiplier == 1 ) ) {
//
//               // Use depthwise ( channelMultiplier == 2 ) could achieve almost the same effect but depthwise will look like
//               // pre-channel-shuffled. So, in this case, pointwise1 (higher half copy lower, lower half pass through) could be
//               // discarded. But the ( channelShuffler_inputGroupCount == 2 ) should be used for prefix squeeze-and-excitation
//               // and pointwise2. So that they could undo the depthwise's pre-channel-shuffling.
//               //
//               this.depthwise1_nHigherHalfDifferent
//                 = ValueDesc.Depthwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF_DEPTHWISE2;
//
//               this.depthwise_AvgMax_Or_ChannelMultiplier_modified = 2;
//               this.depthwise1_inputChannelCount_lowerHalf = input0_channelCount;
//               this.depthwise1_channelShuffler_outputGroupCount = pointwise20_channelShuffler_outputGroupCount; // (i.e. Whether Shuffle.)
//
//             } else {

          this.pointwise1_nHigherHalfDifferent
            = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH;

          // Since this is an almost copy operation, bias and activation is not necessary.
          this.pointwise1Bias = false;
          this.pointwise1ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;
          this.pointwise1ActivationName = ValueDesc.ActivationFunction.Singleton.getStringOf( this.pointwise1ActivationId );

          this.pointwise1_outputChannelCount_lowerHalf = input0_channelCount; // For depthwise1 (by pass-through-input-to-output)

//!!! (2022/07/13 Remarked) Does not work.
//               // Enlarge pointwise1 to ( pointwise1_channel_count + input_channel_count ) so that depthwise1 could include depthwise2.
//               this.pointwise1ChannelCount_modified = (
//                   this.pointwise1_outputChannelCount_lowerHalf // For depthwise1.
//                 + input0_channelCount                          // For depthwise2 (by depthwise1).
//               );
//             }
        }

        // Enlarge pointwise1 to ( pointwise1_channel_count + input_channel_count ) so that depthwise1 could include depthwise2.
        this.pointwise1ChannelCount_modified = (
            this.pointwise1_outputChannelCount_lowerHalf // For depthwise1.
          + input0_channelCount                          // For depthwise2 (by depthwise1).
        );

      // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_BODY (6) )
      // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_TAIL (7) )
      // (i.e. pointwise1 of ShuffleNetV2_ByMobileNetV1's body/tail)
      } else {

        // So that bHigherHalfPassThrough (or bAllPassThrough).
        this.pointwise1_nHigherHalfDifferent = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH;

        let pointwise1_higherHalfPassThrough = ChannelCountCalculator.HigherHalfPassThrough.Pool.get_or_create_by(
          this.input0_channelCount, this.pointwise1ChannelCount );

        this.pointwise1_inputChannelCount_lowerHalf = pointwise1_higherHalfPassThrough.inputChannelCount_lowerHalf;
        this.pointwise1_outputChannelCount_lowerHalf = pointwise1_higherHalfPassThrough.outputChannelCount_lowerHalf;

        pointwise1_higherHalfPassThrough.disposeResources_and_recycleToPool();
        pointwise1_higherHalfPassThrough = null;
      }

    // In other cases, Pointwise.Base could handle ( pointwise1ChannelCount == 0 ) correctly.
    }

    if ( this.pointwise1_inputChannelCount_lowerHalf > 0 ) {
      this.pointwise1_inputChannelCount_higherHalf = input0_channelCount - this.pointwise1_inputChannelCount_lowerHalf;
    }

    this.outputChannelCount_higherHalf = ???;
  }

  /** @override */
  disposeResources() {
    this.nConvBlockTypeId = undefined;
    this.inputChannelCount = undefined;
    this.outputChannelCount = undefined;

    this.nHigherHalfDifferent = undefined;
    this.inputChannelCount_lowerHalf = undefined;
    this.inputChannelCount_higherHalf = undefined;
    this.outputChannelCount_lowerHalf = undefined;
    this.outputChannelCount_higherHalf = undefined;

    super.disposeResources();
  }

}

<commit_msg>Update pointwise1.js<commit_after>export { pointwise1 };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import { HigherHalfPassThrough } from "./HigherHalfPassThrough.js";

/**
 * Calculate the channel count of lower half (of input and output) and higher half (of input and output) for pointwise1 of
 * ShuffleNetV2_ByMopbileNetV1's head/body/tail.
 *
 * @member {number} nConvBlockTypeId
 *   The convolution type id of the block (i.e. ValueDesc.ConvBlockType.Singleton.Ids.Xxx).
 *
 * @member {number} inputChannelCount
 *   The total input channel count of pointwise1.
 *
 * @member {number} outputChannelCount
 *   The total output channel count of pointwise1.
 *
 * @member {number} inputChannelCount_lowerHalf
 *   The lower half of the input channel count.
 *
 * @member {number} inputChannelCount_higherHalf
 *   The higher half of the input channel count.
 *
 * @member {number} outputChannelCount_lowerHalf
 *   The lower half of the output channel count.
 *
 * @member {number} outputChannelCount_higherHalf
 *   The higher half of the output channel count.
 *
 * @member {ValueDesc.Pointwise_HigherHalfDifferent} nHigherHalfDifferent
 *   It will be one of the following:
 *   - ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE (0)
 *   - ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH (1)
 *   - ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF (2)
 *
 */
class pointwise1 extends Recyclable.Root {

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

  /**
   *
   */
  constructor( nConvBlockTypeId, inputChannelCount, outputChannelCount ) {
    super();
    pointwise1.setAsConstructor_self.call( this, nConvBlockTypeId, inputChannelCount, outputChannelCount );
  }

  /** @override */
  static setAsConstructor( nConvBlockTypeId, inputChannelCount, outputChannelCount ) {
    super.setAsConstructor();
    pointwise1.setAsConstructor_self.call( this, nConvBlockTypeId, inputChannelCount, outputChannelCount );
    return this;
  }

  /** @override */
  static setAsConstructor_self( nConvBlockTypeId, inputChannelCount, outputChannelCount ) {
    this.nConvBlockTypeId = nConvBlockTypeId;
    this.inputChannelCount = inputChannelCount;
    this.outputChannelCount = outputChannelCount;

    let infoConvBlockType = ValueDesc.ConvBlockType.Singleton.getInfoById( nConvBlockTypeId );

    this.nHigherHalfDifferent = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.NONE;
    this.inputChannelCount_lowerHalf = undefined;
    this.inputChannelCount_higherHalf = undefined;
    this.outputChannelCount_lowerHalf = undefined;
    this.outputChannelCount_higherHalf = undefined;

//!!! ...unfinished... (2021/11/15) What if ( depthwise_AvgMax_Or_ChannelMultiplier > 1 )?

    if ( infoConvBlockType.bHigherHalfDifferent == true ) {

      // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_HEAD (5) )
      // (i.e. pointwise1 of ShuffleNetV2_ByMobileNetV1's head)
      if ( infoConvBlockType.bHigherHalfDepthwise2 == true ) {

        this.inputChannelCount_lowerHalf = inputChannelCount;

        if ( outputChannelCount > 0 ) {
          this.nHigherHalfDifferent = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF;
          this.outputChannelCount_lowerHalf = outputChannelCount;

        } else {

          this.nHigherHalfDifferent
            = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH;
!!!
          // Since this is an almost copy operation, bias and activation is not necessary.
          this.pointwise1Bias = false;
          this.pointwise1ActivationId = ValueDesc.ActivationFunction.Singleton.Ids.NONE;
          this.pointwise1ActivationName = ValueDesc.ActivationFunction.Singleton.getStringOf( this.pointwise1ActivationId );

          this.pointwise1_outputChannelCount_lowerHalf = input0_channelCount; // For depthwise1 (by pass-through-input-to-output)
        }

        // Enlarge pointwise1 to ( pointwise1_channel_count + input_channel_count ) so that depthwise1 could include depthwise2.
        this.pointwise1ChannelCount_modified = (
            this.pointwise1_outputChannelCount_lowerHalf // For depthwise1.
          + input0_channelCount                          // For depthwise2 (by depthwise1).
        );

      // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_BODY (6) )
      // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_TAIL (7) )
      // (i.e. pointwise1 of ShuffleNetV2_ByMobileNetV1's body/tail)
      } else {

        // So that bHigherHalfPassThrough (or bAllPassThrough).
        this.pointwise1_nHigherHalfDifferent = ValueDesc.Pointwise_HigherHalfDifferent.Singleton.Ids.HIGHER_HALF_PASS_THROUGH;

        let pointwise1_higherHalfPassThrough = ChannelCountCalculator.HigherHalfPassThrough.Pool.get_or_create_by(
          this.input0_channelCount, this.pointwise1ChannelCount );

        this.pointwise1_inputChannelCount_lowerHalf = pointwise1_higherHalfPassThrough.inputChannelCount_lowerHalf;
        this.pointwise1_outputChannelCount_lowerHalf = pointwise1_higherHalfPassThrough.outputChannelCount_lowerHalf;

        pointwise1_higherHalfPassThrough.disposeResources_and_recycleToPool();
        pointwise1_higherHalfPassThrough = null;
      }

    // In other cases, Pointwise.Base could handle ( pointwise1ChannelCount == 0 ) correctly.
    }

    if ( this.pointwise1_inputChannelCount_lowerHalf > 0 ) {
      this.pointwise1_inputChannelCount_higherHalf = input0_channelCount - this.pointwise1_inputChannelCount_lowerHalf;
    }

    this.outputChannelCount_higherHalf = ???;
  }

  /** @override */
  disposeResources() {
    this.nConvBlockTypeId = undefined;
    this.inputChannelCount = undefined;
    this.outputChannelCount = undefined;

    this.nHigherHalfDifferent = undefined;
    this.inputChannelCount_lowerHalf = undefined;
    this.inputChannelCount_higherHalf = undefined;
    this.outputChannelCount_lowerHalf = undefined;
    this.outputChannelCount_higherHalf = undefined;

    super.disposeResources();
  }

}

<|endoftext|>


<commit_before>function changeStyle(req, res) {
    console.log("session: " + req.session);
    if(!req.session.style) {
        console.log("no css set yet");
        req.session.style = "default.css";
    } else if (req.url == '/changeStyle?') {
        console.log("change css");
        switch(req.session.style) {
            case 'default.css':
                console.log("stylechange: is style defautl");
                req.session.style = 'style2.css';
                break;
            case 'style2.css':
                console.log("stylechange: is style style2");
                req.session.style = 'default.css';
                break;
            default:
                req.session.style = 'default.css';
        }
    }
    console.log("req.session.style: " + req.session.style);
    res.redirect("/");
}

function getStyle(req, res) {
    if (!req.session.style) {
        req.session.style = "default.css";
    }
    return req.session.style;
}

module.exports = {changeStyle: changeStyle, getStyle: getStyle};
<commit_msg>fix url check for styleSwitcher :smiley:<commit_after>function changeStyle(req, res) {
    console.log("session: " + req.session);
    if(!req.session.style) {
        console.log("no css set yet");
        req.session.style = "default.css";
    } else {
        console.log("change css");
        switch(req.session.style) {
            case 'default.css':
                console.log("stylechange: is style defautl");
                req.session.style = 'style2.css';
                break;
            case 'style2.css':
                console.log("stylechange: is style style2");
                req.session.style = 'default.css';
                break;
            default:
                req.session.style = 'default.css';
        }
    }
    console.log("req.session.style: " + req.session.style);
    res.redirect("/");
}

function getStyle(req, res) {
    if (!req.session.style) {
        req.session.style = "default.css";
    }
    return req.session.style;
}

module.exports = {changeStyle: changeStyle, getStyle: getStyle};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';

import AvatarEditor from 'react-avatar-editor';

import ImageEditor, { DEFAULT_SCALE, DEFAULT_POSITION } from '../index';
import EditorPlaceholder from '../EditorPlaceholder';

import getInitScale from '../utils/getInitScale';
import getInitPosition from '../utils/getInitPosition';

// from: https://css-tricks.com/snippets/html/base64-encode-of-1x1px-transparent-gif/
const TRANSPARENT_IMAGE = (
    'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
);
const BLACK_IMAGE = (
    'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='
);

it('renders without crashing', () => {
    const div = document.createElement('div');
    const element = <ImageEditor />;

    ReactDOM.render(element, div);
});

it('shows placeholder with canvas height when image not specified', () => {
    const wrapper = shallow(<ImageEditor />);

    expect(wrapper.find(AvatarEditor).exists()).toBeFalsy();
    expect(wrapper.containsMatchingElement(
        <EditorPlaceholder
            canvasHeight={ImageEditor.defaultProps.height} />
    )).toBeTruthy();
});

it('shows loading placeholder with canvas height when set as loading', () => {
    const wrapper = shallow(<ImageEditor loading />);

    expect(wrapper.find(AvatarEditor).exists()).toBeFalsy();
    expect(wrapper.containsMatchingElement(
        <EditorPlaceholder
            loading
            canvasHeight={ImageEditor.defaultProps.height} />
    )).toBeTruthy();
});

it('shows to <AvatarEditor> for cropping given image', () => {
    const wrapper = shallow(<ImageEditor image={TRANSPARENT_IMAGE} />);

    expect(wrapper.find(AvatarEditor).exists()).toBeTruthy();
    expect(wrapper.find(AvatarEditor).prop('image')).toBe(TRANSPARENT_IMAGE);
});

it('shows scale slider when control is true', () => {
    const wrapper = shallow(<ImageEditor image={TRANSPARENT_IMAGE} />);
    expect(wrapper.find('input[type="range"]').exists()).toBeFalsy();

    wrapper.setProps({ control: true });
    expect(wrapper.find('input[type="range"]').exists()).toBeTruthy();
});

it('controls scale of <AvatarEditor> with slider while not read-only', () => {
    const wrapper = shallow(<ImageEditor control image={TRANSPARENT_IMAGE} />);
    expect(wrapper.find(AvatarEditor).prop('scale')).toBe(DEFAULT_SCALE);

    wrapper.find('input[type="range"]').simulate('change', {
        target: { value: 1.5 },
    });
    expect(wrapper.find(AvatarEditor).prop('scale')).toBe(1.5);
});

it('caches and controls position of <AvatarEditor> while not read-only', () => {
    const wrapper = shallow(<ImageEditor image={TRANSPARENT_IMAGE} />);
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);

    wrapper.find(AvatarEditor).simulate('positionChange', { x: 0.5, y: 0.5 });
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual({ x: 0.5, y: 0.5 });

    wrapper.find(AvatarEditor).simulate('positionChange', { x: 0.2, y: 0.7 });
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual({ x: 0.2, y: 0.7 });
});

it('blocks changes to <AvatarEditor> while in read-only mode', () => {
    const wrapper = shallow(
        <ImageEditor
            readOnly
            control
            image={TRANSPARENT_IMAGE} />
    );
    expect(wrapper.find('input[type="range"]').prop('disabled')).toBeTruthy();
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);

    wrapper.find(AvatarEditor).simulate('positionChange', { x: 0.5, y: 0.5 });
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);
});

it('notifies new cropping rect whenever <AvatarEditor> think it changes', () => {
    const CROP_RECT_FOO = { x: 0, y: 0, width: 1, height: 1 };

    const getCroppingRect = jest.fn(() => CROP_RECT_FOO);
    const handleCropChange = jest.fn();

    const wrapper = shallow(
        <ImageEditor
            image={TRANSPARENT_IMAGE}
            onCropChange={handleCropChange} />);

    // mock <AvatarEditor> instance API
    wrapper.instance().setCanvasRef({ getCroppingRect });

    wrapper.find(AvatarEditor).simulate('imageChange');
    expect(handleCropChange).toHaveBeenLastCalledWith(CROP_RECT_FOO);

    // should not break even when `onCropChange` isn't provided
    wrapper.setProps({ onCropChange: undefined });
    expect(() => wrapper.find(AvatarEditor).simulate('imageChange')).not.toThrow();
});

it('takes an initial cropping rect to set scale and position', () => {
    const cropRect = {
        x: 0.1819,
        y: 0.0647,
        width: 0.3057,
        height: 0.5882,
    };
    const wrapper = shallow(
        <ImageEditor
            image={TRANSPARENT_IMAGE}
            initCropRect={cropRect} />
    );

    expect(wrapper.find(AvatarEditor).prop('scale'))
        .toEqual(getInitScale(cropRect));
    expect(wrapper.find(AvatarEditor).prop('position'))
        .toEqual(getInitPosition(cropRect));
});

it('resets cached scale and position when image changes', () => {
    const cropRect = {
        x: 0.1819,
        y: 0.0647,
        width: 0.3057,
        height: 0.5882,
    };
    const wrapper = shallow(
        <ImageEditor
            image={TRANSPARENT_IMAGE}
            initCropRect={cropRect} />
    );

    expect(wrapper.find(AvatarEditor).prop('scale')).not.toBe(DEFAULT_SCALE);
    expect(wrapper.find(AvatarEditor).prop('position')).not.toEqual(DEFAULT_POSITION);

    wrapper.setProps({ image: BLACK_IMAGE });
    expect(wrapper.find(AvatarEditor).prop('scale')).toBe(DEFAULT_SCALE);
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);
});
<commit_msg>Update tests for <ImageEditor> to cover read-only mode<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';

import AvatarEditor from 'react-avatar-editor';

import ImageEditor, { DEFAULT_SCALE, DEFAULT_POSITION } from '../index';
import EditorPlaceholder from '../EditorPlaceholder';

import getInitScale from '../utils/getInitScale';
import getInitPosition from '../utils/getInitPosition';

// from: https://css-tricks.com/snippets/html/base64-encode-of-1x1px-transparent-gif/
const TRANSPARENT_IMAGE = (
    'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
);
const BLACK_IMAGE = (
    'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='
);

it('renders without crashing', () => {
    const div = document.createElement('div');
    const element = <ImageEditor />;

    ReactDOM.render(element, div);
});

it('shows placeholder with canvas height when image not specified', () => {
    const wrapper = shallow(<ImageEditor />);

    expect(wrapper.find(AvatarEditor).exists()).toBeFalsy();
    expect(wrapper.containsMatchingElement(
        <EditorPlaceholder
            canvasHeight={ImageEditor.defaultProps.height} />
    )).toBeTruthy();
});

it('shows loading placeholder with canvas height when set as loading', () => {
    const wrapper = shallow(<ImageEditor loading />);

    expect(wrapper.find(AvatarEditor).exists()).toBeFalsy();
    expect(wrapper.containsMatchingElement(
        <EditorPlaceholder
            loading
            canvasHeight={ImageEditor.defaultProps.height} />
    )).toBeTruthy();
});

it('shows to <AvatarEditor> for cropping given image', () => {
    const wrapper = shallow(<ImageEditor image={TRANSPARENT_IMAGE} />);

    expect(wrapper.find(AvatarEditor).exists()).toBeTruthy();
    expect(wrapper.find(AvatarEditor).prop('image')).toBe(TRANSPARENT_IMAGE);
});

it('shows scale slider when control is true', () => {
    const wrapper = shallow(<ImageEditor image={TRANSPARENT_IMAGE} />);
    expect(wrapper.find('input[type="range"]').exists()).toBeFalsy();

    wrapper.setProps({ control: true });
    expect(wrapper.find('input[type="range"]').exists()).toBeTruthy();
});

it('controls scale of <AvatarEditor> with slider while not read-only', () => {
    const wrapper = shallow(<ImageEditor control image={TRANSPARENT_IMAGE} />);
    expect(wrapper.find(AvatarEditor).prop('scale')).toBe(DEFAULT_SCALE);

    wrapper.find('input[type="range"]').simulate('change', {
        target: { value: 1.5 },
    });
    expect(wrapper.find(AvatarEditor).prop('scale')).toBe(1.5);
});

it('caches and controls position of <AvatarEditor> while not read-only', () => {
    const wrapper = shallow(<ImageEditor image={TRANSPARENT_IMAGE} />);
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);

    wrapper.find(AvatarEditor).simulate('positionChange', { x: 0.5, y: 0.5 });
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual({ x: 0.5, y: 0.5 });

    wrapper.find(AvatarEditor).simulate('positionChange', { x: 0.2, y: 0.7 });
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual({ x: 0.2, y: 0.7 });
});

it('blocks changes to <AvatarEditor> while in read-only mode', () => {
    const wrapper = shallow(
        <ImageEditor
            readOnly
            control
            image={TRANSPARENT_IMAGE} />
    );
    expect(wrapper.find('input[type="range"]').prop('disabled')).toBeTruthy();
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);

    wrapper.find(AvatarEditor).simulate('positionChange', { x: 0.5, y: 0.5 });
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);
});

it('notifies new cropping rect whenever <AvatarEditor> think it changes', () => {
    const CROP_RECT_FOO = { x: 0, y: 0, width: 1, height: 1 };

    const getCroppingRect = jest.fn(() => CROP_RECT_FOO);
    const handleCropChange = jest.fn();

    const wrapper = shallow(
        <ImageEditor
            image={TRANSPARENT_IMAGE}
            onCropChange={handleCropChange} />);

    // mock <AvatarEditor> instance API
    wrapper.instance().setCanvasRef({ getCroppingRect });

    wrapper.find(AvatarEditor).simulate('imageChange');
    expect(handleCropChange).toHaveBeenLastCalledWith(CROP_RECT_FOO);
    expect(handleCropChange).toHaveBeenCalledTimes(1);

    // should not notify under read-only mode
    wrapper.setProps({ readOnly: true });
    wrapper.find(AvatarEditor).simulate('imageChange');
    expect(handleCropChange).toHaveBeenCalledTimes(1);

    // should not break even when `onCropChange` isn't provided
    wrapper.setProps({ readOnly: false, onCropChange: undefined });
    expect(() => wrapper.find(AvatarEditor).simulate('imageChange')).not.toThrow();
});

it('takes an initial cropping rect to set scale and position', () => {
    const cropRect = {
        x: 0.1819,
        y: 0.0647,
        width: 0.3057,
        height: 0.5882,
    };
    const wrapper = shallow(
        <ImageEditor
            image={TRANSPARENT_IMAGE}
            initCropRect={cropRect} />
    );

    expect(wrapper.find(AvatarEditor).prop('scale'))
        .toEqual(getInitScale(cropRect));
    expect(wrapper.find(AvatarEditor).prop('position'))
        .toEqual(getInitPosition(cropRect));
});

it('resets cached scale and position when image changes', () => {
    const cropRect = {
        x: 0.1819,
        y: 0.0647,
        width: 0.3057,
        height: 0.5882,
    };
    const wrapper = shallow(
        <ImageEditor
            image={TRANSPARENT_IMAGE}
            initCropRect={cropRect} />
    );

    expect(wrapper.find(AvatarEditor).prop('scale')).not.toBe(DEFAULT_SCALE);
    expect(wrapper.find(AvatarEditor).prop('position')).not.toEqual(DEFAULT_POSITION);

    wrapper.setProps({ image: BLACK_IMAGE });
    expect(wrapper.find(AvatarEditor).prop('scale')).toBe(DEFAULT_SCALE);
    expect(wrapper.find(AvatarEditor).prop('position')).toEqual(DEFAULT_POSITION);
});
<|endoftext|>


<commit_before>export { BoundsArraySet };

import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
//import * as Weights from "../../Unpacker/Weights.js";
import * as ActivationEscaping from "../ActivationEscaping.js";

/**
 * Element value bounds for every operation's result of a convolution-bias-activation. The main purpose is to find out the
 * activationEscaping_ScaleArraySet so that it can be used to let channel escape from activation function's non-linear effect.
 *
 *
 * @member {FloatValue.BoundsArray} input
 *   The (per channel) bounds of the input element value. Or say, the domain of the convolution-bias-activation.
 *
 * @member {FloatValue.BoundsArray} afterUndoPreviousActivationEscaping
 *   The (per channel) bounds of the element value after applying the previousConvBiasActivation.BoundsArraySet.ActivationEscaping.undo
 * to this.input. (i.e. beforeFilter)
 *
 * @member {FloatValue.BoundsArray} afterFilter
 *   The (per channel) bounds of the element value after applying the convolution filters to this.afterUndoPreviousActivationEscaping.
 * (i.e. beforeBias)
 *
 * @member {FloatValue.BoundsArray} afterBias
 *   The (per channel) bounds of the element value after applying the convolution biases to this.afterFilter. (i.e. beforeActivationEscaping)
 *
 * @member {FloatValue.BoundsArray} afterActivationEscaping
 *   The (per channel) bounds of the element value after applying this.activationEscaping_ScaleArraySet.do to this.afterBias. (i.e. beforeActivation)
 *
 * @member {FloatValue.BoundsArray} afterActivation
 *   The (per channel) bounds of the element value after applying activation function to this.afterActivationEscaping.
 *
 * @member {FloatValue.BoundsArray} output
 *   The (per channel) bounds of the output element value. Or say, the range of the convolution-bias-activation. It is just
 * the this.afterActivation.
 *
 * @member {ActivationEscaping.ScaleArraySet} activationEscaping_ScaleArraySet
 *   The scales for moving this.afterBias bounds into the linear domain of the activation function. That is, for
 * letting this.afterBias escape from activation function's non-linear domain. And the .undo for undoing the scales.
 *
 * @member {boolean[]} bPassThrough
 *   If true for a output channel, the output channel should be arranged to pass-through from input to output.
 */
class BoundsArraySet {

  /**
   */
  constructor( inputChannelCount, outputChannelCount ) {
    this.input = new FloatValue.BoundsArray( inputChannelCount );
    this.afterUndoPreviousActivationEscaping = new FloatValue.BoundsArray( inputChannelCount );
    this.afterFilter = new FloatValue.BoundsArray( outputChannelCount );
    this.afterBias = new FloatValue.BoundsArray( outputChannelCount );
    this.afterActivationEscaping = new FloatValue.BoundsArray( outputChannelCount );
    this.afterActivation = new FloatValue.BoundsArray( outputChannelCount ); // i.e. .output

    this.activationEscaping_ScaleArraySet = new ActivationEscaping.ScaleArraySet( outputChannelCount );
    this.bPassThrough = new Array( outputChannelCount );

    //this.set_all_byBounds.set_all_byBounds( Weights.Base.ValueBounds );
  }

  /**
   * @return {BoundsArraySet} Return a newly created BoundsArraySet which is a copy of this BoundsArraySet.
   */
  clone() {
    let result = new BoundsArraySet( this.input.lowers.length, this.output.lowers.length );
    result.set_byBoundsArraySet( this );
    return result;
  }

  /**
   * @param {FloatValue.Bounds} aBounds
   *   Set all BoundsArray to the same as the specified aBounds. Set the this.activationEscaping_ScaleArraySet to default ( 1 );
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object.
   */
  set_all_byBounds( aBounds ) {
    this.input.set_all_byBounds( aBounds );
    this.afterUndoPreviousActivationEscaping.set_all_byBounds( aBounds );
    this.afterFilter.set_all_byBounds( aBounds );
    this.afterBias.set_all_byBounds( aBounds );
    this.afterActivationEscaping.set_all_byBounds( aBounds );
    this.afterActivation.set_all_byBounds( aBounds );
    this.activationEscaping_ScaleArraySet.set_all_byN( 1 ); // scale 1 and translate 0. (i.e. no scale and no translate.)
    this.bPassThrough.fill( false ); // Assume all are not pass-through.
    return this;
  }

  /**
   * @param {BoundsArraySet} aBoundsArraySet
   *   The BoundsArraySet to be copied.
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object which is copied from aBoundsArraySet.
   */
  set_all_byBoundsArraySet( aBoundsArraySet ) {
    this.input                              .set_all_byBoundsArray( aBoundsArraySet.input );
    this.afterUndoPreviousActivationEscaping.set_all_byBoundsArray( aBoundsArraySet.afterUndoPreviousActivationEscaping );
    this.afterFilter                        .set_all_byBoundsArray( aBoundsArraySet.afterFilter );
    this.afterBias                          .set_all_byBoundsArray( aBoundsArraySet.afterBias );
    this.afterActivationEscaping            .set_all_byBoundsArray( aBoundsArraySet.afterActivationEscaping );
    this.afterActivation                    .set_all_byBoundsArray( aBoundsArraySet.afterActivation );
    this.activationEscaping_ScaleArraySet.set_byScaleArraySet( aBoundsArraySet.activationEscaping_ScaleArraySet );

    for ( let i = 0; i < this.bPassThrough.length; ++i ) {
      this.bPassThrough[ i ] = aBoundsArraySet.bPassThrough[ i ];
    }

    return this;
  }

  /**
   * Determine .activationEscaping_ScaleArraySet and .afterActivationEscaping and .afterActivation, by .afterBias and .bPassThrough and nActivationId.
   *
   * The following properties will be used:
   *   - this.afterBias
   *   - this.bPassThrough
   *
   * The following properties will be modified:
   *   - this.activationEscaping_ScaleArraySet
   *   - this.afterActivationEscaping
   *   - this.afterActivation
   *
   * @param {number} nActivationId
   *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) of this depthwise convolution.
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object.
   */
  set_activationEscaping_afterActivationEscaping_afterActivation_by_afterBias_bPassThrough_nActivationId( nActivationId ) {
    let theActivationFunctionInfo = ValueDesc.ActivationFunction.Singleton.getInfoById( nActivationId );

    for ( let outChannel = 0; outChannel < this.afterBias.lowers.length; ++outChannel ) {

      // 1. Determine .activationEscaping_ScaleArraySet
      {
        // 1.1 Determine .do

        if ( nActivationId == ValueDesc.ActivationFunction.Singleton.Ids.NONE ) {

          // Since no activation function, no need to escape. (i.e. scale = 1 for no scale)
          this.activationEscaping_ScaleArraySet.do.set_one_byN( outChannel, 1 );

        } else {

          if ( this.bPassThrough[ outChannel ] ) { // For pass-through half channels.

            // Calculate the scale for escaping bias result from activation function's non-linear domain into linear domain.
            //
            // Note: This does not work for avg/max pooling.
            this.activationEscaping_ScaleArraySet.do.set_one_by_fromLowerUpper_toLowerUpper( outChannel,
              this.afterBias.lowers[ outChannel ], this.afterBias.uppers[ outChannel ],
              theActivationFunctionInfo.inputDomainLinear.lower, theActivationFunctionInfo.inputDomainLinear.upper
            );

            let doEscapingScale = this.activationEscaping_ScaleArraySet.do.scales[ outChannel ];
            tf.util.assert( ( Number.isNaN( doEscapingScale ) == false ),
              `ConvBiasActivation.BoundsArraySet.`
                + `set_activationEscaping_afterActivationEscaping_afterActivation_by_afterBias_bPassThrough_nActivationId(): `
                + `this.activationEscaping_ScaleArraySet.do.scales[ ${outChannel} ] ( ${doEscapingScale} ) `
                + `should not be NaN. `
                + `Please use activation function (e.g. tanh()) which has both negative and positive parts near origin point.`
            );

          } else { // Non pass-through half channels.
            // Since non-pass-through, no need to escape. (i.e. scale = 1 for no scale)
            this.activationEscaping_ScaleArraySet.do.set_one_byN( outChannel, 1 );
          }
        }

        // 1.2 Determine .undo (Prepared for the next convolution-bias-activation. Not for this.)
        this.activationEscaping_ScaleArraySet.undo.set_one_byUndo_ScaleArray(
          outChannel, this.activationEscaping_ScaleArraySet.do, outChannel );
      }

      // 2. Determine .afterActivationEscaping
      this.afterActivationEscaping
        .set_one_byBoundsArray( outChannel, this.afterBias, outChannel )
        .multiply_one_byNs( outChannel, this.activationEscaping_ScaleArraySet.do.scales, outChannel );
    }

    // 3. Determine .afterActivation
    {
      // If no activation function, the output range is determined by .afterActivationEscaping.
      if ( this.nActivationId == ValueDesc.ActivationFunction.Singleton.Ids.NONE ) {
        this.afterActivation.set_one_byBoundsArray( outChannel, this.afterActivationEscaping, outChannel )

      // Otherwise, the activation function dominates the output range.
      //
      // Note: Consider the implementation of ScaleArray.set_one_by_fromLowerUpper_toLowerUpper(), they are all not so good no
      //       matter using set_one_byXxx() or clamp_one_byXxx() of this.afterActivation. However, when using clamp_one_byXxx(),
      //       even if the activation function output range has Infinity (e.g. RELU is [ 0, +Infinity ]), the result bounds
      //       is more feasible (at least, will not become another bounds with Infinity).
      } else {
        if ( this.bPassThrough[ outChannel ] ) { // For pass-through half channels, it is clamped by the output range for linearDomainLinear.
          //this.afterActivation.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRangeLinear );
          this.afterActivation.clamp_one_byBounds( outChannel, theActivationFunctionInfo.outputRangeLinear );

        } else { // Non pass-through half channels, it is clamped by the output range for the whole input domain.
          //this.afterActivation.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRange );
          this.afterActivation.clamp_one_byBounds( outChannel, theActivationFunctionInfo.outputRange );
        }
      }
    }

    return this;
  }

  /**
   * Rearrange output related channel information (.afterFilter, .afterBias, .afterActivationEscaping, .afterActivation,
   * .activationEscaping_ScaleArraySet, .bPassThrough) by interleaving as ( groupCount == 2 ). This element count must be even (i.e. divisible by 2).
   *
   * @param {Array} arrayTemp
   *   A temporary array for placing the original elements temporarily. Provide this array could reduce memory re-allocation
   * and improve performance.
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object.
   */
  interleave_asGrouptTwo( arrayTemp ) {
    this.afterFilter.interleave_asGrouptTwo( arrayTemp );
    this.afterBias.interleave_asGrouptTwo( arrayTemp );
    this.afterActivationEscaping.interleave_asGrouptTwo( arrayTemp );
    this.afterActivation.interleave_asGrouptTwo( arrayTemp );
    this.activationEscaping_ScaleArraySet.interleave_asGrouptTwo( arrayTemp );
    FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.bPassThrough, 0, this.bPassThrough.length, arrayTemp );
    return this;
  }

  get output() {
    return this.afterActivation;
  }

}

<commit_msg>Update BoundsArraySet.js<commit_after>export { BoundsArraySet };

import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
//import * as Weights from "../../Unpacker/Weights.js";
import * as ActivationEscaping from "../ActivationEscaping.js";

/**
 * Element value bounds for every operation's result of a convolution-bias-activation. The main purpose is to find out the
 * activationEscaping_ScaleArraySet so that it can be used to let channel escape from activation function's non-linear effect.
 *
 *
 * @member {FloatValue.BoundsArray} input
 *   The (per channel) bounds of the input element value. Or say, the domain of the convolution-bias-activation.
 *
 * @member {FloatValue.BoundsArray} afterUndoPreviousActivationEscaping
 *   The (per channel) bounds of the element value after applying the previousConvBiasActivation.BoundsArraySet.ActivationEscaping.undo
 * to this.input. (i.e. beforeFilter)
 *
 * @member {FloatValue.BoundsArray} afterFilter
 *   The (per channel) bounds of the element value after applying the convolution filters to this.afterUndoPreviousActivationEscaping.
 * (i.e. beforeBias)
 *
 * @member {FloatValue.BoundsArray} afterBias
 *   The (per channel) bounds of the element value after applying the convolution biases to this.afterFilter. (i.e. beforeActivationEscaping)
 *
 * @member {FloatValue.BoundsArray} afterActivationEscaping
 *   The (per channel) bounds of the element value after applying this.activationEscaping_ScaleArraySet.do to this.afterBias. (i.e. beforeActivation)
 *
 * @member {FloatValue.BoundsArray} afterActivation
 *   The (per channel) bounds of the element value after applying activation function to this.afterActivationEscaping.
 *
 * @member {FloatValue.BoundsArray} output
 *   The (per channel) bounds of the output element value. Or say, the range of the convolution-bias-activation. It is just
 * the this.afterActivation.
 *
 * @member {ActivationEscaping.ScaleArraySet} activationEscaping_ScaleArraySet
 *   The scales for moving this.afterBias bounds into the linear domain of the activation function. That is, for
 * letting this.afterBias escape from activation function's non-linear domain. And the .undo for undoing the scales.
 *
 * @member {boolean[]} bPassThrough
 *   If true for a output channel, the output channel should be arranged to pass-through from input to output.
 */
class BoundsArraySet {

  /**
   */
  constructor( inputChannelCount, outputChannelCount ) {
    this.input = new FloatValue.BoundsArray( inputChannelCount );
    this.afterUndoPreviousActivationEscaping = new FloatValue.BoundsArray( inputChannelCount );
    this.afterFilter = new FloatValue.BoundsArray( outputChannelCount );
    this.afterBias = new FloatValue.BoundsArray( outputChannelCount );
    this.afterActivationEscaping = new FloatValue.BoundsArray( outputChannelCount );
    this.afterActivation = new FloatValue.BoundsArray( outputChannelCount ); // i.e. .output

    this.activationEscaping_ScaleArraySet = new ActivationEscaping.ScaleArraySet( outputChannelCount );
    this.bPassThrough = new Array( outputChannelCount );

    //this.set_all_byBounds.set_all_byBounds( Weights.Base.ValueBounds );
  }

  /**
   * @return {BoundsArraySet} Return a newly created BoundsArraySet which is a copy of this BoundsArraySet.
   */
  clone() {
    let result = new BoundsArraySet( this.input.lowers.length, this.output.lowers.length );
    result.set_byBoundsArraySet( this );
    return result;
  }

  /**
   * @param {FloatValue.Bounds} aBounds
   *   Set all BoundsArray to the same as the specified aBounds. Set the this.activationEscaping_ScaleArraySet to default ( 1 );
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object.
   */
  set_all_byBounds( aBounds ) {
    this.input.set_all_byBounds( aBounds );
    this.afterUndoPreviousActivationEscaping.set_all_byBounds( aBounds );
    this.afterFilter.set_all_byBounds( aBounds );
    this.afterBias.set_all_byBounds( aBounds );
    this.afterActivationEscaping.set_all_byBounds( aBounds );
    this.afterActivation.set_all_byBounds( aBounds );
    this.activationEscaping_ScaleArraySet.set_all_byN( 1 ); // scale 1 and translate 0. (i.e. no scale and no translate.)
    this.bPassThrough.fill( false ); // Assume all are not pass-through.
    return this;
  }

  /**
   * @param {BoundsArraySet} aBoundsArraySet
   *   The BoundsArraySet to be copied.
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object which is copied from aBoundsArraySet.
   */
  set_all_byBoundsArraySet( aBoundsArraySet ) {
    this.input                              .set_all_byBoundsArray( aBoundsArraySet.input );
    this.afterUndoPreviousActivationEscaping.set_all_byBoundsArray( aBoundsArraySet.afterUndoPreviousActivationEscaping );
    this.afterFilter                        .set_all_byBoundsArray( aBoundsArraySet.afterFilter );
    this.afterBias                          .set_all_byBoundsArray( aBoundsArraySet.afterBias );
    this.afterActivationEscaping            .set_all_byBoundsArray( aBoundsArraySet.afterActivationEscaping );
    this.afterActivation                    .set_all_byBoundsArray( aBoundsArraySet.afterActivation );
    this.activationEscaping_ScaleArraySet.set_byScaleArraySet( aBoundsArraySet.activationEscaping_ScaleArraySet );

    for ( let i = 0; i < this.bPassThrough.length; ++i ) {
      this.bPassThrough[ i ] = aBoundsArraySet.bPassThrough[ i ];
    }

    return this;
  }

  /**
   * Determine .activationEscaping_ScaleArraySet and .afterActivationEscaping and .afterActivation, by .afterBias and .bPassThrough and nActivationId.
   *
   * The following properties will be used:
   *   - this.afterBias
   *   - this.bPassThrough
   *
   * The following properties will be modified:
   *   - this.activationEscaping_ScaleArraySet
   *   - this.afterActivationEscaping
   *   - this.afterActivation
   *
   * @param {number} nActivationId
   *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) of this depthwise convolution.
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object.
   */
  set_activationEscaping_afterActivationEscaping_afterActivation_by_afterBias_bPassThrough_nActivationId( nActivationId ) {
    let theActivationFunctionInfo = ValueDesc.ActivationFunction.Singleton.getInfoById( nActivationId );

    for ( let outChannel = 0; outChannel < this.afterBias.lowers.length; ++outChannel ) {

      // 1. Determine .activationEscaping_ScaleArraySet
      {
        // 1.1 Determine .do

        if ( nActivationId == ValueDesc.ActivationFunction.Singleton.Ids.NONE ) {

          // Since no activation function, no need to escape. (i.e. scale = 1 for no scale)
          this.activationEscaping_ScaleArraySet.do.set_one_byN( outChannel, 1 );

        } else {

          if ( this.bPassThrough[ outChannel ] ) { // For pass-through half channels.

            // Calculate the scale for escaping bias result from activation function's non-linear domain into linear domain.
            //
            // Note: This does not work for avg/max pooling.
            this.activationEscaping_ScaleArraySet.do.set_one_by_fromLowerUpper_toLowerUpper( outChannel,
              this.afterBias.lowers[ outChannel ], this.afterBias.uppers[ outChannel ],
              theActivationFunctionInfo.inputDomainLinear.lower, theActivationFunctionInfo.inputDomainLinear.upper
            );

            let doEscapingScale = this.activationEscaping_ScaleArraySet.do.scales[ outChannel ];
            tf.util.assert( ( Number.isNaN( doEscapingScale ) == false ),
              `ConvBiasActivation.BoundsArraySet.`
                + `set_activationEscaping_afterActivationEscaping_afterActivation_by_afterBias_bPassThrough_nActivationId(): `
                + `this.activationEscaping_ScaleArraySet.do.scales[ ${outChannel} ] ( ${doEscapingScale} ) `
                + `should not be NaN. `
                + `Please use activation function (e.g. tanh()) which has both negative and positive parts near origin point.`
            );

          } else { // Non pass-through half channels.
            // Since non-pass-through, no need to escape. (i.e. scale = 1 for no scale)
            this.activationEscaping_ScaleArraySet.do.set_one_byN( outChannel, 1 );
          }
        }

        // 1.2 Determine .undo (Prepared for the next convolution-bias-activation. Not for this.)
        this.activationEscaping_ScaleArraySet.undo.set_one_byUndo_ScaleArray(
          outChannel, this.activationEscaping_ScaleArraySet.do, outChannel );
      }

      // 2. Determine .afterActivationEscaping
      this.afterActivationEscaping
        .set_one_byBoundsArray( outChannel, this.afterBias, outChannel )
        .multiply_one_byNs( outChannel, this.activationEscaping_ScaleArraySet.do.scales, outChannel );
    }

    // 3. Determine .afterActivation
    {
      // If no activation function, the output range is determined by .afterActivationEscaping.
      if ( this.nActivationId == ValueDesc.ActivationFunction.Singleton.Ids.NONE ) {
        this.afterActivation.set_one_byBoundsArray( outChannel, this.afterActivationEscaping, outChannel )

      // Otherwise, the activation function dominates the output range.
      //
      // Note: Consider the implementation of ScaleArray.set_one_by_fromLowerUpper_toLowerUpper(), they are all not so good no
      //       matter using set_one_byXxx() or clamp_one_byXxx() of this.afterActivation. However, when using clamp_one_byXxx(),
      //       even if the activation function output range has Infinity (e.g. RELU is [ 0, +Infinity ]), the result bounds
      //       is more feasible (at least, will not become another bounds with Infinity).
      } else {
        if ( this.bPassThrough[ outChannel ] ) { // For pass-through half channels, it is clamped by the output range for linearDomainLinear.
          //this.afterActivation.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRangeLinear );
          this.afterActivation.clamp_one_byBounds( outChannel, theActivationFunctionInfo.outputRangeLinear );

        } else { // Non pass-through half channels, it is clamped by the output range for the whole input domain.
          //this.afterActivation.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRange );
          this.afterActivation.clamp_one_byBounds( outChannel, theActivationFunctionInfo.outputRange );
        }
      }
    }

    return this;
  }

  /**
   * Rearrange output related channel information (.afterFilter, .afterBias, .afterActivationEscaping, .afterActivation,
   * .activationEscaping_ScaleArraySet, .bPassThrough) by interleaving as ( groupCount == 2 ). This element count must be even (i.e. divisible by 2).
   *
   * @param {Array} arrayTemp
   *   A temporary array for placing the original elements temporarily. Provide this array could reduce memory re-allocation
   * and improve performance.
   *
   * @return {BoundsArraySet}
   *   Return this (modified) object.
   */
  output_interleave_asGrouptTwo( arrayTemp ) {
    this.afterFilter.interleave_asGrouptTwo( arrayTemp );
    this.afterBias.interleave_asGrouptTwo( arrayTemp );
    this.afterActivationEscaping.interleave_asGrouptTwo( arrayTemp );
    this.afterActivation.interleave_asGrouptTwo( arrayTemp );
    this.activationEscaping_ScaleArraySet.interleave_asGrouptTwo( arrayTemp );
    FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.bPassThrough, 0, this.bPassThrough.length, arrayTemp );
    return this;
  }

  get output() {
    return this.afterActivation;
  }

}

<|endoftext|>


<commit_before>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual("chillin");
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<commit_msg>It an call a method on the derived object with Crockford's inheritance improvement<commit_after>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual("chillin");
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual("eat a tire");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>import { isEnabled } from '@ember/canary-features';
import applyMixins from './apply-mixins';
import getAllPropertyNames from './get-all-property-names';
import { all } from 'rsvp';

export default function moduleFor(description, TestClass, ...mixins) {
  QUnit.module(description, {
    beforeEach: function(...args) {
      let instance = new TestClass(...args);
      this.instance = instance;
      if (instance.beforeEach) {
        return instance.beforeEach(...args);
      }
    },

    afterEach: function() {
      let promises = [];
      let instance = this.instance;
      this.instance = null;
      if (instance.teardown) {
        promises.push(instance.teardown());
      }
      if (instance.afterEach) {
        promises.push(instance.afterEach());
      }

      // this seems odd, but actually saves significant time
      // in the test suite
      //
      // returning a promise from a QUnit test always adds a 13ms
      // delay to the test, this filtering prevents returning a
      // promise when it is not needed
      //
      // Remove after we can update to QUnit that includes
      // https://github.com/qunitjs/qunit/pull/1246
      let filteredPromises = promises.filter(Boolean);
      if (filteredPromises.length > 0) {
        return all(filteredPromises);
      }
    },
  });

  if (mixins.length > 0) {
    applyMixins(TestClass, ...mixins);
  }

  let properties = getAllPropertyNames(TestClass);
  properties.forEach(generateTest);

  function shouldTest(features) {
    return features.every(feature => {
      if (feature[0] === '!' && isEnabled(feature.slice(1))) {
        return false;
      } else if (!isEnabled(feature)) {
        return false;
      } else {
        return true;
      }
    });
  }

  function generateTest(name) {
    if (name.indexOf('@test ') === 0) {
      QUnit.test(name.slice(5), function(assert) {
        return this.instance[name](assert);
      });
    } else if (name.indexOf('@only ') === 0) {
      QUnit.only(name.slice(5), function(assert) {
        return this.instance[name](assert);
      });
    } else if (name.indexOf('@skip ') === 0) {
      QUnit.skip(name.slice(5), function(assert) {
        return this.instance[name](assert);
      });
    } else {
      let match = /^@feature\(([a-z-!]+)\) /.exec(name);

      if (match) {
        let features = match[1].replace(/ /g, '').split(',');

        if (shouldTest(features)) {
          QUnit.test(name.slice(match[0].length), function(assert) {
            return this.instance[name](assert);
          });
        }
      }
    }
  }
}
<commit_msg>Ensure `moduleFor` allows for all caps feature names...<commit_after>import { isEnabled } from '@ember/canary-features';
import applyMixins from './apply-mixins';
import getAllPropertyNames from './get-all-property-names';
import { all } from 'rsvp';

export default function moduleFor(description, TestClass, ...mixins) {
  QUnit.module(description, {
    beforeEach: function(...args) {
      let instance = new TestClass(...args);
      this.instance = instance;
      if (instance.beforeEach) {
        return instance.beforeEach(...args);
      }
    },

    afterEach: function() {
      let promises = [];
      let instance = this.instance;
      this.instance = null;
      if (instance.teardown) {
        promises.push(instance.teardown());
      }
      if (instance.afterEach) {
        promises.push(instance.afterEach());
      }

      // this seems odd, but actually saves significant time
      // in the test suite
      //
      // returning a promise from a QUnit test always adds a 13ms
      // delay to the test, this filtering prevents returning a
      // promise when it is not needed
      //
      // Remove after we can update to QUnit that includes
      // https://github.com/qunitjs/qunit/pull/1246
      let filteredPromises = promises.filter(Boolean);
      if (filteredPromises.length > 0) {
        return all(filteredPromises);
      }
    },
  });

  if (mixins.length > 0) {
    applyMixins(TestClass, ...mixins);
  }

  let properties = getAllPropertyNames(TestClass);
  properties.forEach(generateTest);

  function shouldTest(features) {
    return features.every(feature => {
      if (feature[0] === '!' && isEnabled(feature.slice(1))) {
        return false;
      } else if (!isEnabled(feature)) {
        return false;
      } else {
        return true;
      }
    });
  }

  function generateTest(name) {
    if (name.indexOf('@test ') === 0) {
      QUnit.test(name.slice(5), function(assert) {
        return this.instance[name](assert);
      });
    } else if (name.indexOf('@only ') === 0) {
      QUnit.only(name.slice(5), function(assert) {
        return this.instance[name](assert);
      });
    } else if (name.indexOf('@skip ') === 0) {
      QUnit.skip(name.slice(5), function(assert) {
        return this.instance[name](assert);
      });
    } else {
      let match = /^@feature\(([A-Z_a-z-!]+)\) /.exec(name);

      if (match) {
        let features = match[1].replace(/ /g, '').split(',');

        if (shouldTest(features)) {
          QUnit.test(name.slice(match[0].length), function(assert) {
            return this.instance[name](assert);
          });
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>import styled from 'styled-components'
import {
  StyledInputCss,
  StyledEditableWrapperCss,
  Button
} from 'tocco-ui'
import {StyledButton} from 'tocco-ui/src/Button'
import {StyledButtonGroup} from 'tocco-ui/src/ButtonGroup'
import {theme} from 'tocco-ui/src/utilStyles'

export const StyledLoginFormInput = styled.input`
  @keyframes onAutoFillStart { from {} }

  && {
    transition: background-color 50000s, color 50000s, filter 50000s;
     &:-webkit-autofill {
      animation-duration: 50000s;
      animation-name: onAutoFillStart;
     }
  }

  ${StyledInputCss}
`

export const StyledLoginFormInputWrapper = styled.div`
  && {
    ${StyledEditableWrapperCss}
  }
`

export const StyledLoginButton = styled(Button)`
  &&& {
    border-radius: ${theme.radii('large')};
    display: flex;
    justify-content: center;

    &:not(:last-child) {
      margin-right: 0;
    }

    && > span {
      width: auto;
      padding-left: .4em;
    }
  }
`

export const StyledPasswordButton = styled(Button)`
  &&& {
    margin-right: 0;
    background-color: transparent;
    color: ${theme.color('primary')};

    &:hover {
      background-color: transparent;
    }
  }
`

export const StyledLoginFormWrapper = styled.div`
  ${StyledButtonGroup} {
    margin-top: 1.8rem;
    width: auto;
    flex-direction: column;

    ${StyledButton} {
      flex-grow: 1;

      > span {
        width: 100%;
        padding: 1rem 0 1rem 0;
      }
    }
  }
`
<commit_msg>refactor(login): rectify theme import <commit_after>import styled from 'styled-components'
import {
  StyledInputCss,
  StyledEditableWrapperCss,
  Button,
  theme
} from 'tocco-ui'
import {StyledButton} from 'tocco-ui/src/Button'
import {StyledButtonGroup} from 'tocco-ui/src/ButtonGroup'

export const StyledLoginFormInput = styled.input`
  @keyframes onAutoFillStart { from {} }

  && {
    transition: background-color 50000s, color 50000s, filter 50000s;
     &:-webkit-autofill {
      animation-duration: 50000s;
      animation-name: onAutoFillStart;
     }
  }

  ${StyledInputCss}
`

export const StyledLoginFormInputWrapper = styled.div`
  && {
    ${StyledEditableWrapperCss}
  }
`

export const StyledLoginButton = styled(Button)`
  &&& {
    border-radius: ${theme.radii('large')};
    display: flex;
    justify-content: center;

    &:not(:last-child) {
      margin-right: 0;
    }

    && > span {
      width: auto;
      padding-left: .4em;
    }
  }
`

export const StyledPasswordButton = styled(Button)`
  &&& {
    margin-right: 0;
    background-color: transparent;
    color: ${theme.color('primary')};

    &:hover {
      background-color: transparent;
    }
  }
`

export const StyledLoginFormWrapper = styled.div`
  ${StyledButtonGroup} {
    margin-top: 1.8rem;
    width: auto;
    flex-direction: column;

    ${StyledButton} {
      flex-grow: 1;

      > span {
        width: 100%;
        padding: 1rem 0 1rem 0;
      }
    }
  }
`
<|endoftext|>


<commit_before>mapkob = Object.create(null);

/**
 * Generic function to prepare input for consumption
 *
 * Type can be one of:
 *  - "newline delim": Take a string where sentences are delimited by newlines
 *  -
 *
 * @param {Object} data The input data
 * @param {String} type The type of input
 * @returns {Array} An array of strings, sentences delimited by undefined
 */
mapkob.prepareInput = function(data, type) {

  // newline delim
  var splitRe = new RegExp("([\n\r\.]+)")
  if (type === "newline delim") {
    var sentences = data.split(splitRe);
    var delimited = [];
    sentences.map(function(sentence, i) {
      delimited.push(sentence);
      if (i < sentences.length - 1) {
        delimited.push(undefined)
      }
    });

    return delimited.map(function(sentence) {
      return sentence === undefined ? [undefined] : sentence.split(" ");
    }).reduce(function(x,y) {return x.concat(y)})
  }
  return
}

/**
 * Initializes a n x n zero matrix for the states
 *
 * @param {Array} stateSpace The state space
 * @returns {Object} A mapkob zero matrix
 */
mapkob.InitializeZeroMatrix = function(stateSpace) {
  var frequencyMatrix = {};
  var stateObject = {};

  stateSpace.map(function(word) {
    var stateObject = {};
    stateSpace.map(function(word) {stateObject[word] = 0;})
    frequencyMatrix[word] = stateObject;
  });

  this.stateSpace = stateSpace;
  this.matrix = frequencyMatrix;
  return this;
}

/**
 * A basic matrix serving as a parent
 *
 * returns {Object} A mapkob matrix object
 */
mapkob.Matrix = function() {
  this.matrix = {};
  this.stateSpace = [];
  this.type = "mapkob matrix";
  return this;
}

/**
 * Fills a mapkob zero matrix with the state counts provided
 *
 * @param {Object} matrix A mapkob zero matrix
 * @param {Array} states The states provided
 * @returns {Object} A mapkob frequency matrix
 */
mapkob.FillZeroMatrix = function(matrix, states) {
  mapkob.Matrix.call(this);

  states.concat(undefined).map(function(state, i) {
    matrix.matrix[state][states[i + 1]] += 1;
  });

  matrix.stateSpace.map(function(state) {
    matrix.matrix[undefined][state] = 0;
  })
  matrix.matrix.undefined.undefined = 1;

  this.matrix = matrix.matrix;
  this.stateSpace = matrix.stateSpace;
  this.states = states;
  this.type = "mapkob zero matrix";
  return this;
}

/**
 * Basic constructor for a transition matrix
 *
 * @param {Array} words An Array of words. Sentences are delimited by undefined.
 * @returns {TransitionMatrix} A TransitionMatric object
 */
mapkob.TransitionMatrix = function(words) {
  mapkob.Matrix.call(this);
  var uniqueWords = mapkob.unique(words);
  this.stateSpace = uniqueWords;

  var zeroMatrix = new mapkob.InitializeZeroMatrix(uniqueWords);
  var frequencyMatrix = new mapkob.FillZeroMatrix(zeroMatrix, words);

  this.matrix = frequencyMatrix.getRowProbabilities();
  this.type = "mapkob frequency matrix";
  return this;
}

/**
 * Returns a list of unique elements
 *
 * @param {Array} input The array of elements
 * @returns {Array} The deduped array
 */
mapkob.unique = function(input) {
  var output = [];
  input.map(function(element) {
    if (output.indexOf(element) === -1) {
      output.push(element)}});
  return output;
}

/**
 * Returns the row of a matrix
 *
 * @param {String} row The row by name to look up
 * @returns {Object} The row of the matrix
 */
mapkob.Matrix.prototype.getRow = function(row) {
  return this.matrix[row];
}

/**
 * Returns the sum of a row of a matrix
 *
 * @param {String} row The row by name to look up
 * @returns {Number} The sum of the row's values
 */
mapkob.Matrix.prototype.getRowSum = function(row) {
  var sum = 0;
  var currentRow = this.getRow(row);
  this.stateSpace.map(function(col) {sum += currentRow[col]})
  return sum;
}

/**
 * Calculates the cumulative sum for every column of a row
 *
 * @param {String} row The name of the state
 * @returns {Array} an array of length n with the cumulative sums
 */
mapkob.Matrix.prototype.getRowCumSum = function(row) {
  var output = [];
  var sum = 0;
  var currentRow = this.getRow(row);

  this.stateSpace.map(function(state) {
    sum += currentRow[state];
    output.push(sum);
  })
  return output;
}

/**
 * Returns the element of a matrix
 *
 * @param {String} row The row by name to look up
 * @param {String} col The column by name to look up
 * @returns {Number} The value of the element
 */
mapkob.Matrix.prototype.getElement = function(row, col) {
  return this.getRow(row)[col];
}

/**
 * Calculates the probabilities for a row of a frequencyMatrix
 *
 * @param{String} row The name of the row
 * @return {Object} A maokob row
 */
mapkob.Matrix.prototype.getProbabilitiesForRow = function(row) {
  var thisRow = this.getRow(row);
  var stateSpace = this.stateSpace;
  var sum = this.getRowSum(row);
  var output = {};
  stateSpace.map(function(state, i) {output[state] = thisRow[state] / sum})
  return output;
}

/**
 * Calculates rowwise density, i.e. probabilities
 * Should proably initialize a Matrix
 *
 * @returns {Object} An transition matrix (no mapkob object as of now)
 */
mapkob.Matrix.prototype.getRowProbabilities = function() {
  var stateSpace = this.stateSpace;
  var output = {};
  stateSpace.map(function(state) {
    output[state] = this.getProbabilitiesForRow(state);
  }, this);
  return output;
}

// Let Special Matrix types inherit generic methods
mapkob.InitializeZeroMatrix.prototype = new mapkob.Matrix();
mapkob.FillZeroMatrix.prototype = new mapkob.Matrix();
mapkob.TransitionMatrix.prototype = new mapkob.Matrix();

/**
 * Generates a sumulated Markov chain
 *
 * @returns {String} A Computer generated string
 */
mapkob.TransitionMatrix.prototype.generateChain = function() {
  var stateI = Math.floor(Math.random() * this.stateSpace.length);
  var currentState = this.stateSpace[stateI];
  var output = [];

  while (currentState !== undefined) {
    output.push(currentState);
    var cumSums = this.getRowCumSum(currentState);
    var r = Math.random();
    for (var col in cumSums) {
      if (r <= cumSums[col] && (cumSums[col] === undefined || cumSums[col] > r)) {
        stateI = col;
        break;
      }
    }
    currentState = this.stateSpace[stateI];
  }
  return output.join(" ");
}
<commit_msg>Switching to sparse matrices<commit_after>mapkob = Object.create(null);

/**
 * Generic function to prepare input for consumption
 *
 * Type can be one of:
 *  - "newline delim": Take a string where sentences are delimited by newlines
 *  -
 *
 * @param {Object} data The input data
 * @param {String} type The type of input
 * @returns {Array} An array of strings, sentences delimited by undefined
 */
mapkob.prepareInput = function(data, type) {

  // newline delim
  var splitRe = new RegExp("([\n\r\.]+)")
  if (type === "newline delim") {
    var sentences = data.split(splitRe);
    var delimited = [];
    sentences.map(function(sentence, i) {
      delimited.push(sentence);
      if (i < sentences.length - 1) {
        delimited.push(undefined)
      }
    });

    return delimited.map(function(sentence) {
      return sentence === undefined ? [undefined] : sentence.split(" ");
    }).reduce(function(x,y) {return x.concat(y)})
  }
  return
}

/**
 * A Row mapkob row constructor
 *
 * @param {Object} input A simple object
 * @returns {Object} A maokob row
 */
mapkob.Row = function(input) {
  this.row = input;
  this.stateSpace = Object.keys(input);
  return this;
}

/**
 * Initializes a n x n zero matrix for the states
 *
 * @param {Array} stateSpace The state space
 * @returns {Object} A mapkob zero matrix
 */
mapkob.InitializeZeroMatrix = function(stateSpace) {
  var frequencyMatrix = {};
  var stateObject = {};

  stateSpace.map(function(word) {
    var stateObject = {};
    stateSpace.map(function(word) {stateObject[word] = 0;})
    frequencyMatrix[word] = stateObject;
  });

  this.stateSpace = stateSpace;
  this.matrix = frequencyMatrix;
  return this;
}

/**
 * A basic matrix serving as a parent
 *
 * returns {Object} A mapkob matrix object
 */
mapkob.Matrix = function() {
  this.matrix = {};
  this.stateSpace = [];
  this.type = "mapkob matrix";
  return this;
}

mapkob.SparseTransitionMatrix = function(words) {
  mapkob.Matrix.call(this);
  var uniqueWords = mapkob.unique(words.concat(undefined));
  this.stateSpace = uniqueWords;

  var matrix = {};
  uniqueWords.map(function(word) {matrix[word] = {};});
  words.map(function(word, i) {
    var nextWord = words[i + 1];

    if (matrix[word][nextWord] === undefined) {
      matrix[word][nextWord] = 1;
    } else {
      matrix[word][nextWord] += 1;
    }
  })
  this.matrix = matrix;
  this.type = "mapkob frequency matrix";
  return this;
}

/**
 * Returns a list of unique elements
 *
 * @param {Array} input The array of elements
 * @returns {Array} The deduped array
 */
mapkob.unique = function(input) {
  var output = [];
  input.map(function(element) {
    if (output.indexOf(element) === -1) {
      output.push(element)}});
  return output;
}

/**
 * Returns the row of a matrix
 *
 * @param {String} row The row by name to look up
 * @returns {Object} The row of the matrix
 */
mapkob.Matrix.prototype.getRow = function(row) {
  var row = new mapkob.Row(this.matrix[row]);
  return row;
}

// Let Special Matrix types inherit generic methods
mapkob.SparseTransitionMatrix.prototype = new mapkob.Matrix();

/**
 * Generates a sumulated Markov chain
 *
 * @returns {String} A Computer generated string
 */
mapkob.SparseTransitionMatrix.prototype.generateChain = function() {
  var stateI = Math.floor(Math.random() * this.stateSpace.length);
  var currentState = this.stateSpace[stateI];
  var output = [];

  while (currentState !== "undefined" && currentState !== undefined) {
    output.push(currentState);
    var currentRow = this.getRow(currentState);
    var rowSum = currentRow.stateSpace.map(function(state) {
      return currentRow.row[state];
    }).reduce(function(x, y) {return x + y});

    var probs = currentRow.stateSpace.map(function(state) {
      return currentRow.row[state] / rowSum;
    });

    var cumSums = probs.map(function(state, stateI) {
      var sum = 0;
      for (var i = 0; i <= stateI; i++) {
        sum += probs[i];
      }
      return sum;
    })

    var r = Math.random();
    for (var col in cumSums) {
      if (r <= cumSums[col] && (cumSums[col+1] === undefined || cumSums[col+1] > r)) {
        stateI = col;
        break;
      }
    }
    currentState = currentRow.stateSpace[stateI];
  }
  return output.join(" ");
}
<|endoftext|>