<commit_before>Travis.Views.Repositories.Item = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, 'render', 'setSelected', 'setLastBuild', '_setStatus', '_setDuration', '_setFinishedAt', '_setNumber');

    this.model.bind('select', this.setSelected);
    this.model.bind('deselect', this.setSelected);
    this.model.bind('change:last_build_number', this.setLastBuild);
    this.model.bind('change:last_build_status', this.setLastBuild);
    this.model.bind('change:last_build_duration', this.setLastBuild);
    this.model.bind('change:last_build_finished_at', this.setLastBuild);

    this.template = Travis.templates['repositories/item'];
  },
  render: function() {
    this.el = $(this.template(this.model.toJSON()));
    this.el.updateTimes();
    return this;
  },
  setSelected: function() {
    this.model.selected ? this.el.addClass('selected') : this.el.removeClass('selected');
  },
  setLastBuild: function() {
    this.el.parent().prepend(this.el);
    this._setStatus();
    this._setDuration();
    this._setFinishedAt();
    this._setNumber();
    this.el.updateTimes();
  },
  _setStatus: function() {
    this.el.removeClass('red green').addClass(this.model.color());
  },
  _setDuration: function() {
    this.el.find('.duration').attr('title', this.model.last_build_duration());
  },
  _setFinishedAt: function() {
    this.el.find('.finished_at').attr('title', this.model.get('last_build_finished_at'));
  },
  _setNumber: function() {
    this.el.find('.build').attr('href', '#!/' + this.model.get('slug') + '/builds/' + this.model.get('last_build_id')).text('#' + this.model.get('last_build_number'))
  },
});

Travis.Views.Repositories.MyItem = Backbone.View.extend({
  events: {
    'click .enable_travis': 'enableTravis'
  },
  initialize: function() {
    _.bindAll(this, 'render', 'enableTravis', 'onTravisEnabled');
    this.template = Travis.templates['repositories/my_item'];
  },
  render: function() {
    this.el = $(this.template(this.model.toJSON()));
    this.delegateEvents()
    return this;
  },
  enableTravis: function(e) {
    e.preventDefault()
    $.ajax({
      type: "POST",
      url: "/repositories",
      contentType: "application/json",
      dataType: "json",
      data: JSON.stringify({
        name: this.model.get('name'),
        owner_name: this.model.get('owner'),
        authenticity_token: this.model.get('authenticity_token')
      }),
      success: this.onTravisEnabled
    });
  },
  onTravisEnabled: function() {
    this.el.find('enable_travis').hide('fade')
  }
});
<commit_msg>Hiding button after if service hook was successfully added. <commit_after>Travis.Views.Repositories.Item = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, 'render', 'setSelected', 'setLastBuild', '_setStatus', '_setDuration', '_setFinishedAt', '_setNumber');

    this.model.bind('select', this.setSelected);
    this.model.bind('deselect', this.setSelected);
    this.model.bind('change:last_build_number', this.setLastBuild);
    this.model.bind('change:last_build_status', this.setLastBuild);
    this.model.bind('change:last_build_duration', this.setLastBuild);
    this.model.bind('change:last_build_finished_at', this.setLastBuild);

    this.template = Travis.templates['repositories/item'];
  },
  render: function() {
    this.el = $(this.template(this.model.toJSON()));
    this.el.updateTimes();
    return this;
  },
  setSelected: function() {
    this.model.selected ? this.el.addClass('selected') : this.el.removeClass('selected');
  },
  setLastBuild: function() {
    this.el.parent().prepend(this.el);
    this._setStatus();
    this._setDuration();
    this._setFinishedAt();
    this._setNumber();
    this.el.updateTimes();
  },
  _setStatus: function() {
    this.el.removeClass('red green').addClass(this.model.color());
  },
  _setDuration: function() {
    this.el.find('.duration').attr('title', this.model.last_build_duration());
  },
  _setFinishedAt: function() {
    this.el.find('.finished_at').attr('title', this.model.get('last_build_finished_at'));
  },
  _setNumber: function() {
    this.el.find('.build').attr('href', '#!/' + this.model.get('slug') + '/builds/' + this.model.get('last_build_id')).text('#' + this.model.get('last_build_number'))
  },
});

Travis.Views.Repositories.MyItem = Backbone.View.extend({
  events: {
    'click .enable_travis': 'enableTravis'
  },
  initialize: function() {
    _.bindAll(this, 'render', 'enableTravis', 'onTravisEnabled');
    this.template = Travis.templates['repositories/my_item'];
  },
  render: function() {
    this.el = $(this.template(this.model.toJSON()));
    this.delegateEvents()
    return this;
  },
  enableTravis: function(e) {
    e.preventDefault()
    $.ajax({
      type: "POST",
      url: "/repositories",
      contentType: "application/json",
      dataType: "json",
      data: JSON.stringify({
        name: this.model.get('name'),
        owner_name: this.model.get('owner'),
        authenticity_token: this.model.get('authenticity_token')
      }),
      success: this.onTravisEnabled
    });
  },
  onTravisEnabled: function() {
    this.el.find('.enable_travis').hide('fade')
  }
});
<|endoftext|>


