<commit_before>if (!lib) {
   var lib = {}
}

lib.ajax = {}

// This is the default error handler
lib.ajax.errorFunc = function(ErrMsg){
   $('body').html("Default error handler:" + ErrMsg);
}

lib.ajax.call = function(CallName, SuccessFunc){
   console.log(CallName);
   var Url = CallName;
   $.ajax({
       url : Url,
       success : function (Data) {
          if (Data.error){
             lib.ajax.errorFunc(Data.error);
             return;
          } else {
            SuccessFunc(Data);
          }
       },
       error : function(jqXHR, textStatus, errorThrown){
           lib.ajax.errorFunc("Call: '" + CallName + "' failed. " + textStatus + " " + errorThrown);
       }
   });
}

<commit_msg>Update ajax.js<commit_after>if (!lib) {
   var lib = {}
}

lib.ajax = {}

// This is the default error handler
lib.ajax.errorFunc = function(ErrMsg){
   $('body').html("Default error handler:" + ErrMsg);
}

// Have to figure out with Bret if we should change this to use HTTP error codes rather than inspecting the
// JSON payload - it would be a change in this and in lib.webserver
lib.ajax.call = function(CallName, SuccessFunc){
   console.log(CallName);
   var Url = CallName;
   $.ajax({
       url : Url,
       success : function (Data) {
          if (Data.error){
             lib.ajax.errorFunc(Data.error);
             return;
          } else {
            SuccessFunc(Data);
          }
       },
       error : function(jqXHR, textStatus, errorThrown){
           lib.ajax.errorFunc("Call: '" + CallName + "' failed. " + textStatus + " " + errorThrown);
       }
   });
}

<|endoftext|>


<commit_before>type listItemProps = {
  index: number,
  style: Object,
  data: {
    item: Array<{
      label: string,
      id: string,
      summary: string,
    }>,
  },
  cartItems: Array<Object>,
  removeItem: Function,
}

export { listItemProps }
<commit_msg>refactor: move export line<commit_after>export type listItemProps = {
  index: number,
  style: Object,
  data: {
    item: Array<{
      label: string,
      id: string,
      summary: string,
    }>,
  },
  cartItems: Array<Object>,
  removeItem: Function,
}
<|endoftext|>


<commit_before>function NodeList() {

}

NodeList.prototype.addCtrlSpaceAndArrows = function(search, clearingEvents, listElements, updateSelection) {
    for (var i = 0; i < listElements.length; i++) {
        listElements[i].visible = true;
        listElements[i].prev = (i > 0) ? listElements[i - 1] : listElements[listElements.length - 1];
        listElements[i].next = (i < listElements.length - 1) ? listElements[i + 1] : listElements[0];
    }

    // ctrl+space should focus on the search field and up/down arrows should
    // work for selection
    Kefir.merge([
            Kefir.fromEvents(document.body, 'keyup')
                 .filter(function(evt) {
                     // control / alt / cmd + space
                     return (evt.which == 32 || evt.keyCode == 32) && (evt.altKey || evt.metaKey || evt.ctrlKey);
                 }),
            Kefir.fromEvents(search.node(), 'click')
        ]).flatMap(function(switchedOn) {
             console.log('start!'); search.node().focus();
             if (listElements.length > 0) updateSelection(listElements[0]);
             return Kefir.fromEvents(document.body, 'keyup')
                         .map(function(evt) { return evt.which || evt.keyCode; })
                         .filter(function(key) { return (key === 38) || (key === 40); })
                         .map(function(key) { return (key === 38) ? 'up' : 'down'; })
                         .takeUntilBy(Kefir.merge([
                                          Kefir.fromEvents(document.body, 'keyup')
                                               .filter(function(evt) {
                                                   return (evt.which == 13 || evt.keyCode == 13); // key == enter
                                               }).map(function() { return true; }),
                                          Kefir.fromEvents(document.body, 'keyup').filter(function(evt) {
                                              return (evt.which == 27 || evt.keyCode == 27); // key === escape
                                          }).map(function() { return false; }),
                                          Kefir.fromEvents(document.body, 'click').filter(function(evt) {
                                              return evt.target !== search.node();
                                          }).map(function() { return false; }),
                                          clearingEvents.map(function() { return false; })/*,
                                          Kefir.fromEvents(search.node(), 'click')*/
                                      ]).take(1).onValue(function(doAdd) {
                                          if (doAdd && selected) {
                                              console.log('enter', 'add', selected.def.fullName);
                                          }
                                          console.log('clear selection');
                                          search.node().blur();
                                          updateSelection(null);
                                      }))
                         .onValue(function(key) {
                             if (currentlyVisible == 0) return;
                             search.node().blur();
                             if (key === 'up') {
                                 var current = selected ? selected.prev : listElements[listElements.length - 1];
                                 while (current && !current.visible) {
                                     current = current.prev;
                                 }
                             } else if (key === 'down') {
                                 var current = selected ? selected.next : listElements[0];
                                 while (current && !current.visible) {
                                     current = current.next;
                                 }
                             }
                             console.log('select', current ? current.def.fullName : 'NONE');
                             if (current) updateSelection(current);
                         });
         }).onValue(function() {});
}
<commit_msg>improving selection logic for node list, p.7 (#321)<commit_after>function NodeList(conf) {
    this.listElements = [];

    this.selected = null;

    this.searchInput = conf.createSearchInput();
    this.clearSearchButton = conf.createClearSearchButton();
}

NodeList.prototype.addCtrlSpaceAndArrows = function(search, clearingEvents, listElements, updateSelection) {
    for (var i = 0; i < listElements.length; i++) {
        listElements[i].visible = true;
        listElements[i].prev = (i > 0) ? listElements[i - 1] : listElements[listElements.length - 1];
        listElements[i].next = (i < listElements.length - 1) ? listElements[i + 1] : listElements[0];
    }

    // ctrl+space should focus on the search field and up/down arrows should
    // work for selection
    Kefir.merge([
            Kefir.fromEvents(document.body, 'keyup')
                 .filter(function(evt) {
                     // control / alt / cmd + space
                     return (evt.which == 32 || evt.keyCode == 32) && (evt.altKey || evt.metaKey || evt.ctrlKey);
                 }),
            Kefir.fromEvents(search.node(), 'click')
        ]).flatMap(function(switchedOn) {
             console.log('start!'); search.node().focus();
             if (listElements.length > 0) updateSelection(listElements[0]);
             return Kefir.fromEvents(document.body, 'keyup')
                         .map(function(evt) { return evt.which || evt.keyCode; })
                         .filter(function(key) { return (key === 38) || (key === 40); })
                         .map(function(key) { return (key === 38) ? 'up' : 'down'; })
                         .takeUntilBy(Kefir.merge([
                                          Kefir.fromEvents(document.body, 'keyup')
                                               .filter(function(evt) {
                                                   return (evt.which == 13 || evt.keyCode == 13); // key == enter
                                               }).map(function() { return true; }),
                                          Kefir.fromEvents(document.body, 'keyup').filter(function(evt) {
                                              return (evt.which == 27 || evt.keyCode == 27); // key === escape
                                          }).map(function() { return false; }),
                                          Kefir.fromEvents(document.body, 'click').filter(function(evt) {
                                              return evt.target !== search.node();
                                          }).map(function() { return false; }),
                                          clearingEvents.map(function() { return false; })/*,
                                          Kefir.fromEvents(search.node(), 'click')*/
                                      ]).take(1).onValue(function(doAdd) {
                                          if (doAdd && selected) {
                                              console.log('enter', 'add', selected.def.fullName);
                                          }
                                          console.log('clear selection');
                                          search.node().blur();
                                          updateSelection(null);
                                      }))
                         .onValue(function(key) {
                             if (currentlyVisible == 0) return;
                             search.node().blur();
                             if (key === 'up') {
                                 var current = selected ? selected.prev : listElements[listElements.length - 1];
                                 while (current && !current.visible) {
                                     current = current.prev;
                                 }
                             } else if (key === 'down') {
                                 var current = selected ? selected.next : listElements[0];
                                 while (current && !current.visible) {
                                     current = current.next;
                                 }
                             }
                             console.log('select', current ? current.def.fullName : 'NONE');
                             if (current) updateSelection(current);
                         });
         }).onValue(function() {});
}
<|endoftext|>