<commit_before>var performCommand = function(event) {
	if(event.command === 'hibernateTabs') {
		var c = 0;

		var xmlHttp = new XMLHttpRequest();
		xmlHttp.open('GET', safari.extension.baseURI + 'lib/hibernationPage/index.html', true);
		xmlHttp.onreadystatechange = function() {
			if(xmlHttp.readyState === 4) {
				var html = xmlHttp.responseText;

				_.each(safari.application.browserWindows, function(win) {
					_.each(win.tabs, function(tab) {
						if(tab === win.activeTab) return;
						if(!tab.url.match(/^https?:\/\//)) return;

						_.delay(function() {
							var pageInfo = {
								url: tab.url,
								title: tab.title
							};

							var pageHtml = html.replace(/\{\/\*pageInfoObject\*\/\}/, JSON.stringify(pageInfo));
							var dataURL = 'data:text/html;charset=utf-8,' + encodeURIComponent(pageHtml);
							tab.url = dataURL;
						}, c * 100);

						c++;
					});
				});
			}
		};
		xmlHttp.send(null);
	}
};

safari.application.addEventListener('command', performCommand, false);
<commit_msg>Check if tab’s url is defined before hibernating<commit_after>var performCommand = function(event) {
	if(event.command === 'hibernateTabs') {
		var c = 0;

		var xmlHttp = new XMLHttpRequest();
		xmlHttp.open('GET', safari.extension.baseURI + 'lib/hibernationPage/index.html', true);
		xmlHttp.onreadystatechange = function() {
			if(xmlHttp.readyState === 4) {
				var html = xmlHttp.responseText;

				_.each(safari.application.browserWindows, function(win) {
					_.each(win.tabs, function(tab) {
						if(typeof tab.url !== 'undefined') {
							if(tab === win.activeTab) return;
							if(!tab.url.match(/^https?:\/\//)) return;

							_.delay(function() {
								var pageInfo = {
									url: tab.url,
									title: tab.title
								};

								var pageHtml = html.replace(/\{\/\*pageInfoObject\*\/\}/, JSON.stringify(pageInfo));
								var dataURL = 'data:text/html;charset=utf-8,' + encodeURIComponent(pageHtml);
								tab.url = dataURL;
							}, c * 100);

							c++;
						}
					});
				});
			}
		};
		xmlHttp.send(null);
	}
};

safari.application.addEventListener('command', performCommand, false);
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/ui-map';

export default Ember.Component.extend({

  layout: layout,

  tagName: 'ui-map',

  classNames: ['ui-map'],

  action: 'mapEvent',

  markerAction: 'markerEvent',

  readyAction: 'mapReady',

  /**
   *
   */
  setup: function () {
    var map = this.get('map');

    Ember.run.scheduleOnce('afterRender', this, function () {

      map.on('action', this, function () {
        this.sendAction.apply(this, ['action'].concat([].slice.call(arguments)));
      });

      map.on('markerAction', this, function () {
        this.sendAction.apply(this, ['markerAction'].concat([].slice.call(arguments)));
      });

      map.one('readyAction', this, function () {
        this.sendAction.apply(this, ['readyAction'].concat([].slice.call(arguments)));
      });

      map.register(this);
    });
  }.on('didInsertElement'),

  /**
   *
   */
  teardown: function () {
    var map = this.get('map');

    map.off('action', this);
    map.off('markerAction', this);

    map.unregister(this);
  }.on('willDestroyElement')
});

<commit_msg>made attachment of event handlers more compact.<commit_after>import Ember from 'ember';
import layout from '../templates/components/ui-map';

export default Ember.Component.extend({

  layout: layout,

  tagName: 'ui-map',

  classNames: ['ui-map'],

  action: 'mapEvent',

  markerAction: 'markerEvent',

  readyAction: 'mapReady',

  /**
   *
   */
  setup: function () {
    var map = this.get('map');

    Ember.run.scheduleOnce('afterRender', this, function () {
      ['action', 'markerAction', 'readyAction'].forEach(function (action) {
        map.on(action, this, function () {
          this.sendAction.apply(this, [action].concat([].slice.call(arguments)));
        });
      }, this);

      map.register(this);
    });
  }.on('didInsertElement'),

  /**
   *
   */
  teardown: function () {
    var map = this.get('map');

    map.off('readyAction', this);
    map.off('action', this);
    map.off('markerAction', this);

    map.unregister(this);
  }.on('willDestroyElement')
});

<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Object.extend({
  objsForPage: function(page) {
    var range = this.range(page);
    return this.get('all').slice(range.start,range.end+1);
  },

  totalPages: function() {
    var allLength = parseFloat(this.get('all.length'));
    var perPage = parseFloat(this.get('perPage'));
    return Math.ceil(allLength/perPage);
  },

  range: function(page) {
    var perPage = this.get('perPage');
    var s = (page - 1) * perPage;
    var e = s + perPage - 1;

    return {start: s, end: e};
  }
});<commit_msg>range function returning correct range<commit_after>import Ember from 'ember';

export default Ember.Object.extend({
  objsForPage: function(page) {
    var range = this.range(page);
    return this.get('all').slice(range.start,range.end+1);
  },

  totalPages: function() {
    var allLength = parseInt(this.get('all.length'));
    var perPage = parseInt(this.get('perPage'));
    return Math.ceil(allLength/perPage);
  },

  range: function(page) {
    var perPage = parseInt(this.get('perPage'));
    var s = (parseInt(page) - 1) * perPage;
    var e = s + perPage - 1;

    return {start: s, end: e};
  }
});<|endoftext|>


<commit_before>import Ember from 'ember';

export function waves(params, hash) {
  let wavesClass = hash.wavesClass || 'waves-light';
  return Ember.String.htmlSafe(`<div class="waves-effect ${wavesClass}"></div>`);
}

export default Ember.Helper.helper(waves);
<commit_msg>Adding the waves container<commit_after>import Ember from 'ember';

export function addWaves(params, hash) {
  let wavesClass = hash.wavesClass || 'waves-light';
  return Ember.String.htmlSafe(`<div class="waves-container waves-effect ${wavesClass}"></div>`);
}

export default Ember.Helper.helper(addWaves);
<|endoftext|>


<commit_before>/* global Components, Services, AddonManager */

EXPORTED_SYMBOLS = ['WakaTime'];

const {interfaces: Ci, utils: Cu, classes: Cc} = Components;

const API_URL = 'https://wakatime.com/api/v1/actions';

// global imports
Cu.import('resource://gre/modules/Services.jsm');

let WakaTime = {

    init: function(data) {

        // module imports
        Cu.import('resource://wakatime/modules/util.jsm');

        this.version = data.version;

        Services.wm.addListener(this.windowListener);
    },
    destroy: function() {
        Services.wm.removeListener(this.windowListener);
        Log.info('Wakatime: destroyed');
    },
    sendHeartbeat: function(file, time, project, language, isWrite, lines) {
        if(this.enoughTimePassed()) {
            Http.send(API_URL, {
                method: 'POST',
                mimeType: 'application/json',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + btoa(Prefs.getPref('api_key'))
                },
                onload: function(e) {
                    Log.info("Response Text: " + e.target.responseText);
                },
                onerror: function(e) {
                    Log.info("Error Status: " + e.target.status);
                },
                data: JSON.stringify({
                    time: time/1000,
                    file: file,
                    project: project,
                    language: language,
                    is_write: isWrite ? true : false,
                    lines: lines,
                    plugin: 'thunderbird-wakatime/' + WakaTime.version
                })
            });

            this.lastAction = Date.now();
        }
    },
    enoughTimePassed: function() {
        if(!this.lastAction) {
            this.lastAction = Date.now();
            return true;
        } else {
            return this.lastAction + 120000 < Date.now();
        }
    },
    promptForApiKey: function() {
        // TODO: implement this
    },
    windowListener: {
        onOpenWindow: function (w) {
            // Wait for the window to finish loading
            let domWindow = w.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
            function _listener() {
                domWindow.removeEventListener('load', _listener, false); //this removes this load function from the window
                //window has now loaded now do stuff to it
                Log.info('window: ' + w + ' - loaded');
            }
            domWindow.addEventListener('load', _listener, false);
        },
        onCloseWindow: function (w) {
            Log.info('window: ' + w + ' - closed');
        },
        onWindowTitleChange: function (w, title) {
            var project = Prefs.getPref('project');
            project = project ? project : 'thunderbird-test';
            WakaTime.sendHeartbeat(title + '.eml', Date.now(), project, 'Email', true, 4);
            Log.info('window: ' + w + ' - title: ' + title);
        }
    }
};
<commit_msg>Change default project to "Email" if not set<commit_after>/* global Components, Services, AddonManager */

EXPORTED_SYMBOLS = ['WakaTime'];

const {interfaces: Ci, utils: Cu, classes: Cc} = Components;

const API_URL = 'https://wakatime.com/api/v1/actions';

// global imports
Cu.import('resource://gre/modules/Services.jsm');

let WakaTime = {

    init: function(data) {

        // module imports
        Cu.import('resource://wakatime/modules/util.jsm');

        this.version = data.version;

        Services.wm.addListener(this.windowListener);
    },
    destroy: function() {
        Services.wm.removeListener(this.windowListener);
        Log.info('Wakatime: destroyed');
    },
    sendHeartbeat: function(file, time, project, language, isWrite, lines) {
        if(this.enoughTimePassed()) {
            Http.send(API_URL, {
                method: 'POST',
                mimeType: 'application/json',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + btoa(Prefs.getPref('api_key'))
                },
                onload: function(e) {
                    Log.info("Response Text: " + e.target.responseText);
                },
                onerror: function(e) {
                    Log.info("Error Status: " + e.target.status);
                },
                data: JSON.stringify({
                    time: time/1000,
                    file: file,
                    project: project,
                    language: language,
                    is_write: isWrite ? true : false,
                    lines: lines,
                    plugin: 'thunderbird-wakatime/' + WakaTime.version
                })
            });

            this.lastAction = Date.now();
        }
    },
    enoughTimePassed: function() {
        if(!this.lastAction) {
            this.lastAction = Date.now();
            return true;
        } else {
            return this.lastAction + 120000 < Date.now();
        }
    },
    promptForApiKey: function() {
        // TODO: implement this
    },
    windowListener: {
        onOpenWindow: function (w) {
            // Wait for the window to finish loading
            let domWindow = w.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
            function _listener() {
                domWindow.removeEventListener('load', _listener, false); //this removes this load function from the window
                //window has now loaded now do stuff to it
                Log.info('window: ' + w + ' - loaded');
            }
            domWindow.addEventListener('load', _listener, false);
        },
        onCloseWindow: function (w) {
            Log.info('window: ' + w + ' - closed');
        },
        onWindowTitleChange: function (w, title) {
            var project = Prefs.getPref('project');
            project = project ? project : 'Email';
            WakaTime.sendHeartbeat(title + '.eml', Date.now(), project, 'Email', true, 4);
            Log.info('window: ' + w + ' - title: ' + title);
        }
    }
};
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3d item")
description("This will return the 3d item control")
base_component_id("threedee_item_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "position",
            name:       "Position",
            type:       "String",
            default:    "-2.1 4 -10"
        }
    ]
)//properties
logo_url("/driver_icons/threedee_item.png")
*/

    Vue.component("threedee_item_control",{
        props: ["args","design_mode", "refresh"]
        ,
      template: `<a-entity v-bind:refresh='refresh'>
                    <a-entity v-if='args'
                              geometry="primitive: box"
                              material="color: #166678; side: double"
                              physics-body="mass: 5; boundingBox: 2 2 2; shape: auto;"
                              dynamic-body
                              v-bind:refresh='refresh'
                              v-bind:position='args.position'>
                  </a-entity>
              </a-entity>`
    })
}
<commit_msg>Added Mass property to 3d objects<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("3d item")
description("This will return the 3d item control")
base_component_id("threedee_item_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "position",
            name:       "Position",
            type:       "String",
            default:    "-2.1 4 -10"
        }
        ,
        {
            id:         "mass",
            name:       "Mass",
            type:       "Number",
            default:    5
        }
    ]
)//properties
logo_url("/driver_icons/threedee_item.png")
*/

    Vue.component("threedee_item_control",{
        props: [  "meta", "args"  ,  "design_mode"  ,  "refresh"  ,  "name" ]
        ,
      template: `<a-entity v-bind:refresh='refresh'>
                    <a-entity v-if='args'
                              geometry="primitive: box"
                              material="color: #166678; side: double"
                              v-bind:physics-body='"mass: " + args.mass + "; boundingBox: 2 2 2; shape: auto;"'
                              dynamic-body
                              v-bind:refresh='refresh'
                              v-bind:position='args.position'>
                  </a-entity>
              </a-entity>`

        ,

        mounted: function() {
            var mm = this
            registerComponent(this)
        }

    })
}
<|endoftext|>


<commit_before>import { TransitionPromise, animate } from 'liquid-fire-tweenlite';

export default function scale(opts={}) {
  return new TransitionPromise({
    animateIn: function() {
      return animate(this.oldElement, {scale: 0.2}, opts);
    }.bind(this),
    animateOut: function() {
      return animate(this.newElement, {scale: 1}, opts);
    }.bind(this)
  });
}
<commit_msg>fix(scale-transition): corrects order of operations<commit_after>import { TransitionPromise, animate } from 'liquid-fire-tweenlite';

export default function scale(opts={}) {
  return new TransitionPromise({
    animateOut: function() {
      return animate(this.oldElement, { scale: [1, 0.2] }, opts, 'scale--out');
    }.bind(this),
    animateIn: function() {
      return animate(this.newElement, { scale: [0.2, 1] }, opts, 'scale--in');
    }.bind(this)
  });
}
<|endoftext|>


<commit_before>
/*
 ----------------------------------------------------------------------------
 Elliptic Curve Parameters
 ----------------------------------------------------------------------------
 */

var rng;

function initializeEllipticCurveParameters() {

   if (getN("eccP").value.length == 0) {
      set_secp160r1();
   }

   rng = new SecureRandom();
}