<commit_before>export { ConvBiasActivation };

import * as Pool from "../../util/Pool.js";
import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.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 {

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

  /**
   *   - 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
    ConvBiasActivation.setAsConstructor_self.call( this, input0, outputChannelCount0 );
  }

  /** @override */
  static setAsConstructor( input0, outputChannelCount0 ) {
    super.setAsConstructor( input0, undefined, outputChannelCount0, undefined );
    ConvBiasActivation.setAsConstructor_self.call( this, input0, outputChannelCount0 );
    return this;
  }

  /** @override */
  static setAsConstructor_self( input0, outputChannelCount0 ) {

    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;
  }

  /**
   * Sub-class should override this method (and call super.disposeResources() before return).
   *
   * @override
   */
  disposeResources() {

    // For reducing memory re-allocation when this BoundsArraySet is recycled and re-issued, the .afterUndoPreviousActivationEscaping,
    // .afterFilter, .afterBias, .bPassThrough are not disposed by here.

    super.disposeResources();
  }

  /**
   * @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 = ConvBiasActivation.Pool.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 {
        if ( this.input1 )
          this.input1 = undefined;
      }
    }

    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 ];
            if ( Number.isNaN( doEscapingScale ) == true )
              throw Error( `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;
  }

}

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

import * as Pool from "../../util/Pool.js";
import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.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 {

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

  /**
   *   - 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
    ConvBiasActivation.setAsConstructor_self.call( this, input0, outputChannelCount0 );
  }

  /** @override */
  static setAsConstructor( input0, outputChannelCount0 ) {
    super.setAsConstructor( input0, undefined, outputChannelCount0, undefined );
    ConvBiasActivation.setAsConstructor_self.call( this, input0, outputChannelCount0 );
    return this;
  }

  /** @override */
  static setAsConstructor_self( input0, outputChannelCount0 ) {

    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;
  }

  /**
   * Sub-class should override this method (and call super.disposeResources() before return).
   *
   * @override
   */
  disposeResources() {

    // For reducing memory re-allocation when this BoundsArraySet is recycled and re-issued, the .afterUndoPreviousActivationEscaping,
    // .afterFilter, .afterBias, .bPassThrough are not disposed by here.

    super.disposeResources();
  }

  /**
   * @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 = ConvBiasActivation.Pool.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 {
        if ( this.input1 )
          this.input1 = undefined;
      }
    }

    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 ];
            if ( Number.isNaN( doEscapingScale ) == true )
              throw Error( `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 );

!!! ...unfinished... (2022/07/07)
// seems it is necessary to use clamp_one_byXxx() instead of set_one_byBounds().
// Otherwise, squeeze-and-excitation when pass-through (constant 1 when pass through) will generate +-3 instead 1.

        // 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;
  }

}

<|endoftext|>


<commit_before>import LTT from 'list-to-tree';
import {
  filter,
  find,
  flatten,
  includes,
  isEmpty,
  map,
  orderBy
} from 'lodash';

export function convertToTree (itemList) {
  // ------------------------------------
  // Combine navigation number and names
  // and
  // Give each item in the navigation a level specific id for sorting
  // ------------------------------------
  itemList.results.map(item => {
    item.name = item.function_id + ' ' + item.name;
    item.sort_id = item.function_id.substring(item.function_id.length - 2, item.function_id.length);
    item.path = [];
  });
  const ltt = new LTT(itemList.results, {
    key_id: 'id',
    key_parent: 'parent',
    key_child: 'children'
  });
  const unOrderedTree = ltt.GetTree();
  // ------------------------------------
  // Sort the tree, as ltt doesnt automatically do it
  // ------------------------------------
  const sortTree = tree => {
    tree = orderBy(tree, ['sort_id'], 'asc');
    return tree.map(item => {
      if (item.children !== undefined) {
        // ------------------------------------
        // Generate path to show when navigation is minimized and TOS is shown
        // ------------------------------------
        item.path.push(item.name);
        item.children.map(child => {
          item.path.map(path => child.path.push(path));
        });
        item.children = orderBy(item.children, ['sort_id'], 'asc');
        sortTree(item.children);
      }
      return item;
    });
  };
  return sortTree(unOrderedTree);
}

/**
 * Normalize tos for API
 * @param tos
 * @returns {*}
 */
export function normalizeTosForApi (tos) {
  // TODO: needs some serious refactoring...
  const phases = Object.keys(tos.phases).map(phase => tos.phases[phase]);
  phases.map(phase => phase.actions.map((action, actionIndex) => {
    delete phase.actions[actionIndex];
    phase.actions[actionIndex] = tos.actions[action];
    phase.actions[actionIndex].records.map((record, recordsIndex) => {
      delete phase.actions[actionIndex].records[recordsIndex];
      phase.actions[actionIndex].records[recordsIndex] = tos.records[record];
    });
  }));

  delete tos.actions;
  delete tos.records;
  tos.phases = phases;
  return tos;
}

/**
 * Find item by id (nested array with `children`-key)
 * @param items
 * @param id
 * @returns {*}
 */
export function itemById (items, id) {
  let searchResult = find(items, (item) => (item.id === id));

  if (!searchResult) {
    let filteredItems = filter(items, (item) => (item.children));
    let subset = flatten(map(filteredItems, (item) => (item.children)));

    if (subset.length !== 0) {
      return itemById(subset, id);
    }
    return null;
  }
  return searchResult;
}

/**
 * Centered PopUp-Window
 * @param url
 * @param title
 * @param w
 * @param h
 * @returns {Window}
 */
export function centeredPopUp (url, title, w, h) {
  const left = (screen.width / 2) - (w / 2);
  const top = (screen.height / 2) - (h / 2);
  return window.open(
    url,
    title,
    `
    toolbar=no,
    location=no,
    directories=no,
    status=no, menubar=no,
    scrollbars=no,
    resizable=no,
    copyhistory=no,
    width=${w}, height=${h}, top=${top}, left=${left}
  `);
}

/**
 * Check for user permissions
 * @param user
 * @param permission
 * @returns {*}
 */
export function checkPermissions (user, permission) {
  return !isEmpty(user) && includes(user.permissions, permission);
}
<commit_msg>Don’t mutate tos on normalizeTosForApi<commit_after>import LTT from 'list-to-tree';
import {
  filter,
  find,
  flatten,
  includes,
  isEmpty,
  map,
  orderBy
} from 'lodash';

export function convertToTree (itemList) {
  // ------------------------------------
  // Combine navigation number and names
  // and
  // Give each item in the navigation a level specific id for sorting
  // ------------------------------------
  itemList.results.map(item => {
    item.name = item.function_id + ' ' + item.name;
    item.sort_id = item.function_id.substring(item.function_id.length - 2, item.function_id.length);
    item.path = [];
  });
  const ltt = new LTT(itemList.results, {
    key_id: 'id',
    key_parent: 'parent',
    key_child: 'children'
  });
  const unOrderedTree = ltt.GetTree();
  // ------------------------------------
  // Sort the tree, as ltt doesnt automatically do it
  // ------------------------------------
  const sortTree = tree => {
    tree = orderBy(tree, ['sort_id'], 'asc');
    return tree.map(item => {
      if (item.children !== undefined) {
        // ------------------------------------
        // Generate path to show when navigation is minimized and TOS is shown
        // ------------------------------------
        item.path.push(item.name);
        item.children.map(child => {
          item.path.map(path => child.path.push(path));
        });
        item.children = orderBy(item.children, ['sort_id'], 'asc');
        sortTree(item.children);
      }
      return item;
    });
  };
  return sortTree(unOrderedTree);
}

/**
 * Normalize tos for API
 * @param tos
 * @returns {*}
 */
export function normalizeTosForApi (tos) {
  // TODO: needs some serious refactoring...
  const finalTos = Object.assign({}, tos);
  const phases = Object.keys(finalTos.phases).map(phase => finalTos.phases[phase]);
  phases.map(phase => phase.actions.map((action, actionIndex) => {
    delete phase.actions[actionIndex];
    phase.actions[actionIndex] = finalTos.actions[action];
    phase.actions[actionIndex].records.map((record, recordsIndex) => {
      delete phase.actions[actionIndex].records[recordsIndex];
      phase.actions[actionIndex].records[recordsIndex] = finalTos.records[record];
    });
  }));

  delete finalTos.actions;
  delete finalTos.records;
  finalTos.phases = phases;
  return finalTos;
}

/**
 * Find item by id (nested array with `children`-key)
 * @param items
 * @param id
 * @returns {*}
 */
export function itemById (items, id) {
  let searchResult = find(items, (item) => (item.id === id));

  if (!searchResult) {
    let filteredItems = filter(items, (item) => (item.children));
    let subset = flatten(map(filteredItems, (item) => (item.children)));

    if (subset.length !== 0) {
      return itemById(subset, id);
    }
    return null;
  }
  return searchResult;
}

/**
 * Centered PopUp-Window
 * @param url
 * @param title
 * @param w
 * @param h
 * @returns {Window}
 */
export function centeredPopUp (url, title, w, h) {
  const left = (screen.width / 2) - (w / 2);
  const top = (screen.height / 2) - (h / 2);
  return window.open(
    url,
    title,
    `
    toolbar=no,
    location=no,
    directories=no,
    status=no, menubar=no,
    scrollbars=no,
    resizable=no,
    copyhistory=no,
    width=${w}, height=${h}, top=${top}, left=${left}
  `);
}

/**
 * Check for user permissions
 * @param user
 * @param permission
 * @returns {*}
 */
export function checkPermissions (user, permission) {
  return !isEmpty(user) && includes(user.permissions, permission);
}
<|endoftext|>


<commit_before>/* jshint node: true */

require('node-jsx').install();

module.exports = require('./flocks.jsx');
<commit_msg>the extension too<commit_after>/* jshint node: true */

require('node-jsx').install({extension: '.jsx'});

module.exports = require('./flocks.jsx');
<|endoftext|>


<commit_before>/** @jsx React.DOM*/

var React = require('react');
var Router = require('react-router-component');
var NavLink =require('./NavLink');
var AccountStore = require("../stores/AccountStore");
var AccountActions = require('../actions/AccountActions');

var Header = React.createClass({displayName: 'Header',
    mixins:[Router.NavigatableMixin],

    handleLogout:function(){
        AccountActions.logOut();
    },
    onChange:function(){
        var accountState = AccountStore.getState();
        if (!accountState.Error) {
            this.navigate("/Login");
            return;
        }
    },
    componentDidMount:function(){
        AccountStore.addChangeListner(this.onChange);
    },
    componentWillUnmount:function(){
        AccountStore.removeChangeListner(this.onChange);
    },
    render: function () {

        var cursorStyle ={
            cursor:"pointer"
        };

        return (React.DOM.div( {className:"ui small inverted menu"},
        NavLink( {value:"Home", href:"/Home"} ),
        NavLink( {value:"Resources", href:"/Resources"} ),
        NavLink( {value:"Locations", href:"/Locations"} ),
        NavLink( {value:"About", href:"/About"} ),
        React.DOM.div( {style:cursorStyle, className:"right menu"},
            React.DOM.a( {className:"item", onClick:this.handleLogout}, "Logout")
        )
    ));
    }
});

module.exports = Header;<commit_msg>Delete Header.js<commit_after><|endoftext|>


<commit_before>var replayContext;
const tileDepth = 0.78;
const tileWidth = 0.97;
const tileHeight = 1.28;
const gap = 0.2;

function initReplay() {
    replayContext = new RenderContext("replayCanvas");
    replayContext.setCameraPosition(0, -21, 31);
    replayCreateLights();

    replayContext.createTiles(() => arrange());
}

function arrange() {
    const input = document.querySelector("#gameDataJson");
    const json = input.value;
    const data = JSON.parse(json);
    const wall = data.slice(0, 136);
    const dice = data.slice(136, 138);

    createWall(wall, dice, 0);
    createPond();
    createHands();
}

function createWall(wall, dice, oyaId) {
    const layoutOffset = -(17 * tileWidth + tileHeight + gap) / 2;

    const diceSum = dice[0] + dice[1];
    const wallOffset = 142 - (((19 - diceSum - oyaId) * 34 + diceSum * 2) % 136);

    var wallId = 0;

    for (let i = 0; i < 4; i++) {
        let x = layoutOffset + 0.5 * tileWidth + tileHeight + gap;
        const y = layoutOffset + 0.5 * tileHeight;
        for (let j = 0; j < 17; j++) {
            for (let k = 0; k < 2; k++) {
                const shiftedId = (wallId + wallOffset) % 136;
                if (shiftedId === 0) {
                    x += gap;
                }
                const tileId = wall[shiftedId];
                addTile(i, tileId, x, y, k * tileDepth, shiftedId === 5 ? 0 : 2, 0);
                wallId += 1;
                if (shiftedId === 13) {
                    x += gap;
                }
            }
            x += tileWidth;
        }
    }
}

function createMeld(playerId, x, tileIds) {
    const b = -(11 * tileWidth);
    const y = b - 0.5 * tileHeight;
    for (let i = 0; i < tileIds.length; i++) {
        const tileId = tileIds[i];
        if (tileIds.length === 4 && i === 0) {
            addTile(playerId, tileId, x, y, 0, 2, 0);
            x -= tileWidth;
        } else if (tileIds.length === 4 && i === 3) {
            addTile(playerId, tileId, x, y, 0, 0, 1);
            x -= tileHeight;
        } else {
            addTile(playerId, tileId, x, y, 0, 0, 0);
            x -= tileWidth;
        }
    }
    return x;
}

function createHands() {
    const a = -(14 * tileWidth + gap) / 2;
    const b = -(11 * tileWidth);
    const y = b - 0.5 * tileHeight;
    var tileId = 0;
    for (let i = 0; i < 4; i++) {
        let x = a + 0.5 * tileWidth - tileWidth;
        let meldX = -a + 4 * tileWidth;
        const tilesInHand = 2;
        for (let k = 0; k < tilesInHand; k++) {
            addTile(i, tileId, x, y, 0, i === 0 ? -0.40 : 3, 0);
            tileId += 1;
            if (k === tilesInHand - 2 && tilesInHand % 3 === 2) {
                x += gap;
            }
            x += tileWidth;
        }

        const meldCount = Math.floor((14 - tilesInHand) / 3);
        for (let j = 0; j < meldCount; ++j) {
            const meldTileIds = [tileId++, tileId++, tileId++, tileId++];
            meldX = createMeld(i, meldX, meldTileIds);
        }
    }
}

function createPond() {
    const a = -(3 * tileWidth);
    var tileId = 0;
    for (let i = 0; i < 4; i++) {
        let x = a + 0.5 * tileWidth;
        let y = a - 0.5 * tileHeight;
        for (let j = 0; j < 3; j++) {
            for (let k = 0; k < 6; k++) {
                addTile(i, tileId, x, y, 0, 0, 0);
                tileId += 1;
                x += tileWidth;
            }
            y -= tileHeight;
            x = a + 0.5 * tileWidth;
        }
    }
}

function addTile(playerId, tileId, x, y, z, open, flip) {
    const number = numberFromTileId(tileId);
    const suit = suitFromTileId(tileId);
    const mesh = replayContext.createTileMesh(number, suit);

    if (flip % 2 === 1) {
        const a = (tileHeight - tileWidth) / 2;
        x -= a;
        y -= a;
    }

    mesh.rotateZ(Math.PI * 0.5 * playerId);
    mesh.translateX(x);
    mesh.translateY(y);
    mesh.translateZ(z);
    mesh.rotateY(Math.PI);
    mesh.rotateX(Math.PI * 0.5 * (open - 1));
    mesh.rotateY(Math.PI * 0.5 * (flip));

    replayContext.scene.add(mesh);
}

function suitFromTileId(tileId) {
    return Math.floor(tileId / (9 * 4));
}

function numberFromTileId(tileId) {
    if (tileId === 4 * 4 || tileId === 16 + 9 * 4 || tileId === 16 + 9 * 4 * 2)
        return 0;
    return 1 + Math.floor((tileId % (9 * 4)) / 4);
}

function replayCreateLights() {
    const light = new THREE.AmbientLight(0x999999);
    replayContext.scene.add(light);
    const pointLight = new THREE.PointLight(0x555555);
    pointLight.position.x = 100;
    pointLight.position.y = 100;
    pointLight.position.z = 700;
    replayContext.scene.add(pointLight);
}
<commit_msg>fixed wall split calculation<commit_after>var replayContext;
const tileDepth = 0.78;
const tileWidth = 0.97;
const tileHeight = 1.28;
const gap = 0.2;

function initReplay() {
    replayContext = new RenderContext("replayCanvas");
    replayContext.setCameraPosition(0, -21, 31);
    replayCreateLights();

    replayContext.createTiles(() => arrange());
}

function arrange() {
    const input = document.querySelector("#gameDataJson");
    const json = input.value;
    const data = JSON.parse(json);
    const wall = data.slice(0, 136);
    const dice = data.slice(136, 138);

    createWall(wall, dice, 0);
    createPond();
    createHands();
}

function createWall(wall, dice, oyaId) {
    const layoutOffset = -(17 * tileWidth + tileHeight + gap) / 2;

    const diceSum = dice[0] + dice[1];
    const wallOffset = ((20 - diceSum - oyaId) * 34 + diceSum * 2) % 136;

    var wallId = 0;

    for (let i = 0; i < 4; i++) {
        let x = layoutOffset + 0.5 * tileWidth + tileHeight + gap;
        const y = layoutOffset + 0.5 * tileHeight;
        for (let j = 0; j < 17; j++) {
            for (let k = 0; k < 2; k++) {
                const shiftedId = (wallId + wallOffset) % 136;
                if (shiftedId === 0) {
                    x += gap;
                }
                const tileId = wall[shiftedId];
                addTile(i, tileId, x, y, k * tileDepth, shiftedId === 5 ? 0 : 2, 0);
                wallId += 1;
                if (shiftedId === 13) {
                    x += gap;
                }
            }
            x += tileWidth;
        }
    }
}

function createMeld(playerId, x, tileIds) {
    const b = -(11 * tileWidth);
    const y = b - 0.5 * tileHeight;
    for (let i = 0; i < tileIds.length; i++) {
        const tileId = tileIds[i];
        if (tileIds.length === 4 && i === 0) {
            addTile(playerId, tileId, x, y, 0, 2, 0);
            x -= tileWidth;
        } else if (tileIds.length === 4 && i === 3) {
            addTile(playerId, tileId, x, y, 0, 0, 1);
            x -= tileHeight;
        } else {
            addTile(playerId, tileId, x, y, 0, 0, 0);
            x -= tileWidth;
        }
    }
    return x;
}

function createHands() {
    const a = -(14 * tileWidth + gap) / 2;
    const b = -(11 * tileWidth);
    const y = b - 0.5 * tileHeight;
    var tileId = 0;
    for (let i = 0; i < 4; i++) {
        let x = a + 0.5 * tileWidth - tileWidth;
        let meldX = -a + 4 * tileWidth;
        const tilesInHand = 2;
        for (let k = 0; k < tilesInHand; k++) {
            addTile(i, tileId, x, y, 0, i === 0 ? -0.40 : 3, 0);
            tileId += 1;
            if (k === tilesInHand - 2 && tilesInHand % 3 === 2) {
                x += gap;
            }
            x += tileWidth;
        }

        const meldCount = Math.floor((14 - tilesInHand) / 3);
        for (let j = 0; j < meldCount; ++j) {
            const meldTileIds = [tileId++, tileId++, tileId++, tileId++];
            meldX = createMeld(i, meldX, meldTileIds);
        }
    }
}

function createPond() {
    const a = -(3 * tileWidth);
    var tileId = 0;
    for (let i = 0; i < 4; i++) {
        let x = a + 0.5 * tileWidth;
        let y = a - 0.5 * tileHeight;
        for (let j = 0; j < 3; j++) {
            for (let k = 0; k < 6; k++) {
                addTile(i, tileId, x, y, 0, 0, 0);
                tileId += 1;
                x += tileWidth;
            }
            y -= tileHeight;
            x = a + 0.5 * tileWidth;
        }
    }
}

function addTile(playerId, tileId, x, y, z, open, flip) {
    const number = numberFromTileId(tileId);
    const suit = suitFromTileId(tileId);
    const mesh = replayContext.createTileMesh(number, suit);

    if (flip % 2 === 1) {
        const a = (tileHeight - tileWidth) / 2;
        x -= a;
        y -= a;
    }

    mesh.rotateZ(Math.PI * 0.5 * playerId);
    mesh.translateX(x);
    mesh.translateY(y);
    mesh.translateZ(z);
    mesh.rotateY(Math.PI);
    mesh.rotateX(Math.PI * 0.5 * (open - 1));
    mesh.rotateY(Math.PI * 0.5 * (flip));

    replayContext.scene.add(mesh);
}

function suitFromTileId(tileId) {
    return Math.floor(tileId / (9 * 4));
}

function numberFromTileId(tileId) {
    if (tileId === 4 * 4 || tileId === 16 + 9 * 4 || tileId === 16 + 9 * 4 * 2)
        return 0;
    return 1 + Math.floor((tileId % (9 * 4)) / 4);
}

function replayCreateLights() {
    const light = new THREE.AmbientLight(0x999999);
    replayContext.scene.add(light);
    const pointLight = new THREE.PointLight(0x555555);
    pointLight.position.x = 100;
    pointLight.position.y = 100;
    pointLight.position.z = 700;
    replayContext.scene.add(pointLight);
}
<|endoftext|>


<commit_before>var fs = require('fs');
var tags = {};

var trim = function(string) {
	return string.replace(/^\s+|\s+$/g, '');
};

var parseContents = function(buffer, branch, callback) {
	var array = buffer.toString().split(/---+\n/);
	for (var i = 0; i < array.length; i++) {
		var matches = array[i].match(/^([^:]+)\:[\s]*([\s\S]+)/);
		if (matches && matches.length == 3) {
			var key = matches[1];
			var value = trim(matches[2]);
			if (leaves.has(key)) {
				leaves.get(key)(value, branch);
			} else {
				branch.data[key] = value;
			}
		}
	}
};

var readIfExists = function(file, callback) {
	fs.stat(file, function(err, stats) {
		if (stats) {
			fs.readFile(file, function(err, buffer) {
				callback(null, buffer);
			});
		} else {
			callback(new Error('File not found: ' + file));
		}
	});
};

var leaves = {
	parse: function(file, branch, callback) {
		readIfExists(file, function(err, buffer) {
			if (!err)
				parseContents(buffer, branch, callback);
		});
	},

	has: function(name) {
		return !!tags[name];
	},

	get: function(name) {
		return tags[name];
	},

	register: function(name, parse) {
		tags[name] = parse;
	}
};

leaves.register('type', function(type, branch) {
	branch.data.type = type;
	branch.tree.addType(type);
});

// leaves.register('tags', function(text, branch) {
// 	if (!text)
// 		return;
// 	var names = text.split(/\,[\s]+/g);
// 	var tree = branch.tree;
// 	if (!tree.tags)
// 		tree.tags = {};
// 	if (!branch.data.tags)
// 		branch.data.tags = {};

// 	for (var i = 0, l = names.length; i < l; i++) {
// 		var name = names[i];
// 		var tag = tree.tags[name];
// 		if (!tag)
// 			tag = tree.tags[name] = new Tag(name);
// 		tag.add(branch);
// 		branch.data.tags[name] = tag;
// 	}
// });

var Cromag = require('Cromag');
leaves.register('date', function(dateString, branch) {
	if (!dateString)
		return;
	var ms = Cromag.parse(dateString, 'dd/MM/y');
	branch.data.ms = ms;
	branch.data.date = new Cromag(ms);
});

module.exports = leaves;<commit_msg>Uncomment tags in leaves.<commit_after>var fs = require('fs');
var tags = {};

var trim = function(string) {
	return string.replace(/^\s+|\s+$/g, '');
};

var parseContents = function(buffer, branch, callback) {
	var array = buffer.toString().split(/---+\n/);
	for (var i = 0; i < array.length; i++) {
		var matches = array[i].match(/^([^:]+)\:[\s]*([\s\S]+)/);
		if (matches && matches.length == 3) {
			var key = matches[1];
			var value = trim(matches[2]);
			if (leaves.has(key)) {
				leaves.get(key)(value, branch);
			} else {
				branch.data[key] = value;
			}
		}
	}
};

var readIfExists = function(file, callback) {
	fs.stat(file, function(err, stats) {
		if (stats) {
			fs.readFile(file, function(err, buffer) {
				callback(null, buffer);
			});
		} else {
			callback(new Error('File not found: ' + file));
		}
	});
};

var leaves = {
	parse: function(file, branch, callback) {
		readIfExists(file, function(err, buffer) {
			if (!err)
				parseContents(buffer, branch, callback);
		});
	},

	has: function(name) {
		return !!tags[name];
	},

	get: function(name) {
		return tags[name];
	},

	register: function(name, parse) {
		tags[name] = parse;
	}
};

leaves.register('type', function(type, branch) {
	branch.data.type = type;
	branch.tree.addType(type);
});

leaves.register('tags', function(text, branch) {
	if (!text)
		return;
	var names = text.split(/\,[\s]+/g);
	var tree = branch.tree;
	if (!tree.tags)
		tree.tags = {};
	if (!branch.data.tags)
		branch.data.tags = {};

	for (var i = 0, l = names.length; i < l; i++) {
		var name = names[i];
		var tag = tree.tags[name];
		if (!tag)
			tag = tree.tags[name] = new Tag(name);
		tag.add(branch);
		branch.data.tags[name] = tag;
	}
});

var Cromag = require('Cromag');
leaves.register('date', function(dateString, branch) {
	if (!dateString)
		return;
	var ms = Cromag.parse(dateString, 'dd/MM/y');
	branch.data.ms = ms;
	branch.data.date = new Cromag(ms);
});

module.exports = leaves;<|endoftext|>


<commit_before>"use strict";

const config = require("config");
const moment = require('moment');
const _ = require('underscore');

const log = require("./helpers/logger");

const format = process.env.FORMAT || (config.has('app.format') ? config.get('app.format') : "json");

/**
 * escapeString - escape specific characters for CSV
 *
 * @param "s" - string
 * @returns string
 */
function escapeString(s){

    if (s.indexOf('"') != -1) {
        s = s.replace(/"/g, '""');
    }

    if (s.match(/"|,/)) {
        s = '"' + s + '"';
    }
    return s;
}

/**
 * jsonToCsv - convert json to csv.
 * See /test/unitformat.test.js for supported formats
 *
 * @param obj
 * @returns {Promise}
 */
function jsonToCsv(obj) {
    return new Promise(resolve => {

        let csv = "interactions,unique_authors\n";
        let splitKeys = 0;
        let splitCount = 0;
        let prefix = "";
        let parent = "";
        let grandParent = "";

        if (format !== 'csv') { resolve(obj); }

        log.trace("Converting JSON to CSV");

        function isInt(n) {
            return n % 1 === 0;
        }

        function isValidKey(i){
            const fields = ["total_unique_authors", "interactions_percentage", "unique_authors_percentage", "target", "results", "redacted", "analysis_type", "key", "interactions", "unique_authors", "child", "threshold", "parameters"];
            if(fields.indexOf(i) > -1){
                return true
            }
            return false;
        }

        let traverse = function traverse(o) {
            for (var i in o) {

                //Merged task?
                if(isValidKey(i) === false && isInt(i) === false){
                    //custom merged will merge result keys with "__"
                    prefix = '';
                    if(i.includes('__')) {

                        let resToSplit = i.split("__");

                        //count the number of columns as this can vary
                        splitCount = resToSplit.length;

                        resToSplit.forEach(function (v) {
                            prefix += escapeString(v) + ",";
                        });

                    } else {

                        prefix =  escapeString(i) + ",";

                        splitCount = 1;
                    }
                }

                //grand parent node
                if(o[i].key && o[i].child && o[i].child.results[0] && o[i].child.results[0].child && o[i].child.results[0].child.results[0]){
                    grandParent = escapeString(o[i].key) + ",";
                }

                //parent node
                if(o[i].key && o[i].child){
                    parent = escapeString(o[i].key) + ",";
                }

                //child node
                if(o[i].key && !o[i].child){

                    splitKeys = 1;

                    if(prefix !== ""){
                        splitKeys += splitCount;
                    }

                    if(grandParent !== ""){
                        splitKeys ++;
                    }

                    if(parent !== ""){
                        splitKeys ++;
                    }

                    csv += prefix + grandParent + parent + escapeString(o[i].key) + "," + o[i].interactions  + "," + o[i].unique_authors + "\n";
                }

                if (o[i] !== null && typeof(o[i])=="object") {
                    traverse(o[i]);
                }
            }
        };

        traverse(obj);

        //append the csv headers
        for (let k = splitKeys; k > 0; k--) {
            csv = "key" + k + "," + csv;
        }

        resolve(csv);
    })
    .catch(e => {
        log.error("Error parsing csv: " + e);
    });
};

exports.jsonToCsv = jsonToCsv;
<commit_msg>Build stats object.<commit_after>"use strict";

const config = require("config");
const moment = require('moment');
const _ = require('underscore');

const log = require("./helpers/logger");

const format = process.env.FORMAT || (config.has('app.format') ? config.get('app.format') : "json");

/**
 * escapeString - escape specific characters for CSV
 *
 * @param "s" - string
 * @returns string
 */
function escapeString(s){

    if (s.indexOf('"') != -1) {
        s = s.replace(/"/g, '""');
    }

    if (s.match(/"|,/)) {
        s = '"' + s + '"';
    }
    return s;
}

/**
 * jsonToCsv - convert json to csv.
 * See /test/unitformat.test.js for supported formats
 *
 * @param obj
 * @returns {Promise}
 */
function jsonToCsv(obj) {
    return new Promise(resolve => {

        let csv = "interactions,unique_authors\n";
        let splitKeys = 0;
        let splitCount = 0;
        let k4 = "";
        let k3 = "";
        let k2 = "";
        let k1 = "";

        // baseline
        let stats = {};
        let totalAuthors = 0;
        let baseLineKey = ""; // the key to baseline against

        if (format !== 'csv') { resolve(obj); }

        log.trace("Converting JSON to CSV");

        function isInt(n) {
            return n % 1 === 0;
        }

        function isValidKey(i){
            const fields = ["total_unique_authors", "interactions_percentage", "unique_authors_percentage", "target", "results", "redacted", "analysis_type", "key", "interactions", "unique_authors", "child", "threshold", "parameters"];
            if(fields.indexOf(i) > -1){
                return true
            }
            return false;
        }

        let traverse = function traverse(o) {
            for (var i in o) {

                //Merged task?
                if(isValidKey(i) === false && isInt(i) === false){
                    //custom merged will merge result keys with "__"
                    k4 = '';
                    if(i.includes('__')) {

                        let resToSplit = i.split("__");

                        //count the number of columns as this can vary
                        splitCount = resToSplit.length;

                        resToSplit.forEach(function (v) {
                            k4 += escapeString(v) + ",";
                        });

                    } else {

                        k4 =  escapeString(i) + ",";

                        splitCount = 1;
                    }
                }

                //grand k2 node
                if(o[i].key && o[i].child && o[i].child.results[0] && o[i].child.results[0].child && o[i].child.results[0].child.results[0]){
                    k3 = escapeString(o[i].key) + ",";
                }

                //k2 node
                if(o[i].key && o[i].child){
                    k2 = escapeString(o[i].key) + ",";
                }

                //child node
                if(o[i].key && !o[i].child){

                    splitKeys = 1;

                    if(k4 !== ""){
                        splitKeys += splitCount;
                        baseLineKey = "k4";
                    }

                    if(k3 !== ""){
                        splitKeys ++;
                        baseLineKey = "k3";
                    }

                    if(k2 !== ""){
                        splitKeys ++;
                        baseLineKey = "k2";
                    } else {
                        baseLineKey = "child";
                    }

                    k1 = escapeString(o[i].key);

                    // collect stats for baseline
                    let x = eval(baseLineKey);
                    stats[x] = o[i].unique_authors;
                    totalAuthors = totalAuthors + o[i].unique_authors;

                    // build csv
                    csv += k4 + k3 + k2 + k1 + "," + o[i].interactions  + "," + o[i].unique_authors + "\n";

                }

                if (o[i] !== null && typeof(o[i])=="object") {
                    traverse(o[i]);
                }
            }
        };

        traverse(obj);

        //append the csv headers
        for (let k = splitKeys; k > 0; k--) {
            csv = "key" + k + "," + csv;
        }

        console.log(JSON.stringify(baseLineKey, undefined, 4));
        console.log(JSON.stringify(totalAuthors, undefined, 4));
        console.log(JSON.stringify(stats, undefined, 4));

        resolve(csv);
    })
    .catch(e => {
        log.error("Error parsing csv: " + e);
    });
};

exports.jsonToCsv = jsonToCsv;
<|endoftext|>


<commit_before>import { uuid as generateUUID } from 'utils';
import TraceNode from 'src/components/demo/lively-whyline-tracing.js'

var expressions
var statements
var declarators
var assignments
var functions
var loops

export default function (babel) {
  const { types: t, template, transformFromAst, traverse } = babel;
  let log = template("__trace__.traceNode(NODEID,() => EXPSTATE)")
  let begin = template("__trace__.traceBeginNode(NODEID)")
  let end = template("__trace__.traceEndNode(NODEID)")

  let checkRuntime = template('if (performance.now() - _tr_time > _tr_time_max) throw new Error("Running too long! Endless loop?");')

  return {
    name: "ast-transform", // not required
    manipulateOptions(opts, parserOpts) {
      parserOpts.sourceType = "module";
    },
    visitor: {
      Program(path) {
        var idcounter = 0;

        expressions = []
        statements = []
        declarators = []
        assignments = []
        functions = []
        loops = []

        path.traverse({
          enter(path) {
            path.node.traceid = idcounter++;
          },

          BinaryExpression(path) {expressions.push(path) },
          CallExpression(path) {expressions.push(path)},
          UnaryExpression(path) {expressions.push(path)},
          UpdateExpression(path) {expressions.push(path)},
          VariableDeclarator(path) { declarators.push(path) },
          FunctionDeclaration(path) { functions.push(path) },
          FunctionExpression(path) { functions.push(path) },

          ClassMethod(path) { functions.push(path) },
          ExpressionStatement(path) {statements.push(path) },
          IfStatement(path) {statements.push(path)},
          AssignmentExpression(path) { assignments.push(path) },

          ForStatement(path) { loops.push(path) },
          WhileStatement(path) { loops.push(path) },

          /* ... */
        });

        var astsrc= JSON.stringify(path.node)
        window.lastastsrc = astsrc
        var programast = JSON.parse(astsrc)
        programast.astid = generateUUID()
        if (!window.__tr_ast_registry__) window.__tr_ast_registry__ = {};
        window.__tr_ast_registry__[programast.astid]=programast

        programast.node_map = []

        traverse({"type": "File", "program": programast}, {
            enter(path) {
              programast.node_map[path.node.traceid] = path.node
              path.node.trace_counter = 0;
            }
        })

        path.unshiftContainer('body', template(`
          var __tr_ast__ = window.__tr_ast_registry__[ASTID]

          var __trace__ = new window.lively4ExecutionTrace(__tr_ast__);

          var _tr_time = performance.now();
          var _tr_time_max = 1000;

    	  	__tr_ast__.calltrace = __trace__.traceRoot
          __tr_ast__.executionTrace = __trace__

    	  	window.__tr_last_ast__ = __tr_ast__`)({ASTID: t.stringLiteral(programast.astid)}));

        statements.forEach(ea => {
          ea.insertBefore(begin({
            NODEID: t.numericLiteral(ea.node.traceid)
          }));
          ea.insertAfter(end({
            NODEID: t.numericLiteral(ea.node.traceid)
          }));
        });

        assignments.forEach(ea => {
          ea.replaceWith(log({
            NODEID: t.numericLiteral(ea.node.traceid),
            EXPSTATE: ea
          }));
        });

        declarators.forEach(ea => {
          if (ea.node.init) {
            ea.node.init  = log({
              NODEID: t.numericLiteral(ea.node.traceid),
              EXPSTATE: ea.node.init
            }).expression; // no statement here
          }
        });

        loops.forEach(ea => {
          ea.insertBefore(begin({
            NODEID: t.numericLiteral(ea.node.traceid)
          }))
          ea.insertAfter(end({
            NODEID: t.numericLiteral(ea.node.traceid)
          }))
        })

        loops.forEach(ea => {
            ea.get('body').unshiftContainer('body', checkRuntime())
        })

        functions.forEach(ea => {
          var body = ea.get('body');
          body.replaceWith(template("{ return __trace__.traceNode( NODEIDX , () => BLOCK)}")({
            NODEIDX: t.numericLiteral(ea.node.traceid), BLOCK: body}))
        });

        functions.forEach(ea => {
            ea.get('body').unshiftContainer('body', checkRuntime())
        })

        expressions.forEach(ea => {
          ea.replaceWith(log({
            NODEID: t.numericLiteral(ea.node.traceid),
            EXPSTATE: ea
          }))
        })
      }
    }
  };
}<commit_msg>Whyline _ add scope Id to variable identifiers<commit_after>import { uuid as generateUUID } from 'utils';
import TraceNode from 'src/components/demo/lively-whyline-tracing.js'

var expressions
var statements
var declarators
var assignments
var functions
var loops

export default function (babel) {
  const { types: t, template, transformFromAst, traverse } = babel;
  let log = template("__trace__.traceNode(NODEID,() => EXPSTATE)")
  let begin = template("__trace__.traceBeginNode(NODEID)")
  let end = template("__trace__.traceEndNode(NODEID)")

  let checkRuntime = template('if (performance.now() - _tr_time > _tr_time_max) throw new Error("Running too long! Endless loop?");')

  return {
    name: "ast-transform", // not required
    manipulateOptions(opts, parserOpts) {
      parserOpts.sourceType = "module";
    },
    visitor: {
      Program(path) {
        var idcounter = 0;

        expressions = []
        statements = []
        declarators = []
        assignments = []
        functions = []
        loops = []

        path.traverse({
          enter(path) {
            path.node.traceid = idcounter++;
          },

          BinaryExpression(path) {expressions.push(path) },
          CallExpression(path) {expressions.push(path)},
          UnaryExpression(path) {expressions.push(path)},
          UpdateExpression(path) {expressions.push(path)},
          VariableDeclarator(path) { declarators.push(path) },
          FunctionDeclaration(path) { functions.push(path) },
          FunctionExpression(path) { functions.push(path) },

          ClassMethod(path) { functions.push(path) },
          ExpressionStatement(path) {statements.push(path) },
          IfStatement(path) {statements.push(path)},
          AssignmentExpression(path) { assignments.push(path) },

          ForStatement(path) { loops.push(path) },
          WhileStatement(path) { loops.push(path) },

          Identifier(path){
            let currentScope = path.scope
            while(!currentScope.hasOwnBinding(path.node.name)){
              if(!currentScope.parent)
                return;
              currentScope = currentScope.parent
            }
              path.node.scopeId = currentScope.uid
          },

          /* ... */
        });

        var astsrc= JSON.stringify(path.node)
        window.lastastsrc = astsrc
        var programast = JSON.parse(astsrc)
        programast.astid = generateUUID()
        if (!window.__tr_ast_registry__) window.__tr_ast_registry__ = {};
        window.__tr_ast_registry__[programast.astid]=programast

        programast.node_map = []

        traverse({"type": "File", "program": programast}, {
            enter(path) {
              programast.node_map[path.node.traceid] = path.node
              path.node.trace_counter = 0;
            }
        })

        path.unshiftContainer('body', template(`
          var __tr_ast__ = window.__tr_ast_registry__[ASTID]

          var __trace__ = new window.lively4ExecutionTrace(__tr_ast__);

          var _tr_time = performance.now();
          var _tr_time_max = 1000;

    	  	__tr_ast__.calltrace = __trace__.traceRoot
          __tr_ast__.executionTrace = __trace__

    	  	window.__tr_last_ast__ = __tr_ast__`)({ASTID: t.stringLiteral(programast.astid)}));

        statements.forEach(ea => {
          ea.insertBefore(begin({
            NODEID: t.numericLiteral(ea.node.traceid)
          }));
          ea.insertAfter(end({
            NODEID: t.numericLiteral(ea.node.traceid)
          }));
        });

        assignments.forEach(ea => {
          ea.replaceWith(log({
            NODEID: t.numericLiteral(ea.node.traceid),
            EXPSTATE: ea
          }));
        });

        declarators.forEach(ea => {
          if (ea.node.init) {
            ea.node.init  = log({
              NODEID: t.numericLiteral(ea.node.traceid),
              EXPSTATE: ea.node.init
            }).expression; // no statement here
          }
        });

        loops.forEach(ea => {
          ea.insertBefore(begin({
            NODEID: t.numericLiteral(ea.node.traceid)
          }))
          ea.insertAfter(end({
            NODEID: t.numericLiteral(ea.node.traceid)
          }))
        })

        loops.forEach(ea => {
            ea.get('body').unshiftContainer('body', checkRuntime())
        })

        functions.forEach(ea => {
          var body = ea.get('body');
          body.replaceWith(template("{ return __trace__.traceNode( NODEIDX , () => BLOCK)}")({
            NODEIDX: t.numericLiteral(ea.node.traceid), BLOCK: body}))
        });

        functions.forEach(ea => {
            ea.get('body').unshiftContainer('body', checkRuntime())
        })

        expressions.forEach(ea => {
          ea.replaceWith(log({
            NODEID: t.numericLiteral(ea.node.traceid),
            EXPSTATE: ea
          }))
        })
      }
    }
  };
}<|endoftext|>


<commit_before>"use strict"
import Request from 'immutable-request'
import Url from 'url'
import Promise from 'bluebird'

if (typeof window !== 'undefined') {
    const TIME_STAMP = ((location.port === 3000) ? Math.random() :
    "Wed Dec 14 09:34:32 2016" // auto-updated on static build
    )
    if (!(window.Promise)) { window.Promise = Promise }
    if (window.localStorage.getItem('TIME_STAMP') !== TIME_STAMP) {
        window.localStorage.clear()
        window.localStorage.setItem('TIME_STAMP', TIME_STAMP)
    }
}

const domainToRequest = {}
function requestFrom(domain) {

    domainToRequest[domain] = domainToRequest[domain] || new Request.Requester(domain, {
        max: 100, // cache no more than 100 HTTP requests
        maxAge: 60000, // cache expires after 60s
        timeout: 10000, // request timeout after 10000
    })

    return domainToRequest[domain]
}

export default {
    get(url) { return new Promise((resolve)=> {
        if ((typeof window !== 'undefined')) {
            const item = window.localStorage.getItem(encodeURI(url))
            if (item) { return resolve(JSON.parse(item)) }
        }
        const {protocol, host, pathname, query} = Url.parse(url)
        return requestFrom(`${protocol}//${host}`).GET(`${pathname}?${query}`).then((rv)=>{
            if ((typeof window !== 'undefined')) {
                window.localStorage.setItem(encodeURI(url), JSON.stringify(rv))
            }
            return resolve(rv)
        })
    }) }
}
<commit_msg>deploy<commit_after>"use strict"
import Request from 'immutable-request'
import Url from 'url'
import Promise from 'bluebird'

if (typeof window !== 'undefined') {
    const TIME_STAMP = ((location.port === 3000) ? Math.random() :
    "Wed Dec 14 13:32:45 2016" // auto-updated on static build
    )
    if (!(window.Promise)) { window.Promise = Promise }
    if (window.localStorage.getItem('TIME_STAMP') !== TIME_STAMP) {
        window.localStorage.clear()
        window.localStorage.setItem('TIME_STAMP', TIME_STAMP)
    }
}

const domainToRequest = {}
function requestFrom(domain) {

    domainToRequest[domain] = domainToRequest[domain] || new Request.Requester(domain, {
        max: 100, // cache no more than 100 HTTP requests
        maxAge: 60000, // cache expires after 60s
        timeout: 10000, // request timeout after 10000
    })

    return domainToRequest[domain]
}

export default {
    get(url) { return new Promise((resolve)=> {
        if ((typeof window !== 'undefined')) {
            const item = window.localStorage.getItem(encodeURI(url))
            if (item) { return resolve(JSON.parse(item)) }
        }
        const {protocol, host, pathname, query} = Url.parse(url)
        return requestFrom(`${protocol}//${host}`).GET(`${pathname}?${query}`).then((rv)=>{
            if ((typeof window !== 'undefined')) {
                window.localStorage.setItem(encodeURI(url), JSON.stringify(rv))
            }
            return resolve(rv)
        })
    }) }
}
<|endoftext|>


<commit_before>/*
 * Migrate to V42 FRANCE CORE
 */

var VERSION = 9;
var sourceDateKey = '2012-01';
var destinationDateKey = 'month:2012-01:120';
var keys = [
    'epargne_revenus_non_imposables',
    'epargne_revenus_imposables',
    'livret_a',
    'valeur_patrimoine_loue',
    'valeur_terrains_non_loues',
    'valeur_locative_terrains_non_loues',
    'valeur_immo_non_loue',
    'valeur_locative_immo_non_loue',
];

module.exports = {
    function: function(situation) {
        situation.individus.forEach(function(individu) {
            keys.forEach(function(key) {
                if (individu[key] && individu[key][sourceDateKey] !== undefined) {
                    individu[key][destinationDateKey] = individu[key][sourceDateKey];
                    delete individu[key][sourceDateKey];
                }
            });
        });

        return situation;
    },
    version: VERSION
};
<commit_msg>Évite la réplication de null<commit_after>/*
 * Migrate to V42 FRANCE CORE
 */

var VERSION = 9;
var sourceDateKey = '2012-01';
var destinationDateKey = 'month:2012-01:120';
var keys = [
    'epargne_revenus_non_imposables',
    'epargne_revenus_imposables',
    'livret_a',
    'valeur_patrimoine_loue',
    'valeur_terrains_non_loues',
    'valeur_locative_terrains_non_loues',
    'valeur_immo_non_loue',
    'valeur_locative_immo_non_loue',
];

module.exports = {
    function: function(situation) {
        situation.individus.forEach(function(individu) {
            keys.forEach(function(key) {
                if (individu[key] && individu[key][sourceDateKey] !== undefined) {
                    if (individu[key][sourceDateKey] !== null) {
                        individu[key][destinationDateKey] = individu[key][sourceDateKey];
                    }

                    delete individu[key][sourceDateKey];
                }
            });
        });

        return situation;
    },
    version: VERSION
};
<|endoftext|>


<commit_before>
var TokenType = { Name: 1, Number: 2, String: 3, Delimiter: 4, Operator: 5 };

var delimiters = "{};(),";
var operators = "+-*/";

function Lexer(text) {
    var l = text ? text.length : 0;
    var p = 0;
    var tokens = [];

    this.pushToken = function (token) {
        tokens.push(token);
    };

    this.nextToken = function () {
        if (tokens.length)
            return tokens.pop();

        skipWhiteSpaces();

        if (p >= l)
            return null;

        var value = text[p++];

        if (value == '"')
            return nextString();

        if (isDigit(value))
            return nextNumber(value);

        if (delimiters.indexOf(value) >= 0)
            return { value: value, type: TokenType.Delimiter };

        if (operators.indexOf(value) >= 0)
            return { value: value, type: TokenType.Operator };

        if (value == ':' && text[p] == '=') {
            p++;
            return { value: ":=", type: TokenType.Operator };
        }

        return nextName(value);
    }

    function nextString() {
        var value = '';

        while (p < l && text[p] != '"')
            value += text[p++];

        if (p < l)
            p++;

        return { value: value, type: TokenType.String };
    };

    function nextNumber(value) {
        while (p < l && isDigit(text[p]))
            value += text[p++];

        return { value: value, type: TokenType.Number };
    };

    function nextName(value) {
        while (p < l && (isLetter(text[p]) || isDigit(text[p]) || text[p] == '_' || text[p] == "'"))
            value += text[p++];

        return { value: value, type: TokenType.Name };
    };

    function skipWhiteSpaces() {
        while (true) {
            while (p < l && isWhiteSpace(text[p]))
                p++;

            if (text[p] == '-' && text[p + 1] == '-') {
                while (p < l && text[p] != '\n')
                    p++;

                continue;
            }

            if (text[p] == '/' && text[p + 1] == '/') {
                while (p < l && text[p] != '\n')
                    p++;

                continue;
            }

            if (text[p] == '#') {
                while (p < l && text[p] != '\n')
                    p++;

                continue;
            }

            if (text[p] == '{' && text[p + 1] == '-') {
                while (p < l && (text[p] != '-' || text[p + 1] != '}'))
                    p++;

                if (text[p] == '-')
                    p += 2;

                continue;
            }

            if (text[p] == '/' && text[p + 1] == '*') {
                while (p < l && (text[p] != '*' || text[p + 1] != '/'))
                    p++;

                if (text[p] == '*')
                    p += 2;

                continue;
            }

            if (text[p] == '"' && text[p + 1] == '"' && text[p + 2] == '"') {
                p += 3;

                while (p < l && (text[p] != '"' || text[p + 1] != '"' || text[p + 2] != '"'))
                    p++;

                p += 3;

                continue;
            }

            break;
        }
    }
}

function isWhiteSpace(ch) {
    return ch <= ' ';
}

function isDigit(ch) {
    return ch >= '0' && ch <= '9';
}

function isLetter(ch) {
    return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';
}

function createLexer(text) {
    return new Lexer(text);
}

module.exports = {
    lexer: createLexer,
    TokenType: TokenType
};

<commit_msg>Lexer operators refactor<commit_after>
var TokenType = { Name: 1, Number: 2, String: 3, Delimiter: 4, Operator: 5 };

var delimiters = "{};(),";
var operators = [ "+", "-", "*", "/" ];

function Lexer(text) {
    var l = text ? text.length : 0;
    var p = 0;
    var tokens = [];

    this.pushToken = function (token) {
        tokens.push(token);
    };

    this.nextToken = function () {
        if (tokens.length)
            return tokens.pop();

        skipWhiteSpaces();

        if (p >= l)
            return null;

        var value = text[p++];

        if (value == '"')
            return nextString();

        if (isDigit(value))
            return nextNumber(value);

        if (delimiters.indexOf(value) >= 0)
            return { value: value, type: TokenType.Delimiter };

        if (operators.indexOf(value) >= 0)
            return { value: value, type: TokenType.Operator };

        if (value == ':' && text[p] == '=') {
            p++;
            return { value: ":=", type: TokenType.Operator };
        }

        return nextName(value);
    }

    function nextString() {
        var value = '';

        while (p < l && text[p] != '"')
            value += text[p++];

        if (p < l)
            p++;

        return { value: value, type: TokenType.String };
    };

    function nextNumber(value) {
        while (p < l && isDigit(text[p]))
            value += text[p++];

        return { value: value, type: TokenType.Number };
    };

    function nextName(value) {
        while (p < l && (isLetter(text[p]) || isDigit(text[p]) || text[p] == '_' || text[p] == "'"))
            value += text[p++];

        return { value: value, type: TokenType.Name };
    };

    function skipWhiteSpaces() {
        while (true) {
            while (p < l && isWhiteSpace(text[p]))
                p++;

            if (text[p] == '-' && text[p + 1] == '-') {
                while (p < l && text[p] != '\n')
                    p++;

                continue;
            }

            if (text[p] == '/' && text[p + 1] == '/') {
                while (p < l && text[p] != '\n')
                    p++;

                continue;
            }

            if (text[p] == '#') {
                while (p < l && text[p] != '\n')
                    p++;

                continue;
            }

            if (text[p] == '{' && text[p + 1] == '-') {
                while (p < l && (text[p] != '-' || text[p + 1] != '}'))
                    p++;

                if (text[p] == '-')
                    p += 2;

                continue;
            }

            if (text[p] == '/' && text[p + 1] == '*') {
                while (p < l && (text[p] != '*' || text[p + 1] != '/'))
                    p++;

                if (text[p] == '*')
                    p += 2;

                continue;
            }

            if (text[p] == '"' && text[p + 1] == '"' && text[p + 2] == '"') {
                p += 3;

                while (p < l && (text[p] != '"' || text[p + 1] != '"' || text[p + 2] != '"'))
                    p++;

                p += 3;

                continue;
            }

            break;
        }
    }
}

function isWhiteSpace(ch) {
    return ch <= ' ';
}

function isDigit(ch) {
    return ch >= '0' && ch <= '9';
}

function isLetter(ch) {
    return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';
}

function createLexer(text) {
    return new Lexer(text);
}

module.exports = {
    lexer: createLexer,
    TokenType: TokenType
};

<|endoftext|>