function set_ec_params(name) {
   var c = getSECCurveByName(name);

   getN("eccP").value = c.getCurve().getQ().toString();
   getN("eccA").value = c.getCurve().getA().toBigInteger().toString();
   getN("eccB").value = c.getCurve().getB().toBigInteger().toString();
   getN("eccGx").value = c.getG().getX().toBigInteger().toString();
   getN("eccGy").value = c.getG().getY().toBigInteger().toString();
   getN("eccN").value = c.getN().toString();

   // Changing EC params invalidates everything else
   getN("sendersPrivateMultiplier").value = "";
   getN("receiversPrivateMultiplier").value = "";
   getN("sendersMultipliedX").value = "";
   getN("sendersMultipliedY").value = "";
   getN("receiversMultipliedX").value = "";
   getN("receiversMultipliedY").value = "";
   getN("sendersCommonSecretKeyX").value = "";
   getN("sendersCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";
}

function set_secp128r1() {
   set_ec_params("secp128r1");
}

function set_secp160k1() {
   set_ec_params("secp160k1");
}

function set_secp160r1() {
   set_ec_params("secp160r1");
}

function set_secp192k1() {
   set_ec_params("secp192k1");
}

function set_secp192r1() {
   set_ec_params("secp192r1");
}

function set_secp224r1() {
   set_ec_params("secp224r1");
}

function set_secp256r1() {
   set_ec_params("secp256r1");
}

function get_curve() {
   return new ECCurveFp(new BigInteger(getN("eccP").value),
      new BigInteger(getN("eccA").value),
      new BigInteger(getN("eccB").value));
}

function get_G(curve) {
   return new ECPointFp(curve,
      curve.fromBigInteger(new BigInteger(getN("eccGx").value)),
      curve.fromBigInteger(new BigInteger(getN("eccGy").value)));
}

/*
 ----------------------------------------------------------------------------
 Sender's Parameters
 ----------------------------------------------------------------------------
 */

function generateSendersPrivateMultiplier() {

   var r = pick_rand();

   getN("sendersPrivateMultiplier").value = r.toString();

   /*
    ----------------------------------------------------------------------------
    Changing the sender's private multiplier implies
    the common secret key and the encrypted message.
    are no longer valid.
    ----------------------------------------------------------------------------
    */

   getN("sendersMultipliedX").value = "";
   getN("sendersMultipliedY").value = "";

   getN("sendersCommonSecretKeyX").value = "";
   getN("sendersCommonSecretKeyY").value = "";

   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateSendersMultipliedPoint() {

   if (getN("sendersPrivateMultiplier").value.length == 0) {
      alert("Please generate the sender's private multiplier first.");
      return;
   }

   var curve = get_curve();
   var G = get_G(curve);
   var a = new BigInteger(getN("sendersPrivateMultiplier").value);
   var P = G.multiply(a);

   getN("sendersMultipliedX").value = P.getX().toBigInteger().toString();
   getN("sendersMultipliedY").value = P.getY().toBigInteger().toString();

   /*
    ----------------------------------------------------------------------------
    Changing the sender's multiplied point (public key) implies
    the common secret key and the encrypted message.
    are no longer valid.
    ----------------------------------------------------------------------------
    */

   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateSendersCommonSecretKey() {

   /*
    ----------------------------------------------------------------------------
    Check that 1) the private multipliers and
    2) the multiplied (x,y)-points
    are defined for both the sender and the receiver
    ----------------------------------------------------------------------------
    */

   if(getN("sendersPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the sender's private multiplier first.");
      return;
   }

   if(getN("receiversPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the receiver's private multiplier first.");
      return;
   }

   if(getN("sendersMultipliedX").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("sendersMultipliedY").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("receiversMultipliedX").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   if(getN("receiversMultipliedY").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   /*
    ----------------------------------------------------------------------------
    Calculate the new common secret key.
    ----------------------------------------------------------------------------
    */

   var curve = get_curve();
   var P = new ECPointFp(curve,
      curve.fromBigInteger(new BigInteger(getN("receiversMultipliedX").value)),
      curve.fromBigInteger(new BigInteger(getN("receiversMultipliedY").value)));

   var a = new BigInteger(getN("sendersPrivateMultiplier").value);
   var S = P.multiply(a);

   getN("sendersCommonSecretKeyX").value = S.getX().toBigInteger().toString();
   getN("sendersCommonSecretKeyY").value = S.getY().toBigInteger().toString();

   /*
    ----------------------------------------------------------------------------
    Everything is valid except for the encrypted message.
    ----------------------------------------------------------------------------
    */

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

/*
 ----------------------------------------------------------------------------
 Receiver's Parameters
 ----------------------------------------------------------------------------
 */

function generateReceiversPrivateMultiplier() {

   var r = pick_rand();

   getN("receiversPrivateMultiplier").value = r.toString();

   /*
    ----------------------------------------------------------------------------
    Changing the receiver's private multiplier invalidates
    the sender's other values, the common secret key, and
    the encrypted message.
    ----------------------------------------------------------------------------
    */

   getN("receiversMultipliedX").value = "";
   getN("receiversMultipliedY").value = "";

   getN("sendersCommonSecretKeyX").value = "";
   getN("sendersCommonSecretKeyY").value = "";

   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateReceiversMultipliedPoint() {

   if(getN("receiversPrivateMultiplier").value.length == 0) {
      alert("Please generate the receiver's private multiplier first.");
      return;
   }

   var curve = get_curve();
   var G = get_G(curve);
   var a = new BigInteger(getN("receiversPrivateMultiplier").value);
   var P = G.multiply(a);

   getN("receiversMultipliedX").value = P.getX().toBigInteger().toString();
   getN("receiversMultipliedY").value = P.getY().toBigInteger().toString();

   /*
    ----------------------------------------------------------------------------
    Changing the receiver's multiplied point (public key) implies
    the common secret key and the encrypted message.
    are no longer valid.
    ----------------------------------------------------------------------------
    */

   getN("sendersCommonSeceretKeyX").value = "";
   getN("sendersCommonSeceretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateReceiversCommonSecretKey() {

   /*
    ----------------------------------------------------------------------------
    Check that 1) the private multipliers and
    2) the multiplied (x,y)-points
    are defined for both the sender and the receiver
    ----------------------------------------------------------------------------
    */

   if(getN("sendersPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the sender's private multiplier first.");
      return;
   }

   if(getN("receiversPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the receiver's private multiplier first.");
      return;
   }

   if(getN("sendersMultipliedX").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("sendersMultipliedY").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("receiversMultipliedX").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   if(getN("receiversMultipliedY").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   /*
    ----------------------------------------------------------------------------
    Calculate the new common secret key.
    ----------------------------------------------------------------------------
    */

   var curve = get_curve();
   var P = new ECPointFp(curve,
      curve.fromBigInteger(new BigInteger(getN("sendersMultipliedX").value)),
      curve.fromBigInteger(new BigInteger(getN("sendersMultipliedY").value)));

   var a = new BigInteger(getN("receiversPrivateMultiplier").value);
   var S = P.multiply(a);

   getN("receiversCommonSecretKeyX").value = S.getX().toBigInteger().toString();
   getN("receiversCommonSecretKeyY").value = S.getY().toBigInteger().toString();

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

/*
 ----------------------------------------------------------------------------
 Encryption
 ----------------------------------------------------------------------------
 */

function encryptMessage() {

	var messagePlainText = getN("messagePlainText").value;
	var eccP = getN("eccP").value;
	var commonSecretKeyX = getN("receiversCommonSecretKeyX").value;
	var commonSecretKeyY = getN("receiversCommonSecretKeyY").value;

	//var messageCipherText = messagePlainText.split("").reverse().join("");

	// Convert each plain text character to its unicode hex value.
	var messageCipherTextUnicodeDecimalArray = [];
	var messageCipherTextUnicodeHexArray = [];
	var i;
	for (i = 0 ; i < messagePlainText.length ; i++) {
		messageCipherTextUnicodeDecimalArray[i] = messagePlainText.charCodeAt(i);
		messageCipherTextUnicodeHexArray[i] = messageCipherTextUnicodeDecimalArray[i].toString(16);
	}
	var messageCipherTextHexString = messageCipherTextUnicodeHexArray.join("");

	// Determine the size of the message block by finding the what number of characters
	// is less than the ECC prime.
	var blockSize = 0;
	var messageBlock;
	var eccPBigInteger = new BigInteger(eccP);
	var comparisonValue;
	for (i = 1 ; i < messageCipherTextHexString.length ; i = i + 2) { // Step by two characters to get a complete 8-bit byte (an octet).
		messageBlock = new BigInteger(messageCipherTextHexString.substr(0, i),16);
		comparisonValue = messageBlock.compareTo(eccPBigInteger);
		if (messageBlock.compareTo(eccPBigInteger) >= 0) {
			blockSize = i - 2;
			break;
		}
	}

	// Short messages will be small numbers, so blockSize will still be zero
	// after going through the loop, above. In that case, make the block size
	// the message length.
	//
	// After determining the block size, encrypt the message.
	var commonSecretKeyXBigInteger = new BigInteger(commonSecretKeyX);
	var commonSecretKeyYBigInteger = new BigInteger(commonSecretKeyY);
	var cipherTextBlock = new BigInteger("0");
	var messageCipherText;

	if (blockSize == 0) {

		blockSize = messageCipherTextHexString.length;

		// Encrypt the message (when the blockSize is the same as the message length).
		messageBlock = new BigInteger(messageCipherTextHexString,16);
		cipherTextBlock = cipherTextBlock.add(commonSecretKeyXBigInteger);
		cipherTextBlock = cipherTextBlock.mod(eccPBigInteger);
		messageCipherText = cipherTextBlock.toString(16);

	} else {

		// Encrypt the message (when the blockSize is less than the message length).
		messageCipherText = "Big block message."

	}

	getN("messageCipherText").value = messageCipherText;

	// if(d.compareTo(m) >= 0) return d.subtract(m);
	// BigInteger.ONE
	// var a = new BigInteger(getN("receiversPrivateMultiplier").value);
	// curveFpEncodePointHex(p)

}

function decryptMessage() {

	var messageCipherText = getN("messageCipherText").value;
	//var decryptedMessage = messageCipherText.split("").reverse().join("");

	var eccP = getN("eccP").value;
	var commonSecretKeyX = getN("receiversCommonSecretKeyX").value;
	var commonSecretKeyY = getN("receiversCommonSecretKeyY").value;

	var eccPBigInteger = new BigInteger(eccP);
	var commonSecretKeyXBigInteger = new BigInteger(commonSecretKeyX);
	var commonSecretKeyYBigInteger = new BigInteger(commonSecretKeyY);

	// The message blocks will be separated by hyphens "-", so split the cipher text
	// at the hyphens. Then, store the number of blocks.
	var messageCipherTextBlockArray = messageCipherText.split("-");
	var numberOfBlocks = messageCipherTextBlockArray.length;

	// Decrypt each of the message blocks.
	var decryptedMessageArray = [];
	var cipherTextBlock = new BigInteger("0");
	var plainTextBlock;
	var i;
	for (i = 1 ; i < numberOfBlocks ; i++) {
		cipherTextBlock = new BigInteger(messageCipherTextBlockArray[i],16);
		cipherTextBlock = cipherTextBlock.subtract(commonSecretKeyXBigInteger);
		cipherTextBlock = cipherTextBlock.mod();

	}

	messageBlock = new BigInteger(messageCipherTextHexString,16);
	cipherTextBlock = commonSecretKeyXBigInteger.mod(eccPBigInteger);

	getN("decryptedMessage").value = decryptedMessage;

}

/*
 ----------------------------------------------------------------------------
 Other Functions
 ----------------------------------------------------------------------------
 */

function pick_rand() {

   var n = new BigInteger(getN("eccN").value);

   var n1 = n.subtract(BigInteger.ONE);

   var r = new BigInteger(n.bitLength(), rng);

   return r.mod(n1).add(BigInteger.ONE);

}

function getN(n) {

   return typeof n == 'object' ? n : document.getElementById(n);

}

<commit_msg>Reworked javascript 3.<commit_after>
/*
 ----------------------------------------------------------------------------
 Elliptic Curve Parameters
 ----------------------------------------------------------------------------
 */

var rng;

function initializeEllipticCurveParameters() {

   if (getN("eccP").value.length == 0) {
      set_secp160r1();
   }

   rng = new SecureRandom();
}

function set_ec_params(name) {
   var c = getSECCurveByName(name);

   getN("eccP").value = c.getCurve().getQ().toString();
   getN("eccA").value = c.getCurve().getA().toBigInteger().toString();
   getN("eccB").value = c.getCurve().getB().toBigInteger().toString();
   getN("eccGx").value = c.getG().getX().toBigInteger().toString();
   getN("eccGy").value = c.getG().getY().toBigInteger().toString();
   getN("eccN").value = c.getN().toString();

   // Changing EC params invalidates everything else
   getN("sendersPrivateMultiplier").value = "";
   getN("receiversPrivateMultiplier").value = "";
   getN("sendersMultipliedX").value = "";
   getN("sendersMultipliedY").value = "";
   getN("receiversMultipliedX").value = "";
   getN("receiversMultipliedY").value = "";
   getN("sendersCommonSecretKeyX").value = "";
   getN("sendersCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";
}

function set_secp128r1() {
   set_ec_params("secp128r1");
}

function set_secp160k1() {
   set_ec_params("secp160k1");
}

function set_secp160r1() {
   set_ec_params("secp160r1");
}

function set_secp192k1() {
   set_ec_params("secp192k1");
}

function set_secp192r1() {
   set_ec_params("secp192r1");
}

function set_secp224r1() {
   set_ec_params("secp224r1");
}

function set_secp256r1() {
   set_ec_params("secp256r1");
}

function get_curve() {
   return new ECCurveFp(new BigInteger(getN("eccP").value),
      new BigInteger(getN("eccA").value),
      new BigInteger(getN("eccB").value));
}

function get_G(curve) {
   return new ECPointFp(curve,
      curve.fromBigInteger(new BigInteger(getN("eccGx").value)),
      curve.fromBigInteger(new BigInteger(getN("eccGy").value)));
}

/*
 ----------------------------------------------------------------------------
 Sender's Parameters
 ----------------------------------------------------------------------------
 */

function generateSendersPrivateMultiplier() {

   var r = pick_rand();

   getN("sendersPrivateMultiplier").value = r.toString();

   /*
    ----------------------------------------------------------------------------
    Changing the sender's private multiplier implies
    the common secret key and the encrypted message.
    are no longer valid.
    ----------------------------------------------------------------------------
    */

   getN("sendersMultipliedX").value = "";
   getN("sendersMultipliedY").value = "";

   getN("sendersCommonSecretKeyX").value = "";
   getN("sendersCommonSecretKeyY").value = "";

   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateSendersMultipliedPoint() {

   if (getN("sendersPrivateMultiplier").value.length == 0) {
      alert("Please generate the sender's private multiplier first.");
      return;
   }

   var curve = get_curve();
   var G = get_G(curve);
   var a = new BigInteger(getN("sendersPrivateMultiplier").value);
   var P = G.multiply(a);

   getN("sendersMultipliedX").value = P.getX().toBigInteger().toString();
   getN("sendersMultipliedY").value = P.getY().toBigInteger().toString();

   /*
    ----------------------------------------------------------------------------
    Changing the sender's multiplied point (public key) implies
    the common secret key and the encrypted message.
    are no longer valid.
    ----------------------------------------------------------------------------
    */

   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateSendersCommonSecretKey() {

   /*
    ----------------------------------------------------------------------------
    Check that 1) the private multipliers and
    2) the multiplied (x,y)-points
    are defined for both the sender and the receiver
    ----------------------------------------------------------------------------
    */

   if(getN("sendersPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the sender's private multiplier first.");
      return;
   }

   if(getN("receiversPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the receiver's private multiplier first.");
      return;
   }

   if(getN("sendersMultipliedX").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("sendersMultipliedY").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("receiversMultipliedX").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   if(getN("receiversMultipliedY").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   /*
    ----------------------------------------------------------------------------
    Calculate the new common secret key.
    ----------------------------------------------------------------------------
    */

   var curve = get_curve();
   var P = new ECPointFp(curve,
      curve.fromBigInteger(new BigInteger(getN("receiversMultipliedX").value)),
      curve.fromBigInteger(new BigInteger(getN("receiversMultipliedY").value)));

   var a = new BigInteger(getN("sendersPrivateMultiplier").value);
   var S = P.multiply(a);

   getN("sendersCommonSecretKeyX").value = S.getX().toBigInteger().toString();
   getN("sendersCommonSecretKeyY").value = S.getY().toBigInteger().toString();

   /*
    ----------------------------------------------------------------------------
    Everything is valid except for the encrypted message.
    ----------------------------------------------------------------------------
    */

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

/*
 ----------------------------------------------------------------------------
 Receiver's Parameters
 ----------------------------------------------------------------------------
 */

function generateReceiversPrivateMultiplier() {

   var r = pick_rand();

   getN("receiversPrivateMultiplier").value = r.toString();

   /*
    ----------------------------------------------------------------------------
    Changing the receiver's private multiplier invalidates
    the sender's other values, the common secret key, and
    the encrypted message.
    ----------------------------------------------------------------------------
    */

   getN("receiversMultipliedX").value = "";
   getN("receiversMultipliedY").value = "";

   getN("sendersCommonSecretKeyX").value = "";
   getN("sendersCommonSecretKeyY").value = "";

   getN("receiversCommonSecretKeyX").value = "";
   getN("receiversCommonSecretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateReceiversMultipliedPoint() {

   if(getN("receiversPrivateMultiplier").value.length == 0) {
      alert("Please generate the receiver's private multiplier first.");
      return;
   }

   var curve = get_curve();
   var G = get_G(curve);
   var a = new BigInteger(getN("receiversPrivateMultiplier").value);
   var P = G.multiply(a);

   getN("receiversMultipliedX").value = P.getX().toBigInteger().toString();
   getN("receiversMultipliedY").value = P.getY().toBigInteger().toString();

   /*
    ----------------------------------------------------------------------------
    Changing the receiver's multiplied point (public key) implies
    the common secret key and the encrypted message.
    are no longer valid.
    ----------------------------------------------------------------------------
    */

   getN("sendersCommonSeceretKeyX").value = "";
   getN("sendersCommonSeceretKeyY").value = "";

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

function calculateReceiversCommonSecretKey() {

   /*
    ----------------------------------------------------------------------------
    Check that 1) the private multipliers and
    2) the multiplied (x,y)-points
    are defined for both the sender and the receiver
    ----------------------------------------------------------------------------
    */

   if(getN("sendersPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the sender's private multiplier first.");
      return;
   }

   if(getN("receiversPrivateMultiplier").value.length == 0) {
      alert("Please enter (or generate) the receiver's private multiplier first.");
      return;
   }

   if(getN("sendersMultipliedX").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("sendersMultipliedY").value.length == 0) {
      alert("Please calculate the sender's public key first.");
      return;
   }

   if(getN("receiversMultipliedX").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   if(getN("receiversMultipliedY").value.length == 0) {
      alert("Please calculate the receiver's public key first.");
      return;
   }

   /*
    ----------------------------------------------------------------------------
    Calculate the new common secret key.
    ----------------------------------------------------------------------------
    */

   var curve = get_curve();
   var P = new ECPointFp(curve,
      curve.fromBigInteger(new BigInteger(getN("sendersMultipliedX").value)),
      curve.fromBigInteger(new BigInteger(getN("sendersMultipliedY").value)));

   var a = new BigInteger(getN("receiversPrivateMultiplier").value);
   var S = P.multiply(a);

   getN("receiversCommonSecretKeyX").value = S.getX().toBigInteger().toString();
   getN("receiversCommonSecretKeyY").value = S.getY().toBigInteger().toString();

   getN("messageCipherText").value = "";
   getN("decryptedMessage").value = "";

}

/*
 ----------------------------------------------------------------------------
 Encryption
 ----------------------------------------------------------------------------
 */

function encryptMessage() {

	var messagePlainText = getN("messagePlainText").value;
	var eccP = getN("eccP").value;
	var commonSecretKeyX = getN("receiversCommonSecretKeyX").value;
	var commonSecretKeyY = getN("receiversCommonSecretKeyY").value;

	//var messageCipherText = messagePlainText.split("").reverse().join("");

	// Convert each plain text character to its unicode hex value.
	var messageCipherTextUnicodeDecimalArray = [];
	var messageCipherTextUnicodeHexArray = [];
	var i;
	for (i = 0 ; i < messagePlainText.length ; i++) {
		messageCipherTextUnicodeDecimalArray[i] = messagePlainText.charCodeAt(i);
		messageCipherTextUnicodeHexArray[i] = messageCipherTextUnicodeDecimalArray[i].toString(16);
	}
	var messageCipherTextHexString = messageCipherTextUnicodeHexArray.join("");

	// Determine the size of the message block by finding the what number of characters
	// is less than the ECC prime.
	var blockSize = 0;
	var messageBlock;
	var eccPBigInteger = new BigInteger(eccP);
	var comparisonValue;

	for (i = 1 ; i < messageCipherTextHexString.length ; i = i + 2) { // Step by two characters to get a complete 8-bit byte (an octet).

		messageBlock = new BigInteger(messageCipherTextHexString.substr(0, i),16);
		comparisonValue = messageBlock.compareTo(eccPBigInteger);

		if (messageBlock.compareTo(eccPBigInteger) >= 0) {
			blockSize = i - 2;
			break;
		}

	}

	// Short messages will be small numbers, so blockSize will still be zero
	// after going through the loop, above. In that case, make the block size
	// the message length.
	//
	// After determining the block size, encrypt the message.
	var commonSecretKeyXBigInteger = new BigInteger(commonSecretKeyX);
	var commonSecretKeyYBigInteger = new BigInteger(commonSecretKeyY);
	var cipherTextBlock = new BigInteger("0");
	var messageCipherText;

	if (blockSize == 0) {

		blockSize = messageCipherTextHexString.length;

		// Encrypt the message (when the blockSize is the same as the message length).
		messageBlock = new BigInteger(messageCipherTextHexString,16);
		cipherTextBlock = cipherTextBlock.add(commonSecretKeyXBigInteger);
		cipherTextBlock = cipherTextBlock.mod(eccPBigInteger);
		messageCipherText = cipherTextBlock.toString(16);

	} else {

		// Encrypt the message (when the blockSize is less than the message length).
		messageCipherText = "Big block message."

	}

	getN("messageCipherText").value = messageCipherText;

	// if(d.compareTo(m) >= 0) return d.subtract(m);
	// BigInteger.ONE
	// var a = new BigInteger(getN("receiversPrivateMultiplier").value);
	// curveFpEncodePointHex(p)

}

function decryptMessage() {

	var messageCipherText = getN("messageCipherText").value;
	//var decryptedMessage = messageCipherText.split("").reverse().join("");

	var eccP = getN("eccP").value;
	var commonSecretKeyX = getN("receiversCommonSecretKeyX").value;
	var commonSecretKeyY = getN("receiversCommonSecretKeyY").value;

	var eccPBigInteger = new BigInteger(eccP);
	var commonSecretKeyXBigInteger = new BigInteger(commonSecretKeyX);
	var commonSecretKeyYBigInteger = new BigInteger(commonSecretKeyY);

	// The message blocks will be separated by hyphens "-", so split the cipher text
	// at the hyphens. Then, store the number of blocks.
	var messageCipherTextBlockArray = messageCipherText.split("-");
	var numberOfBlocks = messageCipherTextBlockArray.length;

	// Decrypt each of the message blocks.
	var cipherTextBlock = new BigInteger("0");
	var plainTextHexBlock;
	var i;

	for (i = 0 ; i < numberOfBlocks ; i++) {

		cipherTextBlock = new BigInteger(messageCipherTextBlockArray[i],16);
		cipherTextBlock = cipherTextBlock.subtract(commonSecretKeyXBigInteger);
		cipherTextBlock = cipherTextBlock.mod(eccPBigInteger);
		plainTextHexBlock = cipherTextBlock.toString(16);

		// Each character is encoded as a hexadecimal value in the plainTextHexBlock,
		// so take the plainTextHexBlock apart 2-characters at a time, and convert
		// them to a character in the message.
		var hexCodeOfCharacter;
		var singleCharacter;
		var decryptedMessage = "";
		var j;

		for (j = 0; j < plainTextHexBlock.length; j = j + 2) {

			hexCodeOfCharacter = "0x" + plainTextHexBlock.substr(j, j+1);
			singleCharacter = String.fromCharCode(hexCodeOfCharacter);
			decryptedMessage = decryptedMessage + singleCharacter;

		}

	}

	getN("decryptedMessage").value = decryptedMessage;

}

/*
 ----------------------------------------------------------------------------
 Other Functions
 ----------------------------------------------------------------------------
 */

function pick_rand() {

   var n = new BigInteger(getN("eccN").value);

   var n1 = n.subtract(BigInteger.ONE);

   var r = new BigInteger(n.bitLength(), rng);

   return r.mod(n1).add(BigInteger.ONE);

}

function getN(n) {

   return typeof n == 'object' ? n : document.getElementById(n);

}

<|endoftext|>


<commit_before>export { ConvBiasActivation };
export { ConvBiasActivationPool };

import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Pool from "../../util/Pool.js";
import { InputsOutputs } from "./BoundsArraySet_InputsOutputs.js";

/**
 * Element value bounds (per channel) 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.
 *
 *   - Only input0 is used. The input1 always is undefined.
 *   - Only outputChannelCount0 is used. The outputChannelCount1 always is undefined.
 *
 * @member {FloatValue.BoundsArray} afterUndoPreviousActivationEscaping
 *   The element value bounds (per channel) after applying the input0.scaleArraySet.undo to this.input0. (i.e. beforeFilter)
 *
 * @member {FloatValue.BoundsArray} afterFilter
 *   The element value bounds (per channel) after applying the convolution filters to this.afterUndoPreviousActivationEscaping.
 * (i.e. beforeBias)
 *
 * @member {FloatValue.BoundsArray} afterBias
 *   The element value bounds (per channel) after applying the convolution biases to this.afterFilter. (i.e. beforeActivationEscaping)
 *
 *
 * @member {FloatValue.BoundsArray} afterActivation
 *   The element value bounds (per channel) after applying activation function to this.afterBias. It is just
 * the this.output0.boundsArray (without this.output0.scaleArraySet).
 *
 * @member {boolean[]} bPassThrough
 *   If true for a output channel, the output channel should be arranged to pass-through from input to output.
 *
 * @see InputsOutputs
 */
class ConvBiasActivation extends InputsOutputs {

  /**
   *   - The .input0 will be set as input0.
   *   - The .afterUndoPreviousActivationEscaping will be set according to  input0 and input0.scaleArraySet.undo.scales.
   *
   * Difference from (parent class) InputsOutputs:
   *   - Only input0 (always no input1), because convolution (no matter pointwise or depthwise) could handle one input tensor.
   *   - Only output0 (always no output1), because convolution (no matter pointwise or depthwise) always generate one output tensor.
   *
   */
  constructor( input0, outputChannelCount0 ) {
    super( input0, undefined, outputChannelCount0, undefined ); // .input0 and .output0
    this.set_input0_outputChannelCount0( input0, outputChannelCount0 );
  }

  /**
   *   - The .input0 will be set as input0.
   *   - The .afterUndoPreviousActivationEscaping will be set according to  input0 and input0.scaleArraySet.undo.scales.
   *
   * Difference from (parent class) InputsOutputs:
   *   - Only input0 (always no input1), because convolution (no matter pointwise or depthwise) could handle one input tensor.
   *   - Only output0 (always no output1), because convolution (no matter pointwise or depthwise) always generate one output tensor.
   *
   */
  set_input0_outputChannelCount0( input0, outputChannelCount0 ) {
    super.set_input0_input1_outputChannelCount0_outputChannelCount1( input0, undefined, outputChannelCount0, undefined ); // .input0 and .output0

    if ( this.afterUndoPreviousActivationEscaping )
      this.afterUndoPreviousActivationEscaping.length = input0.length; // channel count same as input0.
    else
      this.afterUndoPreviousActivationEscaping = new FloatValue.BoundsArray( input0.length ); // channel count same as input0.

    if ( this.afterFilter )
      this.afterFilter.length = outputChannelCount0;
    else
      this.afterFilter = new FloatValue.BoundsArray( outputChannelCount0 );

    if ( this.afterBias )
      this.afterBias.length = outputChannelCount0;
    else
      this.afterBias = new FloatValue.BoundsArray( outputChannelCount0 );

    if ( this.bPassThrough )
      this.bPassThrough.length = outputChannelCount0;
    else
      this.bPassThrough = new Array( outputChannelCount0 );

    this.set_afterUndoPreviousActivationEscaping_by_input0_undoScales();
  }

  /**
   * Set .afterUndoPreviousActivationEscaping as .input0 multiplying .input0.scaleArraySet.undo.scales.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_afterUndoPreviousActivationEscaping_by_input0_undoScales() {
    this.afterUndoPreviousActivationEscaping
      .set_all_byBoundsArray( this.input0.boundsArray )
      .multiply_all_byNs( this.input0.scaleArraySet.undo.scales );
    return this;
  }

  /**
   * @return {ConvBiasActivation}
   *   Return a newly created ConvBiasActivation which is a copy of this ConvBiasActivation. The this.inputs will just past
   * to new ConvBiasActivation (i.e. NOT copied). But the other data members will be copied.
   */
  clone() {
    let result = new ConvBiasActivation( this.input0, this.outputChannelCount0 );
    result.set_all_byBoundsArraySet( this );
    return result;
  }

  /**
   * @param {boolean} bPassThrough
   * Set this.bPassThrough[] all to bPassThrough.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_bPassThrough_all( bPassThrough ) {
    this.bPassThrough.fill( bPassThrough );
    return this;
  }

  /**
   * Set:
   *   - this.bPassThrough[] to false (i.e. all are not pass-through).
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_bPassThrough_all_none() {
    return this.set_bPassThrough_all( false );
  }

  /**
   * Set:
   *   - this.activationEscaping_ScaleArraySet to scale 1 (i.e. all are no scale).
   *   - this.bPassThrough[] to false (i.e. all are not pass-through).
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_activationEscaping_bPassThrough_all_none() {
    super.set_activationEscaping_all_none();
    this.set_bPassThrough_all_none();
    return this;
  }

  /**
   * @param {FloatValue.Bounds} aBounds
   *   Set all outputs related BoundsArray (.afterFilter, .afterBias, .output0.boundsArray (i.e. .afterActivation),
   * .bPassThrough) to the same as the specified aBounds. Set the this.output0.scaleArraySet to default ( 1 ).
   * The .input0 are not modified.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_outputs_all_byBounds( aBounds ) {
    this.afterFilter.set_all_byBounds( aBounds );
    this.afterBias.set_all_byBounds( aBounds );
    super.set_outputs_all_byBounds( aBounds ); // i.e. .output0.boundsArray (i.e. .afterActivation), .output0.scaleArraySet
    this.set_bPassThrough_all_none();
    return this;
  }

  /**
   * @param {BoundsArraySet.ConvBiasActivation} aBoundsArraySet
   *   The BoundsArraySet to be copied. The .inputs will just be referenced (NOT copied). But the other data members will be copied.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object which is copied from aBoundsArraySet.
   */
  set_all_byBoundsArraySet( aBoundsArraySet ) {

    // inputs. Non-copy. Just reference to the same inputs.
    {
      this.input0 = aBoundsArraySet.input0;

      if ( aBoundsArraySet.input1 )
        this.input1 = aBoundsArraySet.input1;
      else
        delete this.input1;
    }

    this.afterUndoPreviousActivationEscaping.set_all_byBoundsArray( aBoundsArraySet.afterUndoPreviousActivationEscaping );
    this.afterFilter                        .set_all_byBoundsArray( aBoundsArraySet.afterFilter );
    this.afterBias                          .set_all_byBoundsArray( aBoundsArraySet.afterBias );

    // .output0.boundsArray (i.e. .afterActivation), .output0.scaleArraySet, .output1.boundsArray, .output1.scaleArraySet
    super.set_outputs_all_byBoundsArraySet( aBoundsArraySet );

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

    return this;
  }

  /**
   * Determine .output0.boundsArray (i.e. .afterActivation) and .output0.scaleArraySet by .afterBias and .bPassThrough and nActivationId.
   * Also adjust .afterFilter and .afterBias by .output0.scaleArraySet.
   *
   * The following properties will be used:
   *   - this.afterBias
   *   - this.bPassThrough
   *
   * The following properties will be modified:
   *   - this.afterFilter
   *   - this.afterBias
   *   - this.output0.boundsArray (i.e. this.afterActivation)
   *   - this.output0.scaleArraySet
   *
   * @param {number} nActivationId
   *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) of this convolution.
   *
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  adjust_afterFilter_afterBias_set_output0_by_afterBias_bPassThrough_nActivationId( nActivationId ) {

    const theActivationFunctionInfo = ValueDesc.ActivationFunction.Singleton.getInfoById( nActivationId );

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

      let bPassThrough = this.bPassThrough[ outChannel ]; // For pass-through half channels.

      // 1. Determine (activationEscaping) .scaleArraySet (of .output0)
      {
        // 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.output0.scaleArraySet.do.set_one_byN( outChannel, 1 );
          doEscapingScale = 1;

        } else {

          if ( bPassThrough ) { // For channels will be activation-escaping.

            // If value bounds is [ 0, 0 ], adjust it to a range which includes zero.
            //
            // This could happen when filters are all zero for outChannel. This adjustment is necessary because the following
            // .set_one_by_fromLowerUpper_toLowerUpper() can not work for bounds [ 0, 0 ].
            //
            if ( ( this.afterBias.lowers[ outChannel ] == 0 ) && ( this.afterBias.uppers[ outChannel ] == 0 ) ) {
              this.afterBias.lowers[ outChannel ] = -1;
              this.afterBias.uppers[ outChannel ] = +1;
            }

            // 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.output0.scaleArraySet.do.set_one_by_fromLowerUpper_toLowerUpper( outChannel,
              this.afterBias.lowers[ outChannel ], this.afterBias.uppers[ outChannel ],
              theActivationFunctionInfo.inputDomainLinear.lower, theActivationFunctionInfo.inputDomainLinear.upper
            );

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

          } else { // For channels will not be activation-escaping.
            this.output0.scaleArraySet.do.set_one_byN( outChannel, 1 ); // No need to escape. (i.e. scale = 1 for no scale)
            doEscapingScale = 1;
          }
        }

        // 1.2 Determine .undo (Prepared for the next convolution-bias-activation. Not for this.)
        this.output0.scaleArraySet.undo.set_one_byUndo_N( outChannel, doEscapingScale );
      }

      // 2. Adjust .afterFilter and .afterBias
      this.afterFilter.multiply_one_byN( outChannel, doEscapingScale );
      this.afterBias.multiply_one_byN( outChannel, doEscapingScale );

      // 3. Determine .afterActivation (i.e. .output0.boundsArray)
      {
        // If no activation function, the output range is determined by adjusted .afterBias.
        if ( nActivationId == ValueDesc.ActivationFunction.Singleton.Ids.NONE ) {
          this.output0.boundsArray.set_one_byBoundsArray( outChannel, this.afterBias, outChannel );

        // Otherwise, the activation function dominates the output range.
        //
        // Note1: clamp_one_byXxx() is not feasible here because output range usually is different from input domain. set_one_byXxx()
        //        is more feasible.
        //
        // Note2: However, set_one_byXxx() is not so friendly for activation function whose output range has Infinity (e.g. RELU is
        //        [ 0, +Infinity ]). The reason is that the result's bounds becomes a bounds with Infinity which is difficult to be
        //        handled for the follow-up processing.
        } else {

          if ( bPassThrough ) { // For activation-escaping, it will be the output range for inputDomainLinear.
            this.output0.boundsArray.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRangeLinear );

          } else { // For non-activation-escaping, it will be the output range for the whole input domain.
            this.output0.boundsArray.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRange );
          }

        }
      }

    }

    return this;
  }

  /**
   * Rearrange output related channel information (.afterFilter, .afterBias, .output0.boundsArray (i.e. .afterActivation),
   * output0.scaleArraySet (i.e. activationEscaping), .bPassThrough) by interleaving as ( groupCount == 2 ). The channel
   * 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 {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_outputs_all_byInterleave_asGrouptTwo( arrayTemp ) {
    this.afterFilter.set_all_byInterleave_asGrouptTwo( arrayTemp );
    this.afterBias.set_all_byInterleave_asGrouptTwo( arrayTemp );
    super.set_outputs_all_byInterleave_asGrouptTwo( arrayTemp ); // i.e. this.afterActivation
    FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.bPassThrough, 0, this.bPassThrough.length, arrayTemp );
    return this;
  }

  get afterActivation() {
    return this.output0.boundsArray;
  }

}

/**
 * Providing ConvBiasActivation.
 *
 */
class ConvBiasActivationPool extends Pool.Root {

  constructor() {
    super( ConvBiasActivation, ConvBiasActivationPool.setAsConstructor );
  }

  /**
   * @param {ConvBiasActivation} this
   *   The ScaleBoundsArray object to be initialized.
   *
   * @return {ConvBiasActivation}
   *   Return the this object.
   */
  static setAsConstructor( input0, outputChannelCount0 ) {
    this.set_input0_outputChannelCount0( input0, outputChannelCount0 );
    return this;
  }

}

/**
 * Used as default BoundsArraySet.ConvBiasActivation provider.
 */
ConvBiasActivationPool.Singleton = new ConvBiasActivationPool();

<commit_msg>Update BoundsArraySet_ConvBiasActivation.js<commit_after>export { ConvBiasActivation };
export { ConvBiasActivationPool };

import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as Pool from "../../util/Pool.js";
import { InputsOutputs } from "./BoundsArraySet_InputsOutputs.js";

/**
 * Element value bounds (per channel) 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.
 *
 *   - Only input0 is used. The input1 always is undefined.
 *   - Only outputChannelCount0 is used. The outputChannelCount1 always is undefined.
 *
 * @member {FloatValue.BoundsArray} afterUndoPreviousActivationEscaping
 *   The element value bounds (per channel) after applying the input0.scaleArraySet.undo to this.input0. (i.e. beforeFilter)
 *
 * @member {FloatValue.BoundsArray} afterFilter
 *   The element value bounds (per channel) after applying the convolution filters to this.afterUndoPreviousActivationEscaping.
 * (i.e. beforeBias)
 *
 * @member {FloatValue.BoundsArray} afterBias
 *   The element value bounds (per channel) after applying the convolution biases to this.afterFilter. (i.e. beforeActivationEscaping)
 *
 *
 * @member {FloatValue.BoundsArray} afterActivation
 *   The element value bounds (per channel) after applying activation function to this.afterBias. It is just
 * the this.output0.boundsArray (without this.output0.scaleArraySet).
 *
 * @member {boolean[]} bPassThrough
 *   If true for a output channel, the output channel should be arranged to pass-through from input to output.
 *
 * @see InputsOutputs
 */
class ConvBiasActivation extends InputsOutputs {

  /**
   *   - The .input0 will be set as input0.
   *   - The .afterUndoPreviousActivationEscaping will be set according to  input0 and input0.scaleArraySet.undo.scales.
   *
   * Difference from (parent class) InputsOutputs:
   *   - Only input0 (always no input1), because convolution (no matter pointwise or depthwise) could handle one input tensor.
   *   - Only output0 (always no output1), because convolution (no matter pointwise or depthwise) always generate one output tensor.
   *
   */
  constructor( input0, outputChannelCount0 ) {
    super( input0, undefined, outputChannelCount0, undefined ); // .input0 and .output0
    this.set_input0_outputChannelCount0( input0, outputChannelCount0 );
  }

  /**
   *   - The .input0 will be set as input0.
   *   - The .afterUndoPreviousActivationEscaping will be set according to  input0 and input0.scaleArraySet.undo.scales.
   *
   * Difference from (parent class) InputsOutputs:
   *   - Only input0 (always no input1), because convolution (no matter pointwise or depthwise) could handle one input tensor.
   *   - Only output0 (always no output1), because convolution (no matter pointwise or depthwise) always generate one output tensor.
   *
   */
  set_input0_outputChannelCount0( input0, outputChannelCount0 ) {
    super.set_input0_input1_outputChannelCount0_outputChannelCount1( input0, undefined, outputChannelCount0, undefined ); // .input0 and .output0

    if ( this.afterUndoPreviousActivationEscaping )
      this.afterUndoPreviousActivationEscaping.length = input0.length; // channel count same as input0.
    else
      this.afterUndoPreviousActivationEscaping = new FloatValue.BoundsArray( input0.length ); // channel count same as input0.

    if ( this.afterFilter )
      this.afterFilter.length = outputChannelCount0;
    else
      this.afterFilter = new FloatValue.BoundsArray( outputChannelCount0 );

    if ( this.afterBias )
      this.afterBias.length = outputChannelCount0;
    else
      this.afterBias = new FloatValue.BoundsArray( outputChannelCount0 );

    if ( this.bPassThrough )
      this.bPassThrough.length = outputChannelCount0;
    else
      this.bPassThrough = new Array( outputChannelCount0 );

    this.set_afterUndoPreviousActivationEscaping_by_input0_undoScales();
  }

  /**
   * Set .afterUndoPreviousActivationEscaping as .input0 multiplying .input0.scaleArraySet.undo.scales.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_afterUndoPreviousActivationEscaping_by_input0_undoScales() {
    this.afterUndoPreviousActivationEscaping
      .set_all_byBoundsArray( this.input0.boundsArray )
      .multiply_all_byNs( this.input0.scaleArraySet.undo.scales );
    return this;
  }

  /**
   * @return {ConvBiasActivation}
   *   Return a newly created ConvBiasActivation which is a copy of this ConvBiasActivation. The this.inputs will just past
   * to new ConvBiasActivation (i.e. NOT copied). But the other data members will be copied.
   */
  clone() {

//!!! (2022/06/22 Remarked) Use pool instead.
//    let result = new ConvBiasActivation( this.input0, this.outputChannelCount0 );
    let result = ConvBiasActivationPool.Singleton.get_or_create_by( this.input0, this.outputChannelCount0 );
    result.set_all_byBoundsArraySet( this );
    return result;
  }

  /**
   * @param {boolean} bPassThrough
   * Set this.bPassThrough[] all to bPassThrough.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_bPassThrough_all( bPassThrough ) {
    this.bPassThrough.fill( bPassThrough );
    return this;
  }

  /**
   * Set:
   *   - this.bPassThrough[] to false (i.e. all are not pass-through).
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_bPassThrough_all_none() {
    return this.set_bPassThrough_all( false );
  }

  /**
   * Set:
   *   - this.activationEscaping_ScaleArraySet to scale 1 (i.e. all are no scale).
   *   - this.bPassThrough[] to false (i.e. all are not pass-through).
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_activationEscaping_bPassThrough_all_none() {
    super.set_activationEscaping_all_none();
    this.set_bPassThrough_all_none();
    return this;
  }

  /**
   * @param {FloatValue.Bounds} aBounds
   *   Set all outputs related BoundsArray (.afterFilter, .afterBias, .output0.boundsArray (i.e. .afterActivation),
   * .bPassThrough) to the same as the specified aBounds. Set the this.output0.scaleArraySet to default ( 1 ).
   * The .input0 are not modified.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_outputs_all_byBounds( aBounds ) {
    this.afterFilter.set_all_byBounds( aBounds );
    this.afterBias.set_all_byBounds( aBounds );
    super.set_outputs_all_byBounds( aBounds ); // i.e. .output0.boundsArray (i.e. .afterActivation), .output0.scaleArraySet
    this.set_bPassThrough_all_none();
    return this;
  }

  /**
   * @param {BoundsArraySet.ConvBiasActivation} aBoundsArraySet
   *   The BoundsArraySet to be copied. The .inputs will just be referenced (NOT copied). But the other data members will be copied.
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object which is copied from aBoundsArraySet.
   */
  set_all_byBoundsArraySet( aBoundsArraySet ) {

    // inputs. Non-copy. Just reference to the same inputs.
    {
      this.input0 = aBoundsArraySet.input0;

      if ( aBoundsArraySet.input1 )
        this.input1 = aBoundsArraySet.input1;
      else
        delete this.input1;
    }

    this.afterUndoPreviousActivationEscaping.set_all_byBoundsArray( aBoundsArraySet.afterUndoPreviousActivationEscaping );
    this.afterFilter                        .set_all_byBoundsArray( aBoundsArraySet.afterFilter );
    this.afterBias                          .set_all_byBoundsArray( aBoundsArraySet.afterBias );

    // .output0.boundsArray (i.e. .afterActivation), .output0.scaleArraySet, .output1.boundsArray, .output1.scaleArraySet
    super.set_outputs_all_byBoundsArraySet( aBoundsArraySet );

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

    return this;
  }

  /**
   * Determine .output0.boundsArray (i.e. .afterActivation) and .output0.scaleArraySet by .afterBias and .bPassThrough and nActivationId.
   * Also adjust .afterFilter and .afterBias by .output0.scaleArraySet.
   *
   * The following properties will be used:
   *   - this.afterBias
   *   - this.bPassThrough
   *
   * The following properties will be modified:
   *   - this.afterFilter
   *   - this.afterBias
   *   - this.output0.boundsArray (i.e. this.afterActivation)
   *   - this.output0.scaleArraySet
   *
   * @param {number} nActivationId
   *   The activation function id (ValueDesc.ActivationFunction.Singleton.Ids.Xxx) of this convolution.
   *
   *
   * @return {ConvBiasActivation}
   *   Return this (modified) object.
   */
  adjust_afterFilter_afterBias_set_output0_by_afterBias_bPassThrough_nActivationId( nActivationId ) {

    const theActivationFunctionInfo = ValueDesc.ActivationFunction.Singleton.getInfoById( nActivationId );

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

      let bPassThrough = this.bPassThrough[ outChannel ]; // For pass-through half channels.

      // 1. Determine (activationEscaping) .scaleArraySet (of .output0)
      {
        // 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.output0.scaleArraySet.do.set_one_byN( outChannel, 1 );
          doEscapingScale = 1;

        } else {

          if ( bPassThrough ) { // For channels will be activation-escaping.

            // If value bounds is [ 0, 0 ], adjust it to a range which includes zero.
            //
            // This could happen when filters are all zero for outChannel. This adjustment is necessary because the following
            // .set_one_by_fromLowerUpper_toLowerUpper() can not work for bounds [ 0, 0 ].
            //
            if ( ( this.afterBias.lowers[ outChannel ] == 0 ) && ( this.afterBias.uppers[ outChannel ] == 0 ) ) {
              this.afterBias.lowers[ outChannel ] = -1;
              this.afterBias.uppers[ outChannel ] = +1;
            }

            // 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.output0.scaleArraySet.do.set_one_by_fromLowerUpper_toLowerUpper( outChannel,
              this.afterBias.lowers[ outChannel ], this.afterBias.uppers[ outChannel ],
              theActivationFunctionInfo.inputDomainLinear.lower, theActivationFunctionInfo.inputDomainLinear.upper
            );

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

          } else { // For channels will not be activation-escaping.
            this.output0.scaleArraySet.do.set_one_byN( outChannel, 1 ); // No need to escape. (i.e. scale = 1 for no scale)
            doEscapingScale = 1;
          }
        }

        // 1.2 Determine .undo (Prepared for the next convolution-bias-activation. Not for this.)
        this.output0.scaleArraySet.undo.set_one_byUndo_N( outChannel, doEscapingScale );
      }

      // 2. Adjust .afterFilter and .afterBias
      this.afterFilter.multiply_one_byN( outChannel, doEscapingScale );
      this.afterBias.multiply_one_byN( outChannel, doEscapingScale );

      // 3. Determine .afterActivation (i.e. .output0.boundsArray)
      {
        // If no activation function, the output range is determined by adjusted .afterBias.
        if ( nActivationId == ValueDesc.ActivationFunction.Singleton.Ids.NONE ) {
          this.output0.boundsArray.set_one_byBoundsArray( outChannel, this.afterBias, outChannel );

        // Otherwise, the activation function dominates the output range.
        //
        // Note1: clamp_one_byXxx() is not feasible here because output range usually is different from input domain. set_one_byXxx()
        //        is more feasible.
        //
        // Note2: However, set_one_byXxx() is not so friendly for activation function whose output range has Infinity (e.g. RELU is
        //        [ 0, +Infinity ]). The reason is that the result's bounds becomes a bounds with Infinity which is difficult to be
        //        handled for the follow-up processing.
        } else {

          if ( bPassThrough ) { // For activation-escaping, it will be the output range for inputDomainLinear.
            this.output0.boundsArray.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRangeLinear );

          } else { // For non-activation-escaping, it will be the output range for the whole input domain.
            this.output0.boundsArray.set_one_byBounds( outChannel, theActivationFunctionInfo.outputRange );
          }

        }
      }

    }

    return this;
  }

  /**
   * Rearrange output related channel information (.afterFilter, .afterBias, .output0.boundsArray (i.e. .afterActivation),
   * output0.scaleArraySet (i.e. activationEscaping), .bPassThrough) by interleaving as ( groupCount == 2 ). The channel
   * 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 {ConvBiasActivation}
   *   Return this (modified) object.
   */
  set_outputs_all_byInterleave_asGrouptTwo( arrayTemp ) {
    this.afterFilter.set_all_byInterleave_asGrouptTwo( arrayTemp );
    this.afterBias.set_all_byInterleave_asGrouptTwo( arrayTemp );
    super.set_outputs_all_byInterleave_asGrouptTwo( arrayTemp ); // i.e. this.afterActivation
    FloatValue.ArrayInterleaver.interleave_asGrouptTwo( this.bPassThrough, 0, this.bPassThrough.length, arrayTemp );
    return this;
  }

  get afterActivation() {
    return this.output0.boundsArray;
  }

}

/**
 * Providing ConvBiasActivation.
 *
 */
class ConvBiasActivationPool extends Pool.Root {

  constructor() {
    super( ConvBiasActivation, ConvBiasActivationPool.setAsConstructor );
  }

  /**
   * @param {ConvBiasActivation} this
   *   The ScaleBoundsArray object to be initialized.
   *
   * @return {ConvBiasActivation}
   *   Return the this object.
   */
  static setAsConstructor( input0, outputChannelCount0 ) {
    this.set_input0_outputChannelCount0( input0, outputChannelCount0 );
    return this;
  }

}

/**
 * Used as default BoundsArraySet.ConvBiasActivation provider.
 */
ConvBiasActivationPool.Singleton = new ConvBiasActivationPool();

<|endoftext|>


<commit_before>import _ from 'lodash/fp';

import {
  GET_CLAIM_DETAIL,
  SET_CLAIM_DETAIL,
} from '../actions';

const initialState = {
  detail: null,
  loading: true
};

export default function claimDetailReducer(state = initialState, action) {
  switch (action.type) {
    case SET_CLAIM_DETAIL: {
      return _.merge(state, {
        detail: action.claim,
        loading: false
      });
    }
    case GET_CLAIM_DETAIL: {
      return _.set('loading', true, state);
    }
    default:
      return state;
  }
}
<commit_msg>Assign claim details to state (#3839)<commit_after>import _ from 'lodash/fp';

import {
  GET_CLAIM_DETAIL,
  SET_CLAIM_DETAIL,
} from '../actions';

const initialState = {
  detail: null,
  loading: true
};

export default function claimDetailReducer(state = initialState, action) {
  switch (action.type) {
    case SET_CLAIM_DETAIL: {
      return _.assign(state, {
        detail: action.claim,
        loading: false
      });
    }
    case GET_CLAIM_DETAIL: {
      return _.set('loading', true, state);
    }
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>function onSearchFormSubmit() {
  var searchValue = $("searchValue");

  var url = (ApplicationBaseURL
	     + "/foldersSearch?ldap-only=YES&search=" + escape(searchValue.value)
	     + "&type=" + window.opener.userFolderType);
  if (document.userFoldersRequest) {
     document.userFoldersRequest.aborted = true;
     document.userFoldersRequest.abort();
  }
  document.userFoldersRequest
     = triggerAjaxRequest(url, userFoldersCallback);

  return false;
}

function addLineToTree(tree, parent, line) {
   var offset = 0;

   var nodes = line.split(";");
   if (window.opener.userFolderType == "user"
       || nodes.length > 1) {
      var parentNode = nodes[0];
      var userInfos = parentNode.split(":");
      var email = userInfos[1] + " <" + userInfos[2] + ">";
      tree.add(parent, 0, email, 0, '#', userInfos[0], 'person',
	       '', '',
	       ResourcesURL + '/abcard.gif',
	       ResourcesURL + '/abcard.gif');
      for (var i = 1; i < nodes.length; i++) {
	 var folderInfos = nodes[i].split(":");
	 var icon = ResourcesURL + '/';
	 if (folderInfos[2] == 'contact')
	    icon += 'tb-mail-addressbook-flat-16x16.png';
	 else
	    icon += 'calendar-folder-16x16.png';
	 var folderId = userInfos[0] + ":" + folderInfos[1];
	 tree.add(parent + i, parent, folderInfos[0], 0, '#', folderId,
		  folderInfos[2] + '-folder', '', '', icon, icon);
      }
      offset = nodes.length - 1;
   }
   else
      window.alert("nope:" + window.opener.userFolderType);

   return offset;
}

function buildTree(response) {
   d = new dTree("d");
   d.config.folderLlinks = true;
   d.config.hideRoot = true;
   d.icon.root = ResourcesURL + '/tbtv_account_17x17.gif';
   d.icon.folder = ResourcesURL + '/tbtv_leaf_corner_17x17.gif';
   d.icon.folderOpen = ResourcesURL + '/tbtv_leaf_corner_17x17.gif';
   d.icon.node = ResourcesURL + '/tbtv_leaf_corner_17x17.gif';
   d.icon.line = ResourcesURL + '/tbtv_line_17x17.gif';
   d.icon.join = ResourcesURL + '/tbtv_junction_17x17.gif';
   d.icon.joinBottom = ResourcesURL + '/tbtv_corner_17x17.gif';
   d.icon.plus = ResourcesURL + '/tbtv_plus_17x17.gif';
   d.icon.plusBottom = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
   d.icon.minus = ResourcesURL + '/tbtv_minus_17x17.gif';
   d.icon.minusBottom = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
   d.icon.nlPlus = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
   d.icon.nlMinus = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
   d.icon.empty = ResourcesURL + '/empty.gif';
   d.add(0, -1, '');

   var lines = response.split("\n");
   var offset = 0;
   for (var i = 0; i < lines.length; i++) {
      if (lines[i].length > 0)
	 offset += addLineToTree(d, i + 1 + offset, lines[i]);
   }

   return d;
}

function onFolderTreeItemClick(event) {
   preventDefault(event);

   var topNode = $("d");
   if (topNode.selectedEntry)
      topNode.selectedEntry.deselect();
   this.select();
   topNode.selectedEntry = this;
}

function userFoldersCallback(http) {
   if (http.readyState == 4) {
      document.userFoldersRequest = null;
      var div = $("folders");
      if (http.status == 200) {
	 var response = http.responseText;
	 div.innerHTML = buildTree(http.responseText);
	 var nodes = document.getElementsByClassName("node", $("d"));
	 for (i = 0; i < nodes.length; i++)
	   Event.observe(nodes[i], "click", onFolderTreeItemClick.bindAsEventListener(nodes[i]));
      }
      else if (http.status == 404) {
	 div.innerHTML = "";
      }
   }
}

function onConfirmFolderSelection(event) {
  var topNode = $("d");
  if (topNode && topNode.selectedEntry) {
      var node = topNode.selectedEntry.parentNode;
      var folder = node.getAttribute("dataname");
      var folderName;
      if (window.opener.userFolderType == "user") {
	 var spans = document.getElementsByClassName("nodeName",
						     topNode.selectedEntry);
	 var email = spans[0].innerHTML;
	 email = email.replace("<", "<");
	 email = email.replace(">", ">");
	 folderName = email;
      }
      else {
	 var spans1 = document.getElementsByClassName("nodeName",
						   node);
	 var spans2 = document.getElementsByClassName("nodeName",
						      node.parentNode.previousSibling);
	 var email = spans2[0].innerHTML;
	 email = email.replace("<", "<");
	 email = email.replace(">", ">");
	 folderName = spans1[0].innerHTML + ' (' + email + ')';
      }
      var data = { folderName: folderName, folder: folder, window: window };
      window.opener.subscribeToFolder(window.opener.userFolderCallback, data);
   }
}

function initUserFoldersWindow() {
   configureSearchField();
   Event.observe($("addButton"), "click",  onConfirmFolderSelection);
}

addEvent(window, 'load', initUserFoldersWindow);
<commit_msg><commit_after>function onSearchFormSubmit() {
  var searchValue = $("searchValue");

  var url = (ApplicationBaseURL
	     + "/foldersSearch?ldap-only=YES&search=" + escape(searchValue.value)
	     + "&type=" + window.opener.userFolderType);
  if (document.userFoldersRequest) {
     document.userFoldersRequest.aborted = true;
     document.userFoldersRequest.abort();
  }
  document.userFoldersRequest
     = triggerAjaxRequest(url, userFoldersCallback);

  return false;
}

function addLineToTree(tree, parent, line) {
   var offset = 0;

   var nodes = line.split(";");
   if (window.opener.userFolderType == "user"
       || nodes.length > 1) {
      var parentNode = nodes[0];
      var userInfos = parentNode.split(":");
      var email = userInfos[1] + " <" + userInfos[2] + ">";
      tree.add(parent, 0, email, 0, '#', userInfos[0], 'person',
	       '', '',
	       ResourcesURL + '/abcard.gif',
	       ResourcesURL + '/abcard.gif');
      for (var i = 1; i < nodes.length; i++) {
	 var folderInfos = nodes[i].split(":");
	 var icon = ResourcesURL + '/';
	 if (folderInfos[2] == 'contact')
	    icon += 'tb-mail-addressbook-flat-16x16.png';
	 else
	    icon += 'calendar-folder-16x16.png';
	 var folderId = userInfos[0] + ":" + folderInfos[1];
	 tree.add(parent + i, parent, folderInfos[0], 0, '#', folderId,
		  folderInfos[2] + '-folder', '', '', icon, icon);
      }
      offset = nodes.length - 1;
   }
//    else
//       window.alert("nope:" + window.opener.userFolderType);

   return offset;
}

function buildTree(response) {
   d = new dTree("d");
   d.config.folderLlinks = true;
   d.config.hideRoot = true;
   d.icon.root = ResourcesURL + '/tbtv_account_17x17.gif';
   d.icon.folder = ResourcesURL + '/tbtv_leaf_corner_17x17.gif';
   d.icon.folderOpen = ResourcesURL + '/tbtv_leaf_corner_17x17.gif';
   d.icon.node = ResourcesURL + '/tbtv_leaf_corner_17x17.gif';
   d.icon.line = ResourcesURL + '/tbtv_line_17x17.gif';
   d.icon.join = ResourcesURL + '/tbtv_junction_17x17.gif';
   d.icon.joinBottom = ResourcesURL + '/tbtv_corner_17x17.gif';
   d.icon.plus = ResourcesURL + '/tbtv_plus_17x17.gif';
   d.icon.plusBottom = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
   d.icon.minus = ResourcesURL + '/tbtv_minus_17x17.gif';
   d.icon.minusBottom = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
   d.icon.nlPlus = ResourcesURL + '/tbtv_corner_plus_17x17.gif';
   d.icon.nlMinus = ResourcesURL + '/tbtv_corner_minus_17x17.gif';
   d.icon.empty = ResourcesURL + '/empty.gif';
   d.add(0, -1, '');

   var lines = response.split("\n");
   var offset = 0;
   for (var i = 0; i < lines.length; i++) {
      if (lines[i].length > 0)
	 offset += addLineToTree(d, i + 1 + offset, lines[i]);
   }

   return d;
}

function onFolderTreeItemClick(event) {
   preventDefault(event);

   var topNode = $("d");
   if (topNode.selectedEntry)
      topNode.selectedEntry.deselect();
   this.select();
   topNode.selectedEntry = this;
}

function userFoldersCallback(http) {
   if (http.readyState == 4) {
      document.userFoldersRequest = null;
      var div = $("folders");
      if (http.status == 200) {
	 var response = http.responseText;
	 div.innerHTML = buildTree(http.responseText);
	 var nodes = document.getElementsByClassName("node", $("d"));
	 for (i = 0; i < nodes.length; i++)
	   Event.observe(nodes[i], "click", onFolderTreeItemClick.bindAsEventListener(nodes[i]));
      }
      else if (http.status == 404) {
	 div.innerHTML = "";
      }
   }
}

function onConfirmFolderSelection(event) {
  var topNode = $("d");
  if (topNode && topNode.selectedEntry) {
      var node = topNode.selectedEntry.parentNode;
      var folder = node.getAttribute("dataname");
      var folderName;
      if (window.opener.userFolderType == "user") {
	 var spans = document.getElementsByClassName("nodeName",
						     topNode.selectedEntry);
	 var email = spans[0].innerHTML;
	 email = email.replace("<", "<");
	 email = email.replace(">", ">");
	 folderName = email;
      }
      else {
	 var spans1 = document.getElementsByClassName("nodeName",
						   node);
	 var spans2 = document.getElementsByClassName("nodeName",
						      node.parentNode.previousSibling);
	 var email = spans2[0].innerHTML;
	 email = email.replace("<", "<");
	 email = email.replace(">", ">");
	 folderName = spans1[0].innerHTML + ' (' + email + ')';
      }
      var data = { folderName: folderName, folder: folder, window: window };
      window.opener.subscribeToFolder(window.opener.userFolderCallback, data);
   }
}

function initUserFoldersWindow() {
   configureSearchField();
   Event.observe($("addButton"), "click",  onConfirmFolderSelection);
}

addEvent(window, 'load', initUserFoldersWindow);
<|endoftext|>